From d2d1ebd5c63caaad8413ed4791033c9f0fce85c5 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Mon, 9 Nov 2026 15:33:45 -0600 Subject: [PATCH 01/32] =?UTF-8?q?Guarda=20campos=20opcionales=20vac=C3=ADo?= =?UTF-8?q?s=20como=20""=20en=20lugar=20de=20NULL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Las columnas de texto opcionales de clientes, sucursales y contactos pasan a NOT NULL DEFAULT '', lo que elimina emptyToNull y los esquemas de entrada duplicados. Los esquemas se renombran a customerSchema, branchSchema y contactSchema, se agregan createCustomerSchema y updateCustomerSchema, y cada campo define su propia longitud máxima en lugar del helper required(). --- .../customers/branches/branch-form.tsx | 21 +++----- .../customers/contacts/contact-form.tsx | 19 +++---- .../components/customers/customer-form.tsx | 12 ++--- .../$customerId/branches/$branchId/index.tsx | 2 +- packages/api/src/routers/customers/create.ts | 4 +- packages/api/src/routers/customers/update.ts | 4 +- packages/db/src/schema/branches.ts | 6 +-- packages/db/src/schema/contacts.ts | 4 +- packages/db/src/schema/customers.ts | 4 +- packages/db/src/validation/branches.ts | 52 +++++++++++++------ packages/db/src/validation/contacts.ts | 27 +++++----- packages/db/src/validation/customers.ts | 47 ++++++++++++----- packages/db/src/validation/shared.ts | 9 ---- 13 files changed, 114 insertions(+), 97 deletions(-) delete mode 100644 packages/db/src/validation/shared.ts diff --git a/apps/web/src/components/customers/branches/branch-form.tsx b/apps/web/src/components/customers/branches/branch-form.tsx index 9b8523f..eacf632 100644 --- a/apps/web/src/components/customers/branches/branch-form.tsx +++ b/apps/web/src/components/customers/branches/branch-form.tsx @@ -1,8 +1,5 @@ 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"; @@ -17,7 +14,7 @@ import type { Settlement } from "@/hooks/use-postal-code"; type Branch = AppRouterOutputs["branches"]["list"][number]; -type FormValues = z.input; +type FormValues = z.input; interface BranchFormProps { customerId: string; @@ -54,13 +51,13 @@ 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, }; } @@ -98,18 +95,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?.() } ); } diff --git a/apps/web/src/components/customers/contacts/contact-form.tsx b/apps/web/src/components/customers/contacts/contact-form.tsx index 728e419..797692e 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,7 +10,7 @@ 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; @@ -44,8 +41,8 @@ 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, }; } @@ -64,18 +61,16 @@ 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) { updateContact.mutate( - { id: contact.id, ...parsed }, + { id: contact.id, ...value }, { onSuccess: () => onSuccess?.() } ); } else if (customerId && branchId) { createContact.mutate( - { customerId, branchId, ...parsed }, + { customerId, branchId, ...value }, { onSuccess: () => onSuccess?.() } ); } diff --git a/apps/web/src/components/customers/customer-form.tsx b/apps/web/src/components/customers/customer-form.tsx index 931e8e6..5592e28 100644 --- a/apps/web/src/components/customers/customer-form.tsx +++ b/apps/web/src/components/customers/customer-form.tsx @@ -3,7 +3,7 @@ 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"; @@ -18,7 +18,7 @@ import { useIsAdmin } from "@/hooks/use-is-admin"; import { postalCodeQueryOptions, usePostalCode } from "@/hooks/use-postal-code"; import type { Settlement } from "@/hooks/use-postal-code"; -type FormValues = Omit, "acquisition"> & { +type FormValues = Omit, "acquisition"> & { acquisition: (typeof ACQUISITION_CHANNELS)[number] | ""; }; @@ -59,7 +59,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,7 +68,7 @@ function toFormValues(customer?: CustomerFormProps["customer"]): FormValues { state: customer.state, street: customer.street, extNumber: customer.extNumber, - intNumber: customer.intNumber ?? "", + intNumber: customer.intNumber, }; } @@ -114,9 +114,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( 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..940b0fa 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 @@ -62,7 +62,7 @@ function RouteComponent() { ); const placeholder = "/placeholder.webp"; - const branchImage = branch.frontImageUrl ?? placeholder; + const branchImage = branch.frontImageUrl || placeholder; const content: Record<(typeof TABS)[number]["value"], ReactNode> = { info: ( diff --git a/packages/api/src/routers/customers/create.ts b/packages/api/src/routers/customers/create.ts index d39f618..f3cf58a 100644 --- a/packages/api/src/routers/customers/create.ts +++ b/packages/api/src/routers/customers/create.ts @@ -1,11 +1,11 @@ import { customer } from "@suni/db/schema/customers"; -import { customerInputSchema } from "@suni/db/validation/customers"; +import { createCustomerSchema } from "@suni/db/validation/customers"; import { isAdmin, protectedProcedure } from "../../index"; export const create = protectedProcedure .route({ method: "POST", path: "/" }) - .input(customerInputSchema) + .input(createCustomerSchema) .handler(async ({ input, context }) => { const userId = context.session.user.id; diff --git a/packages/api/src/routers/customers/update.ts b/packages/api/src/routers/customers/update.ts index bee3e82..9196723 100644 --- a/packages/api/src/routers/customers/update.ts +++ b/packages/api/src/routers/customers/update.ts @@ -1,6 +1,6 @@ import { ORPCError } from "@orpc/server"; import { customer } from "@suni/db/schema/customers"; -import { customerInputSchema } from "@suni/db/validation/customers"; +import { updateCustomerSchema } from "@suni/db/validation/customers"; import { and, eq, isNull } from "drizzle-orm"; import { z } from "zod"; @@ -8,7 +8,7 @@ import { isAdmin, protectedProcedure } from "../../index"; export const update = protectedProcedure .route({ method: "PATCH", path: "/{id}" }) - .input(customerInputSchema.partial().extend({ id: z.string() })) + .input(updateCustomerSchema.extend({ id: z.string() })) .handler(async ({ input, context }) => { const { id, type, ...fields } = input; diff --git a/packages/db/src/schema/branches.ts b/packages/db/src/schema/branches.ts index 376ab14..6759aff 100644 --- a/packages/db/src/schema/branches.ts +++ b/packages/db/src/schema/branches.ts @@ -9,14 +9,14 @@ export const branch = pgTable("customer_branches", { .$defaultFn(() => crypto.randomUUID()), 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..0937ea9 100644 --- a/packages/db/src/schema/contacts.ts +++ b/packages/db/src/schema/contacts.ts @@ -11,8 +11,8 @@ export const contact = pgTable("contact", { 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), diff --git a/packages/db/src/schema/customers.ts b/packages/db/src/schema/customers.ts index 6f7b990..490b650 100644 --- a/packages/db/src/schema/customers.ts +++ b/packages/db/src/schema/customers.ts @@ -14,14 +14,14 @@ export const customer = pgTable("customer", { 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/validation/branches.ts b/packages/db/src/validation/branches.ts index 639ced6..8f672aa 100644 --- a/packages/db/src/validation/branches.ts +++ b/packages/db/src/validation/branches.ts @@ -1,30 +1,48 @@ 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 = branchSchema.extend({ + customerId: z.string().min(1, "El cliente es requerido"), }); -export const createBranchSchema = branchInputSchema.extend({ - customerId: required("El cliente es requerido"), -}); - -export const updateBranchSchema = branchInputSchema.partial().extend({ +export const updateBranchSchema = branchSchema.partial().extend({ archived: z.coerce.date().nullable().optional(), }); diff --git a/packages/db/src/validation/contacts.ts b/packages/db/src/validation/contacts.ts index 4008fc5..5eb9458 100644 --- a/packages/db/src/validation/contacts.ts +++ b/packages/db/src/validation/contacts.ts @@ -1,26 +1,23 @@ 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), + position: z.string().trim().max(100, "Máximo 100 caracteres"), }); -export const createContactSchema = contactInputSchema.extend({ - customerId: required("El cliente es requerido"), - branchId: required("La sucursal es requerida"), +export const createContactSchema = contactSchema.extend({ + customerId: z.string().min(1, "El cliente es requerido"), + branchId: z.string().min(1, "La sucursal es requerida"), }); -export const updateContactSchema = contactInputSchema.partial().extend({ - customerId: required("El cliente es requerido").optional(), +export const updateContactSchema = contactSchema.partial().extend({ + customerId: z.string().min(1, "El cliente es requerido").optional(), archived: z.coerce.date().nullable().optional(), }); diff --git a/packages/db/src/validation/customers.ts b/packages/db/src/validation/customers.ts index 4d1b9b4..2b4c616 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"), @@ -22,8 +45,6 @@ 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), -}); +export const createCustomerSchema = customerSchema; + +export const updateCustomerSchema = customerSchema.partial(); 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); -} From 7afa36ed7a735c428060fd90a6e422db647caefe Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Mon, 9 Nov 2026 15:36:58 -0600 Subject: [PATCH 02/32] =?UTF-8?q?Agrega=20migraci=C3=B3n=20para=20guardar?= =?UTF-8?q?=20campos=20opcionales=20vac=C3=ADos=20como=20""?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migration.sql | 14 + .../snapshot.json | 1532 +++++++++++++++++ 2 files changed, 1546 insertions(+) create mode 100644 packages/db/src/migrations/20261109213441_regular_luckman/migration.sql create mode 100644 packages/db/src/migrations/20261109213441_regular_luckman/snapshot.json 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 From cbf60d60a8fe60a1d5bd04c8759f06c9b1cb52b0 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Mon, 9 Nov 2026 16:52:49 -0600 Subject: [PATCH 03/32] Resuelve el rol una vez por request con scopedProcedure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El middleware consulta el rol en la base de datos e inyecta context.userId y context.admin, así los handlers de clientes, sucursales y contactos dejan de llamar a isAdmin. adminProcedure se construye sobre él e isAdmin deja de exportarse. --- packages/api/AGENTS.md | 2 +- packages/api/src/index.ts | 21 +++++++++++++------ packages/api/src/routers/branches/get.ts | 8 +++---- packages/api/src/routers/branches/list.ts | 8 +++---- .../api/src/routers/branches/set-archived.ts | 7 +++---- packages/api/src/routers/branches/update.ts | 8 +++---- packages/api/src/routers/contacts/create.ts | 7 +++---- packages/api/src/routers/contacts/get.ts | 7 +++---- packages/api/src/routers/contacts/list.ts | 9 ++++---- .../api/src/routers/contacts/set-archived.ts | 7 +++---- packages/api/src/routers/contacts/update.ts | 8 +++---- packages/api/src/routers/customers/create.ts | 8 +++---- packages/api/src/routers/customers/get.ts | 6 +++--- packages/api/src/routers/customers/list.ts | 6 +++--- packages/api/src/routers/customers/update.ts | 10 ++++----- 15 files changed, 60 insertions(+), 62 deletions(-) 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..242e4e5 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -22,7 +22,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 +32,21 @@ 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"); + } + + return next(); +}); diff --git a/packages/api/src/routers/branches/get.ts b/packages/api/src/routers/branches/get.ts index c72e0f9..6079a1a 100644 --- a/packages/api/src/routers/branches/get.ts +++ b/packages/api/src/routers/branches/get.ts @@ -1,18 +1,18 @@ import { ORPCError } from "@orpc/server"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; -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); + const { admin } = context; const found = await context.db.query.branch.findFirst({ where: admin ? { id: input.id } - : { id: input.id, sellerId: context.session.user.id }, + : { id: input.id, sellerId: context.userId }, columns: admin ? undefined : { sellerId: false, modifiedBy: false }, with: { customer: { columns: { id: true, name: true, archived: true } }, diff --git a/packages/api/src/routers/branches/list.ts b/packages/api/src/routers/branches/list.ts index cf4990c..e469406 100644 --- a/packages/api/src/routers/branches/list.ts +++ b/packages/api/src/routers/branches/list.ts @@ -1,10 +1,10 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; import { statusWhere } from "../../util/status"; -export const list = protectedProcedure +export const list = scopedProcedure .route({ method: "GET", path: "/" }) .input( z.object({ @@ -13,7 +13,7 @@ export const list = protectedProcedure }) ) .handler(async ({ input, context }) => { - const userId = context.session.user.id; + const { userId } = context; const where = { AND: [ @@ -22,7 +22,7 @@ export const list = protectedProcedure ], }; - if (await isAdmin(context, userId)) { + if (context.admin) { return context.db.query.branch.findMany({ where, with: { diff --git a/packages/api/src/routers/branches/set-archived.ts b/packages/api/src/routers/branches/set-archived.ts index 0339bee..cd57915 100644 --- a/packages/api/src/routers/branches/set-archived.ts +++ b/packages/api/src/routers/branches/set-archived.ts @@ -3,14 +3,13 @@ import { branch } from "@suni/db/schema/branches"; import { and, eq, sql } from "drizzle-orm"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; -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); + const { userId, admin } = context; const [updated] = await context.db .update(branch) diff --git a/packages/api/src/routers/branches/update.ts b/packages/api/src/routers/branches/update.ts index 43c8152..d0dbc11 100644 --- a/packages/api/src/routers/branches/update.ts +++ b/packages/api/src/routers/branches/update.ts @@ -4,15 +4,15 @@ import { updateBranchSchema } from "@suni/db/validation/branches"; import { and, eq, isNull } from "drizzle-orm"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; -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 }) => { const { id, ...fields } = input; - const userId = context.session.user.id; + const { userId, admin } = context; if (Object.values(fields).every((v) => v === undefined)) { throw new ORPCError("BAD_REQUEST", { @@ -20,8 +20,6 @@ export const update = protectedProcedure }); } - const admin = await isAdmin(context, userId); - const [updated] = await context.db .update(branch) .set({ ...fields, modifiedBy: userId }) diff --git a/packages/api/src/routers/contacts/create.ts b/packages/api/src/routers/contacts/create.ts index 9f3e56f..4d42a5e 100644 --- a/packages/api/src/routers/contacts/create.ts +++ b/packages/api/src/routers/contacts/create.ts @@ -2,14 +2,13 @@ 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"; -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); + const { userId, admin } = context; const parent = await context.db.query.branch.findFirst({ where: { diff --git a/packages/api/src/routers/contacts/get.ts b/packages/api/src/routers/contacts/get.ts index 4a2cc90..f0bf4a2 100644 --- a/packages/api/src/routers/contacts/get.ts +++ b/packages/api/src/routers/contacts/get.ts @@ -1,14 +1,13 @@ import { ORPCError } from "@orpc/server"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; -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); + const { userId, admin } = context; const found = await context.db.query.contact.findFirst({ where: { diff --git a/packages/api/src/routers/contacts/list.ts b/packages/api/src/routers/contacts/list.ts index a81448d..73a2eaa 100644 --- a/packages/api/src/routers/contacts/list.ts +++ b/packages/api/src/routers/contacts/list.ts @@ -1,10 +1,10 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; import { statusWhere } from "../../util/status"; -export const list = protectedProcedure +export const list = scopedProcedure .route({ method: "GET", path: "/" }) .input( z.object({ @@ -13,9 +13,8 @@ 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); + .handler(({ input, context }) => { + const { userId, admin } = context; return context.db.query.contact.findMany({ where: { diff --git a/packages/api/src/routers/contacts/set-archived.ts b/packages/api/src/routers/contacts/set-archived.ts index 29fc631..136e5f1 100644 --- a/packages/api/src/routers/contacts/set-archived.ts +++ b/packages/api/src/routers/contacts/set-archived.ts @@ -4,14 +4,13 @@ import { contact } from "@suni/db/schema/contacts"; import { and, eq, inArray, sql } from "drizzle-orm"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; -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); + const { userId, admin } = context; const [updated] = await context.db .update(contact) diff --git a/packages/api/src/routers/contacts/update.ts b/packages/api/src/routers/contacts/update.ts index 74e1a2f..dd50260 100644 --- a/packages/api/src/routers/contacts/update.ts +++ b/packages/api/src/routers/contacts/update.ts @@ -5,9 +5,9 @@ import { updateContactSchema } 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"; -export const update = protectedProcedure +export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) .input( updateContactSchema @@ -16,7 +16,7 @@ export const update = protectedProcedure ) .handler(async ({ input, context }) => { const { id, ...fields } = input; - const userId = context.session.user.id; + const { userId, admin } = context; if (Object.values(fields).every((v) => v === undefined)) { throw new ORPCError("BAD_REQUEST", { @@ -24,8 +24,6 @@ export const update = protectedProcedure }); } - const admin = await isAdmin(context, userId); - const [updated] = await context.db .update(contact) .set({ ...fields, modifiedBy: userId }) diff --git a/packages/api/src/routers/customers/create.ts b/packages/api/src/routers/customers/create.ts index f3cf58a..536ad84 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 { createCustomerSchema } 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(createCustomerSchema) .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..e0d8ade 100644 --- a/packages/api/src/routers/customers/get.ts +++ b/packages/api/src/routers/customers/get.ts @@ -1,19 +1,19 @@ import { ORPCError } from "@orpc/server"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; 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)) { + if (context.admin) { const found = await context.db.query.customer.findFirst({ where, with: { seller: { columns: { id: true, name: true } } }, diff --git a/packages/api/src/routers/customers/list.ts b/packages/api/src/routers/customers/list.ts index 7f651ee..8684269 100644 --- a/packages/api/src/routers/customers/list.ts +++ b/packages/api/src/routers/customers/list.ts @@ -1,21 +1,21 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; -import { isAdmin, protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; 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)) { + if (context.admin) { return context.db.query.customer.findMany({ where, with: { seller: { columns: { id: true, name: true } } }, diff --git a/packages/api/src/routers/customers/update.ts b/packages/api/src/routers/customers/update.ts index 9196723..a240c30 100644 --- a/packages/api/src/routers/customers/update.ts +++ b/packages/api/src/routers/customers/update.ts @@ -4,19 +4,17 @@ import { updateCustomerSchema } 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"; -export const update = protectedProcedure +export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) .input(updateCustomerSchema.extend({ id: z.string() })) .handler(async ({ input, context }) => { const { id, type, ...fields } = input; - const userId = context.session.user.id; + const { userId } = context; - const data = (await isAdmin(context, userId)) - ? { ...fields, type } - : fields; + const data = context.admin ? { ...fields, type } : fields; if (Object.values(data).every((v) => v === undefined)) { throw new ORPCError("BAD_REQUEST", { From d9f2c681a972748f3c145b0700b78d33984222a5 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Mon, 9 Nov 2026 17:07:55 -0600 Subject: [PATCH 04/32] =?UTF-8?q?Centraliza=20el=20filtro=20de=20due=C3=B1?= =?UTF-8?q?o=20de=20sucursales=20y=20contactos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Los helpers de util/scope.ts definen en un solo lugar que un vendedor solo alcanza sus sucursales y los contactos que cuelgan de ellas, en forma de filtro relacional y de SQL para los updates. Los handlers dejan de repetir la condición y la subconsulta de contactos. --- packages/api/src/routers/branches/get.ts | 5 +-- packages/api/src/routers/branches/list.ts | 6 +-- .../api/src/routers/branches/set-archived.ts | 9 ++--- packages/api/src/routers/branches/update.ts | 9 ++--- packages/api/src/routers/contacts/create.ts | 5 ++- packages/api/src/routers/contacts/get.ts | 8 ++-- packages/api/src/routers/contacts/list.ts | 15 ++++---- .../api/src/routers/contacts/set-archived.ts | 21 ++--------- packages/api/src/routers/contacts/update.ts | 16 ++------ packages/api/src/util/scope.ts | 37 +++++++++++++++++++ 10 files changed, 69 insertions(+), 62 deletions(-) create mode 100644 packages/api/src/util/scope.ts diff --git a/packages/api/src/routers/branches/get.ts b/packages/api/src/routers/branches/get.ts index 6079a1a..25ca39e 100644 --- a/packages/api/src/routers/branches/get.ts +++ b/packages/api/src/routers/branches/get.ts @@ -2,6 +2,7 @@ import { ORPCError } from "@orpc/server"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownBranches } from "../../util/scope"; export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) @@ -10,9 +11,7 @@ export const get = scopedProcedure const { admin } = context; const found = await context.db.query.branch.findFirst({ - where: admin - ? { id: input.id } - : { id: input.id, sellerId: context.userId }, + where: { id: input.id, ...ownBranches(context) }, columns: admin ? undefined : { sellerId: false, modifiedBy: false }, with: { customer: { columns: { id: true, name: true, archived: true } }, diff --git a/packages/api/src/routers/branches/list.ts b/packages/api/src/routers/branches/list.ts index e469406..092d626 100644 --- a/packages/api/src/routers/branches/list.ts +++ b/packages/api/src/routers/branches/list.ts @@ -2,6 +2,7 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownBranches } from "../../util/scope"; import { statusWhere } from "../../util/status"; export const list = scopedProcedure @@ -13,11 +14,10 @@ export const list = scopedProcedure }) ) .handler(async ({ input, context }) => { - const { userId } = context; - const where = { AND: [ statusWhere("branch", input.status), + ownBranches(context), ...(input.customerId ? [{ customerId: input.customerId }] : []), ], }; @@ -35,7 +35,7 @@ export const list = scopedProcedure // Seller identity is admin-only. const rows = await context.db.query.branch.findMany({ - where: { AND: [where, { sellerId: userId }] }, + where, columns: { sellerId: false, modifiedBy: false }, with: { customer: { columns: { id: true, name: true, archived: true } }, diff --git a/packages/api/src/routers/branches/set-archived.ts b/packages/api/src/routers/branches/set-archived.ts index cd57915..9539f4a 100644 --- a/packages/api/src/routers/branches/set-archived.ts +++ b/packages/api/src/routers/branches/set-archived.ts @@ -4,12 +4,13 @@ import { and, eq, sql } from "drizzle-orm"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownBranchesSql } from "../../util/scope"; 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, admin } = context; + const { userId } = context; const [updated] = await context.db .update(branch) @@ -19,11 +20,7 @@ export const setArchived = scopedProcedure : null, modifiedBy: userId, }) - .where( - admin - ? eq(branch.id, input.id) - : and(eq(branch.id, input.id), eq(branch.sellerId, userId)) - ) + .where(and(eq(branch.id, input.id), ownBranchesSql(context))) .returning({ id: branch.id }); if (!updated) { diff --git a/packages/api/src/routers/branches/update.ts b/packages/api/src/routers/branches/update.ts index d0dbc11..e15541c 100644 --- a/packages/api/src/routers/branches/update.ts +++ b/packages/api/src/routers/branches/update.ts @@ -5,6 +5,7 @@ import { and, eq, isNull } from "drizzle-orm"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownBranchesSql } from "../../util/scope"; export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) @@ -12,7 +13,7 @@ export const update = scopedProcedure .handler(async ({ input, context }) => { const { id, ...fields } = input; - const { userId, admin } = context; + const { userId } = context; if (Object.values(fields).every((v) => v === undefined)) { throw new ORPCError("BAD_REQUEST", { @@ -24,11 +25,7 @@ export const update = scopedProcedure .update(branch) .set({ ...fields, modifiedBy: userId }) .where( - and( - eq(branch.id, id), - isNull(branch.archived), - admin ? undefined : eq(branch.sellerId, userId) - ) + and(eq(branch.id, id), isNull(branch.archived), ownBranchesSql(context)) ) .returning({ id: branch.id }); diff --git a/packages/api/src/routers/contacts/create.ts b/packages/api/src/routers/contacts/create.ts index 4d42a5e..3ce1ef3 100644 --- a/packages/api/src/routers/contacts/create.ts +++ b/packages/api/src/routers/contacts/create.ts @@ -3,19 +3,20 @@ import { contact } from "@suni/db/schema/contacts"; import { createContactSchema } from "@suni/db/validation/contacts"; import { scopedProcedure } from "../../index"; +import { ownBranches } from "../../util/scope"; export const create = scopedProcedure .route({ method: "POST", path: "/" }) .input(createContactSchema) .handler(async ({ input, context }) => { - const { userId, admin } = context; + 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, + ...ownBranches(context), }, columns: { id: true }, }); diff --git a/packages/api/src/routers/contacts/get.ts b/packages/api/src/routers/contacts/get.ts index f0bf4a2..9396b17 100644 --- a/packages/api/src/routers/contacts/get.ts +++ b/packages/api/src/routers/contacts/get.ts @@ -2,18 +2,16 @@ import { ORPCError } from "@orpc/server"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownContacts } from "../../util/scope"; export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) .handler(async ({ input, context }) => { - const { userId, admin } = context; + 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 } }, diff --git a/packages/api/src/routers/contacts/list.ts b/packages/api/src/routers/contacts/list.ts index 73a2eaa..4fad244 100644 --- a/packages/api/src/routers/contacts/list.ts +++ b/packages/api/src/routers/contacts/list.ts @@ -2,6 +2,7 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownContacts } from "../../util/scope"; import { statusWhere } from "../../util/status"; export const list = scopedProcedure @@ -13,21 +14,19 @@ export const list = scopedProcedure status: z.enum(CUSTOMER_STATUSES).default("active"), }) ) - .handler(({ input, context }) => { - const { userId, admin } = context; - - 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 136e5f1..550a267 100644 --- a/packages/api/src/routers/contacts/set-archived.ts +++ b/packages/api/src/routers/contacts/set-archived.ts @@ -1,16 +1,16 @@ 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, sql } from "drizzle-orm"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownContactsSql } from "../../util/scope"; 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, admin } = context; + const { userId } = context; const [updated] = await context.db .update(contact) @@ -20,20 +20,7 @@ export const setArchived = scopedProcedure : null, modifiedBy: userId, }) - .where( - and( - eq(contact.id, input.id), - admin - ? undefined - : inArray( - contact.branchId, - context.db - .select({ id: branch.id }) - .from(branch) - .where(eq(branch.sellerId, userId)) - ) - ) - ) + .where(and(eq(contact.id, input.id), ownContactsSql(context))) .returning({ id: contact.id }); if (!updated) { diff --git a/packages/api/src/routers/contacts/update.ts b/packages/api/src/routers/contacts/update.ts index dd50260..d8dc681 100644 --- a/packages/api/src/routers/contacts/update.ts +++ b/packages/api/src/routers/contacts/update.ts @@ -1,11 +1,11 @@ import { ORPCError } from "@orpc/server"; -import { branch } from "@suni/db/schema/branches"; import { contact } from "@suni/db/schema/contacts"; import { updateContactSchema } from "@suni/db/validation/contacts"; -import { and, eq, inArray, isNull } from "drizzle-orm"; +import { and, eq, isNull } from "drizzle-orm"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownContactsSql } from "../../util/scope"; export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) @@ -16,7 +16,7 @@ export const update = scopedProcedure ) .handler(async ({ input, context }) => { const { id, ...fields } = input; - const { userId, admin } = context; + const { userId } = context; if (Object.values(fields).every((v) => v === undefined)) { throw new ORPCError("BAD_REQUEST", { @@ -31,15 +31,7 @@ export const update = scopedProcedure 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)) - ) + ownContactsSql(context) ) ) .returning({ id: contact.id }); diff --git a/packages/api/src/util/scope.ts b/packages/api/src/util/scope.ts new file mode 100644 index 0000000..0bd5a28 --- /dev/null +++ b/packages/api/src/util/scope.ts @@ -0,0 +1,37 @@ +import { branch } from "@suni/db/schema/branches"; +import { contact } from "@suni/db/schema/contacts"; +import { eq, inArray } from "drizzle-orm"; + +import type { Context } from "../context"; + +interface Scope extends Pick { + admin: boolean; + userId: string; +} + +// Non-admins only reach the 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 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)) + ); +} From 6082fe302d207d7603bd5ef4d4dc3c8783c00cad Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Mon, 9 Nov 2026 17:07:57 -0600 Subject: [PATCH 05/32] =?UTF-8?q?Aplica=20la=20regla=20de=20due=C3=B1o=20a?= =?UTF-8?q?=20clientes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Un vendedor solo ve, edita y archiva los clientes que tienen su sellerId, y solo puede crear sucursales bajo un cliente propio y no archivado. --- packages/api/src/routers/branches/create.ts | 23 ++++++++++++++++--- packages/api/src/routers/customers/get.ts | 3 ++- packages/api/src/routers/customers/list.ts | 9 ++++++-- .../api/src/routers/customers/set-archived.ts | 11 +++++---- packages/api/src/routers/customers/update.ts | 9 +++++++- packages/api/src/util/scope.ts | 11 ++++++++- 6 files changed, 53 insertions(+), 13 deletions(-) diff --git a/packages/api/src/routers/branches/create.ts b/packages/api/src/routers/branches/create.ts index 1a586ee..be53e57 100644 --- a/packages/api/src/routers/branches/create.ts +++ b/packages/api/src/routers/branches/create.ts @@ -1,13 +1,30 @@ +import { ORPCError } from "@orpc/server"; 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"; -export const create = protectedProcedure +export const create = scopedProcedure .route({ method: "POST", path: "/" }) .input(createBranchSchema) .handler(async ({ input, context }) => { - const userId = context.session.user.id; + const { userId } = context; + + const parent = await context.db.query.customer.findFirst({ + where: { + id: input.customerId, + archived: { isNull: true }, + ...ownCustomers(context), + }, + columns: { id: true }, + }); + + if (!parent) { + throw new ORPCError("NOT_FOUND", { + message: "El cliente no existe o está archivado", + }); + } const [created] = await context.db .insert(branch) diff --git a/packages/api/src/routers/customers/get.ts b/packages/api/src/routers/customers/get.ts index e0d8ade..045b1cc 100644 --- a/packages/api/src/routers/customers/get.ts +++ b/packages/api/src/routers/customers/get.ts @@ -2,6 +2,7 @@ import { ORPCError } from "@orpc/server"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownCustomers } from "../../util/scope"; function notFound() { return new ORPCError("NOT_FOUND", { message: "Customer not found" }); @@ -11,7 +12,7 @@ export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) .handler(async ({ input, context }) => { - const where = { id: input.id }; + const where = { id: input.id, ...ownCustomers(context) }; if (context.admin) { const found = await context.db.query.customer.findFirst({ diff --git a/packages/api/src/routers/customers/list.ts b/packages/api/src/routers/customers/list.ts index 8684269..411ce37 100644 --- a/packages/api/src/routers/customers/list.ts +++ b/packages/api/src/routers/customers/list.ts @@ -2,6 +2,7 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownCustomers } from "../../util/scope"; const statusFilters = { active: { archived: { isNull: true } }, @@ -12,8 +13,12 @@ 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]; + const where = { + AND: [ + input.status === "all" ? {} : statusFilters[input.status], + ownCustomers(context), + ], + }; if (context.admin) { return context.db.query.customer.findMany({ diff --git a/packages/api/src/routers/customers/set-archived.ts b/packages/api/src/routers/customers/set-archived.ts index 0bf4782..45c7df4 100644 --- a/packages/api/src/routers/customers/set-archived.ts +++ b/packages/api/src/routers/customers/set-archived.ts @@ -1,11 +1,12 @@ import { ORPCError } from "@orpc/server"; import { customer } from "@suni/db/schema/customers"; -import { eq, sql } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { z } from "zod"; -import { protectedProcedure } from "../../index"; +import { scopedProcedure } from "../../index"; +import { ownCustomersSql } from "../../util/scope"; -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 }) => { @@ -17,9 +18,9 @@ export const setArchived = protectedProcedure archived: input.archived ? sql`COALESCE(${customer.archived}, now())` : null, - modifiedBy: context.session.user.id, + modifiedBy: context.userId, }) - .where(eq(customer.id, input.id)) + .where(and(eq(customer.id, input.id), ownCustomersSql(context))) .returning({ id: customer.id }); if (!updated) { diff --git a/packages/api/src/routers/customers/update.ts b/packages/api/src/routers/customers/update.ts index a240c30..003dfcc 100644 --- a/packages/api/src/routers/customers/update.ts +++ b/packages/api/src/routers/customers/update.ts @@ -5,6 +5,7 @@ import { and, eq, isNull } from "drizzle-orm"; import { z } from "zod"; import { scopedProcedure } from "../../index"; +import { ownCustomersSql } from "../../util/scope"; export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) @@ -26,7 +27,13 @@ export const update = scopedProcedure .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) { diff --git a/packages/api/src/util/scope.ts b/packages/api/src/util/scope.ts index 0bd5a28..223cd96 100644 --- a/packages/api/src/util/scope.ts +++ b/packages/api/src/util/scope.ts @@ -1,5 +1,6 @@ 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"; @@ -9,9 +10,17 @@ interface Scope extends Pick { userId: string; } -// Non-admins only reach the branches they sell and the contacts under them. +// 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 }; } From 35bdd07011392fd371d7b32cdd4cb8366b24864e Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Mon, 9 Nov 2026 17:26:31 -0600 Subject: [PATCH 06/32] =?UTF-8?q?Declara=20NOT=5FFOUND=20como=20error=20ti?= =?UTF-8?q?pado=20con=20mensajes=20en=20espa=C3=B1ol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La base de los procedures define NOT_FOUND con .errors(), así el cliente recibe un error definido, y los handlers lo lanzan con errors.NOT_FOUND. Los mensajes que seguían en inglés pasan a español, igual que los de UNAUTHORIZED y FORBIDDEN. --- packages/api/src/index.ts | 12 +++++++++--- packages/api/src/routers/branches/create.ts | 5 ++--- packages/api/src/routers/branches/get.ts | 5 ++--- packages/api/src/routers/branches/set-archived.ts | 5 ++--- packages/api/src/routers/branches/update.ts | 4 ++-- packages/api/src/routers/contacts/create.ts | 5 ++--- packages/api/src/routers/contacts/get.ts | 5 ++--- packages/api/src/routers/contacts/set-archived.ts | 5 ++--- packages/api/src/routers/contacts/update.ts | 4 ++-- packages/api/src/routers/customers/get.ts | 11 +++-------- packages/api/src/routers/customers/set-archived.ts | 5 ++--- packages/api/src/routers/customers/update.ts | 4 ++-- packages/api/src/routers/users/get.ts | 5 ++--- 13 files changed, 34 insertions(+), 41 deletions(-) diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 242e4e5..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({ @@ -45,7 +49,9 @@ export const scopedProcedure = protectedProcedure.use( export const adminProcedure = scopedProcedure.use(({ context, next }) => { if (!context.admin) { - throw new ORPCError("FORBIDDEN"); + 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 be53e57..a04c578 100644 --- a/packages/api/src/routers/branches/create.ts +++ b/packages/api/src/routers/branches/create.ts @@ -1,4 +1,3 @@ -import { ORPCError } from "@orpc/server"; import { branch } from "@suni/db/schema/branches"; import { createBranchSchema } from "@suni/db/validation/branches"; @@ -8,7 +7,7 @@ import { ownCustomers } from "../../util/scope"; export const create = scopedProcedure .route({ method: "POST", path: "/" }) .input(createBranchSchema) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const { userId } = context; const parent = await context.db.query.customer.findFirst({ @@ -21,7 +20,7 @@ export const create = scopedProcedure }); if (!parent) { - throw new ORPCError("NOT_FOUND", { + throw errors.NOT_FOUND({ message: "El cliente no existe o está archivado", }); } diff --git a/packages/api/src/routers/branches/get.ts b/packages/api/src/routers/branches/get.ts index 25ca39e..35e7967 100644 --- a/packages/api/src/routers/branches/get.ts +++ b/packages/api/src/routers/branches/get.ts @@ -1,4 +1,3 @@ -import { ORPCError } from "@orpc/server"; import { z } from "zod"; import { scopedProcedure } from "../../index"; @@ -7,7 +6,7 @@ import { ownBranches } from "../../util/scope"; export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const { admin } = context; const found = await context.db.query.branch.findFirst({ @@ -21,7 +20,7 @@ export const get = scopedProcedure }); 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 }; diff --git a/packages/api/src/routers/branches/set-archived.ts b/packages/api/src/routers/branches/set-archived.ts index 9539f4a..c66c6e3 100644 --- a/packages/api/src/routers/branches/set-archived.ts +++ b/packages/api/src/routers/branches/set-archived.ts @@ -1,4 +1,3 @@ -import { ORPCError } from "@orpc/server"; import { branch } from "@suni/db/schema/branches"; import { and, eq, sql } from "drizzle-orm"; import { z } from "zod"; @@ -9,7 +8,7 @@ import { ownBranchesSql } from "../../util/scope"; export const setArchived = scopedProcedure .route({ method: "POST", path: "/{id}/archived" }) .input(z.object({ id: z.string(), archived: z.boolean() })) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const { userId } = context; const [updated] = await context.db @@ -24,7 +23,7 @@ export const setArchived = scopedProcedure .returning({ id: branch.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { message: "Branch not found" }); + throw errors.NOT_FOUND({ message: "La sucursal no existe" }); } return updated; diff --git a/packages/api/src/routers/branches/update.ts b/packages/api/src/routers/branches/update.ts index e15541c..99faf99 100644 --- a/packages/api/src/routers/branches/update.ts +++ b/packages/api/src/routers/branches/update.ts @@ -10,7 +10,7 @@ import { ownBranchesSql } from "../../util/scope"; export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) .input(updateBranchSchema.omit({ archived: true }).extend({ id: z.string() })) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const { id, ...fields } = input; const { userId } = context; @@ -30,7 +30,7 @@ export const update = scopedProcedure .returning({ id: branch.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { + throw errors.NOT_FOUND({ message: "La sucursal no existe o está archivada", }); } diff --git a/packages/api/src/routers/contacts/create.ts b/packages/api/src/routers/contacts/create.ts index 3ce1ef3..9708dae 100644 --- a/packages/api/src/routers/contacts/create.ts +++ b/packages/api/src/routers/contacts/create.ts @@ -1,4 +1,3 @@ -import { ORPCError } from "@orpc/server"; import { contact } from "@suni/db/schema/contacts"; import { createContactSchema } from "@suni/db/validation/contacts"; @@ -8,7 +7,7 @@ import { ownBranches } from "../../util/scope"; export const create = scopedProcedure .route({ method: "POST", path: "/" }) .input(createContactSchema) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const { userId } = context; const parent = await context.db.query.branch.findFirst({ @@ -22,7 +21,7 @@ export const create = scopedProcedure }); if (!parent) { - throw new ORPCError("NOT_FOUND", { + throw errors.NOT_FOUND({ message: "La sucursal no existe, está archivada o no pertenece al cliente", }); diff --git a/packages/api/src/routers/contacts/get.ts b/packages/api/src/routers/contacts/get.ts index 9396b17..7b08589 100644 --- a/packages/api/src/routers/contacts/get.ts +++ b/packages/api/src/routers/contacts/get.ts @@ -1,4 +1,3 @@ -import { ORPCError } from "@orpc/server"; import { z } from "zod"; import { scopedProcedure } from "../../index"; @@ -7,7 +6,7 @@ import { ownContacts } from "../../util/scope"; export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const { admin } = context; const found = await context.db.query.contact.findFirst({ @@ -20,7 +19,7 @@ export const get = scopedProcedure }); 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/set-archived.ts b/packages/api/src/routers/contacts/set-archived.ts index 550a267..1f9ba6a 100644 --- a/packages/api/src/routers/contacts/set-archived.ts +++ b/packages/api/src/routers/contacts/set-archived.ts @@ -1,4 +1,3 @@ -import { ORPCError } from "@orpc/server"; import { contact } from "@suni/db/schema/contacts"; import { and, eq, sql } from "drizzle-orm"; import { z } from "zod"; @@ -9,7 +8,7 @@ import { ownContactsSql } from "../../util/scope"; export const setArchived = scopedProcedure .route({ method: "POST", path: "/{id}/archived" }) .input(z.object({ id: z.string(), archived: z.boolean() })) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const { userId } = context; const [updated] = await context.db @@ -24,7 +23,7 @@ export const setArchived = scopedProcedure .returning({ id: contact.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { message: "Contact not found" }); + throw errors.NOT_FOUND({ message: "El contacto no existe" }); } return updated; diff --git a/packages/api/src/routers/contacts/update.ts b/packages/api/src/routers/contacts/update.ts index d8dc681..207f742 100644 --- a/packages/api/src/routers/contacts/update.ts +++ b/packages/api/src/routers/contacts/update.ts @@ -14,7 +14,7 @@ export const update = scopedProcedure .omit({ archived: true, customerId: true }) .extend({ id: z.string() }) ) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const { id, ...fields } = input; const { userId } = context; @@ -37,7 +37,7 @@ export const update = scopedProcedure .returning({ id: contact.id }); if (!updated) { - throw new ORPCError("NOT_FOUND", { + throw errors.NOT_FOUND({ message: "El contacto no existe o está archivado", }); } diff --git a/packages/api/src/routers/customers/get.ts b/packages/api/src/routers/customers/get.ts index 045b1cc..207ba93 100644 --- a/packages/api/src/routers/customers/get.ts +++ b/packages/api/src/routers/customers/get.ts @@ -1,17 +1,12 @@ -import { ORPCError } from "@orpc/server"; import { z } from "zod"; import { scopedProcedure } from "../../index"; import { ownCustomers } from "../../util/scope"; -function notFound() { - return new ORPCError("NOT_FOUND", { message: "Customer not found" }); -} - export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const where = { id: input.id, ...ownCustomers(context) }; if (context.admin) { @@ -21,7 +16,7 @@ export const get = scopedProcedure }); if (!found) { - throw notFound(); + throw errors.NOT_FOUND({ message: "El cliente no existe" }); } return found; @@ -34,7 +29,7 @@ export const get = scopedProcedure }); if (!found) { - throw notFound(); + throw errors.NOT_FOUND({ message: "El cliente no existe" }); } return { ...found, seller: null }; diff --git a/packages/api/src/routers/customers/set-archived.ts b/packages/api/src/routers/customers/set-archived.ts index 45c7df4..3c504de 100644 --- a/packages/api/src/routers/customers/set-archived.ts +++ b/packages/api/src/routers/customers/set-archived.ts @@ -1,4 +1,3 @@ -import { ORPCError } from "@orpc/server"; import { customer } from "@suni/db/schema/customers"; import { and, eq, sql } from "drizzle-orm"; import { z } from "zod"; @@ -9,7 +8,7 @@ import { ownCustomersSql } from "../../util/scope"; export const setArchived = scopedProcedure .route({ method: "POST", path: "/{id}/archived" }) .input(z.object({ id: z.string(), archived: z.boolean() })) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { // 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. const [updated] = await context.db @@ -24,7 +23,7 @@ export const setArchived = scopedProcedure .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 003dfcc..917ac75 100644 --- a/packages/api/src/routers/customers/update.ts +++ b/packages/api/src/routers/customers/update.ts @@ -10,7 +10,7 @@ import { ownCustomersSql } from "../../util/scope"; export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) .input(updateCustomerSchema.extend({ id: z.string() })) - .handler(async ({ input, context }) => { + .handler(async ({ input, context, errors }) => { const { id, type, ...fields } = input; const { userId } = context; @@ -37,7 +37,7 @@ export const update = scopedProcedure .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/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; From 043f25a5c70b75b79fb95b2a5ab5b1285dd5d003 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Mon, 9 Nov 2026 17:41:41 -0600 Subject: [PATCH 07/32] Valida los updates con el schema completo del formulario MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Los formularios ya mandan el registro entero, así que los updates de clientes, sucursales, contactos y usuarios validan con el mismo schema que el formulario en vez de uno parcial, y desaparece la comprobación de "no hay campos". El servidor responde los errores de validación con el mensaje del schema y con los mensajes por defecto de Zod en español. --- apps/server/src/index.ts | 29 +++++++++++++++++++- packages/api/src/routers/branches/update.ts | 11 ++------ packages/api/src/routers/contacts/update.ts | 15 ++-------- packages/api/src/routers/customers/update.ts | 11 ++------ packages/api/src/routers/users/update.ts | 19 +++---------- packages/db/src/validation/branches.ts | 4 --- packages/db/src/validation/contacts.ts | 5 ---- packages/db/src/validation/customers.ts | 2 -- 8 files changed, 38 insertions(+), 58 deletions(-) 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/packages/api/src/routers/branches/update.ts b/packages/api/src/routers/branches/update.ts index 99faf99..e8c9ff1 100644 --- a/packages/api/src/routers/branches/update.ts +++ b/packages/api/src/routers/branches/update.ts @@ -1,6 +1,5 @@ -import { ORPCError } from "@orpc/server"; import { branch } from "@suni/db/schema/branches"; -import { updateBranchSchema } from "@suni/db/validation/branches"; +import { branchSchema } from "@suni/db/validation/branches"; import { and, eq, isNull } from "drizzle-orm"; import { z } from "zod"; @@ -9,18 +8,12 @@ import { ownBranchesSql } from "../../util/scope"; export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) - .input(updateBranchSchema.omit({ archived: true }).extend({ id: z.string() })) + .input(branchSchema.extend({ id: z.string() })) .handler(async ({ input, context, errors }) => { const { id, ...fields } = input; const { userId } = context; - if (Object.values(fields).every((v) => v === undefined)) { - throw new ORPCError("BAD_REQUEST", { - message: "No hay campos para actualizar", - }); - } - const [updated] = await context.db .update(branch) .set({ ...fields, modifiedBy: userId }) diff --git a/packages/api/src/routers/contacts/update.ts b/packages/api/src/routers/contacts/update.ts index 207f742..20a499d 100644 --- a/packages/api/src/routers/contacts/update.ts +++ b/packages/api/src/routers/contacts/update.ts @@ -1,6 +1,5 @@ -import { ORPCError } from "@orpc/server"; import { contact } from "@suni/db/schema/contacts"; -import { updateContactSchema } from "@suni/db/validation/contacts"; +import { contactSchema } from "@suni/db/validation/contacts"; import { and, eq, isNull } from "drizzle-orm"; import { z } from "zod"; @@ -9,21 +8,11 @@ import { ownContactsSql } from "../../util/scope"; export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) - .input( - updateContactSchema - .omit({ archived: true, customerId: true }) - .extend({ id: z.string() }) - ) + .input(contactSchema.extend({ id: z.string() })) .handler(async ({ input, context, errors }) => { const { id, ...fields } = input; const { userId } = context; - if (Object.values(fields).every((v) => v === undefined)) { - throw new ORPCError("BAD_REQUEST", { - message: "No hay campos para actualizar", - }); - } - const [updated] = await context.db .update(contact) .set({ ...fields, modifiedBy: userId }) diff --git a/packages/api/src/routers/customers/update.ts b/packages/api/src/routers/customers/update.ts index 917ac75..dff7b8b 100644 --- a/packages/api/src/routers/customers/update.ts +++ b/packages/api/src/routers/customers/update.ts @@ -1,6 +1,5 @@ -import { ORPCError } from "@orpc/server"; import { customer } from "@suni/db/schema/customers"; -import { updateCustomerSchema } from "@suni/db/validation/customers"; +import { customerSchema } from "@suni/db/validation/customers"; import { and, eq, isNull } from "drizzle-orm"; import { z } from "zod"; @@ -9,7 +8,7 @@ import { ownCustomersSql } from "../../util/scope"; export const update = scopedProcedure .route({ method: "PATCH", path: "/{id}" }) - .input(updateCustomerSchema.extend({ id: z.string() })) + .input(customerSchema.extend({ id: z.string() })) .handler(async ({ input, context, errors }) => { const { id, type, ...fields } = input; @@ -17,12 +16,6 @@ export const update = scopedProcedure const data = context.admin ? { ...fields, type } : fields; - if (Object.values(data).every((v) => v === undefined)) { - throw new ORPCError("BAD_REQUEST", { - message: "No hay campos para actualizar", - }); - } - const [updated] = await context.db .update(customer) .set({ ...data, modifiedBy: userId }) diff --git a/packages/api/src/routers/users/update.ts b/packages/api/src/routers/users/update.ts index 7438637..e7cd9c9 100644 --- a/packages/api/src/routers/users/update.ts +++ b/packages/api/src/routers/users/update.ts @@ -11,26 +11,15 @@ export const update = adminProcedure .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(), + name: z.string().min(2), + email: z.email().toLowerCase(), + role, }) ) .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/db/src/validation/branches.ts b/packages/db/src/validation/branches.ts index 8f672aa..70c95bf 100644 --- a/packages/db/src/validation/branches.ts +++ b/packages/db/src/validation/branches.ts @@ -42,7 +42,3 @@ export const branchSchema = z.object({ export const createBranchSchema = branchSchema.extend({ customerId: z.string().min(1, "El cliente es requerido"), }); - -export const updateBranchSchema = branchSchema.partial().extend({ - archived: z.coerce.date().nullable().optional(), -}); diff --git a/packages/db/src/validation/contacts.ts b/packages/db/src/validation/contacts.ts index 5eb9458..91e8c59 100644 --- a/packages/db/src/validation/contacts.ts +++ b/packages/db/src/validation/contacts.ts @@ -16,8 +16,3 @@ export const createContactSchema = contactSchema.extend({ customerId: z.string().min(1, "El cliente es requerido"), branchId: z.string().min(1, "La sucursal es requerida"), }); - -export const updateContactSchema = contactSchema.partial().extend({ - customerId: z.string().min(1, "El cliente es requerido").optional(), - archived: z.coerce.date().nullable().optional(), -}); diff --git a/packages/db/src/validation/customers.ts b/packages/db/src/validation/customers.ts index 2b4c616..50c7d32 100644 --- a/packages/db/src/validation/customers.ts +++ b/packages/db/src/validation/customers.ts @@ -46,5 +46,3 @@ export const customerSchema = z.object({ }); export const createCustomerSchema = customerSchema; - -export const updateCustomerSchema = customerSchema.partial(); From fb889ec46a40a87260be855f68ed11ddda8ff66c Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Mon, 9 Nov 2026 17:48:46 -0600 Subject: [PATCH 08/32] Comparte el schema de usuarios entre el formulario y la API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El formulario web y los procedures de crear y editar usuarios validan con el mismo userSchema de @suni/db/validation. El nombre exige al menos 5 caracteres, se recorta y admite como máximo 100. --- apps/web/src/components/users/user-form.tsx | 11 +++-------- packages/api/src/routers/users/create.ts | 10 ++-------- packages/api/src/routers/users/role.ts | 3 --- packages/api/src/routers/users/update.ts | 11 ++--------- packages/db/src/validation/users.ts | 14 ++++++++++++++ 5 files changed, 21 insertions(+), 28 deletions(-) delete mode 100644 packages/api/src/routers/users/role.ts create mode 100644 packages/db/src/validation/users.ts 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/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/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 e7cd9c9..1913354 100644 --- a/packages/api/src/routers/users/update.ts +++ b/packages/api/src/routers/users/update.ts @@ -1,21 +1,14 @@ 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), - email: z.email().toLowerCase(), - role, - }) - ) + .input(userSchema.extend({ id: z.string() })) .handler(async ({ input, context }) => { const { id, ...data } = input; 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" }), +}); From 95cae8e76dea7fd32fc8f4f198943ee02e2e1262 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Mon, 9 Nov 2026 18:02:14 -0600 Subject: [PATCH 09/32] Genera los IDs con cuid2 en vez de UUID MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clientes, sucursales, contactos y el seed del admin generan sus IDs con createId de @paralleldrive/cuid2, y Better Auth usa el mismo generador con advanced.database.generateId, así todas las tablas comparten formato. Las columnas siguen siendo text, por lo que no hace falta migración y los IDs existentes siguen siendo válidos. La dependencia vive en el catálogo de pnpm porque la usan @suni/db y @suni/auth. --- packages/auth/package.json | 1 + packages/auth/src/index.ts | 4 ++++ packages/db/package.json | 1 + packages/db/src/schema/branches.ts | 3 ++- packages/db/src/schema/contacts.ts | 3 ++- packages/db/src/schema/customers.ts | 3 ++- packages/db/src/seeds/admin-user.ts | 3 ++- pnpm-lock.yaml | 29 +++++++++++++++++++++++++++++ pnpm-workspace.yaml | 1 + 9 files changed, 44 insertions(+), 4 deletions(-) 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/schema/branches.ts b/packages/db/src/schema/branches.ts index 6759aff..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,7 +7,7 @@ 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").notNull().default(""), diff --git a/packages/db/src/schema/contacts.ts b/packages/db/src/schema/contacts.ts index 0937ea9..5e461b5 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,7 +8,7 @@ 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(), diff --git a/packages/db/src/schema/customers.ts b/packages/db/src/schema/customers.ts index 490b650..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,7 +11,7 @@ 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(), 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/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 From 86640d18cc8c3bcfa94e745fd03b2e7c99600b76 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 10 Nov 2026 11:27:20 -0600 Subject: [PATCH 10/32] Unifica el uso de los hooks de consultas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Los grids de sucursales y contactos usan useListBranches y useListContacts en vez de llamar a useQuery directo, así heredan cualquier opción que se agregue a los hooks. Todos los hooks de listas pasan placeholderData dentro de queryOptions. useListBranches recibe skipToken en vez de un booleano enabled, para que el selector de sucursal no pueda pedir todas las sucursales por accidente. useUpdateBranch invalida sucursales y contactos en paralelo, y el botón del toast de error dice "Reintentar". --- .../components/customers/branches/grid.tsx | 5 ++--- .../customers/contacts/contact-grid.tsx | 7 ++----- .../customers/select-entity-button.tsx | 4 ++-- apps/web/src/hooks/use-branches.ts | 21 +++++++++++-------- apps/web/src/hooks/use-contacts.ts | 10 +++++---- apps/web/src/hooks/use-customers.ts | 10 +++++---- apps/web/src/utils/orpc.ts | 2 +- 7 files changed, 31 insertions(+), 28 deletions(-) diff --git a/apps/web/src/components/customers/branches/grid.tsx b/apps/web/src/components/customers/branches/grid.tsx index f23cf09..99f0079 100644 --- a/apps/web/src/components/customers/branches/grid.tsx +++ b/apps/web/src/components/customers/branches/grid.tsx @@ -1,9 +1,8 @@ import { Button } from "@suni/ui/components/button"; -import { useQuery } from "@tanstack/react-query"; import { Building2, Plus, SearchX } from "lucide-react"; import { useMemo, useState } from "react"; -import { orpc } from "@/utils/orpc"; +import { useListBranches } from "@/hooks/use-branches"; import { BranchFormDialog } from "./branch-form-dialog"; import BranchCard from "./card"; @@ -28,7 +27,7 @@ export function BranchesGrid({ customerId }: BranchesGridProps) { data: branches = [], isPending, isError, - } = useQuery(orpc.branches.list.queryOptions({ input: { customerId } })); + } = useListBranches({ customerId }); const filtered = useMemo(() => { const term = filters.name.trim().toLowerCase(); diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx index b53a3e0..d5820c2 100644 --- a/apps/web/src/components/customers/contacts/contact-grid.tsx +++ b/apps/web/src/components/customers/contacts/contact-grid.tsx @@ -1,9 +1,8 @@ -import { useQuery } from "@tanstack/react-query"; import { SearchX, Users } from "lucide-react"; import { useMemo, useState } from "react"; import { NewEntityButton } from "@/components/customers/select-entity-button"; -import { orpc } from "@/utils/orpc"; +import { useListContacts } from "@/hooks/use-contacts"; import ContactCard from "./contact-card"; import { ContactsFilters } from "./contact-filters"; @@ -28,9 +27,7 @@ export function ContactsGrid({ customerId, branchId }: ContactsGridProps) { data: contacts = [], isPending, isError, - } = useQuery( - orpc.contacts.list.queryOptions({ input: { customerId, branchId } }) - ); + } = useListContacts({ customerId, branchId }); const filtered = useMemo(() => { const term = filters.name.trim().toLowerCase(); diff --git a/apps/web/src/components/customers/select-entity-button.tsx b/apps/web/src/components/customers/select-entity-button.tsx index 6a06152..83f4469 100644 --- a/apps/web/src/components/customers/select-entity-button.tsx +++ b/apps/web/src/components/customers/select-entity-button.tsx @@ -8,6 +8,7 @@ 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"; @@ -57,8 +58,7 @@ function BranchPicker({ onValueChange, }: PickerProps & { customerId: string | null }) { const { data: branches = [], isPending } = useListBranches( - customerId ? { customerId } : {}, - !!customerId + customerId ? { customerId } : skipToken ); const options = useMemo( diff --git a/apps/web/src/hooks/use-branches.ts b/apps/web/src/hooks/use-branches.ts index a4ee52e..0792574 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), }) 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..69d3988 100644 --- a/apps/web/src/hooks/use-customers.ts +++ b/apps/web/src/hooks/use-customers.ts @@ -15,10 +15,12 @@ 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, - }); + return useQuery( + orpc.customers.list.queryOptions({ + input: params, + placeholderData: keepPreviousData, + }) + ); } export function useCreateCustomer() { 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(); }, From dcf6985fb35b1b72d89af38e9db32a6aadef0142 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 10 Nov 2026 11:27:22 -0600 Subject: [PATCH 11/32] Refresca sucursales y contactos al archivar su padre MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Las tarjetas de contactos leen branch.archived y customer.archived, y las de sucursales leen customer.archived, para mostrar que su padre está archivado. Archivar una sucursal ahora invalida también los contactos, y archivar un cliente invalida también sucursales y contactos, así esas tarjetas dejan de mostrar el estado anterior. --- apps/web/src/hooks/use-branches.ts | 6 +++++- apps/web/src/hooks/use-customers.ts | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/web/src/hooks/use-branches.ts b/apps/web/src/hooks/use-branches.ts index 0792574..5ce7d90 100644 --- a/apps/web/src/hooks/use-branches.ts +++ b/apps/web/src/hooks/use-branches.ts @@ -67,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-customers.ts b/apps/web/src/hooks/use-customers.ts index 69d3988..d92ffc6 100644 --- a/apps/web/src/hooks/use-customers.ts +++ b/apps/web/src/hooks/use-customers.ts @@ -63,7 +63,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.`, }); From 70a56913f6f1aa50d3be53cee6a235c0bac76e1b Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Tue, 10 Nov 2026 12:20:07 -0600 Subject: [PATCH 12/32] Muestra el cliente y el estado archivado en las tarjetas de sucursales MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La página de sucursales pasa el cliente a cada tarjeta, así se ve a quién pertenece cada sucursal. El estado archivado se muestra con un solo badge "Archivada" en la esquina de la imagen, sea por la sucursal o por su cliente. Cuando el cliente está archivado, su fila muestra el ícono de archivo y el nombre atenuado, y el menú muestra "Desarchivar" deshabilitado con la indicación de desarchivar primero el cliente. Los íconos del encabezado y del cuerpo quedan alineados. --- .../components/customers/branches/card.tsx | 54 +++++++++++++------ apps/web/src/routes/_auth/branches/index.tsx | 6 ++- 2 files changed, 42 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/customers/branches/card.tsx b/apps/web/src/components/customers/branches/card.tsx index c790aea..0285dc5 100644 --- a/apps/web/src/components/customers/branches/card.tsx +++ b/apps/web/src/components/customers/branches/card.tsx @@ -69,6 +69,12 @@ function BranchImage({ src={src} />
+ {isArchived && ( + + + Archivada + + )} {hasImage && onExpandClick && (

- 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..ab71d38 100644 --- a/apps/web/src/components/customers/branches/branch-info.tsx +++ b/apps/web/src/components/customers/branches/branch-info.tsx @@ -20,7 +20,7 @@ export function BranchInfoContent({ onImagePreview, onImageUpload, }: BranchInfoContentProps) { - const isArchived = !!branch.archived; + const isArchived = !!branch.archived || !!branch.customer?.archived; 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 0285dc5..07db5f4 100644 --- a/apps/web/src/components/customers/branches/card.tsx +++ b/apps/web/src/components/customers/branches/card.tsx @@ -27,7 +27,7 @@ import { useState } from "react"; import { BranchFormDialog } from "./branch-form-dialog"; import { ChangeBranchStatusDialog } from "./change-branch-status-dialog"; -import { formatAddress } from "./util/branch-address"; +import { branchImageSrc, formatAddress } from "./util/branch-address"; type Branch = AppRouterOutputs["branches"]["list"][number]; @@ -108,13 +108,8 @@ export default function BranchCard({ branch, customer }: BranchCardProps) { 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 */} diff --git a/apps/web/src/components/customers/branches/change-branch-status-dialog.tsx b/apps/web/src/components/customers/branches/change-branch-status-dialog.tsx index 12882e7..dc813cc 100644 --- a/apps/web/src/components/customers/branches/change-branch-status-dialog.tsx +++ b/apps/web/src/components/customers/branches/change-branch-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 { useArchiveBranch } from "@/hooks/use-branches"; -type BranchRow = AppRouterOutputs["branches"]["list"][number]; - -const ACTIONS = { - archive: { - label: "Archivar", - Icon: Archive, - confirmVariant: "destructive", - nameClassName: "text-destructive", - description: "Esto archivará", - }, - unarchive: { - label: "Desarchivar", - Icon: ArchiveRestore, - confirmVariant: "default", - nameClassName: "text-success", - description: "Esto restaurará", - }, -} as const; +type Row = AppRouterOutputs["branches"]["list"][number]; interface ChangeBranchStatusDialogProps { - branch: Pick; + 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..d2678f1 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" }, @@ -36,25 +29,6 @@ interface BranchesFiltersProps { customers?: { id: string; name: string }[]; } -function FilterBadge({ - children, - onClear, -}: { - children: React.ReactNode; - onClear: () => void; -}) { - return ( - - ); -} - export function BranchesFilters({ filters, onFiltersChange, @@ -92,7 +66,7 @@ export function BranchesFilters({ /> | null) => + onChange={(option: Option | null) => update({ status: option?.value ?? "all" }) } options={STATUS_OPTIONS} @@ -132,7 +106,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 99f0079..c4ca5ec 100644 --- a/apps/web/src/components/customers/branches/grid.tsx +++ b/apps/web/src/components/customers/branches/grid.tsx @@ -1,122 +1,114 @@ -import { Button } from "@suni/ui/components/button"; -import { Building2, Plus, SearchX } from "lucide-react"; +import { skipToken } from "@tanstack/react-query"; +import { Building2 } from "lucide-react"; import { useMemo, useState } from "react"; +import { NewEntityButton } from "@/components/customers/select-entity-button"; +import { EntityGrid } from "@/components/customers/shared/entity-grid"; +import { DEFAULT_BRANCH_FILTERS } 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 { stripAccents } from "@/lib/string-utils"; -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, - } = useListBranches({ 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; - } +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" } + ); - if (filters.status === "archived") { - return !!branch.archived; - } + const visibleBranches = useMemo(() => { + const term = stripAccents(filters.name.trim()).toLowerCase(); - return true; - }); - }, [branches, filters]); + return (query.data ?? []) + .filter( + (branch) => + !term || stripAccents(branch.name).toLowerCase().includes(term) + ) + .toSorted((a, b) => a.name.localeCompare(b.name, "es")); + }, [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-filters.tsx b/apps/web/src/components/customers/contacts/contact-filters.tsx index 1b36983..9e05023 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" }, @@ -31,25 +26,6 @@ interface ContactsFiltersProps { onFiltersChange: (filters: ContactFilters) => void; } -function FilterBadge({ - children, - onClear, -}: { - children: React.ReactNode; - onClear: () => void; -}) { - return ( - - ); -} - export function ContactsFilters({ filters, onFiltersChange, @@ -77,7 +53,7 @@ export function ContactsFilters({ /> | null) => + onChange={(option: Option | null) => update({ status: option?.value ?? "all" }) } options={STATUS_OPTIONS} 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 797692e..398ea9f 100644 --- a/apps/web/src/components/customers/contacts/contact-form.tsx +++ b/apps/web/src/components/customers/contacts/contact-form.tsx @@ -12,13 +12,14 @@ type Contact = AppRouterOutputs["contacts"]["list"][number]; 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; @@ -47,12 +48,11 @@ function toFormValues(contact?: Contact): FormValues { } export function ContactForm({ - customerId, - branchId, - contact, onSuccess, onCancel, + ...target }: ContactFormProps) { + const { contact } = target; const createContact = useCreateContact(); const updateContact = useUpdateContact(); @@ -63,14 +63,18 @@ export function ContactForm({ validationLogic: revalidateLogic(), validators: { onDynamic: contactSchema }, onSubmit: ({ value }) => { - if (contact) { + if (target.contact) { updateContact.mutate( - { id: contact.id, ...value }, + { id: target.contact.id, ...value }, { onSuccess: () => onSuccess?.() } ); - } else if (customerId && branchId) { + } else { createContact.mutate( - { customerId, branchId, ...value }, + { + 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 d5820c2..523b3e0 100644 --- a/apps/web/src/components/customers/contacts/contact-grid.tsx +++ b/apps/web/src/components/customers/contacts/contact-grid.tsx @@ -1,115 +1,112 @@ -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 { EntityGrid } from "@/components/customers/shared/entity-grid"; +import { DEFAULT_CONTACT_FILTERS } from "@/components/customers/shared/filters"; +import type { ContactFilters } from "@/components/customers/shared/filters"; import { useListContacts } from "@/hooks/use-contacts"; +import { stripAccents } from "@/lib/string-utils"; 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 ContactsList({ + filters, + onFiltersChange, + customerId, + branchId, +}: ContactsListProps) { + const query = useListContacts({ + status: filters.status, + customerId, + branchId, + }); + + const visibleContacts = useMemo(() => { + const term = stripAccents(filters.name.trim()).toLowerCase(); + + return (query.data ?? []) + .filter( + (contact) => + !term || stripAccents(contact.name).toLowerCase().includes(term) + ) + .toSorted((a, b) => a.name.localeCompare(b.name, "es")); + }, [query.data, filters.name]); + + const hasFilters = + filters.name.trim() !== "" || + filters.status !== DEFAULT_CONTACT_FILTERS.status; -export function ContactsGrid({ customerId, branchId }: ContactsGridProps) { - const [filters, setFilters] = useState( - DEFAULT_CONTACT_FILTERS + return ( + <> + + + + {visibleContacts.map((contact) => ( + + ))} + + ); +} - const { - data: contacts = [], - isPending, - isError, - } = useListContacts({ customerId, branchId }); - - const filtered = useMemo(() => { - const term = filters.name.trim().toLowerCase(); - - return contacts.filter((contact) => { - if (term && !contact.name.toLowerCase().includes(term)) { - return false; - } - - if (filters.status === "active") { - return !contact.archived; - } - - if (filters.status === "archived") { - return !!contact.archived; - } - - return true; - }); - }, [contacts, filters]); +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/select-entity-button.tsx b/apps/web/src/components/customers/select-entity-button.tsx index 83f4469..81b262a 100644 --- a/apps/web/src/components/customers/select-entity-button.tsx +++ b/apps/web/src/components/customers/select-entity-button.tsx @@ -64,7 +64,6 @@ function BranchPicker({ const options = useMemo( () => branches - .filter((branch) => !branch.archived) .toSorted((a, b) => a.name.localeCompare(b.name, "es")) .map((branch) => ({ value: branch.id, label: branch.name })), [branches] 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..595c91d --- /dev/null +++ b/apps/web/src/components/customers/shared/change-status-dialog.tsx @@ -0,0 +1,95 @@ +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@suni/ui/components/alert-dialog"; + +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) { + const action = entity.archived ? 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: !entity.archived, + }, + { 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..4bb865a --- /dev/null +++ b/apps/web/src/components/customers/shared/entity-grid.tsx @@ -0,0 +1,75 @@ +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..63ed7e3 --- /dev/null +++ b/apps/web/src/components/customers/shared/filters.ts @@ -0,0 +1,25 @@ +import type { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; + +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", +}; diff --git a/apps/web/src/hooks/use-customers.ts b/apps/web/src/hooks/use-customers.ts index d92ffc6..ccfb0a0 100644 --- a/apps/web/src/hooks/use-customers.ts +++ b/apps/web/src/hooks/use-customers.ts @@ -8,13 +8,16 @@ 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"]) { +export function useListCustomers( + params: AppRouterInputs["customers"]["list"] | typeof skipToken +) { return useQuery( orpc.customers.list.queryOptions({ input: params, @@ -44,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), }) diff --git a/apps/web/src/routes/_auth/branches/index.tsx b/apps/web/src/routes/_auth/branches/index.tsx index b0179be..fa2aade 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 { BranchesList } from "@/components/customers/branches/grid"; import { NewEntityButton } from "@/components/customers/select-entity-button"; -import { useListBranches } from "@/hooks/use-branches"; -import { useListCustomers } from "@/hooks/use-customers"; -import { stripAccents } from "@/lib/string-utils"; /* oxlint-disable promise/prefer-await-to-then, github/no-then -- zod `.catch()` is not Promise.catch */ const searchSchema = z.object({ name: z.string().default("").catch(""), - status: z.enum(["all", "active", "archived"]).default("all").catch("all"), + 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,67 +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..e8f826c 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 { ContactsList } from "@/components/customers/contacts/contact-grid"; import { NewEntityButton } from "@/components/customers/select-entity-button"; -import { useListContacts } from "@/hooks/use-contacts"; -import { stripAccents } from "@/lib/string-utils"; /* oxlint-disable promise/prefer-await-to-then, github/no-then -- zod `.catch()` is not Promise.catch */ const searchSchema = z.object({ name: z.string().default("").catch(""), - status: z.enum(["all", "active", "archived"]).default("all").catch("all"), + 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 940b0fa..9556507 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,30 @@ 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 { 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,7 +58,7 @@ 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. @@ -57,25 +66,26 @@ function RouteComponent() { 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 = !!branch.archived || !!branch.customer?.archived; 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 +93,7 @@ function RouteComponent() { return (

- setIsUpdateFormOpen(true)} - /> + setIsUpdateFormOpen(true)} /> @@ -108,7 +114,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..ca80f8e 100644 --- a/apps/web/src/routes/_auth/customers/$customerId/index.tsx +++ b/apps/web/src/routes/_auth/customers/$customerId/index.tsx @@ -100,10 +100,16 @@ function RouteComponent() { ))} - + - +
From 738350a110dd49e260f991020ed0330ab88e5c57 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 11:09:26 -0600 Subject: [PATCH 15/32] =?UTF-8?q?Agrega=20la=20migraci=C3=B3n=20de=20conta?= =?UTF-8?q?ct.branch=5Fid=20NOT=20NULL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La migración aplica el NOT NULL que el schema ya declara para la sucursal de un contacto. Falla si queda algún contacto sin sucursal. --- .../migration.sql | 1 + .../snapshot.json | 1532 +++++++++++++++++ 2 files changed, 1533 insertions(+) create mode 100644 packages/db/src/migrations/20261111170917_lyrical_payback/migration.sql create mode 100644 packages/db/src/migrations/20261111170917_lyrical_payback/snapshot.json 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 From a0abeef97b811344bf87147e1acf28cbeb4d2d46 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 11:09:27 -0600 Subject: [PATCH 16/32] Muestra Desarchivar deshabilitado en contactos con un padre archivado MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Un contacto cuyo cliente o sucursal está archivado abría un menú de acciones vacío, porque Editar y Archivar se ocultaban. Ahora muestra Desarchivar deshabilitado con la indicación de desarchivar primero el cliente o la sucursal, igual que la tarjeta de sucursal. El cliente tiene prioridad sobre la sucursal. --- .../customers/contacts/contact-card.tsx | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/customers/contacts/contact-card.tsx b/apps/web/src/components/customers/contacts/contact-card.tsx index 270380e..13e7e33 100644 --- a/apps/web/src/components/customers/contacts/contact-card.tsx +++ b/apps/web/src/components/customers/contacts/contact-card.tsx @@ -42,20 +42,24 @@ function getArchiveState(contact: Contact) { const isParent = isCustomer || isBranch; let label = "Archivado"; + let parentHint: string | undefined; if (isCustomer) { label = "Cliente archivado"; + parentHint = "Desarchiva primero el cliente"; } else if (isBranch) { label = "Sucursal archivada"; + parentHint = "Desarchiva primero la sucursal"; } - return { isOwn, isParent, isArchived: isOwn || isParent, label }; + return { isOwn, parentHint, isArchived: isOwn || isParent, label }; } interface ContactMenuProps { isArchived: boolean; isOwnArchived: boolean; - isParentArchived: boolean; + /** Set when an archived parent blocks unarchiving the contact. */ + parentHint?: string; onEdit: () => void; onToggleStatus: () => void; } @@ -63,7 +67,7 @@ interface ContactMenuProps { function ContactMenu({ isArchived, isOwnArchived, - isParentArchived, + parentHint, onEdit, onToggleStatus, }: ContactMenuProps) { @@ -84,8 +88,18 @@ function ContactMenu({ )} - {/* Si un padre lo archiva, desarchivarlo no tendría efecto */} - {!isParentArchived && ( + {/* An archived parent wins: unarchiving the contact alone would have no effect */} + {parentHint ? ( + + + + + Desarchivar + + {parentHint} + + + ) : ( setIsUpdateFormOpen(true)} onToggleStatus={() => setIsStatusDialogOpen(true)} /> From 87f3ac1f941298d7d81427c3bed251685b7b95e6 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 11:50:53 -0600 Subject: [PATCH 17/32] Alinea la tarjeta de contacto con la de sucursal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Las filas de cliente y sucursal usan los mismos íconos y espaciado que el cuerpo, y cuando ese padre está archivado muestran el ícono de archivo y el nombre atenuado; la sucursal cuenta como archivada si su cliente lo está. El badge dice siempre "Archivado", porque las filas y el menú ya indican la causa. El cuerpo deja de atenuarse y usa el mismo margen que el encabezado, y el menú se ensancha cuando muestra la indicación de desarchivar. --- .../customers/contacts/contact-card.tsx | 76 +++++++++++++------ 1 file changed, 52 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/customers/contacts/contact-card.tsx b/apps/web/src/components/customers/contacts/contact-card.tsx index 13e7e33..8a8f569 100644 --- a/apps/web/src/components/customers/contacts/contact-card.tsx +++ b/apps/web/src/components/customers/contacts/contact-card.tsx @@ -39,20 +39,23 @@ 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"; let parentHint: string | undefined; if (isCustomer) { - label = "Cliente archivado"; parentHint = "Desarchiva primero el cliente"; } else if (isBranch) { - label = "Sucursal archivada"; parentHint = "Desarchiva primero la sucursal"; } - return { isOwn, parentHint, isArchived: isOwn || isParent, label }; + return { + isOwn, + isCustomerArchived: isCustomer, + // A branch under an archived customer is effectively archived too. + isBranchArchived: isCustomer || isBranch, + parentHint, + isArchived: isOwn || isCustomer || isBranch, + }; } interface ContactMenuProps { @@ -78,7 +81,10 @@ function ContactMenu({ Abrir menú - + Acciones {!isArchived && ( @@ -122,16 +128,32 @@ function ContactMenu({ interface ContactParentsProps { contact: Contact; customer?: { id: string; name: string }; + isCustomerArchived: boolean; + isBranchArchived: boolean; } -function ContactParents({ contact, customer }: ContactParentsProps) { +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, + isCustomerArchived, + isBranchArchived, +}: ContactParentsProps) { + const CustomerIcon = isCustomerArchived ? Archive : Building2; + const BranchIcon = isBranchArchived ? Archive : MapPin; + return ( <> {customer && ( -
- +
+ - +
+ {contact.name} @@ -223,7 +251,12 @@ export default function ContactCard({

)} - +
{!readOnly && ( @@ -239,12 +272,7 @@ export default function ContactCard({
{/* Body */} -
+
+
- {label} + Archivado
)} From 8e66b1dce425b386a196c66ed837a1c1e029ace5 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 11:59:04 -0600 Subject: [PATCH 18/32] Muestra el estado archivado y permite desarchivar en el detalle del cliente --- .../_auth/customers/$customerId/index.tsx | 86 +++++++++++++++---- 1 file changed, 71 insertions(+), 15 deletions(-) diff --git a/apps/web/src/routes/_auth/customers/$customerId/index.tsx b/apps/web/src/routes/_auth/customers/$customerId/index.tsx index ca80f8e..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 + + )} + +
+ + From 78606b0ec2587eaf61181a32c781523c6e5d0bdb Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 12:01:55 -0600 Subject: [PATCH 19/32] =?UTF-8?q?Evita=20que=20el=20di=C3=A1logo=20de=20ar?= =?UTF-8?q?chivo=20muestre=20la=20acci=C3=B3n=20contraria=20al=20guardar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../customers/shared/change-status-dialog.tsx | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/customers/shared/change-status-dialog.tsx b/apps/web/src/components/customers/shared/change-status-dialog.tsx index 595c91d..356401a 100644 --- a/apps/web/src/components/customers/shared/change-status-dialog.tsx +++ b/apps/web/src/components/customers/shared/change-status-dialog.tsx @@ -8,6 +8,7 @@ import { AlertDialogHeader, AlertDialogTitle, } from "@suni/ui/components/alert-dialog"; +import { useState } from "react"; const ACTIONS = { archive: { @@ -48,7 +49,19 @@ export function ChangeStatusDialog({ open, onOpenChange, }: ChangeStatusDialogProps) { - const action = entity.archived ? ACTIONS.unarchive : ACTIONS.archive; + // 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 ( onOpenChange(false) } ) From bce86500355d4099b86940e308da59add0443a03 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:47:51 -0600 Subject: [PATCH 20/32] Centraliza la regla de que solo un admin ve al vendedor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sellerColumns, sellerRelation y withSeller en util/scope.ts reemplazan la lógica copiada en get y list de clientes y sucursales. Cada lectura hace ahora una sola query en lugar de una por rol. --- packages/api/src/routers/branches/get.ts | 15 +++++---- packages/api/src/routers/branches/list.ts | 39 +++++++++------------- packages/api/src/routers/customers/get.ts | 30 ++++++----------- packages/api/src/routers/customers/list.ts | 28 +++++++--------- packages/api/src/util/scope.ts | 20 +++++++++++ 5 files changed, 67 insertions(+), 65 deletions(-) diff --git a/packages/api/src/routers/branches/get.ts b/packages/api/src/routers/branches/get.ts index 76a01d2..836c819 100644 --- a/packages/api/src/routers/branches/get.ts +++ b/packages/api/src/routers/branches/get.ts @@ -1,20 +1,23 @@ import { z } from "zod"; import { scopedProcedure } from "../../index"; -import { ownBranches } from "../../util/scope"; +import { + ownBranches, + sellerColumns, + sellerRelation, + withSeller, +} from "../../util/scope"; export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) .handler(async ({ input, context, errors }) => { - const { admin } = context; - const found = await context.db.query.branch.findFirst({ where: { id: input.id, ...ownBranches(context) }, - columns: admin ? undefined : { sellerId: false, modifiedBy: false }, + columns: sellerColumns(context), with: { customer: { columns: { id: true, name: true, archived: true } }, - ...(admin && { seller: { columns: { id: true, name: true } } }), + ...sellerRelation(context), }, }); @@ -22,5 +25,5 @@ export const get = scopedProcedure 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 c72863f..b6cc19e 100644 --- a/packages/api/src/routers/branches/list.ts +++ b/packages/api/src/routers/branches/list.ts @@ -2,7 +2,12 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; import { scopedProcedure } from "../../index"; -import { ownBranches } from "../../util/scope"; +import { + ownBranches, + sellerColumns, + sellerRelation, + withSeller, +} from "../../util/scope"; import { statusWhere } from "../../util/status"; export const list = scopedProcedure @@ -14,32 +19,20 @@ export const list = scopedProcedure }) ) .handler(async ({ input, context }) => { - const where = { - AND: [ - statusWhere("branch", input.status), - ownBranches(context), - ...(input.customerId ? [{ customerId: input.customerId }] : []), - ], - }; - - if (context.admin) { - return context.db.query.branch.findMany({ - where, - with: { - customer: { columns: { id: true, name: true, archived: true } }, - seller: { columns: { id: true, name: true } }, - }, - }); - } - - // Seller identity is admin-only. const rows = await context.db.query.branch.findMany({ - where, - 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 } }, + ...sellerRelation(context), }, }); - return rows.map((row) => ({ ...row, seller: null })); + return rows.map((row) => withSeller(context, row)); }); diff --git a/packages/api/src/routers/customers/get.ts b/packages/api/src/routers/customers/get.ts index 207ba93..7f4975b 100644 --- a/packages/api/src/routers/customers/get.ts +++ b/packages/api/src/routers/customers/get.ts @@ -1,36 +1,26 @@ import { z } from "zod"; import { scopedProcedure } from "../../index"; -import { ownCustomers } from "../../util/scope"; +import { + ownCustomers, + sellerColumns, + sellerRelation, + withSeller, +} from "../../util/scope"; export const get = scopedProcedure .route({ method: "GET", path: "/{id}" }) .input(z.object({ id: z.string() })) .handler(async ({ input, context, errors }) => { - const where = { id: input.id, ...ownCustomers(context) }; - - if (context.admin) { - const found = await context.db.query.customer.findFirst({ - where, - with: { seller: { columns: { id: true, name: true } } }, - }); - - if (!found) { - throw errors.NOT_FOUND({ message: "El cliente no existe" }); - } - - return found; - } - - // Seller identity is admin-only. 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 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 36cb733..19078d1 100644 --- a/packages/api/src/routers/customers/list.ts +++ b/packages/api/src/routers/customers/list.ts @@ -2,29 +2,25 @@ import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { z } from "zod"; import { scopedProcedure } from "../../index"; -import { ownCustomers } from "../../util/scope"; +import { + ownCustomers, + sellerColumns, + sellerRelation, + withSeller, +} from "../../util/scope"; import { statusWhere } from "../../util/status"; export const list = scopedProcedure .route({ method: "GET", path: "/" }) .input(z.object({ status: z.enum(CUSTOMER_STATUSES).default("active") })) .handler(async ({ input, context }) => { - const where = { - AND: [statusWhere("customer", input.status), ownCustomers(context)], - }; - - if (context.admin) { - 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/util/scope.ts b/packages/api/src/util/scope.ts index 223cd96..3e7c4e8 100644 --- a/packages/api/src/util/scope.ts +++ b/packages/api/src/util/scope.ts @@ -44,3 +44,23 @@ export function ownContactsSql({ admin, userId, db }: Scope) { .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 }; +} From 07f981a9128793903cea6c90c3ccd8eed015edf6 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:47:52 -0600 Subject: [PATCH 21/32] Usa las reglas de archivado de util/status.ts en create y setArchived Los create de sucursal y contacto validan al padre con statusWhere(..., "active") en lugar de repetir el filtro de archivado. El COALESCE que conserva la fecha original al archivar vive en archivedValue. --- packages/api/src/routers/branches/create.ts | 9 ++++++--- packages/api/src/routers/branches/set-archived.ts | 8 +++----- packages/api/src/routers/contacts/create.ts | 11 ++++++----- packages/api/src/routers/contacts/set-archived.ts | 8 +++----- packages/api/src/routers/customers/set-archived.ts | 9 +++------ packages/api/src/util/status.ts | 9 ++++++++- 6 files changed, 29 insertions(+), 25 deletions(-) diff --git a/packages/api/src/routers/branches/create.ts b/packages/api/src/routers/branches/create.ts index a04c578..0d8750f 100644 --- a/packages/api/src/routers/branches/create.ts +++ b/packages/api/src/routers/branches/create.ts @@ -3,6 +3,7 @@ import { createBranchSchema } from "@suni/db/validation/branches"; import { scopedProcedure } from "../../index"; import { ownCustomers } from "../../util/scope"; +import { statusWhere } from "../../util/status"; export const create = scopedProcedure .route({ method: "POST", path: "/" }) @@ -12,9 +13,11 @@ export const create = scopedProcedure const parent = await context.db.query.customer.findFirst({ where: { - id: input.customerId, - archived: { isNull: true }, - ...ownCustomers(context), + AND: [ + { id: input.customerId }, + statusWhere("customer", "active"), + ownCustomers(context), + ], }, columns: { id: true }, }); diff --git a/packages/api/src/routers/branches/set-archived.ts b/packages/api/src/routers/branches/set-archived.ts index 9225e47..c6ee37a 100644 --- a/packages/api/src/routers/branches/set-archived.ts +++ b/packages/api/src/routers/branches/set-archived.ts @@ -1,10 +1,10 @@ import { branch } from "@suni/db/schema/branches"; -import { and, eq, inArray, sql } from "drizzle-orm"; +import { and, eq, inArray } from "drizzle-orm"; import { z } from "zod"; import { scopedProcedure } from "../../index"; import { ownBranchesSql } from "../../util/scope"; -import { activeCustomerIdsSql } from "../../util/status"; +import { activeCustomerIdsSql, archivedValue } from "../../util/status"; export const setArchived = scopedProcedure .route({ method: "POST", path: "/{id}/archived" }) @@ -15,9 +15,7 @@ export const setArchived = scopedProcedure 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. diff --git a/packages/api/src/routers/contacts/create.ts b/packages/api/src/routers/contacts/create.ts index eb292f7..c3e543f 100644 --- a/packages/api/src/routers/contacts/create.ts +++ b/packages/api/src/routers/contacts/create.ts @@ -3,6 +3,7 @@ import { createContactSchema } from "@suni/db/validation/contacts"; import { scopedProcedure } from "../../index"; import { ownBranches } from "../../util/scope"; +import { statusWhere } from "../../util/status"; export const create = scopedProcedure .route({ method: "POST", path: "/" }) @@ -12,11 +13,11 @@ export const create = scopedProcedure const parent = await context.db.query.branch.findFirst({ where: { - id: input.branchId, - customerId: input.customerId, - archived: { isNull: true }, - customer: { archived: { isNull: true } }, - ...ownBranches(context), + AND: [ + { id: input.branchId, customerId: input.customerId }, + statusWhere("branch", "active"), + ownBranches(context), + ], }, columns: { id: true }, }); diff --git a/packages/api/src/routers/contacts/set-archived.ts b/packages/api/src/routers/contacts/set-archived.ts index 64c77c0..811a86a 100644 --- a/packages/api/src/routers/contacts/set-archived.ts +++ b/packages/api/src/routers/contacts/set-archived.ts @@ -1,10 +1,10 @@ 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 { scopedProcedure } from "../../index"; import { ownContactsSql } from "../../util/scope"; -import { activeBranchIdsSql } from "../../util/status"; +import { activeBranchIdsSql, archivedValue } from "../../util/status"; export const setArchived = scopedProcedure .route({ method: "POST", path: "/{id}/archived" }) @@ -15,9 +15,7 @@ export const setArchived = scopedProcedure 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. diff --git a/packages/api/src/routers/customers/set-archived.ts b/packages/api/src/routers/customers/set-archived.ts index 3c504de..eebb9d1 100644 --- a/packages/api/src/routers/customers/set-archived.ts +++ b/packages/api/src/routers/customers/set-archived.ts @@ -1,22 +1,19 @@ import { customer } from "@suni/db/schema/customers"; -import { and, eq, sql } from "drizzle-orm"; +import { and, eq } from "drizzle-orm"; import { z } from "zod"; import { scopedProcedure } from "../../index"; import { ownCustomersSql } from "../../util/scope"; +import { archivedValue } from "../../util/status"; export const setArchived = scopedProcedure .route({ method: "POST", path: "/{id}/archived" }) .input(z.object({ id: z.string(), archived: z.boolean() })) .handler(async ({ input, context, errors }) => { - // 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. const [updated] = await context.db .update(customer) .set({ - archived: input.archived - ? sql`COALESCE(${customer.archived}, now())` - : null, + archived: archivedValue(customer.archived, input.archived), modifiedBy: context.userId, }) .where(and(eq(customer.id, input.id), ownCustomersSql(context))) diff --git a/packages/api/src/util/status.ts b/packages/api/src/util/status.ts index b72aa6f..e4d5843 100644 --- a/packages/api/src/util/status.ts +++ b/packages/api/src/util/status.ts @@ -1,6 +1,7 @@ import { branch } from "@suni/db/schema/branches"; import { customer } from "@suni/db/schema/customers"; -import { and, eq, isNull as isNullSql } from "drizzle-orm"; +import { and, eq, isNull as isNullSql, sql } from "drizzle-orm"; +import type { AnyPgColumn } from "drizzle-orm/pg-core"; import type { Context } from "../context"; @@ -64,3 +65,9 @@ export function activeBranchIdsSql(db: Context["db"]) { .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; +} From 696a8817fc036d5d65ca814302de10c9a4256aa5 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:47:52 -0600 Subject: [PATCH 22/32] Quita el alias createCustomerSchema Era el mismo objeto que customerSchema. --- packages/api/src/routers/customers/create.ts | 4 ++-- packages/db/src/validation/customers.ts | 2 -- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/api/src/routers/customers/create.ts b/packages/api/src/routers/customers/create.ts index 536ad84..53645e6 100644 --- a/packages/api/src/routers/customers/create.ts +++ b/packages/api/src/routers/customers/create.ts @@ -1,11 +1,11 @@ import { customer } from "@suni/db/schema/customers"; -import { createCustomerSchema } from "@suni/db/validation/customers"; +import { customerSchema } from "@suni/db/validation/customers"; import { scopedProcedure } from "../../index"; export const create = scopedProcedure .route({ method: "POST", path: "/" }) - .input(createCustomerSchema) + .input(customerSchema) .handler(async ({ input, context }) => { const { userId } = context; diff --git a/packages/db/src/validation/customers.ts b/packages/db/src/validation/customers.ts index 50c7d32..9a98f2f 100644 --- a/packages/db/src/validation/customers.ts +++ b/packages/db/src/validation/customers.ts @@ -44,5 +44,3 @@ export const customerSchema = z.object({ }), type: z.enum(CUSTOMER_TYPES), }); - -export const createCustomerSchema = customerSchema; From 1b15ddca2d1ddbc38818d4d73615244261376617 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:47:52 -0600 Subject: [PATCH 23/32] Renombra select-entity-button.tsx a new-entity-button.tsx El archivo exporta NewEntityButton. --- apps/web/src/components/customers/branches/grid.tsx | 2 +- apps/web/src/components/customers/contacts/contact-grid.tsx | 2 +- .../{select-entity-button.tsx => new-entity-button.tsx} | 0 apps/web/src/routes/_auth/branches/index.tsx | 2 +- apps/web/src/routes/_auth/contacts/index.tsx | 2 +- 5 files changed, 4 insertions(+), 4 deletions(-) rename apps/web/src/components/customers/{select-entity-button.tsx => new-entity-button.tsx} (100%) diff --git a/apps/web/src/components/customers/branches/grid.tsx b/apps/web/src/components/customers/branches/grid.tsx index c4ca5ec..1497ae5 100644 --- a/apps/web/src/components/customers/branches/grid.tsx +++ b/apps/web/src/components/customers/branches/grid.tsx @@ -2,7 +2,7 @@ import { skipToken } from "@tanstack/react-query"; import { Building2 } from "lucide-react"; import { useMemo, useState } from "react"; -import { NewEntityButton } from "@/components/customers/select-entity-button"; +import { NewEntityButton } from "@/components/customers/new-entity-button"; import { EntityGrid } from "@/components/customers/shared/entity-grid"; import { DEFAULT_BRANCH_FILTERS } from "@/components/customers/shared/filters"; import type { BranchFilters } from "@/components/customers/shared/filters"; diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx index 523b3e0..030d3e3 100644 --- a/apps/web/src/components/customers/contacts/contact-grid.tsx +++ b/apps/web/src/components/customers/contacts/contact-grid.tsx @@ -1,7 +1,7 @@ import { Users } from "lucide-react"; import { useMemo, useState } from "react"; -import { NewEntityButton } from "@/components/customers/select-entity-button"; +import { NewEntityButton } from "@/components/customers/new-entity-button"; import { EntityGrid } from "@/components/customers/shared/entity-grid"; import { DEFAULT_CONTACT_FILTERS } from "@/components/customers/shared/filters"; import type { ContactFilters } from "@/components/customers/shared/filters"; diff --git a/apps/web/src/components/customers/select-entity-button.tsx b/apps/web/src/components/customers/new-entity-button.tsx similarity index 100% rename from apps/web/src/components/customers/select-entity-button.tsx rename to apps/web/src/components/customers/new-entity-button.tsx diff --git a/apps/web/src/routes/_auth/branches/index.tsx b/apps/web/src/routes/_auth/branches/index.tsx index fa2aade..3a234be 100644 --- a/apps/web/src/routes/_auth/branches/index.tsx +++ b/apps/web/src/routes/_auth/branches/index.tsx @@ -4,7 +4,7 @@ import { Building2 } from "lucide-react"; import { z } from "zod"; import { BranchesList } from "@/components/customers/branches/grid"; -import { NewEntityButton } from "@/components/customers/select-entity-button"; +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({ diff --git a/apps/web/src/routes/_auth/contacts/index.tsx b/apps/web/src/routes/_auth/contacts/index.tsx index e8f826c..c1f643f 100644 --- a/apps/web/src/routes/_auth/contacts/index.tsx +++ b/apps/web/src/routes/_auth/contacts/index.tsx @@ -4,7 +4,7 @@ import { Users } from "lucide-react"; import { z } from "zod"; import { ContactsList } from "@/components/customers/contacts/contact-grid"; -import { NewEntityButton } from "@/components/customers/select-entity-button"; +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({ From c96d12d1a620b6adc14d3c7853adb8796346f682 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:48:21 -0600 Subject: [PATCH 24/32] =?UTF-8?q?Quita=20props=20sin=20uso=20y=20comentari?= =?UTF-8?q?os=20que=20repiten=20el=20c=C3=B3digo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BranchImage ya no recibe hasImage, onUploadClick ni onExpandClick, y ContactCard ya no recibe readOnly: ningún llamador los pasaba. branch-form y card usan el tipo Branch de util/branch-address en lugar de redeclararlo. --- .../customers/branches/branch-form.tsx | 3 +- .../components/customers/branches/card.tsx | 49 +---------------- .../customers/contacts/contact-card.tsx | 52 +++++++------------ 3 files changed, 22 insertions(+), 82 deletions(-) diff --git a/apps/web/src/components/customers/branches/branch-form.tsx b/apps/web/src/components/customers/branches/branch-form.tsx index eacf632..1389df7 100644 --- a/apps/web/src/components/customers/branches/branch-form.tsx +++ b/apps/web/src/components/customers/branches/branch-form.tsx @@ -1,4 +1,3 @@ -import type { AppRouterOutputs } from "@suni/api/routers/index"; import { branchSchema } from "@suni/db/validation/branches"; import { Button } from "@suni/ui/components/button"; import { revalidateLogic, useSelector } from "@tanstack/react-form"; @@ -12,7 +11,7 @@ import { useCreateBranch, useUpdateBranch } from "@/hooks/use-branches"; import { postalCodeQueryOptions, usePostalCode } from "@/hooks/use-postal-code"; import type { Settlement } from "@/hooks/use-postal-code"; -type Branch = AppRouterOutputs["branches"]["list"][number]; +import type { Branch } from "./util/branch-address"; type FormValues = z.input; diff --git a/apps/web/src/components/customers/branches/card.tsx b/apps/web/src/components/customers/branches/card.tsx index 07db5f4..01a15db 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 { @@ -15,21 +14,18 @@ import { Archive, ArchiveRestore, Building2, - Camera, ChevronRight, MapPin, MoreVertical, Pencil, Phone, - ZoomIn, } from "lucide-react"; import { useState } from "react"; import { BranchFormDialog } from "./branch-form-dialog"; import { ChangeBranchStatusDialog } from "./change-branch-status-dialog"; import { branchImageSrc, formatAddress } from "./util/branch-address"; - -type Branch = AppRouterOutputs["branches"]["list"][number]; +import type { Branch } from "./util/branch-address"; interface BranchCardProps { branch: Branch; @@ -39,23 +35,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 && ( - - )}
); } @@ -121,13 +82,11 @@ export default function BranchCard({ branch, customer }: BranchCardProps) { )} > - {/* Header */}
@@ -226,9 +185,7 @@ export default function BranchCard({ branch, customer }: BranchCardProps) {
- {/* Body */}
- {/* Address */}
@@ -237,7 +194,6 @@ export default function BranchCard({ branch, customer }: BranchCardProps) {
- {/* Phone */} {branch.phone && (
@@ -246,7 +202,6 @@ export default function BranchCard({ branch, customer }: BranchCardProps) { )}
- {/* View details footer */} - {/* Header */}
@@ -259,19 +253,16 @@ export default function ContactCard({ />
- {!readOnly && ( - setIsUpdateFormOpen(true)} - onToggleStatus={() => setIsStatusDialogOpen(true)} - /> - )} + setIsUpdateFormOpen(true)} + onToggleStatus={() => setIsStatusDialogOpen(true)} + parentHint={parentHint} + />
- {/* Body */}
- {/* Archived badge */} {isArchived && (
@@ -295,20 +285,16 @@ export default function ContactCard({ )}
- {!readOnly && ( - <> - - - - )} + + ); } From 23c966fe6cee477333a341b180b2357f21c86f5c Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:48:38 -0600 Subject: [PATCH 25/32] Centraliza el estado de archivado heredado del padre MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit archiveState replica la regla de la API (un cliente o sucursal archivados archivan lo que cuelga de ellos) y ArchiveMenuItem muestra Archivar, Desarchivar o Desarchivar deshabilitado con su indicación. Los usan la tarjeta, el encabezado y el detalle de sucursal y la tarjeta de contacto. --- .../customers/branches/branch-header.tsx | 9 +-- .../customers/branches/branch-info.tsx | 3 +- .../components/customers/branches/card.tsx | 41 +++--------- .../customers/contacts/contact-card.tsx | 62 +++---------------- .../customers/shared/archive-menu-item.tsx | 38 ++++++++++++ .../customers/shared/archive-state.ts | 28 +++++++++ .../$customerId/branches/$branchId/index.tsx | 5 +- 7 files changed, 96 insertions(+), 90 deletions(-) create mode 100644 apps/web/src/components/customers/shared/archive-menu-item.tsx create mode 100644 apps/web/src/components/customers/shared/archive-state.ts diff --git a/apps/web/src/components/customers/branches/branch-header.tsx b/apps/web/src/components/customers/branches/branch-header.tsx index f65d863..794085e 100644 --- a/apps/web/src/components/customers/branches/branch-header.tsx +++ b/apps/web/src/components/customers/branches/branch-header.tsx @@ -6,6 +6,7 @@ import { Link } from "@tanstack/react-router"; import { Archive, ArchiveRestore, Building2, Pencil } from "lucide-react"; import { useState } from "react"; +import { archiveState } from "../shared/archive-state"; import { ChangeBranchStatusDialog } from "./change-branch-status-dialog"; type Branch = AppRouterOutputs["branches"]["get"]; @@ -16,9 +17,9 @@ interface BranchHeaderProps { } export function BranchHeader({ branch, onEdit }: BranchHeaderProps) { - const isOwnArchived = !!branch.archived; - const isCustomerArchived = !!branch.customer?.archived; - const isArchived = isOwnArchived || isCustomerArchived; + const { isOwnArchived, isCustomerArchived, isArchived } = + archiveState(branch); + const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); return ( @@ -70,7 +71,7 @@ export function BranchHeader({ branch, onEdit }: BranchHeaderProps) { params={{ customerId: branch.customerId }} to="/customers/$customerId" > - {branch.customer?.name} + {branch.customer.name}

diff --git a/apps/web/src/components/customers/branches/branch-info.tsx b/apps/web/src/components/customers/branches/branch-info.tsx index ab71d38..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 || !!branch.customer?.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 01a15db..a0e559d 100644 --- a/apps/web/src/components/customers/branches/card.tsx +++ b/apps/web/src/components/customers/branches/card.tsx @@ -12,7 +12,6 @@ import { cn } from "@suni/ui/lib/utils"; import { Link } from "@tanstack/react-router"; import { Archive, - ArchiveRestore, Building2, ChevronRight, MapPin, @@ -22,6 +21,8 @@ import { } 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 { branchImageSrc, formatAddress } from "./util/branch-address"; @@ -63,9 +64,8 @@ function BranchImage({ name, src, isArchived }: BranchImageProps) { } 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); @@ -139,7 +139,7 @@ export default function BranchCard({ branch, customer }: BranchCardProps) { Acciones @@ -152,32 +152,11 @@ export default function BranchCard({ branch, customer }: BranchCardProps) { Editar )} - {/* An archived customer wins: unarchiving the branch alone would have no effect */} - {isCustomerArchived ? ( - - - - - Desarchivar - - - Desarchiva primero el cliente - - - - ) : ( - setIsStatusDialogOpen(true)} - > - {isOwnArchived ? ( - - ) : ( - - )} - {isOwnArchived ? "Desarchivar" : "Archivar"} - - )} + setIsStatusDialogOpen(true)} + parentHint={parentHint} + /> diff --git a/apps/web/src/components/customers/contacts/contact-card.tsx b/apps/web/src/components/customers/contacts/contact-card.tsx index 30717e0..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"; @@ -34,33 +35,9 @@ interface ContactCardProps { customer?: { id: string; name: string }; } -function getArchiveState(contact: Contact) { - const isOwn = !!contact.archived; - const isCustomer = !!contact.customer?.archived; - const isBranch = !!contact.branch?.archived; - - let parentHint: string | undefined; - - if (isCustomer) { - parentHint = "Desarchiva primero el cliente"; - } else if (isBranch) { - parentHint = "Desarchiva primero la sucursal"; - } - - return { - isOwn, - isCustomerArchived: isCustomer, - // A branch under an archived customer is effectively archived too. - isBranchArchived: isCustomer || isBranch, - parentHint, - isArchived: isOwn || isCustomer || isBranch, - }; -} - interface ContactMenuProps { isArchived: boolean; isOwnArchived: boolean; - /** Set when an archived parent blocks unarchiving the contact. */ parentHint?: string; onEdit: () => void; onToggleStatus: () => void; @@ -93,30 +70,11 @@ function ContactMenu({ )} - {/* An archived parent wins: unarchiving the contact alone would have no effect */} - {parentHint ? ( - - - - - Desarchivar - - {parentHint} - - - ) : ( - - {isOwnArchived ? ( - - ) : ( - - )} - {isOwnArchived ? "Desarchivar" : "Archivar"} - - )} + @@ -200,12 +158,12 @@ function ContactPhone({ contact }: { contact: Contact }) { export default function ContactCard({ contact, customer }: ContactCardProps) { const { - isOwn, + isOwnArchived, isCustomerArchived, isBranchArchived, parentHint, isArchived, - } = getArchiveState(contact); + } = archiveState(contact); const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false); const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); @@ -255,7 +213,7 @@ export default function ContactCard({ contact, customer }: ContactCardProps) { setIsUpdateFormOpen(true)} onToggleStatus={() => setIsStatusDialogOpen(true)} parentHint={parentHint} 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/routes/_auth/customers/$customerId/branches/$branchId/index.tsx b/apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx index 9556507..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 @@ -15,6 +15,7 @@ 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( @@ -61,12 +62,12 @@ function RouteComponent() { 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 isArchived = !!branch.archived || !!branch.customer?.archived; + const { isArchived } = archiveState(branch); const content: Record<(typeof TABS)[number]["value"], ReactNode> = { info: ( From bd3dd751105f56ec5ad9eeb3a95d3dddb74dc802 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:48:38 -0600 Subject: [PATCH 26/32] =?UTF-8?q?Calcula=20los=20filtros=20activos=20y=20l?= =?UTF-8?q?a=20b=C3=BAsqueda=20por=20nombre=20en=20un=20solo=20lugar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Los grids calculan hasFilters y se lo pasan a los filtros en lugar de que ambos lo calculen. matchingName y byName reemplazan la búsqueda sin acentos y el orden por nombre que estaban copiados en los grids y en los selectores de NewEntityButton. --- .../components/customers/branches/filters.tsx | 9 +++---- .../components/customers/branches/grid.tsx | 21 +++++++-------- .../customers/contacts/contact-filters.tsx | 5 ++-- .../customers/contacts/contact-grid.tsx | 26 +++++++++---------- .../customers/new-entity-button.tsx | 5 ++-- .../components/customers/shared/filters.ts | 20 ++++++++++++++ 6 files changed, 51 insertions(+), 35 deletions(-) diff --git a/apps/web/src/components/customers/branches/filters.tsx b/apps/web/src/components/customers/branches/filters.tsx index d2678f1..86c81b1 100644 --- a/apps/web/src/components/customers/branches/filters.tsx +++ b/apps/web/src/components/customers/branches/filters.tsx @@ -25,12 +25,14 @@ const MAX_CUSTOMER_BADGE_LENGTH = 20; interface BranchesFiltersProps { filters: BranchFilters; + hasFilters: boolean; onFiltersChange: (filters: BranchFilters) => void; customers?: { id: string; name: string }[]; } export function BranchesFilters({ filters, + hasFilters, onFiltersChange, customers, }: BranchesFiltersProps) { @@ -46,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 +89,7 @@ export function BranchesFilters({
)} - {hasActiveFilters && ( + {hasFilters && (
Filtros activos: diff --git a/apps/web/src/components/customers/branches/grid.tsx b/apps/web/src/components/customers/branches/grid.tsx index 1497ae5..d9d1852 100644 --- a/apps/web/src/components/customers/branches/grid.tsx +++ b/apps/web/src/components/customers/branches/grid.tsx @@ -4,11 +4,13 @@ import { useMemo, useState } from "react"; import { NewEntityButton } from "@/components/customers/new-entity-button"; import { EntityGrid } from "@/components/customers/shared/entity-grid"; -import { DEFAULT_BRANCH_FILTERS } from "@/components/customers/shared/filters"; +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 { stripAccents } from "@/lib/string-utils"; import BranchCard from "./card"; import { BranchesFilters } from "./filters"; @@ -38,16 +40,10 @@ export function BranchesList({ customerId ? skipToken : { status: "all" } ); - const visibleBranches = useMemo(() => { - const term = stripAccents(filters.name.trim()).toLowerCase(); - - return (query.data ?? []) - .filter( - (branch) => - !term || stripAccents(branch.name).toLowerCase().includes(term) - ) - .toSorted((a, b) => a.name.localeCompare(b.name, "es")); - }, [query.data, filters.name]); + const visibleBranches = useMemo( + () => matchingName(query.data ?? [], filters.name), + [query.data, filters.name] + ); const hasFilters = filters.name.trim() !== "" || @@ -59,6 +55,7 @@ export function BranchesList({ diff --git a/apps/web/src/components/customers/contacts/contact-filters.tsx b/apps/web/src/components/customers/contacts/contact-filters.tsx index 9e05023..f4b7ae4 100644 --- a/apps/web/src/components/customers/contacts/contact-filters.tsx +++ b/apps/web/src/components/customers/contacts/contact-filters.tsx @@ -23,16 +23,17 @@ const STATUS_OPTIONS: Option[] = [ interface ContactsFiltersProps { filters: ContactFilters; + hasFilters: boolean; onFiltersChange: (filters: ContactFilters) => void; } 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 @@ -62,7 +63,7 @@ export function ContactsFilters({ />
- {hasActiveFilters && ( + {hasFilters && (
Filtros activos: diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx index 030d3e3..66f60fd 100644 --- a/apps/web/src/components/customers/contacts/contact-grid.tsx +++ b/apps/web/src/components/customers/contacts/contact-grid.tsx @@ -3,10 +3,12 @@ import { useMemo, useState } from "react"; import { NewEntityButton } from "@/components/customers/new-entity-button"; import { EntityGrid } from "@/components/customers/shared/entity-grid"; -import { DEFAULT_CONTACT_FILTERS } from "@/components/customers/shared/filters"; +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 { stripAccents } from "@/lib/string-utils"; import ContactCard from "./contact-card"; import { ContactsFilters } from "./contact-filters"; @@ -31,16 +33,10 @@ export function ContactsList({ branchId, }); - const visibleContacts = useMemo(() => { - const term = stripAccents(filters.name.trim()).toLowerCase(); - - return (query.data ?? []) - .filter( - (contact) => - !term || stripAccents(contact.name).toLowerCase().includes(term) - ) - .toSorted((a, b) => a.name.localeCompare(b.name, "es")); - }, [query.data, filters.name]); + const visibleContacts = useMemo( + () => matchingName(query.data ?? [], filters.name), + [query.data, filters.name] + ); const hasFilters = filters.name.trim() !== "" || @@ -48,7 +44,11 @@ export function ContactsList({ return ( <> - + customers - .toSorted((a, b) => a.name.localeCompare(b.name, "es")) + .toSorted(byName) .map((customer) => ({ value: customer.id, label: customer.name })), [customers] ); @@ -64,7 +65,7 @@ function BranchPicker({ const options = useMemo( () => branches - .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/filters.ts b/apps/web/src/components/customers/shared/filters.ts index 63ed7e3..8ee4b3e 100644 --- a/apps/web/src/components/customers/shared/filters.ts +++ b/apps/web/src/components/customers/shared/filters.ts @@ -1,5 +1,7 @@ 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 { @@ -23,3 +25,21 @@ 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); +} From 474ffb0b7954758df5b48f3d314dabb8a94cd8cf Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:48:38 -0600 Subject: [PATCH 27/32] =?UTF-8?q?Extrae=20el=20autollenado=20por=20c=C3=B3?= =?UTF-8?q?digo=20postal=20a=20useAddressLookup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit customer-form y branch-form tenían copiada la consulta a SEPOMEX, el mensaje bajo el campo y el bloqueo de colonia, municipio y estado. --- .../customers/branches/branch-form.tsx | 105 +++--------------- .../components/customers/customer-form.tsx | 105 +++--------------- apps/web/src/hooks/use-postal-code.ts | 86 +++++++++++++- 3 files changed, 118 insertions(+), 178 deletions(-) diff --git a/apps/web/src/components/customers/branches/branch-form.tsx b/apps/web/src/components/customers/branches/branch-form.tsx index 1389df7..b9a1f61 100644 --- a/apps/web/src/components/customers/branches/branch-form.tsx +++ b/apps/web/src/components/customers/branches/branch-form.tsx @@ -1,15 +1,12 @@ 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"; import type { Branch } from "./util/branch-address"; @@ -22,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"; @@ -60,32 +55,12 @@ function toFormValues(branch?: Branch): FormValues { }; } -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(); @@ -111,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) => ( )} @@ -234,8 +165,8 @@ export function BranchForm({ )} @@ -245,8 +176,8 @@ export function BranchForm({ )} diff --git a/apps/web/src/components/customers/customer-form.tsx b/apps/web/src/components/customers/customer-form.tsx index 5592e28..a1121b8 100644 --- a/apps/web/src/components/customers/customer-form.tsx +++ b/apps/web/src/components/customers/customer-form.tsx @@ -6,8 +6,6 @@ import { 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,8 +13,7 @@ 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"> & { 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; @@ -72,25 +67,6 @@ function toFormValues(customer?: CustomerFormProps["customer"]): FormValues { }; } -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(); @@ -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/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, + }; +} From 24754e723661c307e2be3d8fb3d0bc76e2c17408 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:46:57 -0600 Subject: [PATCH 28/32] =?UTF-8?q?Marca=20ADMIN=5FEMAIL=20y=20ADMIN=5FNAME?= =?UTF-8?q?=20como=20p=C3=BAblicas=20en=20el=20schema=20de=20entorno?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.schema | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 From c1579fe8dd570aa47e174807ab5f8bfea60c5b76 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 13:56:26 -0600 Subject: [PATCH 29/32] Agrega la regla de lint suni/require-seller-scope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Las queries relacionales sobre customer y branch deben pasar columns: sellerColumns(context) o una lista explícita de columnas en true sin sellerId ni modifiedBy, y cargar al vendedor con sellerRelation. Así un procedimiento nuevo no puede entregarle la identidad del vendedor a un usuario que no es admin. --- oxlint.config.ts | 1 + tools/oxlint/suni/index.ts | 2 + .../oxlint/suni/rules/require-seller-scope.ts | 111 ++++++++++++++++++ 3 files changed, 114 insertions(+) create mode 100644 tools/oxlint/suni/rules/require-seller-scope.ts 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/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..b23c672 --- /dev/null +++ b/tools/oxlint/suni/rules/require-seller-scope.ts @@ -0,0 +1,111 @@ +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.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.", + }); + } + }, + }; + }, +}); From d291ffab091fac18b2c9eadc6647af950b76c7f2 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 14:19:52 -0600 Subject: [PATCH 30/32] Bloquea el teclado en las tarjetas obsoletas mientras carga el filtro --- apps/web/src/components/customers/shared/entity-grid.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/customers/shared/entity-grid.tsx b/apps/web/src/components/customers/shared/entity-grid.tsx index 4bb865a..756e931 100644 --- a/apps/web/src/components/customers/shared/entity-grid.tsx +++ b/apps/web/src/components/customers/shared/entity-grid.tsx @@ -66,8 +66,10 @@ export function EntityGrid({ aria-busy={query.isPlaceholderData} className={cn( "grid grid-cols-1 gap-4 transition-opacity md:grid-cols-2", - query.isPlaceholderData && "pointer-events-none opacity-50" + query.isPlaceholderData && "opacity-50" )} + // Stale rows stay visible while the new filter loads; block pointer and keyboard on them. + inert={query.isPlaceholderData} > {children} From 4a35587f5c7972c9e072dde9d14b3e98ab982415 Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 14:19:54 -0600 Subject: [PATCH 31/32] =?UTF-8?q?Restaura=20el=20l=C3=ADmite=20de=20255=20?= =?UTF-8?q?caracteres=20del=20puesto=20del=20contacto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/db/src/validation/contacts.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/db/src/validation/contacts.ts b/packages/db/src/validation/contacts.ts index 91e8c59..db8b9dd 100644 --- a/packages/db/src/validation/contacts.ts +++ b/packages/db/src/validation/contacts.ts @@ -9,7 +9,7 @@ export const contactSchema = z.object({ 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(100, "Máximo 100 caracteres"), + position: z.string().trim().max(255, "Máximo 255 caracteres"), }); export const createContactSchema = contactSchema.extend({ From 348eb256e81fb83b95be02c6759f7da1bfb00eac Mon Sep 17 00:00:00 2001 From: Adrian Ayala Date: Wed, 11 Nov 2026 14:19:55 -0600 Subject: [PATCH 32/32] Rechaza claves computadas en la lista de columnas de require-seller-scope --- tools/oxlint/suni/rules/require-seller-scope.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/oxlint/suni/rules/require-seller-scope.ts b/tools/oxlint/suni/rules/require-seller-scope.ts index b23c672..b821fb3 100644 --- a/tools/oxlint/suni/rules/require-seller-scope.ts +++ b/tools/oxlint/suni/rules/require-seller-scope.ts @@ -34,6 +34,7 @@ function isSafeAllowlist(node: ESTree.Node) { node.properties.every( (property) => property.type === "Property" && + !property.computed && property.value.type === "Literal" && property.value.value === true && !ADMIN_ONLY_COLUMNS.has(propertyName(property.key) ?? "")