diff --git a/.env.schema b/.env.schema index 1c4bbc0..df8895c 100644 --- a/.env.schema +++ b/.env.schema @@ -45,10 +45,10 @@ SMTP_PASS= # @public @optional @type=url LOGO_URL= -# @required @type=email +# @required @public @type=email ADMIN_EMAIL=if(forEnv(development), "suni@localhost.com") -# @required +# @required @public ADMIN_NAME=if(forEnv(development), "Suni") # @public @type=url diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index adc217e..e166de4 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -1,6 +1,6 @@ import { OpenAPIHandler } from "@orpc/openapi/fetch"; import { OpenAPIReferencePlugin } from "@orpc/openapi/plugins"; -import { onError } from "@orpc/server"; +import { ORPCError, onError, ValidationError } from "@orpc/server"; import { RPCHandler } from "@orpc/server/fetch"; import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4"; import { appRouter } from "@suni/api/routers/index"; @@ -12,6 +12,7 @@ import { evlog } from "evlog/hono"; import type { EvlogVariables } from "evlog/hono"; import { Hono } from "hono"; import { cors } from "hono/cors"; +import { z } from "zod"; import { createContext } from "./context"; import { ENV } from "./env.server"; @@ -33,6 +34,30 @@ function handleError(error: T) { console.error(error); } +// Default Zod messages (e.g. a missing field) in Spanish; schemas keep their own messages. +z.config(z.locales.es()); + +// oRPC answers failed input validation with a generic English message; send the schema's own message instead. +async function schemaErrorMessage({ next }: { next: () => Promise }) { + try { + return await next(); + } catch (error) { + if ( + error instanceof ORPCError && + error.code === "BAD_REQUEST" && + error.cause instanceof ValidationError + ) { + throw new ORPCError("BAD_REQUEST", { + message: error.cause.issues[0]?.message ?? error.message, + data: error.data, + cause: error.cause, + }); + } + + throw error; + } +} + app.use( evlog(process.env.NODE_ENV === "production" ? {} : { drain: createFsDrain() }) ); @@ -62,10 +87,12 @@ export const apiHandler = new OpenAPIHandler(appRouter, { }), ], interceptors: [onError(handleError)], + clientInterceptors: [schemaErrorMessage], }); export const rpcHandler = new RPCHandler(appRouter, { interceptors: [onError(handleError)], + clientInterceptors: [schemaErrorMessage], }); app.use("/*", async (c, next) => { diff --git a/apps/web/src/components/customers/branches/branch-form.tsx b/apps/web/src/components/customers/branches/branch-form.tsx index 9b8523f..b9a1f61 100644 --- a/apps/web/src/components/customers/branches/branch-form.tsx +++ b/apps/web/src/components/customers/branches/branch-form.tsx @@ -1,23 +1,16 @@ -import type { AppRouterOutputs } from "@suni/api/routers/index"; -import { - branchFormSchema, - branchInputSchema, -} from "@suni/db/validation/branches"; +import { branchSchema } from "@suni/db/validation/branches"; import { Button } from "@suni/ui/components/button"; import { revalidateLogic, useSelector } from "@tanstack/react-form"; -import { useQueryClient } from "@tanstack/react-query"; -import type { UseQueryResult } from "@tanstack/react-query"; import { Loader2 } from "lucide-react"; import type { z } from "zod"; import { useAppForm } from "@/components/form/use-app-form"; import { useCreateBranch, useUpdateBranch } from "@/hooks/use-branches"; -import { postalCodeQueryOptions, usePostalCode } from "@/hooks/use-postal-code"; -import type { Settlement } from "@/hooks/use-postal-code"; +import { POSTAL_CODE_LENGTH, useAddressLookup } from "@/hooks/use-postal-code"; -type Branch = AppRouterOutputs["branches"]["list"][number]; +import type { Branch } from "./util/branch-address"; -type FormValues = z.input; +type FormValues = z.input; interface BranchFormProps { customerId: string; @@ -26,8 +19,6 @@ interface BranchFormProps { onCancel: () => void; } -const POSTAL_CODE_LENGTH = 5; - const PHONE_LENGTH = 10; const FILLED_BY_POSTAL_CODE = "Se llena con el código postal"; @@ -54,42 +45,22 @@ function toFormValues(branch?: Branch): FormValues { name: branch.name, street: branch.street, extNumber: branch.extNumber, - intNumber: branch.intNumber ?? "", + intNumber: branch.intNumber, postalCode: branch.postalCode, suburb: branch.suburb, city: branch.city, state: branch.state, - phone: branch.phone ?? "", - frontImageUrl: branch.frontImageUrl ?? "", + phone: branch.phone, + frontImageUrl: branch.frontImageUrl, }; } -function postalCodeStatus( - query: UseQueryResult, - 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(); @@ -98,18 +69,16 @@ export function BranchForm({ const form = useAppForm({ defaultValues: toFormValues(branch), validationLogic: revalidateLogic(), - validators: { onDynamic: branchFormSchema }, + validators: { onDynamic: branchSchema }, onSubmit: ({ value }) => { - const parsed = branchInputSchema.parse(value); - if (branch) { updateBranch.mutate( - { id: branch.id, ...parsed }, + { id: branch.id, ...value }, { onSuccess: () => onSuccess?.() } ); } else { createBranch.mutate( - { customerId, ...parsed }, + { customerId, ...value }, { onSuccess: () => onSuccess?.() } ); } @@ -117,58 +86,7 @@ export function BranchForm({ }); const zip = useSelector(form.store, (state) => state.values.postalCode); - const postalCode = usePostalCode(zip); - const settlements = postalCode.data ?? []; - - // SEPOMEX define municipio y estado; solo un fallo o un código inexistente los desbloquea. - const regionLocked = !( - postalCode.isError || - (postalCode.isSuccess && settlements.length === 0) - ); - - // La colonia solo espera a la consulta; después queda abierta por si SEPOMEX no la tiene. - const suburbLocked = !(postalCode.isSuccess || postalCode.isError); - - const suburbOptions = [...new Set(settlements.map((s) => s.d_asenta))].map( - (value) => ({ value, label: value }) - ); - - const fillAddress = async (value: string) => { - form.setFieldValue("suburb", ""); - form.setFieldValue("city", ""); - form.setFieldValue("state", ""); - - if (value.length !== POSTAL_CODE_LENGTH) { - return; - } - - let found: Settlement[]; - - try { - found = await queryClient.query(postalCodeQueryOptions(value)); - } catch { - // usePostalCode muestra el error bajo el campo. - return; - } - - // El usuario siguió escribiendo mientras corría la petición. - if (form.getFieldValue("postalCode") !== value) { - return; - } - - const [first] = found; - - if (!first) { - return; - } - - form.setFieldValue("city", first.d_mnpio); - form.setFieldValue("state", first.d_estado); - - if (found.length === 1) { - form.setFieldValue("suburb", first.d_asenta); - } - }; + const address = useAddressLookup(zip); return (
fillAddress(value) }} + listeners={{ + onChange: ({ value }) => + address.fill(value, { + getPostalCode: () => form.getFieldValue("postalCode"), + set: (field, fieldValue) => + form.setFieldValue(field, fieldValue), + }), + }} name="postalCode" > {(field) => ( )} @@ -240,8 +165,8 @@ export function BranchForm({ )} @@ -251,8 +176,8 @@ export function BranchForm({ )} diff --git a/apps/web/src/components/customers/branches/branch-header.tsx b/apps/web/src/components/customers/branches/branch-header.tsx index 2605152..794085e 100644 --- a/apps/web/src/components/customers/branches/branch-header.tsx +++ b/apps/web/src/components/customers/branches/branch-header.tsx @@ -2,25 +2,24 @@ import type { AppRouterOutputs } from "@suni/api/routers/index"; import { Badge } from "@suni/ui/components/badge"; import { Button } from "@suni/ui/components/button"; import { cn } from "@suni/ui/lib/utils"; +import { Link } from "@tanstack/react-router"; import { Archive, ArchiveRestore, Building2, Pencil } from "lucide-react"; import { useState } from "react"; +import { archiveState } from "../shared/archive-state"; import { ChangeBranchStatusDialog } from "./change-branch-status-dialog"; type Branch = AppRouterOutputs["branches"]["get"]; interface BranchHeaderProps { - branch: Pick; - customerName: string; + branch: Pick; onEdit?: () => void; } -export function BranchHeader({ - branch, - customerName, - onEdit, -}: BranchHeaderProps) { - const isArchived = !!branch.archived; +export function BranchHeader({ branch, onEdit }: BranchHeaderProps) { + const { isOwnArchived, isCustomerArchived, isArchived } = + archiveState(branch); + const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); return ( @@ -60,17 +59,25 @@ export function BranchHeader({ {isArchived ? ( - Archivada + {isCustomerArchived ? "Cliente archivado" : "Archivada"} ) : null}

- Sucursal de {customerName} + Sucursal de{" "} + + {branch.customer.name} +

- {onEdit ? ( + {/* An archived customer wins: unarchive it first, from its own page */} + {onEdit && !isCustomerArchived ? (
{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 index 2569104..29af8ad 100644 --- a/apps/web/src/components/customers/branches/branch-info.tsx +++ b/apps/web/src/components/customers/branches/branch-info.tsx @@ -1,6 +1,7 @@ import { cn } from "@suni/ui/lib/utils"; import { Camera, MapPin, Phone, ZoomIn } from "lucide-react"; +import { archiveState } from "../shared/archive-state"; import type { Branch } from "./util/branch-address"; import { formatAddress } from "./util/branch-address"; @@ -20,7 +21,7 @@ export function BranchInfoContent({ onImagePreview, onImageUpload, }: BranchInfoContentProps) { - const isArchived = !!branch.archived; + const { isArchived } = archiveState(branch); const address = formatAddress(branch); return ( diff --git a/apps/web/src/components/customers/branches/card.tsx b/apps/web/src/components/customers/branches/card.tsx index c790aea..a0e559d 100644 --- a/apps/web/src/components/customers/branches/card.tsx +++ b/apps/web/src/components/customers/branches/card.tsx @@ -1,4 +1,3 @@ -import type { AppRouterOutputs } from "@suni/api/routers/index"; import { Badge } from "@suni/ui/components/badge"; import { Button } from "@suni/ui/components/button"; import { @@ -13,23 +12,21 @@ 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 { ArchiveMenuItem } from "../shared/archive-menu-item"; +import { archiveState } from "../shared/archive-state"; 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]; +import { branchImageSrc, formatAddress } from "./util/branch-address"; +import type { Branch } from "./util/branch-address"; interface BranchCardProps { branch: Branch; @@ -39,23 +36,10 @@ interface BranchCardProps { 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"; - +function BranchImage({ name, src, isArchived }: BranchImageProps) { return (
- - {hasImage && onExpandClick && ( - - )} - - {!isArchived && onUploadClick && ( - + {isArchived && ( + + + Archivada + )}
); } export default function BranchCard({ branch, customer }: BranchCardProps) { - const isOwnArchived = !!branch.archived; - const isCustomerArchived = !!branch.customer?.archived; - const isArchived = isOwnArchived || isCustomerArchived; + const { isOwnArchived, isCustomerArchived, isArchived, parentHint } = + archiveState(branch); 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 */}
@@ -146,10 +106,19 @@ export default function BranchCard({ branch, customer }: BranchCardProps) { {customer && ( -
- +
+ {isCustomerArchived ? ( + + ) : ( + + )} Abrir menú - + Acciones {!isArchived && ( @@ -180,20 +152,11 @@ export default function BranchCard({ branch, customer }: BranchCardProps) { Editar )} - {/* Si el cliente es quien la archiva, desarchivarla no tendría efecto */} - {!isCustomerArchived && ( - setIsStatusDialogOpen(true)} - > - {isOwnArchived ? ( - - ) : ( - - )} - {isOwnArchived ? "Desarchivar" : "Archivar"} - - )} + setIsStatusDialogOpen(true)} + parentHint={parentHint} + /> @@ -201,9 +164,7 @@ export default function BranchCard({ branch, customer }: BranchCardProps) {
- {/* Body */} -
- {/* Address */} +
@@ -212,26 +173,14 @@ export default function BranchCard({ branch, customer }: BranchCardProps) {
- {/* Phone */} {branch.phone && (
{branch.phone}
)} - - {/* Archived badge */} - {isArchived && ( -
- - - {isCustomerArchived ? "Cliente archivado" : "Archivada"} - -
- )}
- {/* View details footer */} ; + branch: Pick; open: boolean; onOpenChange: (open: boolean) => void; } @@ -43,51 +16,15 @@ export function ChangeBranchStatusDialog({ open, onOpenChange, }: ChangeBranchStatusDialogProps) { - const action = branch.archived ? ACTIONS.unarchive : ACTIONS.archive; const mutation = useArchiveBranch(); return ( - !mutation.isPending && onOpenChange(next)} + - - - - ¿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 index b16ee4a..86c81b1 100644 --- a/apps/web/src/components/customers/branches/filters.tsx +++ b/apps/web/src/components/customers/branches/filters.tsx @@ -3,26 +3,19 @@ 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", -}; +import { FilterBadge } from "@/components/customers/shared/filter-badge"; +import { DEFAULT_BRANCH_FILTERS } from "@/components/customers/shared/filters"; +import type { + BranchFilters, + StatusFilter, +} from "@/components/customers/shared/filters"; interface Option { value: T; label: string; } -const STATUS_OPTIONS: Option[] = [ +const STATUS_OPTIONS: Option[] = [ { value: "all", label: "Todas" }, { value: "active", label: "Activas" }, { value: "archived", label: "Archivadas" }, @@ -32,31 +25,14 @@ const MAX_CUSTOMER_BADGE_LENGTH = 20; interface BranchesFiltersProps { filters: BranchFilters; + hasFilters: boolean; onFiltersChange: (filters: BranchFilters) => void; customers?: { id: string; name: string }[]; } -function FilterBadge({ - children, - onClear, -}: { - children: React.ReactNode; - onClear: () => void; -}) { - return ( - - ); -} - export function BranchesFilters({ filters, + hasFilters, onFiltersChange, customers, }: BranchesFiltersProps) { @@ -72,11 +48,6 @@ export function BranchesFilters({ ? 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 }); @@ -92,7 +63,7 @@ export function BranchesFilters({ /> | null) => + onChange={(option: Option | null) => update({ status: option?.value ?? "all" }) } options={STATUS_OPTIONS} @@ -118,7 +89,7 @@ export function BranchesFilters({
)} - {hasActiveFilters && ( + {hasFilters && (
Filtros activos: @@ -132,7 +103,11 @@ export function BranchesFilters({ {filters.status !== "all" && ( update({ status: "all" })}> - Estatus: {filters.status === "active" ? "Activas" : "Archivadas"} + Estatus:{" "} + { + STATUS_OPTIONS.find((opt) => opt.value === filters.status) + ?.label + } )} diff --git a/apps/web/src/components/customers/branches/grid.tsx b/apps/web/src/components/customers/branches/grid.tsx index f23cf09..d9d1852 100644 --- a/apps/web/src/components/customers/branches/grid.tsx +++ b/apps/web/src/components/customers/branches/grid.tsx @@ -1,123 +1,111 @@ -import { Button } from "@suni/ui/components/button"; -import { useQuery } from "@tanstack/react-query"; -import { Building2, Plus, SearchX } from "lucide-react"; +import { skipToken } from "@tanstack/react-query"; +import { Building2 } from "lucide-react"; import { useMemo, useState } from "react"; -import { orpc } from "@/utils/orpc"; +import { NewEntityButton } from "@/components/customers/new-entity-button"; +import { EntityGrid } from "@/components/customers/shared/entity-grid"; +import { + DEFAULT_BRANCH_FILTERS, + matchingName, +} from "@/components/customers/shared/filters"; +import type { BranchFilters } from "@/components/customers/shared/filters"; +import { useListBranches } from "@/hooks/use-branches"; +import { useListCustomers } from "@/hooks/use-customers"; -import { BranchFormDialog } from "./branch-form-dialog"; import BranchCard from "./card"; import { BranchesFilters } from "./filters"; -import type { BranchFilters } from "./filters"; -interface BranchesGridProps { - customerId: string; +interface BranchesListProps { + filters: BranchFilters; + onFiltersChange: (filters: BranchFilters) => void; + /** Scopes the list to one customer and hides the customer filter. */ + 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; - } +export function BranchesList({ + filters, + onFiltersChange, + customerId, +}: BranchesListProps) { + const pickedCustomerId = + filters.customerId === "all" ? undefined : filters.customerId; + + const query = useListBranches({ + status: filters.status, + customerId: customerId ?? pickedCustomerId, + }); + + // Archived customers stay listed so a filter on one keeps its label. + const { data: customers } = useListCustomers( + customerId ? skipToken : { status: "all" } + ); - return true; - }); - }, [branches, filters]); + const visibleBranches = useMemo( + () => matchingName(query.data ?? [], filters.name), + [query.data, filters.name] + ); - const hasActiveFilters = - filters.name.trim() !== "" || filters.status !== "all"; + const hasFilters = + filters.name.trim() !== "" || + filters.status !== DEFAULT_BRANCH_FILTERS.status || + (!customerId && filters.customerId !== DEFAULT_BRANCH_FILTERS.customerId); return ( <> -
-
-

Sucursales

- -
- - + - {isPending ? ( -

- Cargando sucursales… -

- ) : null} + + {visibleBranches.map((branch) => ( + + ))} + + + ); +} - {isError ? ( -

- No se pudieron cargar las sucursales. -

- ) : null} +interface BranchesGridProps { + customerId: string; + canCreate: boolean; +} - {!(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} +export function BranchesGrid({ customerId, canCreate }: BranchesGridProps) { + const [filters, setFilters] = useState(DEFAULT_BRANCH_FILTERS); - {filtered.length > 0 ? ( -
- {filtered.map((branch) => ( - - ))} -
+ return ( +
+
+

Sucursales

+ {canCreate ? ( + ) : 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 index 87b86c3..f22875e 100644 --- a/apps/web/src/components/customers/branches/util/branch-address.ts +++ b/apps/web/src/components/customers/branches/util/branch-address.ts @@ -2,6 +2,10 @@ import type { AppRouterOutputs } from "@suni/api/routers/index"; export type Branch = AppRouterOutputs["branches"]["list"][number]; +export function branchImageSrc(branch: Pick) { + return branch.frontImageUrl || "/placeholder.webp"; +} + export function formatAddress(branch: Branch) { const streetParts = [ branch.street, 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 c839de0..ae268a4 100644 --- a/apps/web/src/components/customers/change-customer-status-dialog.tsx +++ b/apps/web/src/components/customers/change-customer-status-dialog.tsx @@ -1,39 +1,12 @@ 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 { ChangeStatusDialog } from "@/components/customers/shared/change-status-dialog"; import { useArchiveCustomer } from "@/hooks/use-customers"; -type CustomerRow = AppRouterOutputs["customers"]["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; +type Row = AppRouterOutputs["customers"]["list"][number]; interface ChangeCustomerStatusDialogProps { - customer: Pick; + customer: Pick; open: boolean; onOpenChange: (open: boolean) => void; } @@ -43,51 +16,15 @@ export function ChangeCustomerStatusDialog({ open, onOpenChange, }: ChangeCustomerStatusDialogProps) { - const action = customer.archived ? ACTIONS.unarchive : ACTIONS.archive; const mutation = useArchiveCustomer(); return ( - !mutation.isPending && onOpenChange(next)} + - - - - ¿Quieres {action.label.toLowerCase()} a {customer.name}? - - - {action.description} al cliente{" "} - - {customer.name} - - . - - - - - Cancelar - - - mutation.mutate( - { - id: customer.id, - name: customer.name, - archived: !customer.archived, - }, - { - onSuccess: () => onOpenChange(false), - } - ) - } - variant={action.confirmVariant} - > - {mutation.isPending ? "Guardando..." : action.label} - - - - + /> ); } 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 index c0184e7..cc102df 100644 --- a/apps/web/src/components/customers/contacts/change-contact-status-dialog.tsx +++ b/apps/web/src/components/customers/contacts/change-contact-status-dialog.tsx @@ -1,36 +1,12 @@ import type { AppRouterOutputs } from "@suni/api/routers/index"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@suni/ui/components/alert-dialog"; +import { ChangeStatusDialog } from "@/components/customers/shared/change-status-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; +type Row = AppRouterOutputs["contacts"]["list"][number]; interface ChangeContactStatusDialogProps { - contact: Pick; + contact: Pick; open: boolean; onOpenChange: (open: boolean) => void; } @@ -40,51 +16,15 @@ export function ChangeContactStatusDialog({ open, onOpenChange, }: ChangeContactStatusDialogProps) { - const action = contact.archived ? ACTIONS.unarchive : ACTIONS.archive; const mutation = useArchiveContact(); return ( - !mutation.isPending && onOpenChange(next)} + - - - - ¿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 index 270380e..8f2162a 100644 --- a/apps/web/src/components/customers/contacts/contact-card.tsx +++ b/apps/web/src/components/customers/contacts/contact-card.tsx @@ -13,7 +13,6 @@ import { cn } from "@suni/ui/lib/utils"; import { Link } from "@tanstack/react-router"; import { Archive, - ArchiveRestore, Building2, Mail, MapPin, @@ -23,6 +22,8 @@ import { } from "lucide-react"; import { useState } from "react"; +import { ArchiveMenuItem } from "../shared/archive-menu-item"; +import { archiveState } from "../shared/archive-state"; import { ChangeContactStatusDialog } from "./change-contact-status-dialog"; import { ContactFormDialog } from "./contact-form-dialog"; @@ -30,32 +31,14 @@ type Contact = AppRouterOutputs["contacts"]["list"][number]; interface ContactCardProps { contact: Contact; - /** Si viene definido, muestra el cliente (útil en listados de varios clientes). */ + /** Shown in lists that span several customers. */ 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; + parentHint?: string; onEdit: () => void; onToggleStatus: () => void; } @@ -63,7 +46,7 @@ interface ContactMenuProps { function ContactMenu({ isArchived, isOwnArchived, - isParentArchived, + parentHint, onEdit, onToggleStatus, }: ContactMenuProps) { @@ -74,7 +57,10 @@ function ContactMenu({ Abrir menú - + Acciones {!isArchived && ( @@ -84,20 +70,11 @@ function ContactMenu({ )} - {/* Si un padre lo archiva, desarchivarlo no tendría efecto */} - {!isParentArchived && ( - - {isOwnArchived ? ( - - ) : ( - - )} - {isOwnArchived ? "Desarchivar" : "Archivar"} - - )} + @@ -108,16 +85,32 @@ function ContactMenu({ interface ContactParentsProps { contact: Contact; customer?: { id: string; name: string }; + isCustomerArchived: boolean; + isBranchArchived: boolean; +} + +const PARENT_LINK = "line-clamp-1 text-sm font-medium hover:underline"; + +function nameColor(isArchived: boolean) { + return isArchived ? "text-muted-foreground" : "text-success"; } -function ContactParents({ contact, customer }: ContactParentsProps) { +function ContactParents({ + contact, + customer, + isCustomerArchived, + isBranchArchived, +}: ContactParentsProps) { + const CustomerIcon = isCustomerArchived ? Archive : Building2; + const BranchIcon = isBranchArchived ? Archive : MapPin; + return ( <> {customer && ( -
- +
+ - +
+ - {/* Header */}

{contact.name} @@ -209,28 +203,25 @@ export default function ContactCard({

)} - +

- {!readOnly && ( - setIsUpdateFormOpen(true)} - onToggleStatus={() => setIsStatusDialogOpen(true)} - /> - )} + setIsUpdateFormOpen(true)} + onToggleStatus={() => setIsStatusDialogOpen(true)} + parentHint={parentHint} + />
- {/* Body */} -
+ - {/* Archived badge */} {isArchived && ( -
+
- {label} + Archivado
)}
- {!readOnly && ( - <> - - - - )} + + ); } diff --git a/apps/web/src/components/customers/contacts/contact-filters.tsx b/apps/web/src/components/customers/contacts/contact-filters.tsx index 1b36983..f4b7ae4 100644 --- a/apps/web/src/components/customers/contacts/contact-filters.tsx +++ b/apps/web/src/components/customers/contacts/contact-filters.tsx @@ -3,24 +3,19 @@ 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", -}; +import { FilterBadge } from "@/components/customers/shared/filter-badge"; +import { DEFAULT_CONTACT_FILTERS } from "@/components/customers/shared/filters"; +import type { + ContactFilters, + StatusFilter, +} from "@/components/customers/shared/filters"; interface Option { value: T; label: string; } -const STATUS_OPTIONS: Option[] = [ +const STATUS_OPTIONS: Option[] = [ { value: "all", label: "Todos" }, { value: "active", label: "Activos" }, { value: "archived", label: "Archivados" }, @@ -28,35 +23,17 @@ const STATUS_OPTIONS: Option[] = [ interface ContactsFiltersProps { filters: ContactFilters; + hasFilters: boolean; onFiltersChange: (filters: ContactFilters) => void; } -function FilterBadge({ - children, - onClear, -}: { - children: React.ReactNode; - onClear: () => void; -}) { - return ( - - ); -} - export function ContactsFilters({ filters, + hasFilters, 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 @@ -77,7 +54,7 @@ export function ContactsFilters({ /> | null) => + onChange={(option: Option | null) => update({ status: option?.value ?? "all" }) } options={STATUS_OPTIONS} @@ -86,7 +63,7 @@ export function ContactsFilters({ />
- {hasActiveFilters && ( + {hasFilters && (
Filtros activos: diff --git a/apps/web/src/components/customers/contacts/contact-form-dialog.tsx b/apps/web/src/components/customers/contacts/contact-form-dialog.tsx index a89e1fe..64fe9db 100644 --- a/apps/web/src/components/customers/contacts/contact-form-dialog.tsx +++ b/apps/web/src/components/customers/contacts/contact-form-dialog.tsx @@ -5,25 +5,22 @@ import { DialogHeader, DialogTitle, } from "@suni/ui/components/dialog"; -import type { ComponentProps } from "react"; import { ContactForm } from "./contact-form"; +import type { ContactFormTarget } from "./contact-form"; -interface ContactFormDialogProps extends Pick< - ComponentProps, - "contact" | "customerId" | "branchId" -> { +type ContactFormDialogProps = ContactFormTarget & { open: boolean; onOpenChange: (open: boolean) => void; -} +}; export function ContactFormDialog({ - contact, - customerId, - branchId, open, onOpenChange, + ...target }: ContactFormDialogProps) { + const { contact } = target; + return ( @@ -38,9 +35,7 @@ export function ContactFormDialog({ 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 index 728e419..398ea9f 100644 --- a/apps/web/src/components/customers/contacts/contact-form.tsx +++ b/apps/web/src/components/customers/contacts/contact-form.tsx @@ -1,8 +1,5 @@ import type { AppRouterOutputs } from "@suni/api/routers/index"; -import { - contactFormSchema, - contactInputSchema, -} from "@suni/db/validation/contacts"; +import { contactSchema } from "@suni/db/validation/contacts"; import { Button } from "@suni/ui/components/button"; import { revalidateLogic } from "@tanstack/react-form"; import { Loader2 } from "lucide-react"; @@ -13,15 +10,16 @@ import { useCreateContact, useUpdateContact } from "@/hooks/use-contacts"; type Contact = AppRouterOutputs["contacts"]["list"][number]; -type FormValues = z.input; +type FormValues = z.input; -interface ContactFormProps { - customerId?: string | null; - branchId?: string | null; - contact?: Contact; +export type ContactFormTarget = + | { contact: Contact } + | { contact?: never; customerId: string; branchId: string }; + +type ContactFormProps = ContactFormTarget & { onSuccess?: () => void; onCancel: () => void; -} +}; const PHONE_LENGTH = 10; @@ -44,18 +42,17 @@ function toFormValues(contact?: Contact): FormValues { name: contact.name, email: contact.email, phone: contact.phone, - phoneExtension: contact.phoneExtension ?? "", - position: contact.position ?? "", + phoneExtension: contact.phoneExtension, + position: contact.position, }; } export function ContactForm({ - customerId, - branchId, - contact, onSuccess, onCancel, + ...target }: ContactFormProps) { + const { contact } = target; const createContact = useCreateContact(); const updateContact = useUpdateContact(); @@ -64,18 +61,20 @@ export function ContactForm({ const form = useAppForm({ defaultValues: toFormValues(contact), validationLogic: revalidateLogic(), - validators: { onDynamic: contactFormSchema }, + validators: { onDynamic: contactSchema }, onSubmit: ({ value }) => { - const parsed = contactInputSchema.parse(value); - - if (contact) { + if (target.contact) { updateContact.mutate( - { id: contact.id, ...parsed }, + { id: target.contact.id, ...value }, { onSuccess: () => onSuccess?.() } ); - } else if (customerId && branchId) { + } else { createContact.mutate( - { customerId, branchId, ...parsed }, + { + customerId: target.customerId, + branchId: target.branchId, + ...value, + }, { onSuccess: () => onSuccess?.() } ); } diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx index b53a3e0..66f60fd 100644 --- a/apps/web/src/components/customers/contacts/contact-grid.tsx +++ b/apps/web/src/components/customers/contacts/contact-grid.tsx @@ -1,118 +1,112 @@ -import { useQuery } from "@tanstack/react-query"; -import { SearchX, Users } from "lucide-react"; +import { Users } from "lucide-react"; import { useMemo, useState } from "react"; -import { NewEntityButton } from "@/components/customers/select-entity-button"; -import { orpc } from "@/utils/orpc"; +import { NewEntityButton } from "@/components/customers/new-entity-button"; +import { EntityGrid } from "@/components/customers/shared/entity-grid"; +import { + DEFAULT_CONTACT_FILTERS, + matchingName, +} from "@/components/customers/shared/filters"; +import type { ContactFilters } from "@/components/customers/shared/filters"; +import { useListContacts } from "@/hooks/use-contacts"; import ContactCard from "./contact-card"; import { ContactsFilters } from "./contact-filters"; -import type { ContactFilters } from "./contact-filters"; -interface ContactsGridProps { - customerId: string; +interface ContactsListProps { + filters: ContactFilters; + onFiltersChange: (filters: ContactFilters) => void; + /** Scopes the list to one customer and hides the customer on each card. */ + 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 } }) +export function ContactsList({ + filters, + onFiltersChange, + customerId, + branchId, +}: ContactsListProps) { + const query = useListContacts({ + status: filters.status, + customerId, + branchId, + }); + + const visibleContacts = useMemo( + () => matchingName(query.data ?? [], filters.name), + [query.data, filters.name] ); - const filtered = useMemo(() => { - const term = filters.name.trim().toLowerCase(); + const hasFilters = + filters.name.trim() !== "" || + filters.status !== DEFAULT_CONTACT_FILTERS.status; - 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 ( + <> + + + + {visibleContacts.map((contact) => ( + + ))} + + + ); +} - return true; - }); - }, [contacts, filters]); +interface ContactsGridProps { + customerId: string; + branchId?: string; + canCreate: boolean; +} - const hasActiveFilters = - filters.name.trim() !== "" || filters.status !== "all"; +export function ContactsGrid({ + customerId, + branchId, + canCreate, +}: ContactsGridProps) { + const [filters, setFilters] = useState(DEFAULT_CONTACT_FILTERS); return (

Contactos

- + {canCreate ? ( + + ) : null}
- - - {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/customer-form.tsx b/apps/web/src/components/customers/customer-form.tsx index 931e8e6..a1121b8 100644 --- a/apps/web/src/components/customers/customer-form.tsx +++ b/apps/web/src/components/customers/customer-form.tsx @@ -3,11 +3,9 @@ import { ACQUISITION_CHANNELS, CUSTOMER_TYPES, } from "@suni/db/schema/customer-enums"; -import { customerFormSchema } from "@suni/db/validation/customers"; +import { customerSchema } from "@suni/db/validation/customers"; 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 { Link, useNavigate } from "@tanstack/react-router"; import { Loader2 } from "lucide-react"; import type { z } from "zod"; @@ -15,10 +13,9 @@ import type { z } from "zod"; import { useAppForm } from "@/components/form/use-app-form"; import { useCreateCustomer, useUpdateCustomer } from "@/hooks/use-customers"; import { useIsAdmin } from "@/hooks/use-is-admin"; -import { postalCodeQueryOptions, usePostalCode } from "@/hooks/use-postal-code"; -import type { Settlement } from "@/hooks/use-postal-code"; +import { POSTAL_CODE_LENGTH, useAddressLookup } from "@/hooks/use-postal-code"; -type FormValues = Omit, "acquisition"> & { +type FormValues = Omit, "acquisition"> & { acquisition: (typeof ACQUISITION_CHANNELS)[number] | ""; }; @@ -26,8 +23,6 @@ interface CustomerFormProps { customer?: AppRouterOutputs["customers"]["get"]; } -const POSTAL_CODE_LENGTH = 5; - const RFC_MAX_LENGTH = 13; const PHONE_LENGTH = 10; @@ -59,7 +54,7 @@ function toFormValues(customer?: CustomerFormProps["customer"]): FormValues { name: customer.name, rfc: customer.rfc, phone: customer.phone, - phoneExtension: customer.phoneExtension ?? "", + phoneExtension: customer.phoneExtension, acquisition: customer.acquisition, type: customer.type, postalCode: customer.postalCode, @@ -68,29 +63,10 @@ function toFormValues(customer?: CustomerFormProps["customer"]): FormValues { state: customer.state, street: customer.street, extNumber: customer.extNumber, - intNumber: customer.intNumber ?? "", + intNumber: customer.intNumber, }; } -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; -} - const ACQUISITION_OPTIONS = ACQUISITION_CHANNELS.map((value) => ({ value, label: value, @@ -100,7 +76,6 @@ const TYPE_OPTIONS = CUSTOMER_TYPES.map((value) => ({ value, label: value })); export function CustomerForm({ customer }: CustomerFormProps) { const navigate = useNavigate(); - const queryClient = useQueryClient(); const isAdmin = useIsAdmin(); const createCustomer = useCreateCustomer(); const updateCustomer = useUpdateCustomer(); @@ -114,9 +89,9 @@ export function CustomerForm({ customer }: CustomerFormProps) { defaultValues: toFormValues(customer), // Valida al enviar y, después del primer envío, en cada cambio. validationLogic: revalidateLogic(), - validators: { onDynamic: customerFormSchema }, + validators: { onDynamic: customerSchema }, onSubmit: ({ value }) => { - const parsed = customerFormSchema.parse(value); + const parsed = customerSchema.parse(value); if (customer) { updateCustomer.mutate( @@ -133,58 +108,7 @@ export function CustomerForm({ customer }: CustomerFormProps) { }); const zip = useSelector(form.store, (state) => state.values.postalCode); - const postalCode = usePostalCode(zip); - const settlements = postalCode.data ?? []; - - // SEPOMEX owns municipio and estado; only a miss or an error unlocks them so the address can be typed by hand. - const regionLocked = !( - postalCode.isError || - (postalCode.isSuccess && settlements.length === 0) - ); - - // Colonia only waits for the lookup; it stays open afterwards so a colonia SEPOMEX lacks can be typed. - 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 surfaces the error under the field. - return; - } - - // The user kept typing while the request was in flight. - if (form.getFieldValue("postalCode") !== value) { - return; - } - - const [first] = found; - - if (!first) { - return; - } - - form.setFieldValue("city", first.d_mnpio); - form.setFieldValue("state", first.d_estado); - - if (found.length === 1) { - form.setFieldValue("suburb", first.d_asenta); - } - }; + const address = useAddressLookup(zip); return (
fillAddress(value) }} + listeners={{ + onChange: ({ value }) => + address.fill(value, { + getPostalCode: () => form.getFieldValue("postalCode"), + set: (field, fieldValue) => + form.setFieldValue(field, fieldValue), + }), + }} name="postalCode" > {(field) => ( )} @@ -296,8 +227,8 @@ export function CustomerForm({ customer }: CustomerFormProps) { )} @@ -307,8 +238,8 @@ export function CustomerForm({ customer }: CustomerFormProps) { )} diff --git a/apps/web/src/components/customers/select-entity-button.tsx b/apps/web/src/components/customers/new-entity-button.tsx similarity index 96% rename from apps/web/src/components/customers/select-entity-button.tsx rename to apps/web/src/components/customers/new-entity-button.tsx index 6a06152..02225c1 100644 --- a/apps/web/src/components/customers/select-entity-button.tsx +++ b/apps/web/src/components/customers/new-entity-button.tsx @@ -8,11 +8,13 @@ import { DialogTitle, } from "@suni/ui/components/dialog"; import { ReactSelect } from "@suni/ui/components/react-select"; +import { skipToken } from "@tanstack/react-query"; 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 { byName } from "@/components/customers/shared/filters"; import { useListBranches } from "@/hooks/use-branches"; import { useListCustomers } from "@/hooks/use-customers"; @@ -29,7 +31,7 @@ function CustomerPicker({ value, onValueChange }: PickerProps) { const options = useMemo( () => customers - .toSorted((a, b) => a.name.localeCompare(b.name, "es")) + .toSorted(byName) .map((customer) => ({ value: customer.id, label: customer.name })), [customers] ); @@ -57,15 +59,13 @@ function BranchPicker({ onValueChange, }: PickerProps & { customerId: string | null }) { const { data: branches = [], isPending } = useListBranches( - customerId ? { customerId } : {}, - !!customerId + customerId ? { customerId } : skipToken ); const options = useMemo( () => branches - .filter((branch) => !branch.archived) - .toSorted((a, b) => a.name.localeCompare(b.name, "es")) + .toSorted(byName) .map((branch) => ({ value: branch.id, label: branch.name })), [branches] ); diff --git a/apps/web/src/components/customers/shared/archive-menu-item.tsx b/apps/web/src/components/customers/shared/archive-menu-item.tsx new file mode 100644 index 0000000..19773b8 --- /dev/null +++ b/apps/web/src/components/customers/shared/archive-menu-item.tsx @@ -0,0 +1,38 @@ +import { DropdownMenuItem } from "@suni/ui/components/dropdown-menu"; +import { Archive, ArchiveRestore } from "lucide-react"; + +interface ArchiveMenuItemProps { + isOwnArchived: boolean; + /** Set when an archived parent blocks the change. */ + parentHint?: string; + onClick: () => void; +} + +export function ArchiveMenuItem({ + isOwnArchived, + parentHint, + onClick, +}: ArchiveMenuItemProps) { + if (parentHint) { + return ( + + + + + Desarchivar + + {parentHint} + + + ); + } + + const Icon = isOwnArchived ? ArchiveRestore : Archive; + + return ( + + + {isOwnArchived ? "Desarchivar" : "Archivar"} + + ); +} diff --git a/apps/web/src/components/customers/shared/archive-state.ts b/apps/web/src/components/customers/shared/archive-state.ts new file mode 100644 index 0000000..e0cc6aa --- /dev/null +++ b/apps/web/src/components/customers/shared/archive-state.ts @@ -0,0 +1,28 @@ +interface Archivable { + archived: unknown; + customer?: { archived: unknown } | null; + branch?: { archived: unknown } | null; +} + +// Mirrors the API rule: an archived customer or branch archives everything under it. +export function archiveState(entity: Archivable) { + const isOwnArchived = !!entity.archived; + const isCustomerArchived = !!entity.customer?.archived; + const isBranchArchived = isCustomerArchived || !!entity.branch?.archived; + + let parentHint: string | undefined; + + if (isCustomerArchived) { + parentHint = "Desarchiva primero el cliente"; + } else if (isBranchArchived) { + parentHint = "Desarchiva primero la sucursal"; + } + + return { + isOwnArchived, + isCustomerArchived, + isBranchArchived, + isArchived: isOwnArchived || isBranchArchived, + parentHint, + }; +} diff --git a/apps/web/src/components/customers/shared/change-status-dialog.tsx b/apps/web/src/components/customers/shared/change-status-dialog.tsx new file mode 100644 index 0000000..356401a --- /dev/null +++ b/apps/web/src/components/customers/shared/change-status-dialog.tsx @@ -0,0 +1,108 @@ +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@suni/ui/components/alert-dialog"; +import { useState } from "react"; + +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 ArchiveMutation { + isPending: boolean; + mutate: ( + variables: { id: string; name: string; archived: boolean }, + options: { onSuccess: () => void } + ) => void; +} + +interface ChangeStatusDialogProps { + entity: { id: string; name: string; archived: unknown }; + /** Article and noun before the name, e.g. "la sucursal". */ + noun: string; + mutation: ArchiveMutation; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function ChangeStatusDialog({ + entity, + noun, + mutation, + open, + onOpenChange, +}: ChangeStatusDialogProps) { + // Freeze the status seen on open: the refetch after saving lands before the close animation ends. + const [archivedOnOpen, setArchivedOnOpen] = useState(!!entity.archived); + const [wasOpen, setWasOpen] = useState(open); + + if (open !== wasOpen) { + setWasOpen(open); + + if (open) { + setArchivedOnOpen(!!entity.archived); + } + } + + const action = archivedOnOpen ? ACTIONS.unarchive : ACTIONS.archive; + + return ( + !mutation.isPending && onOpenChange(next)} + open={open} + > + + + + ¿Quieres {action.label.toLowerCase()} {noun} {entity.name}? + + + {action.description} {noun}{" "} + + {entity.name} + + . + + + + + Cancelar + + + mutation.mutate( + { + id: entity.id, + name: entity.name, + archived: !archivedOnOpen, + }, + { onSuccess: () => onOpenChange(false) } + ) + } + variant={action.confirmVariant} + > + {mutation.isPending ? "Guardando..." : action.label} + + + + + ); +} diff --git a/apps/web/src/components/customers/shared/entity-grid.tsx b/apps/web/src/components/customers/shared/entity-grid.tsx new file mode 100644 index 0000000..756e931 --- /dev/null +++ b/apps/web/src/components/customers/shared/entity-grid.tsx @@ -0,0 +1,77 @@ +import { cn } from "@suni/ui/lib/utils"; +import { SearchX } from "lucide-react"; +import type { LucideIcon } from "lucide-react"; +import type { ReactNode } from "react"; + +interface EntityGridProps { + query: { isPending: boolean; isError: boolean; isPlaceholderData: boolean }; + isEmpty: boolean; + hasFilters: boolean; + icon: LucideIcon; + copy: { + loading: string; + error: string; + notFound: string; + empty: string; + emptyHint: string; + }; + children: ReactNode; +} + +export function EntityGrid({ + query, + isEmpty, + hasFilters, + icon, + copy, + children, +}: EntityGridProps) { + if (query.isPending) { + return ( +

+ {copy.loading} +

+ ); + } + + if (query.isError) { + return ( +

{copy.error}

+ ); + } + + if (isEmpty) { + const Icon = hasFilters ? SearchX : icon; + + return ( +
+ +

+ {hasFilters ? copy.notFound : copy.empty} +

+

+ {hasFilters + ? "Intenta con otros filtros de búsqueda" + : copy.emptyHint} +

+
+ ); + } + + return ( +
+ {children} +
+ ); +} diff --git a/apps/web/src/components/customers/shared/filter-badge.tsx b/apps/web/src/components/customers/shared/filter-badge.tsx new file mode 100644 index 0000000..f06b74e --- /dev/null +++ b/apps/web/src/components/customers/shared/filter-badge.tsx @@ -0,0 +1,20 @@ +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/filters.ts b/apps/web/src/components/customers/shared/filters.ts new file mode 100644 index 0000000..8ee4b3e --- /dev/null +++ b/apps/web/src/components/customers/shared/filters.ts @@ -0,0 +1,45 @@ +import type { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; + +import { stripAccents } from "@/lib/string-utils"; + +export type StatusFilter = (typeof CUSTOMER_STATUSES)[number]; + +export interface BranchFilters { + name: string; + status: StatusFilter; + customerId: string; +} + +export const DEFAULT_BRANCH_FILTERS: BranchFilters = { + name: "", + status: "all", + customerId: "all", +}; + +export interface ContactFilters { + name: string; + status: StatusFilter; +} + +export const DEFAULT_CONTACT_FILTERS: ContactFilters = { + name: "", + status: "all", +}; + +export function byName(a: { name: string }, b: { name: string }) { + return a.name.localeCompare(b.name, "es"); +} + +/** Accent- and case-insensitive name search, sorted by name. */ +export function matchingName( + rows: R, + name: string +): R[number][] { + const term = stripAccents(name.trim()).toLowerCase(); + + return rows + .filter( + (row) => !term || stripAccents(row.name).toLowerCase().includes(term) + ) + .toSorted(byName); +} diff --git a/apps/web/src/components/users/user-form.tsx b/apps/web/src/components/users/user-form.tsx index a6ea37e..ed547d3 100644 --- a/apps/web/src/components/users/user-form.tsx +++ b/apps/web/src/components/users/user-form.tsx @@ -1,9 +1,10 @@ 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 { z } from "zod"; +import type { z } from "zod"; import { useAppForm } from "@/components/form/use-app-form"; import { useCreateUser, useUpdateUser } from "@/hooks/use-users"; @@ -13,12 +14,6 @@ const ROLE_OPTIONS = [ { value: "user", label: "Usuario" }, ] as const; -const userSchema = z.object({ - name: z.string().min(1, { message: "El nombre es requerido" }), - email: z.email({ message: "El correo no es válido" }), - role: z.enum(["admin", "user"]), -}); - interface UserFormProps { user?: AppRouterOutputs["users"]["get"]; } @@ -32,7 +27,7 @@ export function UserForm({ user }: UserFormProps) { const goToUsers = () => navigate({ to: "/users" }); - const defaultValues: z.infer = { + const defaultValues: z.input = { name: user?.name ?? "", email: user?.email ?? "", role: user?.role === "admin" ? "admin" : "user", diff --git a/apps/web/src/hooks/use-branches.ts b/apps/web/src/hooks/use-branches.ts index a4ee52e..5ce7d90 100644 --- a/apps/web/src/hooks/use-branches.ts +++ b/apps/web/src/hooks/use-branches.ts @@ -8,6 +8,7 @@ import { useQuery, useQueryClient, } from "@tanstack/react-query"; +import type { skipToken } from "@tanstack/react-query"; import { toast } from "sonner"; import { client, orpc } from "@/utils/orpc"; @@ -15,14 +16,14 @@ import { client, orpc } from "@/utils/orpc"; type BranchRow = AppRouterOutputs["branches"]["list"][number]; export function useListBranches( - params: AppRouterInputs["branches"]["list"], - enabled = true + params: AppRouterInputs["branches"]["list"] | typeof skipToken ) { - return useQuery({ - ...orpc.branches.list.queryOptions({ input: params }), - placeholderData: keepPreviousData, - enabled, - }); + return useQuery( + orpc.branches.list.queryOptions({ + input: params, + placeholderData: keepPreviousData, + }) + ); } export function useCreateBranch() { @@ -46,8 +47,10 @@ export function useUpdateBranch() { orpc.branches.update.mutationOptions({ onSuccess: async () => { toast.success("Sucursal actualizada"); - await queryClient.invalidateQueries({ queryKey: orpc.branches.key() }); - await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }); + await Promise.all([ + queryClient.invalidateQueries({ queryKey: orpc.branches.key() }), + queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }), + ]); }, onError: (error) => toast.error(error.message), }) @@ -64,7 +67,11 @@ export function useArchiveBranch() { }: Pick & { archived: boolean }) => client.branches.setArchived({ id, archived }), onSuccess: async (_data, { archived, name }) => { - await queryClient.invalidateQueries({ queryKey: orpc.branches.key() }); + // Contacts embed `branch.archived` to show the archived-branch label. + await Promise.all([ + queryClient.invalidateQueries({ queryKey: orpc.branches.key() }), + queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }), + ]); toast.success(archived ? "Sucursal archivada" : "Sucursal desarchivada", { description: `Se ${archived ? "archivó" : "desarchivó"} ${name} con éxito.`, }); diff --git a/apps/web/src/hooks/use-contacts.ts b/apps/web/src/hooks/use-contacts.ts index 6e26b93..0ffdb4c 100644 --- a/apps/web/src/hooks/use-contacts.ts +++ b/apps/web/src/hooks/use-contacts.ts @@ -15,10 +15,12 @@ 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, - }); + return useQuery( + orpc.contacts.list.queryOptions({ + input: params, + placeholderData: keepPreviousData, + }) + ); } export function useCreateContact() { diff --git a/apps/web/src/hooks/use-customers.ts b/apps/web/src/hooks/use-customers.ts index 3b5b7d0..ccfb0a0 100644 --- a/apps/web/src/hooks/use-customers.ts +++ b/apps/web/src/hooks/use-customers.ts @@ -8,17 +8,22 @@ import { useQuery, useQueryClient, } from "@tanstack/react-query"; +import type { skipToken } from "@tanstack/react-query"; import { toast } from "sonner"; import { client, orpc } from "@/utils/orpc"; type CustomerRow = AppRouterOutputs["customers"]["list"][number]; -export function useListCustomers(params: AppRouterInputs["customers"]["list"]) { - return useQuery({ - ...orpc.customers.list.queryOptions({ input: params }), - placeholderData: keepPreviousData, - }); +export function useListCustomers( + params: AppRouterInputs["customers"]["list"] | typeof skipToken +) { + return useQuery( + orpc.customers.list.queryOptions({ + input: params, + placeholderData: keepPreviousData, + }) + ); } export function useCreateCustomer() { @@ -42,7 +47,12 @@ export function useUpdateCustomer() { orpc.customers.update.mutationOptions({ onSuccess: async () => { toast.success("Cliente actualizado"); - await queryClient.invalidateQueries({ queryKey: orpc.customers.key() }); + // Branches and contacts embed `customer.name`. + await Promise.all([ + queryClient.invalidateQueries({ queryKey: orpc.customers.key() }), + queryClient.invalidateQueries({ queryKey: orpc.branches.key() }), + queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }), + ]); }, onError: (error) => toast.error(error.message), }) @@ -61,7 +71,12 @@ export function useArchiveCustomer() { }: Pick & { archived: boolean }) => client.customers.setArchived({ id, archived }), onSuccess: async (_data, { archived, name }) => { - await queryClient.invalidateQueries({ queryKey: orpc.customers.key() }); + // Branches and contacts embed `customer.archived` to show the archived-customer label. + await Promise.all([ + queryClient.invalidateQueries({ queryKey: orpc.customers.key() }), + queryClient.invalidateQueries({ queryKey: orpc.branches.key() }), + queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }), + ]); toast.success(archived ? "Cliente archivado" : "Cliente desarchivado", { description: `Se ${archived ? "archivó" : "desarchivó"} a ${name} con éxito.`, }); diff --git a/apps/web/src/hooks/use-postal-code.ts b/apps/web/src/hooks/use-postal-code.ts index c1df1a1..63c09c5 100644 --- a/apps/web/src/hooks/use-postal-code.ts +++ b/apps/web/src/hooks/use-postal-code.ts @@ -1,4 +1,4 @@ -import { queryOptions, useQuery } from "@tanstack/react-query"; +import { queryOptions, useQuery, useQueryClient } from "@tanstack/react-query"; import { z } from "zod"; import { ENV } from "@/env"; @@ -15,9 +15,9 @@ const responseSchema = z.object({ zip_codes: z.array(settlementSchema), }); -export type Settlement = z.infer; +type Settlement = z.infer; -export function postalCodeQueryOptions(zip: string) { +function postalCodeQueryOptions(zip: string) { return queryOptions({ queryKey: ["postal-code", zip], enabled: /^\d{5}$/u.test(zip), @@ -43,6 +43,84 @@ export function postalCodeQueryOptions(zip: string) { }); } -export function usePostalCode(zip: string) { +function usePostalCode(zip: string) { return useQuery(postalCodeQueryOptions(zip)); } + +export const POSTAL_CODE_LENGTH = 5; + +type AddressField = "suburb" | "city" | "state"; + +interface AddressForm { + /** Current postal code, read after the lookup resolves. */ + getPostalCode: () => string; + set: (field: AddressField, value: string) => void; +} + +/** Fills colonia, municipio and estado from a SEPOMEX postal code lookup. */ +export function useAddressLookup(zip: string) { + const queryClient = useQueryClient(); + const query = usePostalCode(zip); + const settlements = query.data ?? []; + const notFound = query.isSuccess && settlements.length === 0; + + let hint: string | null = null; + + if (query.isFetching) { + hint = "Buscando código postal…"; + } else if (query.isError) { + hint = + "No se pudo consultar el código postal. Captura la dirección a mano."; + } else if (notFound) { + hint = "No encontramos ese código postal. Captura la dirección a mano."; + } + + async function fill(value: string, form: AddressForm) { + form.set("suburb", ""); + form.set("city", ""); + form.set("state", ""); + + if (value.length !== POSTAL_CODE_LENGTH) { + return; + } + + let found: Settlement[]; + + try { + found = await queryClient.query(postalCodeQueryOptions(value)); + } catch { + // `hint` shows the error under the field. + return; + } + + // The user kept typing while the request was in flight. + if (form.getPostalCode() !== value) { + return; + } + + const [first] = found; + + if (!first) { + return; + } + + form.set("city", first.d_mnpio); + form.set("state", first.d_estado); + + if (found.length === 1) { + form.set("suburb", first.d_asenta); + } + } + + return { + hint, + // SEPOMEX owns municipio and estado; only a miss or an error unlocks them so the address can be typed by hand. + regionLocked: !(query.isError || notFound), + // Colonia only waits for the lookup; it stays open afterwards so a colonia SEPOMEX lacks can be typed. + suburbLocked: !(query.isSuccess || query.isError), + suburbOptions: [...new Set(settlements.map((s) => s.d_asenta))].map( + (value) => ({ value, label: value }) + ), + fill, + }; +} diff --git a/apps/web/src/routes/_auth/branches/index.tsx b/apps/web/src/routes/_auth/branches/index.tsx index c93f1d9..3a234be 100644 --- a/apps/web/src/routes/_auth/branches/index.tsx +++ b/apps/web/src/routes/_auth/branches/index.tsx @@ -1,30 +1,22 @@ -import { cn } from "@suni/ui/lib/utils"; +import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { createFileRoute, stripSearchParams } from "@tanstack/react-router"; -import { Building2, SearchX } from "lucide-react"; -import { useMemo } from "react"; +import { Building2 } from "lucide-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"; +import { BranchesList } from "@/components/customers/branches/grid"; +import { NewEntityButton } from "@/components/customers/new-entity-button"; /* 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"), + status: z.enum(CUSTOMER_STATUSES).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)] }, + search: { middlewares: [stripSearchParams(searchSchema.parse({}))] }, component: RouteComponent, }); @@ -32,39 +24,6 @@ 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 (
@@ -84,63 +43,10 @@ function RouteComponent() {
- navigate({ search: next, replace: true })} /> - - {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 index 691eaaa..c1f643f 100644 --- a/apps/web/src/routes/_auth/contacts/index.tsx +++ b/apps/web/src/routes/_auth/contacts/index.tsx @@ -1,28 +1,21 @@ -import { cn } from "@suni/ui/lib/utils"; +import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { createFileRoute, stripSearchParams } from "@tanstack/react-router"; -import { SearchX, Users } from "lucide-react"; -import { useMemo } from "react"; +import { Users } from "lucide-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"; +import { ContactsList } from "@/components/customers/contacts/contact-grid"; +import { NewEntityButton } from "@/components/customers/new-entity-button"; /* 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"), + status: z.enum(CUSTOMER_STATUSES).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)] }, + search: { middlewares: [stripSearchParams(searchSchema.parse({}))] }, component: RouteComponent, }); @@ -30,30 +23,6 @@ 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 (
@@ -73,62 +42,10 @@ function RouteComponent() {
- navigate({ search: next, replace: true })} /> - - {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 index 8998c0c..760cda6 100644 --- a/apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx +++ b/apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx @@ -5,7 +5,7 @@ import { TabsTrigger, } from "@suni/ui/components/tabs"; import { useSuspenseQuery } from "@tanstack/react-query"; -import { createFileRoute } from "@tanstack/react-router"; +import { createFileRoute, redirect } from "@tanstack/react-router"; import { FileText, FolderOpen, HardHat, Info, Users } from "lucide-react"; import type { ReactNode } from "react"; import { useState } from "react"; @@ -13,21 +13,31 @@ 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 { branchImageSrc } from "@/components/customers/branches/util/branch-address"; import { ContactsGrid } from "@/components/customers/contacts/contact-grid"; +import { archiveState } from "@/components/customers/shared/archive-state"; 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 } }) - ), - ]), + loader: async ({ + context: { queryClient }, + params: { customerId, branchId }, + }) => { + const branch = await queryClient.query( + orpc.branches.get.queryOptions({ input: { id: branchId } }) + ); + + // A hand-edited URL can pair a branch with another customer. + if (branch.customerId !== customerId) { + throw redirect({ + to: "/customers/$customerId/branches/$branchId", + params: { customerId: branch.customerId, branchId }, + replace: true, + }); + } + }, component: RouteComponent, errorComponent: () => (

@@ -49,33 +59,34 @@ const TABS = [ ] as const; function RouteComponent() { - const { customerId, branchId } = Route.useParams(); + const { branchId } = Route.useParams(); const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false); - // Lee el caché de queries (no el loader) para que ediciones y archivados se reflejen. + // Reads the query cache, not loader data, so saves and archives show up even after a preload. 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 { isArchived } = archiveState(branch); const content: Record<(typeof TABS)[number]["value"], ReactNode> = { info: ( {}} // eslint-disable-next-line no-empty-function -- pendiente de implementar onImageUpload={() => {}} /> ), - contacts: , + contacts: ( + + ), quotations: null, files: null, "technical-requirements": null, @@ -83,11 +94,7 @@ function RouteComponent() { return (

- setIsUpdateFormOpen(true)} - /> + setIsUpdateFormOpen(true)} /> @@ -108,7 +115,7 @@ function RouteComponent() { diff --git a/apps/web/src/routes/_auth/customers/$customerId/index.tsx b/apps/web/src/routes/_auth/customers/$customerId/index.tsx index 9958bc4..421968b 100644 --- a/apps/web/src/routes/_auth/customers/$customerId/index.tsx +++ b/apps/web/src/routes/_auth/customers/$customerId/index.tsx @@ -1,4 +1,5 @@ -import { buttonVariants } from "@suni/ui/components/button"; +import { Badge } from "@suni/ui/components/badge"; +import { Button, buttonVariants } from "@suni/ui/components/button"; import { Tabs, TabsList, @@ -9,6 +10,8 @@ import { cn } from "@suni/ui/lib/utils"; import { useSuspenseQuery } from "@tanstack/react-query"; import { createFileRoute, Link } from "@tanstack/react-router"; import { + Archive, + ArchiveRestore, ContactRound, FileText, FolderOpen, @@ -17,8 +20,10 @@ import { ShoppingCart, Users, } from "lucide-react"; +import { useState } from "react"; import { BranchesGrid } from "@/components/customers/branches/grid"; +import { ChangeCustomerStatusDialog } from "@/components/customers/change-customer-status-dialog"; import { ContactsGrid } from "@/components/customers/contacts/contact-grid"; import { CustomerData } from "@/components/customers/data"; import { orpc } from "@/utils/orpc"; @@ -53,15 +58,50 @@ function RouteComponent() { orpc.customers.get.queryOptions({ input: { id: customerId } }) ); + const isArchived = !!customer.archived; + const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); + return (
-
-
+
+
-
- +
+ +
+
+

+ {customer.name} +

+ {isArchived ? ( + + + Archivado + + ) : null}
-

{customer.name}

{customer.rfc}

@@ -77,17 +117,33 @@ function RouteComponent() {
- {customer.archived ? null : ( - - Editar - - )} +
+ {isArchived ? null : ( + + Editar + + )} + +
+ + @@ -100,10 +156,16 @@ function RouteComponent() { ))} - + - +
diff --git a/apps/web/src/utils/orpc.ts b/apps/web/src/utils/orpc.ts index a8b7406..34c2dd9 100644 --- a/apps/web/src/utils/orpc.ts +++ b/apps/web/src/utils/orpc.ts @@ -13,7 +13,7 @@ function createQueryClient() { onError: (error, query) => { toast.error(`Error: ${error.message}`, { action: { - label: "retry", + label: "Reintentar", onClick: () => { query.invalidate(); }, diff --git a/oxlint.config.ts b/oxlint.config.ts index b42caea..2e12901 100644 --- a/oxlint.config.ts +++ b/oxlint.config.ts @@ -108,6 +108,7 @@ export default defineConfig({ ], rules: { "oxc/no-accumulating-spread": "error", + "suni/require-seller-scope": "error", "suni/require-suppression-reason": "error", "no-restricted-imports": ["error", { paths: [REACT_HOOK_FORM_BAN] }], "anti-slop/no-array-filter-map": "error", diff --git a/packages/api/AGENTS.md b/packages/api/AGENTS.md index eeecb65..c64c3f4 100644 --- a/packages/api/AGENTS.md +++ b/packages/api/AGENTS.md @@ -19,7 +19,7 @@ See [package.json](package.json) for available scripts. From the repo root, run ## Conventions -- Use `publicProcedure` for an open endpoint, `protectedProcedure` when a session is required, and `adminProcedure` when the user must have the `admin` role. `adminProcedure` reads the role from the database, not the cached session. +- Use `publicProcedure` for an open endpoint, `protectedProcedure` when a session is required, `scopedProcedure` when the handler branches on the role (it adds `context.userId` and `context.admin`), and `adminProcedure` when the user must have the `admin` role. Both read the role from the database, not the cached session. - Create and update users through the Better Auth admin API (`context.auth.api` with `context.headers`) rather than writing auth tables directly. - Type web code with `AppRouterInputs` and `AppRouterOutputs` from `src/routers/index.ts` instead of redeclaring procedure shapes. - Put each procedure in its own file under `src/routers//` and set `prefix` and `tag` once on the router in `index.ts`. diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 594c82a..ed39d89 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -4,13 +4,17 @@ import { eq } from "drizzle-orm"; import type { Context } from "./context"; -export const o = os.$context(); +export const o = os.$context().errors({ + NOT_FOUND: { message: "El registro no existe" }, +}); export const publicProcedure = o; const requireAuth = o.middleware(({ context, next }) => { if (!context.session?.user) { - throw new ORPCError("UNAUTHORIZED"); + throw new ORPCError("UNAUTHORIZED", { + message: "Inicia sesión para continuar", + }); } return next({ @@ -22,7 +26,7 @@ const requireAuth = o.middleware(({ context, next }) => { export const protectedProcedure = publicProcedure.use(requireAuth); -export async function isAdmin(context: Pick, userId: string) { +async function isAdmin(context: Pick, userId: string) { const [currentUser] = await context.db .select({ role: user.role }) .from(user) @@ -32,12 +36,23 @@ export async function isAdmin(context: Pick, userId: string) { return currentUser?.role === "admin"; } -export const adminProcedure = protectedProcedure.use( +// Role is read from the database, not the cached session, so revocations apply immediately. +export const scopedProcedure = protectedProcedure.use( async ({ context, next }) => { - if (!(await isAdmin(context, context.session.user.id))) { - throw new ORPCError("FORBIDDEN"); - } + const userId = context.session.user.id; - return next(); + return next({ + context: { userId, admin: await isAdmin(context, userId) }, + }); } ); + +export const adminProcedure = scopedProcedure.use(({ context, next }) => { + if (!context.admin) { + throw new ORPCError("FORBIDDEN", { + message: "No tienes permiso para esta acción", + }); + } + + return next(); +}); diff --git a/packages/api/src/routers/branches/create.ts b/packages/api/src/routers/branches/create.ts index 1a586ee..0d8750f 100644 --- a/packages/api/src/routers/branches/create.ts +++ b/packages/api/src/routers/branches/create.ts @@ -1,13 +1,32 @@ import { branch } from "@suni/db/schema/branches"; import { createBranchSchema } from "@suni/db/validation/branches"; -import { protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownCustomers } from "../../util/scope"; +import { statusWhere } from "../../util/status"; -export const create = protectedProcedure +export const create = scopedProcedure .route({ method: "POST", path: "/" }) .input(createBranchSchema) - .handler(async ({ input, context }) => { - const userId = context.session.user.id; + .handler(async ({ input, context, errors }) => { + const { userId } = context; + + const parent = await context.db.query.customer.findFirst({ + where: { + AND: [ + { id: input.customerId }, + statusWhere("customer", "active"), + ownCustomers(context), + ], + }, + columns: { id: true }, + }); + + if (!parent) { + throw errors.NOT_FOUND({ + message: "El cliente no existe o está archivado", + }); + } const [created] = await context.db .insert(branch) diff --git a/packages/api/src/routers/branches/get.ts b/packages/api/src/routers/branches/get.ts index c72e0f9..836c819 100644 --- a/packages/api/src/routers/branches/get.ts +++ b/packages/api/src/routers/branches/get.ts @@ -1,29 +1,29 @@ -import { ORPCError } from "@orpc/server"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { + ownBranches, + sellerColumns, + sellerRelation, + withSeller, +} from "../../util/scope"; -export const get = protectedProcedure +export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) - .handler(async ({ input, context }) => { - const admin = await isAdmin(context, context.session.user.id); - + .handler(async ({ input, context, errors }) => { 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 }, + where: { id: input.id, ...ownBranches(context) }, + columns: sellerColumns(context), with: { customer: { columns: { id: true, name: true, archived: true } }, - contacts: true, - ...(admin && { seller: { columns: { id: true, name: true } } }), + ...sellerRelation(context), }, }); if (!found) { - throw new ORPCError("NOT_FOUND", { message: "Branch not found" }); + throw errors.NOT_FOUND({ message: "La sucursal no existe" }); } - return admin ? found : { ...found, seller: null }; + return withSeller(context, found); }); diff --git a/packages/api/src/routers/branches/list.ts b/packages/api/src/routers/branches/list.ts index cf4990c..b6cc19e 100644 --- a/packages/api/src/routers/branches/list.ts +++ b/packages/api/src/routers/branches/list.ts @@ -1,10 +1,16 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { + ownBranches, + sellerColumns, + sellerRelation, + withSeller, +} from "../../util/scope"; import { statusWhere } from "../../util/status"; -export const list = protectedProcedure +export const list = scopedProcedure .route({ method: "GET", path: "/" }) .input( z.object({ @@ -13,35 +19,20 @@ export const list = protectedProcedure }) ) .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 }, + where: { + AND: [ + statusWhere("branch", input.status), + ownBranches(context), + { customerId: input.customerId }, + ], + }, + columns: sellerColumns(context), with: { customer: { columns: { id: true, name: true, archived: true } }, - contacts: true, + ...sellerRelation(context), }, }); - return rows.map((row) => ({ ...row, seller: null })); + return rows.map((row) => withSeller(context, row)); }); diff --git a/packages/api/src/routers/branches/set-archived.ts b/packages/api/src/routers/branches/set-archived.ts index 0339bee..c6ee37a 100644 --- a/packages/api/src/routers/branches/set-archived.ts +++ b/packages/api/src/routers/branches/set-archived.ts @@ -1,34 +1,37 @@ -import { ORPCError } from "@orpc/server"; import { branch } from "@suni/db/schema/branches"; -import { and, eq, sql } from "drizzle-orm"; +import { and, eq, inArray } from "drizzle-orm"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownBranchesSql } from "../../util/scope"; +import { activeCustomerIdsSql, archivedValue } from "../../util/status"; -export const setArchived = protectedProcedure +export const setArchived = scopedProcedure .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); + .handler(async ({ input, context, errors }) => { + const { userId } = context; const [updated] = await context.db .update(branch) .set({ - archived: input.archived - ? sql`COALESCE(${branch.archived}, now())` - : null, + archived: archivedValue(branch.archived, input.archived), modifiedBy: userId, }) + // An archived customer wins: the branch status cannot change under it. .where( - admin - ? eq(branch.id, input.id) - : and(eq(branch.id, input.id), eq(branch.sellerId, userId)) + and( + eq(branch.id, input.id), + inArray(branch.customerId, activeCustomerIdsSql(context.db)), + ownBranchesSql(context) + ) ) .returning({ id: branch.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { message: "Branch not found" }); + throw errors.NOT_FOUND({ + message: "La sucursal no existe o su cliente está archivado", + }); } return updated; diff --git a/packages/api/src/routers/branches/update.ts b/packages/api/src/routers/branches/update.ts index 43c8152..bd30a24 100644 --- a/packages/api/src/routers/branches/update.ts +++ b/packages/api/src/routers/branches/update.ts @@ -1,26 +1,19 @@ -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 { branchSchema } from "@suni/db/validation/branches"; +import { and, eq, inArray, isNull } from "drizzle-orm"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownBranchesSql } from "../../util/scope"; +import { activeCustomerIdsSql } from "../../util/status"; -export const update = protectedProcedure +export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) - .input(updateBranchSchema.omit({ archived: true }).extend({ id: z.string() })) - .handler(async ({ input, context }) => { + .input(branchSchema.extend({ id: z.string() })) + .handler(async ({ input, context, errors }) => { 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 { userId } = context; const [updated] = await context.db .update(branch) @@ -29,14 +22,15 @@ export const update = protectedProcedure and( eq(branch.id, id), isNull(branch.archived), - admin ? undefined : eq(branch.sellerId, userId) + inArray(branch.customerId, activeCustomerIdsSql(context.db)), + ownBranchesSql(context) ) ) .returning({ id: branch.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { - message: "La sucursal no existe o está archivada", + throw errors.NOT_FOUND({ + message: "La sucursal no existe, o ella o su cliente están archivados", }); } diff --git a/packages/api/src/routers/contacts/create.ts b/packages/api/src/routers/contacts/create.ts index 9f3e56f..c3e543f 100644 --- a/packages/api/src/routers/contacts/create.ts +++ b/packages/api/src/routers/contacts/create.ts @@ -1,30 +1,31 @@ -import { ORPCError } from "@orpc/server"; import { contact } from "@suni/db/schema/contacts"; import { createContactSchema } from "@suni/db/validation/contacts"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownBranches } from "../../util/scope"; +import { statusWhere } from "../../util/status"; -export const create = protectedProcedure +export const create = scopedProcedure .route({ method: "POST", path: "/" }) .input(createContactSchema) - .handler(async ({ input, context }) => { - const userId = context.session.user.id; - const admin = await isAdmin(context, userId); + .handler(async ({ input, context, errors }) => { + const { userId } = context; const parent = await context.db.query.branch.findFirst({ where: { - id: input.branchId, - customerId: input.customerId, - archived: { isNull: true }, - sellerId: admin ? undefined : userId, + AND: [ + { id: input.branchId, customerId: input.customerId }, + statusWhere("branch", "active"), + ownBranches(context), + ], }, columns: { id: true }, }); if (!parent) { - throw new ORPCError("NOT_FOUND", { + throw errors.NOT_FOUND({ message: - "La sucursal no existe, está archivada o no pertenece al cliente", + "La sucursal no existe, no pertenece al cliente, o ella o su cliente están archivados", }); } diff --git a/packages/api/src/routers/contacts/get.ts b/packages/api/src/routers/contacts/get.ts index 4a2cc90..7b08589 100644 --- a/packages/api/src/routers/contacts/get.ts +++ b/packages/api/src/routers/contacts/get.ts @@ -1,20 +1,16 @@ -import { ORPCError } from "@orpc/server"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownContacts } from "../../util/scope"; -export const get = protectedProcedure +export const get = scopedProcedure .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); + .handler(async ({ input, context, errors }) => { + const { admin } = context; const found = await context.db.query.contact.findFirst({ - where: { - id: input.id, - branch: admin ? undefined : { sellerId: userId }, - }, + where: { id: input.id, ...ownContacts(context) }, columns: admin ? undefined : { modifiedBy: false }, with: { branch: { columns: { id: true, name: true, archived: true } }, @@ -23,7 +19,7 @@ export const get = protectedProcedure }); if (!found) { - throw new ORPCError("NOT_FOUND", { message: "Contact not found" }); + throw errors.NOT_FOUND({ message: "El contacto no existe" }); } return found; diff --git a/packages/api/src/routers/contacts/list.ts b/packages/api/src/routers/contacts/list.ts index a81448d..4fad244 100644 --- a/packages/api/src/routers/contacts/list.ts +++ b/packages/api/src/routers/contacts/list.ts @@ -1,10 +1,11 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownContacts } from "../../util/scope"; import { statusWhere } from "../../util/status"; -export const list = protectedProcedure +export const list = scopedProcedure .route({ method: "GET", path: "/" }) .input( z.object({ @@ -13,22 +14,19 @@ export const list = protectedProcedure 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({ + .handler(({ input, context }) => + context.db.query.contact.findMany({ where: { AND: [ statusWhere("contact", input.status), { customerId: input.customerId, branchId: input.branchId }, - ...(admin ? [] : [{ branch: { sellerId: userId } }]), + ownContacts(context), ], }, - columns: admin ? undefined : { modifiedBy: false }, + columns: context.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 index 29fc631..811a86a 100644 --- a/packages/api/src/routers/contacts/set-archived.ts +++ b/packages/api/src/routers/contacts/set-archived.ts @@ -1,44 +1,38 @@ -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 { and, eq, inArray } from "drizzle-orm"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownContactsSql } from "../../util/scope"; +import { activeBranchIdsSql, archivedValue } from "../../util/status"; -export const setArchived = protectedProcedure +export const setArchived = scopedProcedure .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); + .handler(async ({ input, context, errors }) => { + const { userId } = context; const [updated] = await context.db .update(contact) .set({ - archived: input.archived - ? sql`COALESCE(${contact.archived}, now())` - : null, + archived: archivedValue(contact.archived, input.archived), modifiedBy: userId, }) + // An archived branch or customer wins: the contact status cannot change under it. .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)) - ) + inArray(contact.branchId, activeBranchIdsSql(context.db)), + ownContactsSql(context) ) ) .returning({ id: contact.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { message: "Contact not found" }); + throw errors.NOT_FOUND({ + message: + "El contacto no existe o su sucursal o cliente están archivados", + }); } return updated; diff --git a/packages/api/src/routers/contacts/update.ts b/packages/api/src/routers/contacts/update.ts index 74e1a2f..104fde7 100644 --- a/packages/api/src/routers/contacts/update.ts +++ b/packages/api/src/routers/contacts/update.ts @@ -1,30 +1,18 @@ -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 { contactSchema } from "@suni/db/validation/contacts"; import { and, eq, inArray, isNull } from "drizzle-orm"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownContactsSql } from "../../util/scope"; +import { activeBranchIdsSql } from "../../util/status"; -export const update = protectedProcedure +export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) - .input( - updateContactSchema - .omit({ archived: true, customerId: true }) - .extend({ id: z.string() }) - ) - .handler(async ({ input, context }) => { + .input(contactSchema.extend({ id: z.string() })) + .handler(async ({ input, context, errors }) => { 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 { userId } = context; const [updated] = await context.db .update(contact) @@ -33,22 +21,16 @@ export const update = protectedProcedure 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)) - ) + inArray(contact.branchId, activeBranchIdsSql(context.db)), + ownContactsSql(context) ) ) .returning({ id: contact.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { - message: "El contacto no existe o está archivado", + throw errors.NOT_FOUND({ + message: + "El contacto no existe, o él, su sucursal o su cliente están archivados", }); } diff --git a/packages/api/src/routers/customers/create.ts b/packages/api/src/routers/customers/create.ts index d39f618..53645e6 100644 --- a/packages/api/src/routers/customers/create.ts +++ b/packages/api/src/routers/customers/create.ts @@ -1,15 +1,15 @@ import { customer } from "@suni/db/schema/customers"; -import { customerInputSchema } from "@suni/db/validation/customers"; +import { customerSchema } from "@suni/db/validation/customers"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; -export const create = protectedProcedure +export const create = scopedProcedure .route({ method: "POST", path: "/" }) - .input(customerInputSchema) + .input(customerSchema) .handler(async ({ input, context }) => { - const userId = context.session.user.id; + const { userId } = context; - const type = (await isAdmin(context, userId)) ? input.type : "Cliente"; + const type = context.admin ? input.type : "Cliente"; const [created] = await context.db .insert(customer) diff --git a/packages/api/src/routers/customers/get.ts b/packages/api/src/routers/customers/get.ts index 16c7424..7f4975b 100644 --- a/packages/api/src/routers/customers/get.ts +++ b/packages/api/src/routers/customers/get.ts @@ -1,40 +1,26 @@ -import { ORPCError } from "@orpc/server"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { + ownCustomers, + sellerColumns, + sellerRelation, + withSeller, +} from "../../util/scope"; -function notFound() { - return new ORPCError("NOT_FOUND", { message: "Customer not found" }); -} - -export const get = protectedProcedure +export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) - .handler(async ({ input, context }) => { - const where = { id: input.id }; - - if (await isAdmin(context, context.session.user.id)) { - const found = await context.db.query.customer.findFirst({ - where, - with: { seller: { columns: { id: true, name: true } } }, - }); - - if (!found) { - throw notFound(); - } - - return found; - } - - // Seller identity is admin-only. + .handler(async ({ input, context, errors }) => { const found = await context.db.query.customer.findFirst({ - where, - columns: { sellerId: false, modifiedBy: false }, + where: { id: input.id, ...ownCustomers(context) }, + columns: sellerColumns(context), + with: sellerRelation(context), }); if (!found) { - throw notFound(); + throw errors.NOT_FOUND({ message: "El cliente no existe" }); } - return { ...found, seller: null }; + return withSeller(context, found); }); diff --git a/packages/api/src/routers/customers/list.ts b/packages/api/src/routers/customers/list.ts index 7f651ee..19078d1 100644 --- a/packages/api/src/routers/customers/list.ts +++ b/packages/api/src/routers/customers/list.ts @@ -1,32 +1,26 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { + ownCustomers, + sellerColumns, + sellerRelation, + withSeller, +} from "../../util/scope"; +import { statusWhere } from "../../util/status"; -const statusFilters = { - active: { archived: { isNull: true } }, - archived: { archived: { isNotNull: true } }, -} as const; - -export const list = protectedProcedure +export const list = scopedProcedure .route({ method: "GET", path: "/" }) .input(z.object({ status: z.enum(CUSTOMER_STATUSES).default("active") })) .handler(async ({ input, context }) => { - const where = - input.status === "all" ? undefined : statusFilters[input.status]; - - if (await isAdmin(context, context.session.user.id)) { - return context.db.query.customer.findMany({ - where, - with: { seller: { columns: { id: true, name: true } } }, - }); - } - - // Seller identity is admin-only. const rows = await context.db.query.customer.findMany({ - where, - columns: { sellerId: false, modifiedBy: false }, + where: { + AND: [statusWhere("customer", input.status), ownCustomers(context)], + }, + columns: sellerColumns(context), + with: sellerRelation(context), }); - return rows.map((row) => ({ ...row, seller: null })); + return rows.map((row) => withSeller(context, row)); }); diff --git a/packages/api/src/routers/customers/set-archived.ts b/packages/api/src/routers/customers/set-archived.ts index 0bf4782..eebb9d1 100644 --- a/packages/api/src/routers/customers/set-archived.ts +++ b/packages/api/src/routers/customers/set-archived.ts @@ -1,29 +1,26 @@ -import { ORPCError } from "@orpc/server"; import { customer } from "@suni/db/schema/customers"; -import { eq, sql } from "drizzle-orm"; +import { and, eq } from "drizzle-orm"; import { z } from "zod"; -import { protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownCustomersSql } from "../../util/scope"; +import { archivedValue } from "../../util/status"; -export const setArchived = protectedProcedure +export const setArchived = scopedProcedure .route({ method: "POST", path: "/{id}/archived" }) .input(z.object({ id: z.string(), archived: z.boolean() })) - .handler(async ({ input, context }) => { - // Set the target state instead of toggling, so a repeated request is a no-op. - // COALESCE keeps the original archive date when it is already archived. + .handler(async ({ input, context, errors }) => { const [updated] = await context.db .update(customer) .set({ - archived: input.archived - ? sql`COALESCE(${customer.archived}, now())` - : null, - modifiedBy: context.session.user.id, + archived: archivedValue(customer.archived, input.archived), + modifiedBy: context.userId, }) - .where(eq(customer.id, input.id)) + .where(and(eq(customer.id, input.id), ownCustomersSql(context))) .returning({ id: customer.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { message: "Customer not found" }); + throw errors.NOT_FOUND({ message: "El cliente no existe" }); } return updated; diff --git a/packages/api/src/routers/customers/update.ts b/packages/api/src/routers/customers/update.ts index bee3e82..dff7b8b 100644 --- a/packages/api/src/routers/customers/update.ts +++ b/packages/api/src/routers/customers/update.ts @@ -1,38 +1,36 @@ -import { ORPCError } from "@orpc/server"; import { customer } from "@suni/db/schema/customers"; -import { customerInputSchema } from "@suni/db/validation/customers"; +import { customerSchema } from "@suni/db/validation/customers"; import { and, eq, isNull } from "drizzle-orm"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownCustomersSql } from "../../util/scope"; -export const update = protectedProcedure +export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) - .input(customerInputSchema.partial().extend({ id: z.string() })) - .handler(async ({ input, context }) => { + .input(customerSchema.extend({ id: z.string() })) + .handler(async ({ input, context, errors }) => { const { id, type, ...fields } = input; - const userId = context.session.user.id; + const { userId } = context; - const data = (await isAdmin(context, userId)) - ? { ...fields, type } - : fields; - - if (Object.values(data).every((v) => v === undefined)) { - throw new ORPCError("BAD_REQUEST", { - message: "No hay campos para actualizar", - }); - } + const data = context.admin ? { ...fields, type } : fields; const [updated] = await context.db .update(customer) .set({ ...data, modifiedBy: userId }) // Archived customers are read-only until restored. - .where(and(eq(customer.id, id), isNull(customer.archived))) + .where( + and( + eq(customer.id, id), + isNull(customer.archived), + ownCustomersSql(context) + ) + ) .returning({ id: customer.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { + throw errors.NOT_FOUND({ message: "El cliente no existe o está archivado", }); } diff --git a/packages/api/src/routers/users/create.ts b/packages/api/src/routers/users/create.ts index 77ccb81..ecc0637 100644 --- a/packages/api/src/routers/users/create.ts +++ b/packages/api/src/routers/users/create.ts @@ -1,19 +1,13 @@ import { APIError } from "@suni/auth"; +import { USER_ROLES, userSchema } from "@suni/db/validation/users"; import { z } from "zod"; import { adminProcedure } from "../../index"; import { toORPCError } from "./errors"; -import { role } from "./role"; export const create = adminProcedure .route({ method: "POST", path: "/" }) - .input( - z.object({ - name: z.string().min(2), - email: z.email().toLowerCase(), - role: role.default("user"), - }) - ) + .input(userSchema.extend({ role: z.enum(USER_ROLES).default("user") })) .handler(async ({ input, context }) => { try { const { user } = await context.auth.api.createUser({ diff --git a/packages/api/src/routers/users/get.ts b/packages/api/src/routers/users/get.ts index e6abda1..c513bc5 100644 --- a/packages/api/src/routers/users/get.ts +++ b/packages/api/src/routers/users/get.ts @@ -1,4 +1,3 @@ -import { ORPCError } from "@orpc/server"; import { user } from "@suni/db/schema/auth"; import { eq } from "drizzle-orm"; import { z } from "zod"; @@ -8,7 +7,7 @@ import { adminProcedure } from "../../index"; export const get = adminProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const [row] = await context.db .select() .from(user) @@ -16,7 +15,7 @@ export const get = adminProcedure .limit(1); if (!row) { - throw new ORPCError("NOT_FOUND"); + throw errors.NOT_FOUND({ message: "El usuario no existe" }); } return row; diff --git a/packages/api/src/routers/users/role.ts b/packages/api/src/routers/users/role.ts deleted file mode 100644 index e742122..0000000 --- a/packages/api/src/routers/users/role.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { z } from "zod"; - -export const role = z.enum(["user", "admin"]); diff --git a/packages/api/src/routers/users/update.ts b/packages/api/src/routers/users/update.ts index 7438637..1913354 100644 --- a/packages/api/src/routers/users/update.ts +++ b/packages/api/src/routers/users/update.ts @@ -1,36 +1,18 @@ import { ORPCError } from "@orpc/server"; import { APIError } from "@suni/auth"; +import { userSchema } from "@suni/db/validation/users"; import { z } from "zod"; import { adminProcedure } from "../../index"; import { toORPCError } from "./errors"; -import { role } from "./role"; export const update = adminProcedure .route({ method: "PATCH", path: "/{id}" }) - .input( - z.object({ - id: z.string(), - name: z.string().min(2).optional(), - email: z.email().toLowerCase().optional(), - image: z.url().nullable().optional(), - role: role.optional(), - }) - ) + .input(userSchema.extend({ id: z.string() })) .handler(async ({ input, context }) => { const { id, ...data } = input; - if (Object.values(data).every((v) => v === undefined)) { - throw new ORPCError("BAD_REQUEST", { - message: "No hay campos para actualizar", - }); - } - - if ( - id === context.session.user.id && - data.role !== undefined && - data.role !== "admin" - ) { + if (id === context.session.user.id && data.role !== "admin") { throw new ORPCError("FORBIDDEN", { message: "No puedes quitarte el rol de administrador", }); diff --git a/packages/api/src/util/scope.ts b/packages/api/src/util/scope.ts new file mode 100644 index 0000000..3e7c4e8 --- /dev/null +++ b/packages/api/src/util/scope.ts @@ -0,0 +1,66 @@ +import { branch } from "@suni/db/schema/branches"; +import { contact } from "@suni/db/schema/contacts"; +import { customer } from "@suni/db/schema/customers"; +import { eq, inArray } from "drizzle-orm"; + +import type { Context } from "../context"; + +interface Scope extends Pick { + admin: boolean; + userId: string; +} + +// Non-admins only reach the customers and branches they sell and the contacts under them. +// Each rule has a relational-query form and a SQL form for update/delete builders. + +export function ownCustomers({ admin, userId }: Scope) { + return admin ? {} : { sellerId: userId }; +} + +export function ownCustomersSql({ admin, userId }: Scope) { + return admin ? undefined : eq(customer.sellerId, userId); +} + +export function ownBranches({ admin, userId }: Scope) { + return admin ? {} : { sellerId: userId }; +} + +export function ownBranchesSql({ admin, userId }: Scope) { + return admin ? undefined : eq(branch.sellerId, userId); +} + +export function ownContacts(scope: Scope) { + return scope.admin ? {} : { branch: ownBranches(scope) }; +} + +export function ownContactsSql({ admin, userId, db }: Scope) { + return admin + ? undefined + : inArray( + contact.branchId, + db + .select({ id: branch.id }) + .from(branch) + .where(eq(branch.sellerId, userId)) + ); +} + +// Seller identity is admin-only. Spread `sellerColumns` and `sellerRelation` +// into a customer or branch query, then pass the result through `withSeller`. + +export function sellerColumns({ admin }: Pick) { + return admin ? undefined : ({ sellerId: false, modifiedBy: false } as const); +} + +export function sellerRelation({ admin }: Pick) { + return admin + ? ({ seller: { columns: { id: true, name: true } } } as const) + : {}; +} + +export function withSeller( + { admin }: Pick, + row: T +) { + return admin ? row : { ...row, seller: null }; +} diff --git a/packages/api/src/util/status.ts b/packages/api/src/util/status.ts index 45b3245..e4d5843 100644 --- a/packages/api/src/util/status.ts +++ b/packages/api/src/util/status.ts @@ -1,3 +1,10 @@ +import { branch } from "@suni/db/schema/branches"; +import { customer } from "@suni/db/schema/customers"; +import { and, eq, isNull as isNullSql, sql } from "drizzle-orm"; +import type { AnyPgColumn } from "drizzle-orm/pg-core"; + +import type { Context } from "../context"; + const isNull = { isNull: true } as const; const isNotNull = { isNotNull: true } as const; @@ -41,3 +48,26 @@ export function statusWhere(entity: Entity, status: Status) { return archived[entity]; } + +// SQL forms for update builders, which cannot filter through relations. + +export function activeCustomerIdsSql(db: Context["db"]) { + return db + .select({ id: customer.id }) + .from(customer) + .where(isNullSql(customer.archived)); +} + +export function activeBranchIdsSql(db: Context["db"]) { + return db + .select({ id: branch.id }) + .from(branch) + .innerJoin(customer, eq(branch.customerId, customer.id)) + .where(and(isNullSql(branch.archived), isNullSql(customer.archived))); +} + +// Set the target state instead of toggling, so a repeated request is a no-op. +// COALESCE keeps the original archive date when it is already archived. +export function archivedValue(column: AnyPgColumn, isArchived: boolean) { + return isArchived ? sql`COALESCE(${column}, now())` : null; +} diff --git a/packages/auth/package.json b/packages/auth/package.json index 02fa0f8..73ae5a4 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -11,6 +11,7 @@ }, "dependencies": { "@better-auth/drizzle-adapter": "1.7.5", + "@paralleldrive/cuid2": "catalog:", "@suni/db": "workspace:*", "better-auth": "catalog:", "drizzle-orm": "catalog:", diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index e706c86..741a96e 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -1,4 +1,5 @@ import { drizzleAdapter } from "@better-auth/drizzle-adapter/relations-v2"; +import { createId } from "@paralleldrive/cuid2"; import type { Database } from "@suni/db"; // oxlint-disable-next-line sonarjs/no-wildcard-import -- the Drizzle adapter takes the whole schema object import * as schema from "@suni/db/schema/auth"; @@ -44,6 +45,9 @@ export function createAuth( return betterAuth({ advanced: { + database: { + generateId: () => createId(), + }, defaultCookieAttributes: { httpOnly: true, sameSite: isProduction ? "none" : "lax", diff --git a/packages/db/package.json b/packages/db/package.json index b85ce1b..168fb7d 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -16,6 +16,7 @@ "db:seed": "varlock run -- bun ./src/seeds/index.ts" }, "dependencies": { + "@paralleldrive/cuid2": "catalog:", "drizzle-orm": "catalog:", "pg": "^8.23.0", "zod": "catalog:" diff --git a/packages/db/src/migrations/20261109213441_regular_luckman/migration.sql b/packages/db/src/migrations/20261109213441_regular_luckman/migration.sql new file mode 100644 index 0000000..b32bdad --- /dev/null +++ b/packages/db/src/migrations/20261109213441_regular_luckman/migration.sql @@ -0,0 +1,14 @@ +ALTER TABLE "customer_branches" ALTER COLUMN "int_number" SET DEFAULT '';--> statement-breakpoint +ALTER TABLE "customer_branches" ALTER COLUMN "int_number" SET NOT NULL;--> statement-breakpoint +ALTER TABLE "customer_branches" ALTER COLUMN "phone" SET DEFAULT '';--> statement-breakpoint +ALTER TABLE "customer_branches" ALTER COLUMN "phone" SET NOT NULL;--> statement-breakpoint +ALTER TABLE "customer_branches" ALTER COLUMN "front_image_url" SET DEFAULT '';--> statement-breakpoint +ALTER TABLE "customer_branches" ALTER COLUMN "front_image_url" SET NOT NULL;--> statement-breakpoint +ALTER TABLE "contact" ALTER COLUMN "phone_extension" SET DEFAULT '';--> statement-breakpoint +ALTER TABLE "contact" ALTER COLUMN "phone_extension" SET NOT NULL;--> statement-breakpoint +ALTER TABLE "contact" ALTER COLUMN "position" SET DEFAULT '';--> statement-breakpoint +ALTER TABLE "contact" ALTER COLUMN "position" SET NOT NULL;--> statement-breakpoint +ALTER TABLE "customer" ALTER COLUMN "int_number" SET DEFAULT '';--> statement-breakpoint +ALTER TABLE "customer" ALTER COLUMN "int_number" SET NOT NULL;--> statement-breakpoint +ALTER TABLE "customer" ALTER COLUMN "phone_extension" SET DEFAULT '';--> statement-breakpoint +ALTER TABLE "customer" ALTER COLUMN "phone_extension" SET NOT NULL; \ No newline at end of file diff --git a/packages/db/src/migrations/20261109213441_regular_luckman/snapshot.json b/packages/db/src/migrations/20261109213441_regular_luckman/snapshot.json new file mode 100644 index 0000000..0e242b1 --- /dev/null +++ b/packages/db/src/migrations/20261109213441_regular_luckman/snapshot.json @@ -0,0 +1,1532 @@ +{ + "version": "8", + "dialect": "postgres", + "id": "610e4596-7be8-4d33-8a16-c0981df4b1c9", + "prevIds": [ + "31829c0c-39bb-4545-ada1-2829bb29f26d" + ], + "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": true, + "dimensions": 0, + "default": "''", + "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": true, + "dimensions": 0, + "default": "''", + "generated": null, + "identity": null, + "name": "phone", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "''", + "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": true, + "dimensions": 0, + "default": "''", + "generated": null, + "identity": null, + "name": "phone_extension", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "''", + "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": true, + "dimensions": 0, + "default": "''", + "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": true, + "dimensions": 0, + "default": "''", + "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/migrations/20261111170917_lyrical_payback/migration.sql b/packages/db/src/migrations/20261111170917_lyrical_payback/migration.sql new file mode 100644 index 0000000..271ea60 --- /dev/null +++ b/packages/db/src/migrations/20261111170917_lyrical_payback/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "contact" ALTER COLUMN "branch_id" SET NOT NULL; \ No newline at end of file diff --git a/packages/db/src/migrations/20261111170917_lyrical_payback/snapshot.json b/packages/db/src/migrations/20261111170917_lyrical_payback/snapshot.json new file mode 100644 index 0000000..4dbf743 --- /dev/null +++ b/packages/db/src/migrations/20261111170917_lyrical_payback/snapshot.json @@ -0,0 +1,1532 @@ +{ + "version": "8", + "dialect": "postgres", + "id": "fd2a056e-c876-4ed0-98c6-3cdeb4d77ab1", + "prevIds": [ + "610e4596-7be8-4d33-8a16-c0981df4b1c9" + ], + "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": true, + "dimensions": 0, + "default": "''", + "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": true, + "dimensions": 0, + "default": "''", + "generated": null, + "identity": null, + "name": "phone", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "''", + "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": true, + "dimensions": 0, + "default": "''", + "generated": null, + "identity": null, + "name": "phone_extension", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "''", + "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": true, + "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": true, + "dimensions": 0, + "default": "''", + "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": true, + "dimensions": 0, + "default": "''", + "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/schema/branches.ts b/packages/db/src/schema/branches.ts index 376ab14..6c3c395 100644 --- a/packages/db/src/schema/branches.ts +++ b/packages/db/src/schema/branches.ts @@ -1,3 +1,4 @@ +import { createId } from "@paralleldrive/cuid2"; import { pgTable, text, timestamp } from "drizzle-orm/pg-core"; import { user } from "./auth"; @@ -6,17 +7,17 @@ import { customer } from "./customers"; export const branch = pgTable("customer_branches", { id: text("id") .primaryKey() - .$defaultFn(() => crypto.randomUUID()), + .$defaultFn(() => createId()), name: text("name").notNull(), street: text("street").notNull(), - intNumber: text("int_number"), + intNumber: text("int_number").notNull().default(""), 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"), + phone: text("phone").notNull().default(""), + frontImageUrl: text("front_image_url").notNull().default(""), customerId: text("customer_id") .notNull() .references(() => customer.id), diff --git a/packages/db/src/schema/contacts.ts b/packages/db/src/schema/contacts.ts index b745449..9c87806 100644 --- a/packages/db/src/schema/contacts.ts +++ b/packages/db/src/schema/contacts.ts @@ -1,3 +1,4 @@ +import { createId } from "@paralleldrive/cuid2"; import { pgTable, text, timestamp } from "drizzle-orm/pg-core"; import { user } from "./auth"; @@ -7,16 +8,18 @@ import { customer } from "./customers"; export const contact = pgTable("contact", { id: text("id") .primaryKey() - .$defaultFn(() => crypto.randomUUID()), + .$defaultFn(() => createId()), name: text("name").notNull(), email: text("email").notNull(), phone: text("phone").notNull(), - phoneExtension: text("phone_extension"), - position: text("position"), + phoneExtension: text("phone_extension").notNull().default(""), + position: text("position").notNull().default(""), customerId: text("customer_id") .notNull() .references(() => customer.id), - branchId: text("branch_id").references(() => branch.id), + branchId: text("branch_id") + .notNull() + .references(() => branch.id), archived: timestamp("archived"), modifiedBy: text("modified_by") .notNull() diff --git a/packages/db/src/schema/customers.ts b/packages/db/src/schema/customers.ts index 6f7b990..e7506a7 100644 --- a/packages/db/src/schema/customers.ts +++ b/packages/db/src/schema/customers.ts @@ -1,3 +1,4 @@ +import { createId } from "@paralleldrive/cuid2"; import { pgEnum, pgTable, text, timestamp } from "drizzle-orm/pg-core"; import { user } from "./auth"; @@ -10,18 +11,18 @@ export const customerTypeEnum = pgEnum("customer_type", CUSTOMER_TYPES); export const customer = pgTable("customer", { id: text("id") .primaryKey() - .$defaultFn(() => crypto.randomUUID()), + .$defaultFn(() => createId()), name: text("name").notNull(), rfc: text("rfc").notNull(), street: text("street").notNull(), - intNumber: text("int_number"), + intNumber: text("int_number").notNull().default(""), 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").notNull(), - phoneExtension: text("phone_extension"), + phoneExtension: text("phone_extension").notNull().default(""), acquisition: acquisitionEnum("acquisition").notNull(), type: customerTypeEnum("type").notNull().default("Cliente"), sellerId: text("seller_id") diff --git a/packages/db/src/seeds/admin-user.ts b/packages/db/src/seeds/admin-user.ts index 9fcf5ce..48f4d65 100644 --- a/packages/db/src/seeds/admin-user.ts +++ b/packages/db/src/seeds/admin-user.ts @@ -1,3 +1,4 @@ +import { createId } from "@paralleldrive/cuid2"; import { eq } from "drizzle-orm"; import { ENV } from "../env"; @@ -35,7 +36,7 @@ export async function createAdminUser() { console.log("👤 Creating admin user..."); - const userId = crypto.randomUUID(); + const userId = createId(); await db.insert(user).values({ email, diff --git a/packages/db/src/validation/branches.ts b/packages/db/src/validation/branches.ts index 639ced6..70c95bf 100644 --- a/packages/db/src/validation/branches.ts +++ b/packages/db/src/validation/branches.ts @@ -1,30 +1,44 @@ import { z } from "zod"; -import { emptyToNull, required } from "./shared"; +const MAX_100_MESSAGE = "Máximo 100 caracteres"; -export const branchFormSchema = z.object({ - name: required("El nombre de la sucursal es requerido"), - street: required("La calle es requerida"), +export const branchSchema = z.object({ + name: z + .string() + .trim() + .min(1, "El nombre de la sucursal es requerido") + .max(100, MAX_100_MESSAGE), + street: z + .string() + .trim() + .min(1, "La calle es requerida") + .max(150, "Máximo 150 caracteres"), 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"), + extNumber: z + .string() + .trim() + .min(1, "El número exterior es requerido") + .max(20, "Máximo 20 caracteres"), + city: z + .string() + .trim() + .min(1, "El municipio es requerido") + .max(100, MAX_100_MESSAGE), + suburb: z + .string() + .trim() + .min(1, "La colonia es requerida") + .max(100, MAX_100_MESSAGE), + state: z + .string() + .trim() + .min(1, "El estado es requerido") + .max(50, "Máximo 50 caracteres"), 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(), +export const createBranchSchema = branchSchema.extend({ + customerId: z.string().min(1, "El cliente es requerido"), }); diff --git a/packages/db/src/validation/contacts.ts b/packages/db/src/validation/contacts.ts index 4008fc5..db8b9dd 100644 --- a/packages/db/src/validation/contacts.ts +++ b/packages/db/src/validation/contacts.ts @@ -1,26 +1,18 @@ import { z } from "zod"; -import { emptyToNull, required } from "./shared"; - -export const contactFormSchema = z.object({ - name: required("El nombre es requerido"), +export const contactSchema = z.object({ + name: z + .string() + .trim() + .min(1, "El nombre es requerido") + .max(100, "Máximo 100 caracteres"), 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(), +export const createContactSchema = contactSchema.extend({ + customerId: z.string().min(1, "El cliente es requerido"), + branchId: z.string().min(1, "La sucursal es requerida"), }); diff --git a/packages/db/src/validation/customers.ts b/packages/db/src/validation/customers.ts index 4d1b9b4..9a98f2f 100644 --- a/packages/db/src/validation/customers.ts +++ b/packages/db/src/validation/customers.ts @@ -1,18 +1,41 @@ import { z } from "zod"; import { ACQUISITION_CHANNELS, CUSTOMER_TYPES } from "../schema/customer-enums"; -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({ - name: required("La razón social es requerida"), +export const customerSchema = z.object({ + name: z + .string() + .trim() + .min(1, "La razón social es requerida") + .max(254, "Máximo 254 caracteres"), rfc: z.string().regex(/^[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}$/u, "RFC inválido"), - street: required("La calle es requerida"), + street: z + .string() + .trim() + .min(1, "La calle es requerida") + .max(150, "Máximo 150 caracteres"), 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"), + extNumber: z + .string() + .trim() + .min(1, "El número exterior es requerido") + .max(20, "Máximo 20 caracteres"), + city: z + .string() + .trim() + .min(1, "El municipio es requerido") + .max(100, "Máximo 100 caracteres"), + suburb: z + .string() + .trim() + .min(1, "La colonia es requerida") + .max(100, "Máximo 100 caracteres"), + state: z + .string() + .trim() + .min(1, "El estado es requerido") + .max(50, "Máximo 50 caracteres"), postalCode: z.string().regex(/^\d{5}$/u, "Debe tener 5 dígitos"), phone: z.string().regex(/^\d{10}$/u, "Debe tener 10 dígitos"), phoneExtension: z.string().regex(/^\d{0,10}$/u, "Solo dígitos"), @@ -21,9 +44,3 @@ export const customerFormSchema = z.object({ }), type: z.enum(CUSTOMER_TYPES), }); - -// The form keeps "" for empty optional fields; the database stores null. -export const customerInputSchema = customerFormSchema.extend({ - intNumber: emptyToNull(customerFormSchema.shape.intNumber), - phoneExtension: emptyToNull(customerFormSchema.shape.phoneExtension), -}); diff --git a/packages/db/src/validation/shared.ts b/packages/db/src/validation/shared.ts deleted file mode 100644 index 2fe833a..0000000 --- a/packages/db/src/validation/shared.ts +++ /dev/null @@ -1,9 +0,0 @@ -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/db/src/validation/users.ts b/packages/db/src/validation/users.ts new file mode 100644 index 0000000..81edadb --- /dev/null +++ b/packages/db/src/validation/users.ts @@ -0,0 +1,14 @@ +import { z } from "zod"; + +export const USER_ROLES = ["user", "admin"] as const; + +// Shared by the web form and the API, so it must stay free of drizzle imports. +export const userSchema = z.object({ + name: z + .string() + .trim() + .min(5, "El nombre debe tener al menos 5 caracteres") + .max(100, "Máximo 100 caracteres"), + email: z.email("El correo no es válido").toLowerCase(), + role: z.enum(USER_ROLES, { message: "Selecciona un rol" }), +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bbe2aa0..ece20c4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -176,6 +176,9 @@ catalogs: '@orpc/zod': specifier: ^1.15.0 version: 1.15.3 + '@paralleldrive/cuid2': + specifier: ^3.3.0 + version: 3.3.0 '@types/bun': specifier: ^1.4.2 version: 1.4.2 @@ -435,6 +438,9 @@ importers: '@better-auth/drizzle-adapter': specifier: 1.7.5 version: 1.7.5(@better-auth/core@1.7.5(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.2)(better-call@1.4.0(zod@4.6.5))(jose@6.2.12)(kysely@0.29.6)(nanostores@1.5.3))(@better-auth/utils@0.4.2)(drizzle-orm@1.0.0-rc.4(@types/pg@8.23.1)(bun-types@1.4.2)(pg@8.23.0)(zod@4.6.5)) + '@paralleldrive/cuid2': + specifier: 'catalog:' + version: 3.3.0 '@suni/db': specifier: workspace:* version: link:../db @@ -468,6 +474,9 @@ importers: packages/db: dependencies: + '@paralleldrive/cuid2': + specifier: 'catalog:' + version: 3.3.0 drizzle-orm: specifier: 'catalog:' version: 1.0.0-rc.4(@types/pg@8.23.1)(bun-types@1.4.2)(pg@8.23.0)(zod@4.6.5) @@ -1857,6 +1866,10 @@ packages: resolution: {integrity: sha512-qqHqML3ME3cxGgFvWJG8wwMnJc9ol5SMdtqkq0k8r7l0USmC+HRXYjzDacME4Dqkx4yqrUsBhj0JYvji8fHxJQ==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + '@paralleldrive/cuid2@3.3.0': + resolution: {integrity: sha512-OqiFvSOF0dBSesELYY2CAMa4YINvlLpvKOz/rv6NeZEqiyttlHgv98Juwv4Ch+GrEV7IZ8jfI2VcEoYUjXXCjw==} + hasBin: true + '@pkgr/core@0.3.6': resolution: {integrity: sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==} engines: {node: ^14.18.0 || >=16.0.0} @@ -2842,6 +2855,9 @@ packages: zod: optional: true + bignumber.js@9.3.1: + resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==} + body-parser@2.3.0: resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==} engines: {node: '>=18'} @@ -3342,6 +3358,9 @@ packages: resolution: {integrity: sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==} engines: {node: '>=18'} + error-causes@3.0.2: + resolution: {integrity: sha512-i0B8zq1dHL6mM85FGoxaJnVtx6LD5nL2v0hlpGdntg5FOSyzQ46c9lmz5qx0xRS2+PWHGOHcYxGIBC5Le2dRMw==} + error-ex@1.3.4: resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==} @@ -6818,6 +6837,12 @@ snapshots: '@oxlint/plugins@1.85.0': {} + '@paralleldrive/cuid2@3.3.0': + dependencies: + '@noble/hashes': 2.4.0 + bignumber.js: 9.3.1 + error-causes: 3.0.2 + '@pkgr/core@0.3.6': {} '@quansync/fs@1.1.0': @@ -7625,6 +7650,8 @@ snapshots: optionalDependencies: zod: 4.6.5 + bignumber.js@9.3.1: {} + body-parser@2.3.0(supports-color@7.2.0): dependencies: bytes: 3.1.2 @@ -7951,6 +7978,8 @@ snapshots: environment@1.1.0: {} + error-causes@3.0.2: {} + error-ex@1.3.4: dependencies: is-arrayish: 0.2.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index eadc88f..9480aaf 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -25,3 +25,4 @@ catalog: tailwindcss: ^4.3.3 drizzle-orm: 1.0.0-rc.4 evlog: ^2.30.0 + "@paralleldrive/cuid2": ^3.3.0 diff --git a/tools/oxlint/suni/index.ts b/tools/oxlint/suni/index.ts index 8101e93..dfab8b1 100644 --- a/tools/oxlint/suni/index.ts +++ b/tools/oxlint/suni/index.ts @@ -1,10 +1,12 @@ import { definePlugin } from "@oxlint/plugins"; +import requireSellerScope from "./rules/require-seller-scope.ts"; import requireSuppressionReason from "./rules/require-suppression-reason.ts"; export default definePlugin({ meta: { name: "suni" }, rules: { + "require-seller-scope": requireSellerScope, "require-suppression-reason": requireSuppressionReason, }, }); diff --git a/tools/oxlint/suni/rules/require-seller-scope.ts b/tools/oxlint/suni/rules/require-seller-scope.ts new file mode 100644 index 0000000..b821fb3 --- /dev/null +++ b/tools/oxlint/suni/rules/require-seller-scope.ts @@ -0,0 +1,112 @@ +import { defineRule, type ESTree } from "@oxlint/plugins"; + +// Tables whose rows carry the seller; see sellerColumns in packages/api/src/util/scope.ts. +const SELLER_TABLES = new Set(["customer", "branch"]); +const QUERY_METHODS = new Set(["findFirst", "findMany"]); +const ADMIN_ONLY_COLUMNS = new Set(["sellerId", "modifiedBy"]); + +function propertyName(node: ESTree.Node): string | undefined { + if (node.type === "Identifier") return node.name; + if (node.type === "Literal" && typeof node.value === "string") + return node.value; + return undefined; +} + +function findProperty(object: ESTree.ObjectExpression, name: string) { + return object.properties.find( + (property): property is ESTree.ObjectProperty => + property.type === "Property" && propertyName(property.key) === name + ); +} + +function isCallTo(node: ESTree.Node, name: string) { + return ( + node.type === "CallExpression" && + node.callee.type === "Identifier" && + node.callee.name === name + ); +} + +// An explicit allowlist (`{ id: true, name: true }`) never selects columns it does not name. +function isSafeAllowlist(node: ESTree.Node) { + return ( + node.type === "ObjectExpression" && + node.properties.every( + (property) => + property.type === "Property" && + !property.computed && + property.value.type === "Literal" && + property.value.value === true && + !ADMIN_ONLY_COLUMNS.has(propertyName(property.key) ?? "") + ) + ); +} + +// Matches `.query..(...)`. +function sellerTableQuery(callee: ESTree.Node) { + if ( + callee.type !== "MemberExpression" || + !QUERY_METHODS.has(propertyName(callee.property) ?? "") + ) + return undefined; + const table = callee.object; + if ( + table.type !== "MemberExpression" || + table.object.type !== "MemberExpression" || + propertyName(table.object.property) !== "query" + ) + return undefined; + const name = propertyName(table.property); + return name && SELLER_TABLES.has(name) ? name : undefined; +} + +export default defineRule({ + meta: { + type: "problem", + docs: { + description: + "Require customer and branch queries to hide seller identity from non-admins.", + }, + }, + create(context) { + return { + CallExpression(node) { + const table = sellerTableQuery(node.callee); + if (!table) return; + + const [config] = node.arguments; + const columns = + config?.type === "ObjectExpression" + ? findProperty(config, "columns")?.value + : undefined; + + if ( + !columns || + !(isCallTo(columns, "sellerColumns") || isSafeAllowlist(columns)) + ) { + context.report({ + node, + message: `Seller identity is admin-only: pass \`columns: sellerColumns(context)\` to this ${table} query, or list only the columns you need with \`true\`.`, + }); + } + + const relations = + config?.type === "ObjectExpression" + ? findProperty(config, "with")?.value + : undefined; + const seller = + relations?.type === "ObjectExpression" + ? findProperty(relations, "seller") + : undefined; + + if (seller) { + context.report({ + node: seller, + message: + "Seller identity is admin-only: spread `...sellerRelation(context)` instead of loading `seller` directly.", + }); + } + }, + }; + }, +});