From 415d523c0ee06d1b6cae61673e3bcb3921576c2a Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Wed, 4 Nov 2026 14:06:57 -0600
Subject: [PATCH 01/30] Crea contact y branch table, define relations y agrega
enum de contact
---
packages/db/src/relations.ts | 53 ++++++++++++++++++++++++-
packages/db/src/schema/branches.ts | 35 ++++++++++++++++
packages/db/src/schema/contact-enums.ts | 5 +++
packages/db/src/schema/contacts.ts | 29 ++++++++++++++
4 files changed, 121 insertions(+), 1 deletion(-)
create mode 100644 packages/db/src/schema/branches.ts
create mode 100644 packages/db/src/schema/contact-enums.ts
create mode 100644 packages/db/src/schema/contacts.ts
diff --git a/packages/db/src/relations.ts b/packages/db/src/relations.ts
index 46cf597..ee5736b 100644
--- a/packages/db/src/relations.ts
+++ b/packages/db/src/relations.ts
@@ -7,6 +7,8 @@ import {
user,
verification,
} from "./schema/auth";
+import { branch } from "./schema/branches";
+import { contact } from "./schema/contacts";
import { customer } from "./schema/customers";
const customerRelations = defineRelationsPart({ customer, user }, (r) => ({
@@ -19,8 +21,57 @@ const customerRelations = defineRelationsPart({ customer, user }, (r) => ({
},
}));
+const branchRelations = defineRelationsPart(
+ { branch, contact, customer, user },
+ (r) => ({
+ branch: {
+ customer: r.one.customer({
+ from: r.branch.customerId,
+ to: r.customer.id,
+ optional: false,
+ }),
+ seller: r.one.user({
+ from: r.branch.sellerId,
+ to: r.user.id,
+ optional: false,
+ }),
+ contacts: r.many.contact({
+ from: r.branch.id,
+ to: r.contact.branchId,
+ }),
+ },
+ })
+);
+
+const contactRelations = defineRelationsPart(
+ { branch, contact, customer },
+ (r) => ({
+ contact: {
+ customer: r.one.customer({
+ from: r.contact.customerId,
+ to: r.customer.id,
+ optional: false,
+ }),
+ branch: r.one.branch({
+ from: r.contact.branchId,
+ to: r.branch.id,
+ }),
+ },
+ })
+);
+
export const relations = {
- ...defineRelations({ account, session, user, verification, customer }),
+ ...defineRelations({
+ account,
+ session,
+ user,
+ verification,
+ customer,
+ branch,
+ contact,
+ }),
...authRelations,
...customerRelations,
+ ...branchRelations,
+ ...contactRelations,
};
diff --git a/packages/db/src/schema/branches.ts b/packages/db/src/schema/branches.ts
new file mode 100644
index 0000000..376ab14
--- /dev/null
+++ b/packages/db/src/schema/branches.ts
@@ -0,0 +1,35 @@
+import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
+
+import { user } from "./auth";
+import { customer } from "./customers";
+
+export const branch = pgTable("customer_branches", {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ name: text("name").notNull(),
+ street: text("street").notNull(),
+ intNumber: text("int_number"),
+ extNumber: text("ext_number").notNull(),
+ city: text("city").notNull(),
+ suburb: text("suburb").notNull(),
+ state: text("state").notNull(),
+ postalCode: text("postal_code").notNull(),
+ phone: text("phone"),
+ frontImageUrl: text("front_image_url"),
+ customerId: text("customer_id")
+ .notNull()
+ .references(() => customer.id),
+ sellerId: text("seller_id")
+ .notNull()
+ .references(() => user.id),
+ modifiedBy: text("modified_by")
+ .notNull()
+ .references(() => user.id),
+ archived: timestamp("archived"),
+ createdAt: timestamp("created_at").defaultNow().notNull(),
+ updatedAt: timestamp("updated_at")
+ .defaultNow()
+ .$onUpdate(() => new Date())
+ .notNull(),
+});
diff --git a/packages/db/src/schema/contact-enums.ts b/packages/db/src/schema/contact-enums.ts
new file mode 100644
index 0000000..c3b4ec0
--- /dev/null
+++ b/packages/db/src/schema/contact-enums.ts
@@ -0,0 +1,5 @@
+export const CONTACT_TYPES = [
+ "Compras",
+ "Cuentas por pagar",
+ "Solicitante del servicio",
+] as const;
diff --git a/packages/db/src/schema/contacts.ts b/packages/db/src/schema/contacts.ts
new file mode 100644
index 0000000..f70deaf
--- /dev/null
+++ b/packages/db/src/schema/contacts.ts
@@ -0,0 +1,29 @@
+import { pgEnum, pgTable, text, timestamp } from "drizzle-orm/pg-core";
+
+import { branch } from "./branches";
+import { CONTACT_TYPES } from "./contact-enums";
+import { customer } from "./customers";
+
+export const contactTypeEnum = pgEnum("contact_type", CONTACT_TYPES);
+
+export const contact = pgTable("contact", {
+ id: text("id")
+ .primaryKey()
+ .$defaultFn(() => crypto.randomUUID()),
+ name: text("name").notNull(),
+ email: text("email").notNull(),
+ phone: text("phone").notNull(),
+ phoneExtension: text("phone_extension"),
+ position: text("position"),
+ type: contactTypeEnum("type").notNull(),
+ customerId: text("customer_id")
+ .notNull()
+ .references(() => customer.id),
+ branchId: text("branch_id").references(() => branch.id),
+ archived: timestamp("archived"),
+ createdAt: timestamp("created_at").defaultNow().notNull(),
+ updatedAt: timestamp("updated_at")
+ .defaultNow()
+ .$onUpdate(() => new Date())
+ .notNull(),
+});
From 6fc5304db9c78dbf37dd6ce4cc2c17e588082885 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Wed, 4 Nov 2026 14:08:13 -0600
Subject: [PATCH 02/30] Crea validations de bran ches y contacts, crea shred
para validaciones compartidas
---
packages/db/src/validation/branches.ts | 30 +++++++++++++++++++++++++
packages/db/src/validation/contacts.ts | 28 +++++++++++++++++++++++
packages/db/src/validation/customers.ts | 9 +-------
packages/db/src/validation/shared.ts | 9 ++++++++
4 files changed, 68 insertions(+), 8 deletions(-)
create mode 100644 packages/db/src/validation/branches.ts
create mode 100644 packages/db/src/validation/contacts.ts
create mode 100644 packages/db/src/validation/shared.ts
diff --git a/packages/db/src/validation/branches.ts b/packages/db/src/validation/branches.ts
new file mode 100644
index 0000000..639ced6
--- /dev/null
+++ b/packages/db/src/validation/branches.ts
@@ -0,0 +1,30 @@
+import { z } from "zod";
+
+import { emptyToNull, required } from "./shared";
+
+export const branchFormSchema = z.object({
+ name: required("El nombre de la sucursal es requerido"),
+ street: required("La calle es requerida"),
+ intNumber: z.string().trim().max(20, "Máximo 20 caracteres"),
+ extNumber: required("El número exterior es requerido"),
+ city: required("El municipio es requerido"),
+ suburb: required("La colonia es requerida"),
+ state: required("El estado es requerido"),
+ postalCode: z.string().regex(/^\d{5}$/u, "Debe tener 5 dígitos"),
+ phone: z.string().regex(/^(?:\d{10})?$/u, "Debe tener 10 dígitos"),
+ frontImageUrl: z.string().trim().max(2048, "URL demasiado larga"),
+});
+
+export const branchInputSchema = branchFormSchema.extend({
+ intNumber: emptyToNull(branchFormSchema.shape.intNumber),
+ phone: emptyToNull(branchFormSchema.shape.phone),
+ frontImageUrl: emptyToNull(branchFormSchema.shape.frontImageUrl),
+});
+
+export const createBranchSchema = branchInputSchema.extend({
+ customerId: required("El cliente es requerido"),
+});
+
+export const updateBranchSchema = branchInputSchema.partial().extend({
+ archived: z.coerce.date().nullable().optional(),
+});
diff --git a/packages/db/src/validation/contacts.ts b/packages/db/src/validation/contacts.ts
new file mode 100644
index 0000000..deaddd2
--- /dev/null
+++ b/packages/db/src/validation/contacts.ts
@@ -0,0 +1,28 @@
+import { z } from "zod";
+
+import { CONTACT_TYPES } from "../schema/contact-enums";
+import { emptyToNull, required } from "./shared";
+
+export const contactFormSchema = z.object({
+ name: required("El nombre es requerido"),
+ email: z.email("Correo inválido"),
+ phone: z.string().regex(/^(?:\d{10})?$/u, "Debe tener 10 dígitos"),
+ phoneExtension: z.string().regex(/^\d{0,10}$/u, "Solo dígitos"),
+ position: z.string().trim().max(255, "Máximo 255 caracteres"),
+ type: z.enum(CONTACT_TYPES, { message: "Selecciona un tipo de contacto" }),
+});
+
+export const contactInputSchema = contactFormSchema.extend({
+ phoneExtension: emptyToNull(contactFormSchema.shape.phoneExtension),
+ position: emptyToNull(contactFormSchema.shape.position),
+});
+
+export const createContactSchema = contactInputSchema.extend({
+ customerId: required("El cliente es requerido"),
+ branchId: required("La sucursal es requerida"),
+});
+
+export const updateContactSchema = contactInputSchema.partial().extend({
+ customerId: required("El cliente es requerido").optional(),
+ archived: z.coerce.date().nullable().optional(),
+});
diff --git a/packages/db/src/validation/customers.ts b/packages/db/src/validation/customers.ts
index deb281e..4d1b9b4 100644
--- a/packages/db/src/validation/customers.ts
+++ b/packages/db/src/validation/customers.ts
@@ -1,10 +1,7 @@
import { z } from "zod";
import { ACQUISITION_CHANNELS, CUSTOMER_TYPES } from "../schema/customer-enums";
-
-function required(message = "Campo requerido") {
- return z.string().trim().min(1, message).max(255, "Máximo 255 caracteres");
-}
+import { emptyToNull, required } from "./shared";
// Shared by the web form and the API, so it must stay free of drizzle imports.
export const customerFormSchema = z.object({
@@ -25,10 +22,6 @@ export const customerFormSchema = z.object({
type: z.enum(CUSTOMER_TYPES),
});
-function emptyToNull(schema: z.ZodString) {
- return schema.nullable().transform((value) => value || null);
-}
-
// The form keeps "" for empty optional fields; the database stores null.
export const customerInputSchema = customerFormSchema.extend({
intNumber: emptyToNull(customerFormSchema.shape.intNumber),
diff --git a/packages/db/src/validation/shared.ts b/packages/db/src/validation/shared.ts
new file mode 100644
index 0000000..2fe833a
--- /dev/null
+++ b/packages/db/src/validation/shared.ts
@@ -0,0 +1,9 @@
+import { z } from "zod";
+
+export function required(message = "Campo requerido") {
+ return z.string().trim().min(1, message).max(255, "Máximo 255 caracteres");
+}
+
+export function emptyToNull(schema: z.ZodString) {
+ return schema.nullable().transform((value) => value || null);
+}
From c33e835d5ad7c808f30847d151978d548a1eeb5c Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 10:45:16 -0600
Subject: [PATCH 03/30] Borrra enum types contact
---
packages/db/src/schema/contact-enums.ts | 5 -----
packages/db/src/schema/contacts.ts | 6 +-----
packages/db/src/validation/contacts.ts | 2 --
3 files changed, 1 insertion(+), 12 deletions(-)
delete mode 100644 packages/db/src/schema/contact-enums.ts
diff --git a/packages/db/src/schema/contact-enums.ts b/packages/db/src/schema/contact-enums.ts
deleted file mode 100644
index c3b4ec0..0000000
--- a/packages/db/src/schema/contact-enums.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export const CONTACT_TYPES = [
- "Compras",
- "Cuentas por pagar",
- "Solicitante del servicio",
-] as const;
diff --git a/packages/db/src/schema/contacts.ts b/packages/db/src/schema/contacts.ts
index f70deaf..0b71333 100644
--- a/packages/db/src/schema/contacts.ts
+++ b/packages/db/src/schema/contacts.ts
@@ -1,11 +1,8 @@
-import { pgEnum, pgTable, text, timestamp } from "drizzle-orm/pg-core";
+import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
import { branch } from "./branches";
-import { CONTACT_TYPES } from "./contact-enums";
import { customer } from "./customers";
-export const contactTypeEnum = pgEnum("contact_type", CONTACT_TYPES);
-
export const contact = pgTable("contact", {
id: text("id")
.primaryKey()
@@ -15,7 +12,6 @@ export const contact = pgTable("contact", {
phone: text("phone").notNull(),
phoneExtension: text("phone_extension"),
position: text("position"),
- type: contactTypeEnum("type").notNull(),
customerId: text("customer_id")
.notNull()
.references(() => customer.id),
diff --git a/packages/db/src/validation/contacts.ts b/packages/db/src/validation/contacts.ts
index deaddd2..4008fc5 100644
--- a/packages/db/src/validation/contacts.ts
+++ b/packages/db/src/validation/contacts.ts
@@ -1,6 +1,5 @@
import { z } from "zod";
-import { CONTACT_TYPES } from "../schema/contact-enums";
import { emptyToNull, required } from "./shared";
export const contactFormSchema = z.object({
@@ -9,7 +8,6 @@ export const contactFormSchema = z.object({
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"),
- type: z.enum(CONTACT_TYPES, { message: "Selecciona un tipo de contacto" }),
});
export const contactInputSchema = contactFormSchema.extend({
From 9b4a7664b3c4490936fb211ce7c8be5887b97b8a Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 11:22:41 -0600
Subject: [PATCH 04/30] Crea CRUD de branches
---
packages/api/src/routers/branches/create.ts | 18 ++++++++
packages/api/src/routers/branches/get.ts | 33 ++++++++++++++
packages/api/src/routers/branches/index.ts | 11 +++++
packages/api/src/routers/branches/list.ts | 29 ++++++++++++
.../api/src/routers/branches/set-archived.ts | 35 +++++++++++++++
packages/api/src/routers/branches/update.ts | 44 +++++++++++++++++++
packages/api/src/routers/index.ts | 2 +
7 files changed, 172 insertions(+)
create mode 100644 packages/api/src/routers/branches/create.ts
create mode 100644 packages/api/src/routers/branches/get.ts
create mode 100644 packages/api/src/routers/branches/index.ts
create mode 100644 packages/api/src/routers/branches/list.ts
create mode 100644 packages/api/src/routers/branches/set-archived.ts
create mode 100644 packages/api/src/routers/branches/update.ts
diff --git a/packages/api/src/routers/branches/create.ts b/packages/api/src/routers/branches/create.ts
new file mode 100644
index 0000000..1a586ee
--- /dev/null
+++ b/packages/api/src/routers/branches/create.ts
@@ -0,0 +1,18 @@
+import { branch } from "@suni/db/schema/branches";
+import { createBranchSchema } from "@suni/db/validation/branches";
+
+import { protectedProcedure } from "../../index";
+
+export const create = protectedProcedure
+ .route({ method: "POST", path: "/" })
+ .input(createBranchSchema)
+ .handler(async ({ input, context }) => {
+ const userId = context.session.user.id;
+
+ const [created] = await context.db
+ .insert(branch)
+ .values({ ...input, sellerId: userId, modifiedBy: userId })
+ .returning({ id: branch.id });
+
+ return created;
+ });
diff --git a/packages/api/src/routers/branches/get.ts b/packages/api/src/routers/branches/get.ts
new file mode 100644
index 0000000..3ac6e25
--- /dev/null
+++ b/packages/api/src/routers/branches/get.ts
@@ -0,0 +1,33 @@
+import { ORPCError } from "@orpc/server";
+import { z } from "zod";
+
+import { isAdmin, protectedProcedure } from "../../index";
+
+function notFound() {
+ return new ORPCError("NOT_FOUND", { message: "Branch not found" });
+}
+
+export const get = protectedProcedure
+ .route({ method: "GET", path: "/{id}" })
+ .input(z.object({ id: z.string() }))
+ .handler(async ({ input, context }) => {
+ const admin = await isAdmin(context, context.session.user.id);
+
+ const found = await context.db.query.branch.findFirst({
+ where: admin
+ ? { id: input.id }
+ : { id: input.id, sellerId: context.session.user.id },
+ columns: admin ? undefined : { sellerId: false, modifiedBy: false },
+ with: {
+ customer: { columns: { id: true, name: true } },
+ contacts: true,
+ ...(admin && { seller: { columns: { id: true, name: true } } }),
+ },
+ });
+
+ if (!found) {
+ throw notFound();
+ }
+
+ return admin ? found : { ...found, seller: null };
+ });
diff --git a/packages/api/src/routers/branches/index.ts b/packages/api/src/routers/branches/index.ts
new file mode 100644
index 0000000..708dd61
--- /dev/null
+++ b/packages/api/src/routers/branches/index.ts
@@ -0,0 +1,11 @@
+import { o } from "../../index";
+import { create } from "./create";
+import { get } from "./get";
+import { list } from "./list";
+import { setArchived } from "./set-archived";
+import { update } from "./update";
+
+export const branchesRouter = o
+ .prefix("/branches")
+ .tag("Branches")
+ .router({ list, get, create, update, setArchived });
diff --git a/packages/api/src/routers/branches/list.ts b/packages/api/src/routers/branches/list.ts
new file mode 100644
index 0000000..b46a81c
--- /dev/null
+++ b/packages/api/src/routers/branches/list.ts
@@ -0,0 +1,29 @@
+import { z } from "zod";
+
+import { isAdmin, protectedProcedure } from "../../index";
+
+export const list = protectedProcedure
+ .route({ method: "GET", path: "/" })
+ .input(z.object({ customerId: z.string().optional() }))
+ .handler(async ({ input, context }) => {
+ const where = input.customerId ? { customerId: input.customerId } : {};
+
+ if (await isAdmin(context, context.session.user.id)) {
+ return context.db.query.branch.findMany({
+ where,
+ with: {
+ customer: { columns: { id: true, name: true } },
+ seller: { columns: { id: true, name: true } },
+ },
+ });
+ }
+
+ // Seller identity is admin-only.
+ const rows = await context.db.query.branch.findMany({
+ where: { ...where, sellerId: context.session.user.id },
+ columns: { sellerId: false, modifiedBy: false },
+ with: { customer: { columns: { id: true, name: true } } },
+ });
+
+ return rows.map((row) => ({ ...row, seller: null }));
+ });
diff --git a/packages/api/src/routers/branches/set-archived.ts b/packages/api/src/routers/branches/set-archived.ts
new file mode 100644
index 0000000..0339bee
--- /dev/null
+++ b/packages/api/src/routers/branches/set-archived.ts
@@ -0,0 +1,35 @@
+import { ORPCError } from "@orpc/server";
+import { branch } from "@suni/db/schema/branches";
+import { and, eq, sql } from "drizzle-orm";
+import { z } from "zod";
+
+import { isAdmin, protectedProcedure } from "../../index";
+
+export const setArchived = protectedProcedure
+ .route({ method: "POST", path: "/{id}/archived" })
+ .input(z.object({ id: z.string(), archived: z.boolean() }))
+ .handler(async ({ input, context }) => {
+ const userId = context.session.user.id;
+ const admin = await isAdmin(context, userId);
+
+ const [updated] = await context.db
+ .update(branch)
+ .set({
+ archived: input.archived
+ ? sql`COALESCE(${branch.archived}, now())`
+ : null,
+ modifiedBy: userId,
+ })
+ .where(
+ admin
+ ? eq(branch.id, input.id)
+ : and(eq(branch.id, input.id), eq(branch.sellerId, userId))
+ )
+ .returning({ id: branch.id });
+
+ if (!updated) {
+ throw new ORPCError("NOT_FOUND", { message: "Branch not found" });
+ }
+
+ return updated;
+ });
diff --git a/packages/api/src/routers/branches/update.ts b/packages/api/src/routers/branches/update.ts
new file mode 100644
index 0000000..43c8152
--- /dev/null
+++ b/packages/api/src/routers/branches/update.ts
@@ -0,0 +1,44 @@
+import { ORPCError } from "@orpc/server";
+import { branch } from "@suni/db/schema/branches";
+import { updateBranchSchema } from "@suni/db/validation/branches";
+import { and, eq, isNull } from "drizzle-orm";
+import { z } from "zod";
+
+import { isAdmin, protectedProcedure } from "../../index";
+
+export const update = protectedProcedure
+ .route({ method: "PATCH", path: "/{id}" })
+ .input(updateBranchSchema.omit({ archived: true }).extend({ id: z.string() }))
+ .handler(async ({ input, context }) => {
+ const { id, ...fields } = input;
+
+ const userId = context.session.user.id;
+
+ if (Object.values(fields).every((v) => v === undefined)) {
+ throw new ORPCError("BAD_REQUEST", {
+ message: "No hay campos para actualizar",
+ });
+ }
+
+ const admin = await isAdmin(context, userId);
+
+ const [updated] = await context.db
+ .update(branch)
+ .set({ ...fields, modifiedBy: userId })
+ .where(
+ and(
+ eq(branch.id, id),
+ isNull(branch.archived),
+ admin ? undefined : eq(branch.sellerId, userId)
+ )
+ )
+ .returning({ id: branch.id });
+
+ if (!updated) {
+ throw new ORPCError("NOT_FOUND", {
+ message: "La sucursal no existe o está archivada",
+ });
+ }
+
+ return updated;
+ });
diff --git a/packages/api/src/routers/index.ts b/packages/api/src/routers/index.ts
index c3c34c1..4332bf4 100644
--- a/packages/api/src/routers/index.ts
+++ b/packages/api/src/routers/index.ts
@@ -5,6 +5,7 @@ import type {
} from "@orpc/server";
import { protectedProcedure, publicProcedure } from "../index";
+import { branchesRouter } from "./branches";
import { customersRouter } from "./customers";
import { usersRouter } from "./users";
@@ -16,6 +17,7 @@ export const appRouter = {
})),
users: usersRouter,
customers: customersRouter,
+ branches: branchesRouter,
};
export type AppRouter = typeof appRouter;
From eededcf206df8a43bfcae291ea1ce2c1a1a774de Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 11:56:25 -0600
Subject: [PATCH 05/30] Crea CRUD de contacts
---
packages/api/src/routers/contacts/create.ts | 37 ++++++++++++
packages/api/src/routers/contacts/get.ts | 30 ++++++++++
packages/api/src/routers/contacts/index.ts | 11 ++++
packages/api/src/routers/contacts/list.ts | 26 +++++++++
.../api/src/routers/contacts/set-archived.ts | 45 +++++++++++++++
packages/api/src/routers/contacts/update.ts | 56 +++++++++++++++++++
packages/api/src/routers/index.ts | 2 +
packages/db/src/schema/contacts.ts | 4 ++
8 files changed, 211 insertions(+)
create mode 100644 packages/api/src/routers/contacts/create.ts
create mode 100644 packages/api/src/routers/contacts/get.ts
create mode 100644 packages/api/src/routers/contacts/index.ts
create mode 100644 packages/api/src/routers/contacts/list.ts
create mode 100644 packages/api/src/routers/contacts/set-archived.ts
create mode 100644 packages/api/src/routers/contacts/update.ts
diff --git a/packages/api/src/routers/contacts/create.ts b/packages/api/src/routers/contacts/create.ts
new file mode 100644
index 0000000..9f3e56f
--- /dev/null
+++ b/packages/api/src/routers/contacts/create.ts
@@ -0,0 +1,37 @@
+import { ORPCError } from "@orpc/server";
+import { contact } from "@suni/db/schema/contacts";
+import { createContactSchema } from "@suni/db/validation/contacts";
+
+import { isAdmin, protectedProcedure } from "../../index";
+
+export const create = protectedProcedure
+ .route({ method: "POST", path: "/" })
+ .input(createContactSchema)
+ .handler(async ({ input, context }) => {
+ const userId = context.session.user.id;
+ const admin = await isAdmin(context, userId);
+
+ const parent = await context.db.query.branch.findFirst({
+ where: {
+ id: input.branchId,
+ customerId: input.customerId,
+ archived: { isNull: true },
+ sellerId: admin ? undefined : userId,
+ },
+ columns: { id: true },
+ });
+
+ if (!parent) {
+ throw new ORPCError("NOT_FOUND", {
+ message:
+ "La sucursal no existe, está archivada o no pertenece al cliente",
+ });
+ }
+
+ const [created] = await context.db
+ .insert(contact)
+ .values({ ...input, modifiedBy: userId })
+ .returning({ id: contact.id });
+
+ return created;
+ });
diff --git a/packages/api/src/routers/contacts/get.ts b/packages/api/src/routers/contacts/get.ts
new file mode 100644
index 0000000..233a196
--- /dev/null
+++ b/packages/api/src/routers/contacts/get.ts
@@ -0,0 +1,30 @@
+import { ORPCError } from "@orpc/server";
+import { z } from "zod";
+
+import { isAdmin, protectedProcedure } from "../../index";
+
+export const get = protectedProcedure
+ .route({ method: "GET", path: "/{id}" })
+ .input(z.object({ id: z.string() }))
+ .handler(async ({ input, context }) => {
+ const userId = context.session.user.id;
+ const admin = await isAdmin(context, userId);
+
+ const found = await context.db.query.contact.findFirst({
+ where: {
+ id: input.id,
+ branch: admin ? undefined : { sellerId: userId },
+ },
+ columns: admin ? undefined : { modifiedBy: false },
+ with: {
+ branch: { columns: { id: true, name: true } },
+ customer: { columns: { id: true, name: true } },
+ },
+ });
+
+ if (!found) {
+ throw new ORPCError("NOT_FOUND", { message: "Contact not found" });
+ }
+
+ return found;
+ });
diff --git a/packages/api/src/routers/contacts/index.ts b/packages/api/src/routers/contacts/index.ts
new file mode 100644
index 0000000..7d49128
--- /dev/null
+++ b/packages/api/src/routers/contacts/index.ts
@@ -0,0 +1,11 @@
+import { o } from "../../index";
+import { create } from "./create";
+import { get } from "./get";
+import { list } from "./list";
+import { setArchived } from "./set-archived";
+import { update } from "./update";
+
+export const contactsRouter = o
+ .prefix("/contacts")
+ .tag("Contacts")
+ .router({ list, get, create, update, setArchived });
diff --git a/packages/api/src/routers/contacts/list.ts b/packages/api/src/routers/contacts/list.ts
new file mode 100644
index 0000000..c6704e7
--- /dev/null
+++ b/packages/api/src/routers/contacts/list.ts
@@ -0,0 +1,26 @@
+import { z } from "zod";
+
+import { isAdmin, protectedProcedure } from "../../index";
+
+export const list = protectedProcedure
+ .route({ method: "GET", path: "/" })
+ .input(
+ z.object({
+ customerId: z.string().optional(),
+ branchId: z.string().optional(),
+ })
+ )
+ .handler(async ({ input, context }) => {
+ const userId = context.session.user.id;
+ const admin = await isAdmin(context, userId);
+
+ return context.db.query.contact.findMany({
+ where: {
+ customerId: input.customerId,
+ branchId: input.branchId,
+ branch: admin ? undefined : { sellerId: userId },
+ },
+ columns: admin ? undefined : { modifiedBy: false },
+ with: { branch: { columns: { id: true, name: true } } },
+ });
+ });
diff --git a/packages/api/src/routers/contacts/set-archived.ts b/packages/api/src/routers/contacts/set-archived.ts
new file mode 100644
index 0000000..29fc631
--- /dev/null
+++ b/packages/api/src/routers/contacts/set-archived.ts
@@ -0,0 +1,45 @@
+import { ORPCError } from "@orpc/server";
+import { branch } from "@suni/db/schema/branches";
+import { contact } from "@suni/db/schema/contacts";
+import { and, eq, inArray, sql } from "drizzle-orm";
+import { z } from "zod";
+
+import { isAdmin, protectedProcedure } from "../../index";
+
+export const setArchived = protectedProcedure
+ .route({ method: "POST", path: "/{id}/archived" })
+ .input(z.object({ id: z.string(), archived: z.boolean() }))
+ .handler(async ({ input, context }) => {
+ const userId = context.session.user.id;
+ const admin = await isAdmin(context, userId);
+
+ const [updated] = await context.db
+ .update(contact)
+ .set({
+ archived: input.archived
+ ? sql`COALESCE(${contact.archived}, now())`
+ : null,
+ modifiedBy: userId,
+ })
+ .where(
+ and(
+ eq(contact.id, input.id),
+ admin
+ ? undefined
+ : inArray(
+ contact.branchId,
+ context.db
+ .select({ id: branch.id })
+ .from(branch)
+ .where(eq(branch.sellerId, userId))
+ )
+ )
+ )
+ .returning({ id: contact.id });
+
+ if (!updated) {
+ throw new ORPCError("NOT_FOUND", { message: "Contact not found" });
+ }
+
+ return updated;
+ });
diff --git a/packages/api/src/routers/contacts/update.ts b/packages/api/src/routers/contacts/update.ts
new file mode 100644
index 0000000..74e1a2f
--- /dev/null
+++ b/packages/api/src/routers/contacts/update.ts
@@ -0,0 +1,56 @@
+import { ORPCError } from "@orpc/server";
+import { branch } from "@suni/db/schema/branches";
+import { contact } from "@suni/db/schema/contacts";
+import { updateContactSchema } from "@suni/db/validation/contacts";
+import { and, eq, inArray, isNull } from "drizzle-orm";
+import { z } from "zod";
+
+import { isAdmin, protectedProcedure } from "../../index";
+
+export const update = protectedProcedure
+ .route({ method: "PATCH", path: "/{id}" })
+ .input(
+ updateContactSchema
+ .omit({ archived: true, customerId: true })
+ .extend({ id: z.string() })
+ )
+ .handler(async ({ input, context }) => {
+ const { id, ...fields } = input;
+ const userId = context.session.user.id;
+
+ if (Object.values(fields).every((v) => v === undefined)) {
+ throw new ORPCError("BAD_REQUEST", {
+ message: "No hay campos para actualizar",
+ });
+ }
+
+ const admin = await isAdmin(context, userId);
+
+ const [updated] = await context.db
+ .update(contact)
+ .set({ ...fields, modifiedBy: userId })
+ .where(
+ and(
+ eq(contact.id, id),
+ isNull(contact.archived),
+ admin
+ ? undefined
+ : inArray(
+ contact.branchId,
+ context.db
+ .select({ id: branch.id })
+ .from(branch)
+ .where(eq(branch.sellerId, userId))
+ )
+ )
+ )
+ .returning({ id: contact.id });
+
+ if (!updated) {
+ throw new ORPCError("NOT_FOUND", {
+ message: "El contacto no existe o está archivado",
+ });
+ }
+
+ return updated;
+ });
diff --git a/packages/api/src/routers/index.ts b/packages/api/src/routers/index.ts
index 4332bf4..7dbffa0 100644
--- a/packages/api/src/routers/index.ts
+++ b/packages/api/src/routers/index.ts
@@ -6,6 +6,7 @@ import type {
import { protectedProcedure, publicProcedure } from "../index";
import { branchesRouter } from "./branches";
+import { contactsRouter } from "./contacts";
import { customersRouter } from "./customers";
import { usersRouter } from "./users";
@@ -18,6 +19,7 @@ export const appRouter = {
users: usersRouter,
customers: customersRouter,
branches: branchesRouter,
+ contacts: contactsRouter,
};
export type AppRouter = typeof appRouter;
diff --git a/packages/db/src/schema/contacts.ts b/packages/db/src/schema/contacts.ts
index 0b71333..b745449 100644
--- a/packages/db/src/schema/contacts.ts
+++ b/packages/db/src/schema/contacts.ts
@@ -1,5 +1,6 @@
import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
+import { user } from "./auth";
import { branch } from "./branches";
import { customer } from "./customers";
@@ -17,6 +18,9 @@ export const contact = pgTable("contact", {
.references(() => customer.id),
branchId: text("branch_id").references(() => branch.id),
archived: timestamp("archived"),
+ modifiedBy: text("modified_by")
+ .notNull()
+ .references(() => user.id),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.defaultNow()
From d59f96755fd6a094ff9181101431a737ead59491 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 11:58:22 -0600
Subject: [PATCH 06/30] Crea hook para branches
---
apps/web/src/hooks/use-branches.ts | 75 ++++++++++++++++++++++++++++++
1 file changed, 75 insertions(+)
create mode 100644 apps/web/src/hooks/use-branches.ts
diff --git a/apps/web/src/hooks/use-branches.ts b/apps/web/src/hooks/use-branches.ts
new file mode 100644
index 0000000..2118735
--- /dev/null
+++ b/apps/web/src/hooks/use-branches.ts
@@ -0,0 +1,75 @@
+import type {
+ AppRouterInputs,
+ AppRouterOutputs,
+} from "@suni/api/routers/index";
+import {
+ keepPreviousData,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
+import { toast } from "sonner";
+
+import { client, orpc } from "@/utils/orpc";
+
+type BranchRow = AppRouterOutputs["branches"]["list"][number];
+
+export function useListBranches(params: AppRouterInputs["branches"]["list"]) {
+ return useQuery({
+ ...orpc.branches.list.queryOptions({ input: params }),
+ placeholderData: keepPreviousData,
+ });
+}
+
+export function useCreateBranch() {
+ const queryClient = useQueryClient();
+
+ return useMutation(
+ orpc.branches.create.mutationOptions({
+ onSuccess: async () => {
+ toast.success("Sucursal creada");
+ await queryClient.invalidateQueries({ queryKey: orpc.branches.key() });
+ },
+ onError: (error) => toast.error(error.message),
+ })
+ );
+}
+
+export function useUpdateBranch() {
+ const queryClient = useQueryClient();
+
+ return useMutation(
+ orpc.branches.update.mutationOptions({
+ onSuccess: async () => {
+ toast.success("Sucursal actualizada");
+ await queryClient.invalidateQueries({ queryKey: orpc.branches.key() });
+ },
+ onError: (error) => toast.error(error.message),
+ })
+ );
+}
+
+export function useArchiveBranch() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({
+ id,
+ archived,
+ }: Pick & { archived: boolean }) =>
+ client.branches.setArchived({ id, archived }),
+ onSuccess: async (_data, { archived, name }) => {
+ await queryClient.invalidateQueries({ queryKey: orpc.branches.key() });
+ toast.success(archived ? "Sucursal archivada" : "Sucursal desarchivada", {
+ description: `Se ${archived ? "archivó" : "desarchivó"} ${name} con éxito.`,
+ });
+ },
+ onError: (error) => {
+ console.error("Error al archivar la sucursal:", error);
+ toast.error("Algo salió mal...", {
+ description:
+ "Hubo un error al cambiar el estado de la sucursal. Intenta de nuevo.",
+ });
+ },
+ });
+}
From b48c8ef36fd5d299498b9dedc9ba5e89a9054965 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 11:59:13 -0600
Subject: [PATCH 07/30] Crea hook para contacts
---
apps/web/src/hooks/use-contacts.ts | 75 ++++++++++++++++++++++++++++++
1 file changed, 75 insertions(+)
create mode 100644 apps/web/src/hooks/use-contacts.ts
diff --git a/apps/web/src/hooks/use-contacts.ts b/apps/web/src/hooks/use-contacts.ts
new file mode 100644
index 0000000..6e26b93
--- /dev/null
+++ b/apps/web/src/hooks/use-contacts.ts
@@ -0,0 +1,75 @@
+import type {
+ AppRouterInputs,
+ AppRouterOutputs,
+} from "@suni/api/routers/index";
+import {
+ keepPreviousData,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
+import { toast } from "sonner";
+
+import { client, orpc } from "@/utils/orpc";
+
+type ContactRow = AppRouterOutputs["contacts"]["list"][number];
+
+export function useListContacts(params: AppRouterInputs["contacts"]["list"]) {
+ return useQuery({
+ ...orpc.contacts.list.queryOptions({ input: params }),
+ placeholderData: keepPreviousData,
+ });
+}
+
+export function useCreateContact() {
+ const queryClient = useQueryClient();
+
+ return useMutation(
+ orpc.contacts.create.mutationOptions({
+ onSuccess: async () => {
+ toast.success("Contacto creado");
+ await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() });
+ },
+ onError: (error) => toast.error(error.message),
+ })
+ );
+}
+
+export function useUpdateContact() {
+ const queryClient = useQueryClient();
+
+ return useMutation(
+ orpc.contacts.update.mutationOptions({
+ onSuccess: async () => {
+ toast.success("Contacto actualizado");
+ await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() });
+ },
+ onError: (error) => toast.error(error.message),
+ })
+ );
+}
+
+export function useArchiveContact() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({
+ id,
+ archived,
+ }: Pick & { archived: boolean }) =>
+ client.contacts.setArchived({ id, archived }),
+ onSuccess: async (_data, { archived, name }) => {
+ await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() });
+ toast.success(archived ? "Contacto archivado" : "Contacto desarchivado", {
+ description: `Se ${archived ? "archivó" : "desarchivó"} a ${name} con éxito.`,
+ });
+ },
+ onError: (error) => {
+ console.error("Error al archivar el contacto:", error);
+ toast.error("Algo salió mal...", {
+ description:
+ "Hubo un error al cambiar el estado del contacto. Intenta de nuevo.",
+ });
+ },
+ });
+}
From 68aae54d27643fb0ee1042fb5ca88c6e7a0849d8 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 18:45:43 -0600
Subject: [PATCH 08/30] Agrega export db
---
packages/db/src/schema/index.ts | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts
index 7f5f1ec..4cbb2bd 100644
--- a/packages/db/src/schema/index.ts
+++ b/packages/db/src/schema/index.ts
@@ -1,3 +1,7 @@
export * from "./auth";
+export * from "./branches";
+
+export * from "./contacts";
+
export * from "./customers";
From a5ecbadc4fdb3a9be6656a09ebe54dce17ee83b6 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 18:46:11 -0600
Subject: [PATCH 09/30] Crea component dialog
---
packages/ui/src/components/dialog.tsx | 139 ++++++++++++++++++++++++++
1 file changed, 139 insertions(+)
create mode 100644 packages/ui/src/components/dialog.tsx
diff --git a/packages/ui/src/components/dialog.tsx b/packages/ui/src/components/dialog.tsx
new file mode 100644
index 0000000..4b22437
--- /dev/null
+++ b/packages/ui/src/components/dialog.tsx
@@ -0,0 +1,139 @@
+import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
+import { X } from "lucide-react";
+import * as React from "react";
+
+import { cn } from "../lib/utils";
+
+function Dialog(props: DialogPrimitive.Root.Props) {
+ return ;
+}
+
+function DialogTrigger(props: DialogPrimitive.Trigger.Props) {
+ return ;
+}
+
+function DialogPortal(props: DialogPrimitive.Portal.Props) {
+ return ;
+}
+
+function DialogClose(props: DialogPrimitive.Close.Props) {
+ return ;
+}
+
+function DialogOverlay({
+ className,
+ ...props
+}: DialogPrimitive.Backdrop.Props) {
+ return (
+
+ );
+}
+
+interface DialogContentProps extends DialogPrimitive.Popup.Props {
+ /** Muestra el botón "X" en la esquina superior derecha. */
+ showCloseButton?: boolean;
+}
+
+function DialogContent({
+ className,
+ children,
+ showCloseButton = true,
+ ...props
+}: DialogContentProps) {
+ return (
+
+
+
+ {children}
+ {showCloseButton && (
+
+
+ Cerrar
+
+ )}
+
+
+ );
+}
+
+function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ );
+}
+
+function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ );
+}
+
+function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
+ return (
+
+ );
+}
+
+function DialogDescription({
+ className,
+ ...props
+}: DialogPrimitive.Description.Props) {
+ return (
+
+ );
+}
+
+export {
+ Dialog,
+ DialogPortal,
+ DialogOverlay,
+ DialogTrigger,
+ DialogClose,
+ DialogContent,
+ DialogHeader,
+ DialogFooter,
+ DialogTitle,
+ DialogDescription,
+};
\ No newline at end of file
From 59b6c101e040030a8ea4e3adc648e93afbc1064f Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 18:46:41 -0600
Subject: [PATCH 10/30] Agrega imagen placeholder
---
apps/web/public/placeholder.webp | Bin 0 -> 3396 bytes
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 apps/web/public/placeholder.webp
diff --git a/apps/web/public/placeholder.webp b/apps/web/public/placeholder.webp
new file mode 100644
index 0000000000000000000000000000000000000000..4fe0d62f6058cafd7e0ed5f0425f446f9e77377f
GIT binary patch
literal 3396
zcmeHHc|6qn8Xhx)GPcMhO&Md?gvvDb22n!B8qSryGEQhL$2b!+s4$iZmsGBi;#dng
zmN}N}k);ebYlN&BD*H0WmUBC|(|`Am`}v&t=bhj7KF{}gp7%A?*V9wy0RS%QYGW<2
z%5cSv|82Z%No;aY!Elh~wNv->ABiJU#8k)jka)se-B*c;>t&qw^`FIl!xL`MNBbib
zY8`z(uDf~FyX6m2en#3cuP!y3&j+q8V%e&4YzlE5S(bm7|3?Yvm0&y8F|>={bOmu-
z2(1Zvo;2LYknV#62Q8XE3TfJO8YZ4_ei1A6jS{^Fms77^F>f|B3jAsBIsuY^}|%M<>heSHErq>2Zu6t;{?0M
zodMTpmRKU~{ypBfBIKe*H=420kvg>}zA!9F)qA`>{lZ4^9PuBQ;pcF1lG#Sv1Pu^Z
zl-W-(J4D8Y6?FkylF&^&t0_?3a2#?+|GP7BgYb|=PeDx6t{DWX8-73so~Aauf#cCs
zBd_D}&zgMpT_hD5Y?}#G*q>O~hTOrvp4)6IQKxIGecjIT9~;22k>xT9;P@}p#@o{t
zt3#-OW;Zvg+vbrs`M#B1ipaxFCxE3^vtv`0f=%R_1l_bBH
z)y-X(H_Xm@=E60p6m{?%RE;F~UO($@!QC1`YH~l(MvE%x8@5K-VsO?B@&hL!LHG}A
zHe=x|O!ZX`=nNGc0M{52{hwyi!#WWV9G#-seF|zS^R$kM5^0u3PG5WBX*r
zt6Db2deum_To0|El|w-d@6OzOIJw`;;7!4nMLX_}x2I;rgO*#-%bmAZFZb1gOwLtLFS4bO*S+ut)_Mqz$j&7&zh%M;dsR8FR+4)Xw0LSsCCk?*l
zw)I8&Y^?!oXULC#(1zMT9ruHTz2DNJbo}=MfN7l;{4zPQp?-$C-ikE~XxDe_
zwvd_gyP4UJ-0pccPN#Ox0yC4+muTr`+GB{l4)-60oi+K3owT#4I;da8=1l0kA1cxoL9tyJT^#@m{o!MpH3gU*j#n3
zI0Aq^(yjcyU(``Dq9>K<4#BffMa`%&oLxH~t!&?Xof+G{@#@h<@=%0`^kJ%j8kM3_
z8Gu72e`2y#JB|RU0PYe$nwFIYN6qElV8e?)w>FrZw^B&-8I0|{M5iEOP9w87*zfdD
z=(s4^Lp1X+z@+=KK>9*LNE%u5r#F#v)3{5KR>dvTPgqz9p}D^(z&mstm
z{G9tE&;xu1p$eevboV9fNVE{ArcrNDbtLN--F;@aV5mNCx1Mx>a9iBt829QPj=a*j
zWh{iW!q7;4k-EmA+Mv0wj@OE6L_fLQW$efD2PF=4*ad+K=du%#4FVmwmC}mkUtVw{
zrk2}c*`&JQndo|wM2Yj9^C5Z`iy>|}W~*@QdcN1O&@(wFW&NouEPB=?LK{vtgK-|f
zlkpDFF{rgT-w8q!tzuM>{{b|Ax%9ygPsi0IAWLITK84-@5zAHYlXAg(k5*z(dM|_6
zo|1^M=T?SXco1|+bqN7FD0vF8iZ?V~GUFfWgu`kZ?f3d#jqbaCIi!D*C*e#tH2-9v
zRf7FAdd)m#?s#Vt{e`R!n^3l)p9_pL@Tt3fr;_NrhZ$om|UKI}Q!9zA(X)5>!zjCA5w!PVMMA0&6lTE$UMX5t{tes^K1}BrUL2&te9wx&lLzD$^N0^Pt*AhmaFXwKS#1G1R~P=Zu<;{tOj~w$O|^k
zI&ym*#z-0g7QaPzKX7n&(hGGU*b3%i0lIW7w=}_^K^S6vJg2C${vc
zmGb85(kj-@T^lcup*a(d0=62PO8Oe%;|W~+2h_r^X=9x%dlr1uT}?cUC8@2h7edc1
z68oQl$XbPdahFhG5dqYNWOayY1thd~aahvRzDrC0P34qPk=?IVJ!ybfv*r<736#Xx
zMk{t&1rl?IlExTmx}9x?N4W%^PdG54Fpo8D85q8Sel^}#&xnafQc_O|9*p)QXq$GV
zZ#bWsmZLpuev4PR#3}9u^(`3_;6(!^nh2s(hX#ke5-xK#W@5
ziHIPOX8}VahLQdm3LZT@C}d9gu!t>S?^T5OPw{1f)+YEKiwtvDER6)f`?Z(>FXcJ~
zAMWQcMHTN0?+FJVY}F%8-I1DCEYI+s&7ECluEg+_+cuY}F-{?UwqweL&DG>_%!`8X
zU;6daMdRmb3Q-(_MY!{mE_hmWUk9rLqtwQZ2f3@5FRqPE1q8Re%hrJ&P9RS=^v!+r
zjgz~VlTk521Mv2gX=wUS5iGkRO@^7t5bM$Yn`Xop`joTAjOXJG&LtDyTRl6^eh2h>
Bl>-0(
literal 0
HcmV?d00001
From 7df64e0e52f1959653bc17f1aa615ece0df5b76b Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 18:47:04 -0600
Subject: [PATCH 11/30] Agrega contacts en list
---
packages/api/src/routers/branches/list.ts | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/packages/api/src/routers/branches/list.ts b/packages/api/src/routers/branches/list.ts
index b46a81c..1b8298f 100644
--- a/packages/api/src/routers/branches/list.ts
+++ b/packages/api/src/routers/branches/list.ts
@@ -14,6 +14,7 @@ export const list = protectedProcedure
with: {
customer: { columns: { id: true, name: true } },
seller: { columns: { id: true, name: true } },
+ contacts: true,
},
});
}
@@ -22,7 +23,7 @@ export const list = protectedProcedure
const rows = await context.db.query.branch.findMany({
where: { ...where, sellerId: context.session.user.id },
columns: { sellerId: false, modifiedBy: false },
- with: { customer: { columns: { id: true, name: true } } },
+ with: { customer: { columns: { id: true, name: true } }, contacts: true },
});
return rows.map((row) => ({ ...row, seller: null }));
From d93f0963a75f64ed88faf331529fefa3d1dd323b Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 18:48:49 -0600
Subject: [PATCH 12/30] Crea branch Form
---
.../customers/branches/branch-form.tsx | 300 ++++++++++++++++++
1 file changed, 300 insertions(+)
create mode 100644 apps/web/src/components/customers/branches/branch-form.tsx
diff --git a/apps/web/src/components/customers/branches/branch-form.tsx b/apps/web/src/components/customers/branches/branch-form.tsx
new file mode 100644
index 0000000..9b8523f
--- /dev/null
+++ b/apps/web/src/components/customers/branches/branch-form.tsx
@@ -0,0 +1,300 @@
+import type { AppRouterOutputs } from "@suni/api/routers/index";
+import {
+ branchFormSchema,
+ branchInputSchema,
+} from "@suni/db/validation/branches";
+import { Button } from "@suni/ui/components/button";
+import { revalidateLogic, useSelector } from "@tanstack/react-form";
+import { useQueryClient } from "@tanstack/react-query";
+import type { UseQueryResult } from "@tanstack/react-query";
+import { Loader2 } from "lucide-react";
+import type { z } from "zod";
+
+import { useAppForm } from "@/components/form/use-app-form";
+import { useCreateBranch, useUpdateBranch } from "@/hooks/use-branches";
+import { postalCodeQueryOptions, usePostalCode } from "@/hooks/use-postal-code";
+import type { Settlement } from "@/hooks/use-postal-code";
+
+type Branch = AppRouterOutputs["branches"]["list"][number];
+
+type FormValues = z.input;
+
+interface BranchFormProps {
+ customerId: string;
+ branch?: Branch;
+ onSuccess?: () => void;
+ onCancel: () => void;
+}
+
+const POSTAL_CODE_LENGTH = 5;
+
+const PHONE_LENGTH = 10;
+
+const FILLED_BY_POSTAL_CODE = "Se llena con el código postal";
+
+const EMPTY_VALUES: FormValues = {
+ name: "",
+ street: "",
+ extNumber: "",
+ intNumber: "",
+ postalCode: "",
+ suburb: "",
+ city: "",
+ state: "",
+ phone: "",
+ frontImageUrl: "",
+};
+
+function toFormValues(branch?: Branch): FormValues {
+ if (!branch) {
+ return EMPTY_VALUES;
+ }
+
+ return {
+ name: branch.name,
+ street: branch.street,
+ extNumber: branch.extNumber,
+ intNumber: branch.intNumber ?? "",
+ postalCode: branch.postalCode,
+ suburb: branch.suburb,
+ city: branch.city,
+ state: branch.state,
+ phone: branch.phone ?? "",
+ frontImageUrl: branch.frontImageUrl ?? "",
+ };
+}
+
+function postalCodeStatus(
+ query: UseQueryResult,
+ settlements: Settlement[]
+): string | null {
+ if (query.isFetching) {
+ return "Buscando código postal…";
+ }
+
+ if (query.isError) {
+ return "No se pudo consultar el código postal. Captura la dirección a mano.";
+ }
+
+ if (query.isSuccess && settlements.length === 0) {
+ return "No encontramos ese código postal. Captura la dirección a mano.";
+ }
+
+ return null;
+}
+
+export function BranchForm({
+ customerId,
+ branch,
+ onSuccess,
+ onCancel,
+}: BranchFormProps) {
+ const queryClient = useQueryClient();
+ const createBranch = useCreateBranch();
+ const updateBranch = useUpdateBranch();
+
+ const submitting = createBranch.isPending || updateBranch.isPending;
+
+ const form = useAppForm({
+ defaultValues: toFormValues(branch),
+ validationLogic: revalidateLogic(),
+ validators: { onDynamic: branchFormSchema },
+ onSubmit: ({ value }) => {
+ const parsed = branchInputSchema.parse(value);
+
+ if (branch) {
+ updateBranch.mutate(
+ { id: branch.id, ...parsed },
+ { onSuccess: () => onSuccess?.() }
+ );
+ } else {
+ createBranch.mutate(
+ { customerId, ...parsed },
+ { onSuccess: () => onSuccess?.() }
+ );
+ }
+ },
+ });
+
+ const zip = useSelector(form.store, (state) => state.values.postalCode);
+ const postalCode = usePostalCode(zip);
+ const settlements = postalCode.data ?? [];
+
+ // SEPOMEX define municipio y estado; solo un fallo o un código inexistente los desbloquea.
+ const regionLocked = !(
+ postalCode.isError ||
+ (postalCode.isSuccess && settlements.length === 0)
+ );
+
+ // La colonia solo espera a la consulta; después queda abierta por si SEPOMEX no la tiene.
+ const suburbLocked = !(postalCode.isSuccess || postalCode.isError);
+
+ const suburbOptions = [...new Set(settlements.map((s) => s.d_asenta))].map(
+ (value) => ({ value, label: value })
+ );
+
+ const fillAddress = async (value: string) => {
+ form.setFieldValue("suburb", "");
+ form.setFieldValue("city", "");
+ form.setFieldValue("state", "");
+
+ if (value.length !== POSTAL_CODE_LENGTH) {
+ return;
+ }
+
+ let found: Settlement[];
+
+ try {
+ found = await queryClient.query(postalCodeQueryOptions(value));
+ } catch {
+ // usePostalCode muestra el error bajo el campo.
+ return;
+ }
+
+ // El usuario siguió escribiendo mientras corría la petición.
+ if (form.getFieldValue("postalCode") !== value) {
+ return;
+ }
+
+ const [first] = found;
+
+ if (!first) {
+ return;
+ }
+
+ form.setFieldValue("city", first.d_mnpio);
+ form.setFieldValue("state", first.d_estado);
+
+ if (found.length === 1) {
+ form.setFieldValue("suburb", first.d_asenta);
+ }
+ };
+
+ return (
+
+ );
+}
From 2fa3bb98efa5bdbab76c017e440d80df36877c3d Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 18:54:20 -0600
Subject: [PATCH 13/30] Agrega branch components
---
.../customers/branches/branch-form-dialog.tsx | 48 ++++
.../customers/branches/branch-header.tsx | 104 +++++++
.../customers/branches/branch-info.tsx | 85 ++++++
.../components/customers/branches/card.tsx | 253 ++++++++++++++++++
.../branches/change-branch-status-dialog.tsx | 93 +++++++
.../components/customers/branches/filters.tsx | 161 +++++++++++
.../components/customers/branches/grid.tsx | 123 +++++++++
.../customers/branches/util/branch-address.ts | 17 ++
.../$customerId/branches/$branchId/index.tsx | 107 ++++++++
.../_auth/customers/$customerId/index.tsx | 11 +-
10 files changed, 1001 insertions(+), 1 deletion(-)
create mode 100644 apps/web/src/components/customers/branches/branch-form-dialog.tsx
create mode 100644 apps/web/src/components/customers/branches/branch-header.tsx
create mode 100644 apps/web/src/components/customers/branches/branch-info.tsx
create mode 100644 apps/web/src/components/customers/branches/card.tsx
create mode 100644 apps/web/src/components/customers/branches/change-branch-status-dialog.tsx
create mode 100644 apps/web/src/components/customers/branches/filters.tsx
create mode 100644 apps/web/src/components/customers/branches/grid.tsx
create mode 100644 apps/web/src/components/customers/branches/util/branch-address.ts
create mode 100644 apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx
diff --git a/apps/web/src/components/customers/branches/branch-form-dialog.tsx b/apps/web/src/components/customers/branches/branch-form-dialog.tsx
new file mode 100644
index 0000000..247b608
--- /dev/null
+++ b/apps/web/src/components/customers/branches/branch-form-dialog.tsx
@@ -0,0 +1,48 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@suni/ui/components/dialog";
+import type { ComponentProps } from "react";
+
+import { BranchForm } from "./branch-form";
+
+interface BranchFormDialogProps extends Pick<
+ ComponentProps,
+ "branch" | "customerId"
+> {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function BranchFormDialog({
+ branch,
+ customerId,
+ open,
+ onOpenChange,
+}: BranchFormDialogProps) {
+ return (
+
+ );
+}
diff --git a/apps/web/src/components/customers/branches/branch-header.tsx b/apps/web/src/components/customers/branches/branch-header.tsx
new file mode 100644
index 0000000..2605152
--- /dev/null
+++ b/apps/web/src/components/customers/branches/branch-header.tsx
@@ -0,0 +1,104 @@
+import type { AppRouterOutputs } from "@suni/api/routers/index";
+import { Badge } from "@suni/ui/components/badge";
+import { Button } from "@suni/ui/components/button";
+import { cn } from "@suni/ui/lib/utils";
+import { Archive, ArchiveRestore, Building2, Pencil } from "lucide-react";
+import { useState } from "react";
+
+import { ChangeBranchStatusDialog } from "./change-branch-status-dialog";
+
+type Branch = AppRouterOutputs["branches"]["get"];
+
+interface BranchHeaderProps {
+ branch: Pick;
+ customerName: string;
+ onEdit?: () => void;
+}
+
+export function BranchHeader({
+ branch,
+ customerName,
+ onEdit,
+}: BranchHeaderProps) {
+ const isArchived = !!branch.archived;
+ const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
+
+ return (
+ <>
+
+
+
+
+
+
+
+
+ {branch.name}
+
+ {isArchived ? (
+
+
+ Archivada
+
+ ) : null}
+
+
+
+ Sucursal de {customerName}
+
+
+
+ {onEdit ? (
+
+ {isArchived ? null : (
+
+ )}
+
+
+ ) : null}
+
+
+
+ >
+ );
+}
diff --git a/apps/web/src/components/customers/branches/branch-info.tsx b/apps/web/src/components/customers/branches/branch-info.tsx
new file mode 100644
index 0000000..2569104
--- /dev/null
+++ b/apps/web/src/components/customers/branches/branch-info.tsx
@@ -0,0 +1,85 @@
+import { cn } from "@suni/ui/lib/utils";
+import { Camera, MapPin, Phone, ZoomIn } from "lucide-react";
+
+import type { Branch } from "./util/branch-address";
+import { formatAddress } from "./util/branch-address";
+
+const overlayButton =
+ "flex size-10 items-center justify-center rounded-full bg-black/50 text-white transition-colors hover:bg-black/70";
+
+interface BranchInfoContentProps {
+ branch: Branch;
+ branchImage: string;
+ onImagePreview: () => void;
+ onImageUpload?: () => void;
+}
+
+export function BranchInfoContent({
+ branch,
+ branchImage,
+ onImagePreview,
+ onImageUpload,
+}: BranchInfoContentProps) {
+ const isArchived = !!branch.archived;
+ const address = formatAddress(branch);
+
+ return (
+
+
+ Dirección
+
+
+
+
+ {address.streetLine}
+ {address.locationLine}
+
+
+
+ {branch.phone ? (
+
+ ) : null}
+
+
+
+
+
+ Imagen de fachada
+
+
+

+
+
+ {!isArchived && onImageUpload ? (
+
+ ) : null}
+
+
+
+
+ );
+}
diff --git a/apps/web/src/components/customers/branches/card.tsx b/apps/web/src/components/customers/branches/card.tsx
new file mode 100644
index 0000000..005ec08
--- /dev/null
+++ b/apps/web/src/components/customers/branches/card.tsx
@@ -0,0 +1,253 @@
+import { Badge } from "@suni/ui/components/badge";
+import { Button } from "@suni/ui/components/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@suni/ui/components/dropdown-menu";
+import { cn } from "@suni/ui/lib/utils";
+import { Link } from "@tanstack/react-router";
+import {
+ Archive,
+ ArchiveRestore,
+ Building2,
+ Camera,
+ ChevronRight,
+ MapPin,
+ MoreVertical,
+ Pencil,
+ Phone,
+ ZoomIn,
+} from "lucide-react";
+import { useState } from "react";
+
+import { BranchFormDialog } from "./branch-form-dialog";
+import { ChangeBranchStatusDialog } from "./change-branch-status-dialog";
+import type { Branch } from "./util/branch-address";
+import { formatAddress } from "./util/branch-address";
+
+interface BranchCardProps {
+ branch: Branch;
+ customer?: { id: string; name: string };
+}
+
+interface BranchImageProps {
+ name: string;
+ src: string;
+ hasImage: boolean;
+ isArchived: boolean;
+ onUploadClick?: () => void;
+ onExpandClick?: () => void;
+}
+
+function BranchImage({
+ name,
+ src,
+ hasImage,
+ isArchived,
+ onUploadClick,
+ onExpandClick,
+}: BranchImageProps) {
+ const overlayButton =
+ "flex size-8 items-center justify-center rounded-full bg-black/50 text-white transition-opacity hover:bg-black/70 pointer-fine:opacity-0 pointer-fine:group-hover/image:opacity-100 pointer-fine:focus-visible:opacity-100";
+
+ return (
+
+

+
+
+ {hasImage && onExpandClick && (
+
+ )}
+
+ {!isArchived && onUploadClick && (
+
+ )}
+
+ );
+}
+
+export default function BranchCard({ branch, customer }: BranchCardProps) {
+ const isArchived = !!branch.archived;
+ const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false);
+ const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
+ const placeholder = "/placeholder.webp";
+ const address = formatAddress(branch);
+
+ const branchImage = branch.frontImageUrl
+ ? `${branch.frontImageUrl}`
+ : placeholder;
+
+ return (
+ <>
+
+
+
+ {/* Header */}
+
+
+
+
+
+ {branch.name}
+
+
+
+ {customer && (
+
+
+
+ {customer.name}
+
+
+ )}
+
+
+
+
+ }
+ >
+ Abrir menú
+
+
+
+
+ Acciones
+ {!isArchived && (
+ setIsUpdateFormOpen(true)}
+ >
+
+ Editar
+
+ )}
+ setIsStatusDialogOpen(true)}
+ >
+ {isArchived ? (
+
+ ) : (
+
+ )}
+ {isArchived ? "Desarchivar" : "Archivar"}
+
+
+
+
+
+
+
+
+ {/* Body */}
+
+ {/* Address */}
+
+
+
+ {address.streetLine}
+ {address.locationLine}
+
+
+
+ {/* Phone */}
+ {branch.phone && (
+
+ )}
+
+ {/* Archived badge */}
+ {isArchived && (
+
+ )}
+
+
+ {/* View details footer */}
+
+
+
+ Ver detalles
+
+
+
+
+
+
+
+
+ >
+ );
+}
diff --git a/apps/web/src/components/customers/branches/change-branch-status-dialog.tsx b/apps/web/src/components/customers/branches/change-branch-status-dialog.tsx
new file mode 100644
index 0000000..12882e7
--- /dev/null
+++ b/apps/web/src/components/customers/branches/change-branch-status-dialog.tsx
@@ -0,0 +1,93 @@
+import type { AppRouterOutputs } from "@suni/api/routers/index";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@suni/ui/components/alert-dialog";
+import { Archive, ArchiveRestore } from "lucide-react";
+
+import { useArchiveBranch } from "@/hooks/use-branches";
+
+type BranchRow = AppRouterOutputs["branches"]["list"][number];
+
+const ACTIONS = {
+ archive: {
+ label: "Archivar",
+ Icon: Archive,
+ confirmVariant: "destructive",
+ nameClassName: "text-destructive",
+ description: "Esto archivará",
+ },
+ unarchive: {
+ label: "Desarchivar",
+ Icon: ArchiveRestore,
+ confirmVariant: "default",
+ nameClassName: "text-success",
+ description: "Esto restaurará",
+ },
+} as const;
+
+interface ChangeBranchStatusDialogProps {
+ branch: Pick;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function ChangeBranchStatusDialog({
+ branch,
+ open,
+ onOpenChange,
+}: ChangeBranchStatusDialogProps) {
+ const action = branch.archived ? ACTIONS.unarchive : ACTIONS.archive;
+ const mutation = useArchiveBranch();
+
+ return (
+ !mutation.isPending && onOpenChange(next)}
+ open={open}
+ >
+
+
+
+ ¿Quieres {action.label.toLowerCase()} la sucursal {branch.name}?
+
+
+ {action.description} la sucursal{" "}
+
+ {branch.name}
+
+ .
+
+
+
+
+ Cancelar
+
+
+ mutation.mutate(
+ {
+ id: branch.id,
+ name: branch.name,
+ archived: !branch.archived,
+ },
+ {
+ onSuccess: () => onOpenChange(false),
+ }
+ )
+ }
+ variant={action.confirmVariant}
+ >
+ {mutation.isPending ? "Guardando..." : action.label}
+
+
+
+
+ );
+}
diff --git a/apps/web/src/components/customers/branches/filters.tsx b/apps/web/src/components/customers/branches/filters.tsx
new file mode 100644
index 0000000..b16ee4a
--- /dev/null
+++ b/apps/web/src/components/customers/branches/filters.tsx
@@ -0,0 +1,161 @@
+import { Button } from "@suni/ui/components/button";
+import { Input } from "@suni/ui/components/input";
+import { ReactSelect } from "@suni/ui/components/react-select";
+import { X } from "lucide-react";
+
+export type BranchStatusFilter = "all" | "active" | "archived";
+
+export interface BranchFilters {
+ name: string;
+ status: BranchStatusFilter;
+ customerId: string;
+}
+
+const DEFAULT_BRANCH_FILTERS: BranchFilters = {
+ name: "",
+ status: "all",
+ customerId: "all",
+};
+
+interface Option {
+ value: T;
+ label: string;
+}
+
+const STATUS_OPTIONS: Option[] = [
+ { value: "all", label: "Todas" },
+ { value: "active", label: "Activas" },
+ { value: "archived", label: "Archivadas" },
+];
+
+const MAX_CUSTOMER_BADGE_LENGTH = 20;
+
+interface BranchesFiltersProps {
+ filters: BranchFilters;
+ onFiltersChange: (filters: BranchFilters) => void;
+ customers?: { id: string; name: string }[];
+}
+
+function FilterBadge({
+ children,
+ onClear,
+}: {
+ children: React.ReactNode;
+ onClear: () => void;
+}) {
+ return (
+
+ );
+}
+
+export function BranchesFilters({
+ filters,
+ onFiltersChange,
+ customers,
+}: BranchesFiltersProps) {
+ const showCustomerFilter = !!customers;
+
+ const customerOptions: Option[] = [
+ { value: "all", label: "Todos los clientes" },
+ ...(customers ?? []).map((c) => ({ value: c.id, label: c.name })),
+ ];
+
+ const selectedCustomerName =
+ filters.customerId === "all"
+ ? null
+ : (customers?.find((c) => c.id === filters.customerId)?.name ?? null);
+
+ const hasActiveFilters =
+ filters.name.trim() !== "" ||
+ filters.status !== "all" ||
+ (showCustomerFilter && filters.customerId !== "all");
+
+ const update = (patch: Partial) =>
+ onFiltersChange({ ...filters, ...patch });
+
+ return (
+
+
+ update({ name: event.target.value })}
+ placeholder="Buscar por nombre de sucursal..."
+ type="text"
+ value={filters.name}
+ />
+ | null) =>
+ update({ status: option?.value ?? "all" })
+ }
+ options={STATUS_OPTIONS}
+ placeholder="Estatus"
+ value={STATUS_OPTIONS.find((opt) => opt.value === filters.status)}
+ />
+
+
+ {showCustomerFilter && (
+
+
+ update({ customerId: option?.value ?? "all" })
+ }
+ options={customerOptions}
+ placeholder="Cliente"
+ value={customerOptions.find(
+ (opt) => opt.value === filters.customerId
+ )}
+ />
+
+ )}
+
+ {hasActiveFilters && (
+
+
+ Filtros activos:
+
+
+ {filters.name.trim() && (
+ update({ name: "" })}>
+ Nombre: “{filters.name.trim()}”
+
+ )}
+
+ {filters.status !== "all" && (
+ update({ status: "all" })}>
+ Estatus: {filters.status === "active" ? "Activas" : "Archivadas"}
+
+ )}
+
+ {showCustomerFilter && selectedCustomerName && (
+ update({ customerId: "all" })}>
+ Cliente:{" "}
+ {selectedCustomerName.length > MAX_CUSTOMER_BADGE_LENGTH
+ ? `${selectedCustomerName.slice(0, MAX_CUSTOMER_BADGE_LENGTH)}...`
+ : selectedCustomerName}
+
+ )}
+
+
+
+ )}
+
+ );
+}
diff --git a/apps/web/src/components/customers/branches/grid.tsx b/apps/web/src/components/customers/branches/grid.tsx
new file mode 100644
index 0000000..f23cf09
--- /dev/null
+++ b/apps/web/src/components/customers/branches/grid.tsx
@@ -0,0 +1,123 @@
+import { Button } from "@suni/ui/components/button";
+import { useQuery } from "@tanstack/react-query";
+import { Building2, Plus, SearchX } from "lucide-react";
+import { useMemo, useState } from "react";
+
+import { orpc } from "@/utils/orpc";
+
+import { BranchFormDialog } from "./branch-form-dialog";
+import BranchCard from "./card";
+import { BranchesFilters } from "./filters";
+import type { BranchFilters } from "./filters";
+
+interface BranchesGridProps {
+ customerId: string;
+}
+
+const DEFAULT_BRANCH_FILTERS: BranchFilters = {
+ name: "",
+ status: "all",
+ customerId: "all",
+};
+
+export function BranchesGrid({ customerId }: BranchesGridProps) {
+ const [filters, setFilters] = useState(DEFAULT_BRANCH_FILTERS);
+ const [isFormOpen, setIsFormOpen] = useState(false);
+
+ const {
+ data: branches = [],
+ isPending,
+ isError,
+ } = useQuery(orpc.branches.list.queryOptions({ input: { customerId } }));
+
+ const filtered = useMemo(() => {
+ const term = filters.name.trim().toLowerCase();
+
+ return branches.filter((branch) => {
+ if (term && !branch.name.toLowerCase().includes(term)) {
+ return false;
+ }
+
+ if (filters.status === "active") {
+ return !branch.archived;
+ }
+
+ if (filters.status === "archived") {
+ return !!branch.archived;
+ }
+
+ return true;
+ });
+ }, [branches, filters]);
+
+ const hasActiveFilters =
+ filters.name.trim() !== "" || filters.status !== "all";
+
+ return (
+ <>
+
+
+
Sucursales
+
+
+
+
+
+ {isPending ? (
+
+ Cargando sucursales…
+
+ ) : null}
+
+ {isError ? (
+
+ No se pudieron cargar las sucursales.
+
+ ) : null}
+
+ {!(isPending || isError) && filtered.length === 0 ? (
+
+ {hasActiveFilters ? (
+
+ ) : (
+
+ )}
+
+ {hasActiveFilters
+ ? "No se encontraron sucursales"
+ : "No hay sucursales para mostrar"}
+
+
+ {hasActiveFilters
+ ? "Intenta con otros filtros de búsqueda"
+ : "Las sucursales del cliente aparecerán aquí"}
+
+
+ ) : null}
+
+ {filtered.length > 0 ? (
+
+ {filtered.map((branch) => (
+
+ ))}
+
+ ) : null}
+
+
+
+ >
+ );
+}
diff --git a/apps/web/src/components/customers/branches/util/branch-address.ts b/apps/web/src/components/customers/branches/util/branch-address.ts
new file mode 100644
index 0000000..87b86c3
--- /dev/null
+++ b/apps/web/src/components/customers/branches/util/branch-address.ts
@@ -0,0 +1,17 @@
+import type { AppRouterOutputs } from "@suni/api/routers/index";
+
+export type Branch = AppRouterOutputs["branches"]["list"][number];
+
+export function formatAddress(branch: Branch) {
+ const streetParts = [
+ branch.street,
+ branch.extNumber && `No. Ext. ${branch.extNumber}`,
+ branch.intNumber && `No. Int. ${branch.intNumber}`,
+ `Col. ${branch.suburb}`,
+ ].filter(Boolean);
+
+ return {
+ streetLine: streetParts.join(", "),
+ locationLine: `${branch.city}, ${branch.state}, CP ${branch.postalCode}`,
+ };
+}
diff --git a/apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx b/apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx
new file mode 100644
index 0000000..0b3ecc0
--- /dev/null
+++ b/apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx
@@ -0,0 +1,107 @@
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@suni/ui/components/tabs";
+import { useSuspenseQuery } from "@tanstack/react-query";
+import { createFileRoute } from "@tanstack/react-router";
+import { FileText, FolderOpen, HardHat, Info, Users } from "lucide-react";
+import { 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 { orpc } from "@/utils/orpc";
+
+export const Route = createFileRoute(
+ "/_auth/customers/$customerId/branches/$branchId/"
+)({
+ loader: ({ context: { queryClient }, params: { customerId, branchId } }) =>
+ Promise.all([
+ queryClient.query(
+ orpc.branches.get.queryOptions({ input: { id: branchId } })
+ ),
+ queryClient.query(
+ orpc.customers.get.queryOptions({ input: { id: customerId } })
+ ),
+ ]),
+ component: RouteComponent,
+ errorComponent: () => (
+
+ No se pudo cargar la sucursal.
+
+ ),
+});
+
+const TABS = [
+ { value: "info", label: "Información general", icon: Info },
+ { value: "quotations", label: "Cotizaciones", icon: FileText },
+ { value: "files", label: "Archivos", icon: FolderOpen },
+ { value: "contacts", label: "Contactos", icon: Users },
+ {
+ value: "technical-requirements",
+ label: "Requerimientos Técnicos",
+ icon: HardHat,
+ },
+] as const;
+
+function RouteComponent() {
+ const { customerId, branchId } = Route.useParams();
+ const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false);
+
+ // Lee el caché de queries (no el loader) para que ediciones y archivados se reflejen.
+ const { data: branch } = useSuspenseQuery(
+ orpc.branches.get.queryOptions({ input: { id: branchId } })
+ );
+
+ const { data: customer } = useSuspenseQuery(
+ orpc.customers.get.queryOptions({ input: { id: customerId } })
+ );
+
+ const placeholder = "/placeholder.webp";
+ const branchImage = branch.frontImageUrl ?? placeholder;
+
+ return (
+
+ setIsUpdateFormOpen(true)}
+ />
+
+
+
+ {TABS.map(({ value, label, icon: Icon }) => (
+
+
+ {label}
+
+ ))}
+
+
+
+ {}}
+ // eslint-disable-next-line no-empty-function
+ onImageUpload={() => {}}
+ />
+
+
+ {TABS.map(({ value }) => (
+
+ ))}
+
+
+
+
+ );
+}
diff --git a/apps/web/src/routes/_auth/customers/$customerId/index.tsx b/apps/web/src/routes/_auth/customers/$customerId/index.tsx
index 7b2f8e7..0242eba 100644
--- a/apps/web/src/routes/_auth/customers/$customerId/index.tsx
+++ b/apps/web/src/routes/_auth/customers/$customerId/index.tsx
@@ -1,5 +1,10 @@
import { buttonVariants } from "@suni/ui/components/button";
-import { Tabs, TabsList, TabsTrigger } from "@suni/ui/components/tabs";
+import {
+ Tabs,
+ TabsList,
+ TabsTrigger,
+ TabsContent,
+} from "@suni/ui/components/tabs";
import { cn } from "@suni/ui/lib/utils";
import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, Link } from "@tanstack/react-router";
@@ -13,6 +18,7 @@ import {
Users,
} from "lucide-react";
+import { BranchesGrid } from "@/components/customers/branches/grid";
import { CustomerData } from "@/components/customers/data";
import { orpc } from "@/utils/orpc";
@@ -92,6 +98,9 @@ function RouteComponent() {
))}
+
+
+
);
From d6754e61065f1301810aeb67cf141ba3aa2d58b0 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Thu, 5 Nov 2026 18:55:22 -0600
Subject: [PATCH 14/30] Agrega sucursales a breacrumb
---
apps/web/src/components/dynamic-breadcrumb.tsx | 1 +
1 file changed, 1 insertion(+)
diff --git a/apps/web/src/components/dynamic-breadcrumb.tsx b/apps/web/src/components/dynamic-breadcrumb.tsx
index 70cd813..5f0cd82 100644
--- a/apps/web/src/components/dynamic-breadcrumb.tsx
+++ b/apps/web/src/components/dynamic-breadcrumb.tsx
@@ -16,6 +16,7 @@ const SEGMENT_LABELS = {
new: "Nuevo",
edit: "Editar",
customers: "Clientes",
+ branches: "Sucursales",
} satisfies Record;
type KnownSegment = keyof typeof SEGMENT_LABELS;
From 7fe00a14a59b9cee36fd3a09c405096ee62f1220 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 00:55:01 -0600
Subject: [PATCH 15/30] Crea contact form
---
.../customers/contacts/contact-form.tsx | 182 ++++++++++++++++++
1 file changed, 182 insertions(+)
create mode 100644 apps/web/src/components/customers/contacts/contact-form.tsx
diff --git a/apps/web/src/components/customers/contacts/contact-form.tsx b/apps/web/src/components/customers/contacts/contact-form.tsx
new file mode 100644
index 0000000..728e419
--- /dev/null
+++ b/apps/web/src/components/customers/contacts/contact-form.tsx
@@ -0,0 +1,182 @@
+import type { AppRouterOutputs } from "@suni/api/routers/index";
+import {
+ contactFormSchema,
+ contactInputSchema,
+} from "@suni/db/validation/contacts";
+import { Button } from "@suni/ui/components/button";
+import { revalidateLogic } from "@tanstack/react-form";
+import { Loader2 } from "lucide-react";
+import type { z } from "zod";
+
+import { useAppForm } from "@/components/form/use-app-form";
+import { useCreateContact, useUpdateContact } from "@/hooks/use-contacts";
+
+type Contact = AppRouterOutputs["contacts"]["list"][number];
+
+type FormValues = z.input;
+
+interface ContactFormProps {
+ customerId?: string | null;
+ branchId?: string | null;
+ contact?: Contact;
+ onSuccess?: () => void;
+ onCancel: () => void;
+}
+
+const PHONE_LENGTH = 10;
+
+const EXTENSION_LENGTH = 10;
+
+const EMPTY_VALUES: FormValues = {
+ name: "",
+ email: "",
+ phone: "",
+ phoneExtension: "",
+ position: "",
+};
+
+function toFormValues(contact?: Contact): FormValues {
+ if (!contact) {
+ return EMPTY_VALUES;
+ }
+
+ return {
+ name: contact.name,
+ email: contact.email,
+ phone: contact.phone,
+ phoneExtension: contact.phoneExtension ?? "",
+ position: contact.position ?? "",
+ };
+}
+
+export function ContactForm({
+ customerId,
+ branchId,
+ contact,
+ onSuccess,
+ onCancel,
+}: ContactFormProps) {
+ const createContact = useCreateContact();
+ const updateContact = useUpdateContact();
+
+ const submitting = createContact.isPending || updateContact.isPending;
+
+ const form = useAppForm({
+ defaultValues: toFormValues(contact),
+ validationLogic: revalidateLogic(),
+ validators: { onDynamic: contactFormSchema },
+ onSubmit: ({ value }) => {
+ const parsed = contactInputSchema.parse(value);
+
+ if (contact) {
+ updateContact.mutate(
+ { id: contact.id, ...parsed },
+ { onSuccess: () => onSuccess?.() }
+ );
+ } else if (customerId && branchId) {
+ createContact.mutate(
+ { customerId, branchId, ...parsed },
+ { onSuccess: () => onSuccess?.() }
+ );
+ }
+ },
+ });
+
+ return (
+
+ );
+}
From 09fc8e53c2f25d9c9d626cf69816ea65b2357655 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 00:56:04 -0600
Subject: [PATCH 16/30] Crea contact form y dialogs
---
.../contacts/change-contact-status-dialog.tsx | 90 ++++++++
.../customers/contacts/contact-card.tsx | 208 ++++++++++++++++++
.../contacts/contact-form-dialog.tsx | 50 +++++
3 files changed, 348 insertions(+)
create mode 100644 apps/web/src/components/customers/contacts/change-contact-status-dialog.tsx
create mode 100644 apps/web/src/components/customers/contacts/contact-card.tsx
create mode 100644 apps/web/src/components/customers/contacts/contact-form-dialog.tsx
diff --git a/apps/web/src/components/customers/contacts/change-contact-status-dialog.tsx b/apps/web/src/components/customers/contacts/change-contact-status-dialog.tsx
new file mode 100644
index 0000000..c0184e7
--- /dev/null
+++ b/apps/web/src/components/customers/contacts/change-contact-status-dialog.tsx
@@ -0,0 +1,90 @@
+import type { AppRouterOutputs } from "@suni/api/routers/index";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@suni/ui/components/alert-dialog";
+
+import { useArchiveContact } from "@/hooks/use-contacts";
+
+type ContactRow = AppRouterOutputs["contacts"]["list"][number];
+
+const ACTIONS = {
+ archive: {
+ label: "Archivar",
+ confirmVariant: "destructive",
+ nameClassName: "text-destructive",
+ description: "Esto archivará",
+ },
+ unarchive: {
+ label: "Desarchivar",
+ confirmVariant: "default",
+ nameClassName: "text-success",
+ description: "Esto restaurará",
+ },
+} as const;
+
+interface ChangeContactStatusDialogProps {
+ contact: Pick;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function ChangeContactStatusDialog({
+ contact,
+ open,
+ onOpenChange,
+}: ChangeContactStatusDialogProps) {
+ const action = contact.archived ? ACTIONS.unarchive : ACTIONS.archive;
+ const mutation = useArchiveContact();
+
+ return (
+ !mutation.isPending && onOpenChange(next)}
+ open={open}
+ >
+
+
+
+ ¿Quieres {action.label.toLowerCase()} al contacto {contact.name}?
+
+
+ {action.description} al contacto{" "}
+
+ {contact.name}
+
+ .
+
+
+
+
+ Cancelar
+
+
+ mutation.mutate(
+ {
+ id: contact.id,
+ name: contact.name,
+ archived: !contact.archived,
+ },
+ {
+ onSuccess: () => onOpenChange(false),
+ }
+ )
+ }
+ variant={action.confirmVariant}
+ >
+ {mutation.isPending ? "Guardando..." : action.label}
+
+
+
+
+ );
+}
diff --git a/apps/web/src/components/customers/contacts/contact-card.tsx b/apps/web/src/components/customers/contacts/contact-card.tsx
new file mode 100644
index 0000000..e0053b2
--- /dev/null
+++ b/apps/web/src/components/customers/contacts/contact-card.tsx
@@ -0,0 +1,208 @@
+import type { AppRouterOutputs } from "@suni/api/routers/index";
+import { Badge } from "@suni/ui/components/badge";
+import { Button } from "@suni/ui/components/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@suni/ui/components/dropdown-menu";
+import { cn } from "@suni/ui/lib/utils";
+import { Link } from "@tanstack/react-router";
+import {
+ Archive,
+ ArchiveRestore,
+ Building2,
+ Mail,
+ MapPin,
+ MoreVertical,
+ Pencil,
+ Phone,
+} from "lucide-react";
+import { useState } from "react";
+
+import { ChangeContactStatusDialog } from "./change-contact-status-dialog";
+import { ContactFormDialog } from "./contact-form-dialog";
+
+type Contact = AppRouterOutputs["contacts"]["list"][number];
+
+interface ContactCardProps {
+ contact: Contact;
+ /** Si viene definido, muestra el cliente (útil en listados de varios clientes). */
+ customer?: { id: string; name: string };
+ readOnly?: boolean;
+}
+
+export default function ContactCard({
+ contact,
+ customer,
+ readOnly = false,
+}: ContactCardProps) {
+ const isArchived = !!contact.archived;
+ const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false);
+ const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
+
+ return (
+ <>
+
+ {/* Header */}
+
+
+
+
+ {contact.name}
+
+
+ {contact.position && (
+
+ {contact.position}
+
+ )}
+
+ {customer && (
+
+
+
+ {customer.name}
+
+
+ )}
+
+ {contact.branch && (
+
+
+
+ {contact.branch.name}
+
+
+ )}
+
+
+ {!readOnly && (
+
+
+ }
+ >
+ Abrir menú
+
+
+
+
+ Acciones
+ {!isArchived && (
+ setIsUpdateFormOpen(true)}
+ >
+
+ Editar
+
+ )}
+ setIsStatusDialogOpen(true)}
+ >
+ {isArchived ? (
+
+ ) : (
+
+ )}
+ {isArchived ? "Desarchivar" : "Archivar"}
+
+
+
+
+
+ )}
+
+
+
+ {/* Body */}
+
+
+
+ {contact.email}
+
+
+ {contact.phone && (
+
+
+
+ {contact.phone}
+ {contact.phoneExtension && ` ext. ${contact.phoneExtension}`}
+
+
+ )}
+
+
+ {/* Archived badge */}
+ {isArchived && (
+
+ )}
+
+
+ {!readOnly && (
+ <>
+
+
+ >
+ )}
+ >
+ );
+}
diff --git a/apps/web/src/components/customers/contacts/contact-form-dialog.tsx b/apps/web/src/components/customers/contacts/contact-form-dialog.tsx
new file mode 100644
index 0000000..a89e1fe
--- /dev/null
+++ b/apps/web/src/components/customers/contacts/contact-form-dialog.tsx
@@ -0,0 +1,50 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@suni/ui/components/dialog";
+import type { ComponentProps } from "react";
+
+import { ContactForm } from "./contact-form";
+
+interface ContactFormDialogProps extends Pick<
+ ComponentProps,
+ "contact" | "customerId" | "branchId"
+> {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function ContactFormDialog({
+ contact,
+ customerId,
+ branchId,
+ open,
+ onOpenChange,
+}: ContactFormDialogProps) {
+ return (
+
+ );
+}
From 0100bf790709847f413348c6d934ff1f62d7bb46 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 00:56:27 -0600
Subject: [PATCH 17/30] Crea grid y agrega a index
---
.../customers/contacts/contact-filters.tsx | 120 ++++++++++++++++
.../customers/contacts/contact-grid.tsx | 133 ++++++++++++++++++
.../$customerId/branches/$branchId/index.tsx | 4 +
3 files changed, 257 insertions(+)
create mode 100644 apps/web/src/components/customers/contacts/contact-filters.tsx
create mode 100644 apps/web/src/components/customers/contacts/contact-grid.tsx
diff --git a/apps/web/src/components/customers/contacts/contact-filters.tsx b/apps/web/src/components/customers/contacts/contact-filters.tsx
new file mode 100644
index 0000000..1b36983
--- /dev/null
+++ b/apps/web/src/components/customers/contacts/contact-filters.tsx
@@ -0,0 +1,120 @@
+import { Button } from "@suni/ui/components/button";
+import { Input } from "@suni/ui/components/input";
+import { ReactSelect } from "@suni/ui/components/react-select";
+import { X } from "lucide-react";
+
+export type ContactStatusFilter = "all" | "active" | "archived";
+
+export interface ContactFilters {
+ name: string;
+ status: ContactStatusFilter;
+}
+
+const DEFAULT_CONTACT_FILTERS: ContactFilters = {
+ name: "",
+ status: "all",
+};
+
+interface Option {
+ value: T;
+ label: string;
+}
+
+const STATUS_OPTIONS: Option[] = [
+ { value: "all", label: "Todos" },
+ { value: "active", label: "Activos" },
+ { value: "archived", label: "Archivados" },
+];
+
+interface ContactsFiltersProps {
+ filters: ContactFilters;
+ onFiltersChange: (filters: ContactFilters) => void;
+}
+
+function FilterBadge({
+ children,
+ onClear,
+}: {
+ children: React.ReactNode;
+ onClear: () => void;
+}) {
+ return (
+
+ );
+}
+
+export function ContactsFilters({
+ filters,
+ onFiltersChange,
+}: ContactsFiltersProps) {
+ const hasName = filters.name.trim() !== "";
+ const hasStatus = filters.status !== "all";
+ const hasActiveFilters = hasName || hasStatus;
+
+ const statusLabel = STATUS_OPTIONS.find(
+ (option) => option.value === filters.status
+ )?.label;
+
+ const update = (patch: Partial) =>
+ onFiltersChange({ ...filters, ...patch });
+
+ return (
+
+
+ update({ name: event.target.value })}
+ placeholder="Buscar por nombre..."
+ type="text"
+ value={filters.name}
+ />
+ | null) =>
+ update({ status: option?.value ?? "all" })
+ }
+ options={STATUS_OPTIONS}
+ placeholder="Estatus"
+ value={STATUS_OPTIONS.find((opt) => opt.value === filters.status)}
+ />
+
+
+ {hasActiveFilters && (
+
+
+ Filtros activos:
+
+
+ {hasName && (
+ update({ name: "" })}>
+ Nombre: “{filters.name.trim()}”
+
+ )}
+
+ {hasStatus && (
+ update({ status: "all" })}>
+ Estatus: {statusLabel}
+
+ )}
+
+
+
+ )}
+
+ );
+}
diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx
new file mode 100644
index 0000000..173f6fe
--- /dev/null
+++ b/apps/web/src/components/customers/contacts/contact-grid.tsx
@@ -0,0 +1,133 @@
+import { Button } from "@suni/ui/components/button";
+import { useQuery } from "@tanstack/react-query";
+import { Plus, SearchX, Users } from "lucide-react";
+import { useMemo, useState } from "react";
+
+import { orpc } from "@/utils/orpc";
+
+import ContactCard from "./contact-card";
+import { ContactsFilters } from "./contact-filters";
+import type { ContactFilters } from "./contact-filters";
+import { ContactFormDialog } from "./contact-form-dialog";
+
+interface ContactsGridProps {
+ customerId: string;
+ branchId?: string;
+}
+
+const DEFAULT_CONTACT_FILTERS: ContactFilters = {
+ name: "",
+ status: "all",
+};
+
+export function ContactsGrid({ customerId, branchId }: ContactsGridProps) {
+ const [filters, setFilters] = useState(
+ DEFAULT_CONTACT_FILTERS
+ );
+
+ const [isFormOpen, setIsFormOpen] = useState(false);
+
+ const {
+ data: contacts = [],
+ isPending,
+ isError,
+ } = useQuery(
+ orpc.contacts.list.queryOptions({ input: { customerId, branchId } })
+ );
+
+ const filtered = useMemo(() => {
+ const term = filters.name.trim().toLowerCase();
+
+ return contacts.filter((contact) => {
+ if (term && !contact.name.toLowerCase().includes(term)) {
+ return false;
+ }
+
+ if (filters.status === "active") {
+ return !contact.archived;
+ }
+
+ if (filters.status === "archived") {
+ return !!contact.archived;
+ }
+
+ return true;
+ });
+ }, [contacts, filters]);
+
+ const hasActiveFilters =
+ filters.name.trim() !== "" || filters.status !== "all";
+
+ return (
+ <>
+
+
+
Contactos
+ {branchId ? (
+
+ ) : 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}
+
+
+ {branchId ? (
+
+ ) : 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 0b3ecc0..8bb2e7f 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
@@ -12,6 +12,7 @@ import { useState } from "react";
import { BranchFormDialog } from "@/components/customers/branches/branch-form-dialog";
import { BranchHeader } from "@/components/customers/branches/branch-header";
import { BranchInfoContent } from "@/components/customers/branches/branch-info";
+import { ContactsGrid } from "@/components/customers/contacts/contact-grid";
import { orpc } from "@/utils/orpc";
export const Route = createFileRoute(
@@ -90,6 +91,9 @@ function RouteComponent() {
onImageUpload={() => {}}
/>
+
+
+
{TABS.map(({ value }) => (
From 2ea5c3dfbf25e799a2bbc5294e081b64332b022c Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 01:00:20 -0600
Subject: [PATCH 18/30] Agrega grid contacts a customers index
---
apps/web/src/routes/_auth/customers/$customerId/index.tsx | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/apps/web/src/routes/_auth/customers/$customerId/index.tsx b/apps/web/src/routes/_auth/customers/$customerId/index.tsx
index 0242eba..9958bc4 100644
--- a/apps/web/src/routes/_auth/customers/$customerId/index.tsx
+++ b/apps/web/src/routes/_auth/customers/$customerId/index.tsx
@@ -19,6 +19,7 @@ import {
} from "lucide-react";
import { BranchesGrid } from "@/components/customers/branches/grid";
+import { ContactsGrid } from "@/components/customers/contacts/contact-grid";
import { CustomerData } from "@/components/customers/data";
import { orpc } from "@/utils/orpc";
@@ -101,6 +102,9 @@ function RouteComponent() {
+
+
+
);
From c088e53c6ca141dba9a706ba01d94642133ac5a7 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 13:42:57 -0600
Subject: [PATCH 19/30] =?UTF-8?q?Invalidar=20consultas=20de=20contacto=20t?=
=?UTF-8?q?ras=20una=20actualizaci=C3=B3n=20de=20la=20sucursal.?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
apps/web/src/hooks/use-branches.ts | 1 +
1 file changed, 1 insertion(+)
diff --git a/apps/web/src/hooks/use-branches.ts b/apps/web/src/hooks/use-branches.ts
index 2118735..2a09553 100644
--- a/apps/web/src/hooks/use-branches.ts
+++ b/apps/web/src/hooks/use-branches.ts
@@ -43,6 +43,7 @@ export function useUpdateBranch() {
onSuccess: async () => {
toast.success("Sucursal actualizada");
await queryClient.invalidateQueries({ queryKey: orpc.branches.key() });
+ await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() });
},
onError: (error) => toast.error(error.message),
})
From 71733dc58d0a7235427c5ae0c818fdaf86e38cbc Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 14:13:29 -0600
Subject: [PATCH 20/30] =?UTF-8?q?Limita=20los=20paneles=20provisionales=20?=
=?UTF-8?q?a=20pesta=C3=B1as=20sin=20contenido.?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../$customerId/branches/$branchId/index.tsx | 36 +++++++++++--------
1 file changed, 21 insertions(+), 15 deletions(-)
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 8bb2e7f..8998c0c 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
@@ -7,6 +7,7 @@ import {
import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import { FileText, FolderOpen, HardHat, Info, Users } from "lucide-react";
+import type { ReactNode } from "react";
import { useState } from "react";
import { BranchFormDialog } from "@/components/customers/branches/branch-form-dialog";
@@ -63,6 +64,23 @@ function RouteComponent() {
const placeholder = "/placeholder.webp";
const branchImage = branch.frontImageUrl ?? placeholder;
+ const content: Record<(typeof TABS)[number]["value"], ReactNode> = {
+ info: (
+ {}}
+ // eslint-disable-next-line no-empty-function -- pendiente de implementar
+ onImageUpload={() => {}}
+ />
+ ),
+ contacts: ,
+ quotations: null,
+ files: null,
+ "technical-requirements": null,
+ };
+
return (
-
- {}}
- // eslint-disable-next-line no-empty-function
- onImageUpload={() => {}}
- />
-
-
-
-
-
{TABS.map(({ value }) => (
-
+
+ {content[value]}
+
))}
From a972c4a04b4c5db40f94f426c2c6f8b671a7685a Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 14:14:28 -0600
Subject: [PATCH 21/30] Agrega migraciones
---
.../migration.sql | 41 +
.../snapshot.json | 1532 +++++++++++++++++
2 files changed, 1573 insertions(+)
create mode 100644 packages/db/src/migrations/20261106201415_organic_tomorrow_man/migration.sql
create mode 100644 packages/db/src/migrations/20261106201415_organic_tomorrow_man/snapshot.json
diff --git a/packages/db/src/migrations/20261106201415_organic_tomorrow_man/migration.sql b/packages/db/src/migrations/20261106201415_organic_tomorrow_man/migration.sql
new file mode 100644
index 0000000..7c814c3
--- /dev/null
+++ b/packages/db/src/migrations/20261106201415_organic_tomorrow_man/migration.sql
@@ -0,0 +1,41 @@
+CREATE TABLE "customer_branches" (
+ "id" text PRIMARY KEY,
+ "name" text NOT NULL,
+ "street" text NOT NULL,
+ "int_number" text,
+ "ext_number" text NOT NULL,
+ "city" text NOT NULL,
+ "suburb" text NOT NULL,
+ "state" text NOT NULL,
+ "postal_code" text NOT NULL,
+ "phone" text,
+ "front_image_url" text,
+ "customer_id" text NOT NULL,
+ "seller_id" text NOT NULL,
+ "modified_by" text NOT NULL,
+ "archived" timestamp,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ "updated_at" timestamp DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "contact" (
+ "id" text PRIMARY KEY,
+ "name" text NOT NULL,
+ "email" text NOT NULL,
+ "phone" text NOT NULL,
+ "phone_extension" text,
+ "position" text,
+ "customer_id" text NOT NULL,
+ "branch_id" text,
+ "archived" timestamp,
+ "modified_by" text NOT NULL,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ "updated_at" timestamp DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+ALTER TABLE "customer_branches" ADD CONSTRAINT "customer_branches_customer_id_customer_id_fkey" FOREIGN KEY ("customer_id") REFERENCES "customer"("id");--> statement-breakpoint
+ALTER TABLE "customer_branches" ADD CONSTRAINT "customer_branches_seller_id_user_id_fkey" FOREIGN KEY ("seller_id") REFERENCES "user"("id");--> statement-breakpoint
+ALTER TABLE "customer_branches" ADD CONSTRAINT "customer_branches_modified_by_user_id_fkey" FOREIGN KEY ("modified_by") REFERENCES "user"("id");--> statement-breakpoint
+ALTER TABLE "contact" ADD CONSTRAINT "contact_customer_id_customer_id_fkey" FOREIGN KEY ("customer_id") REFERENCES "customer"("id");--> statement-breakpoint
+ALTER TABLE "contact" ADD CONSTRAINT "contact_branch_id_customer_branches_id_fkey" FOREIGN KEY ("branch_id") REFERENCES "customer_branches"("id");--> statement-breakpoint
+ALTER TABLE "contact" ADD CONSTRAINT "contact_modified_by_user_id_fkey" FOREIGN KEY ("modified_by") REFERENCES "user"("id");
\ No newline at end of file
diff --git a/packages/db/src/migrations/20261106201415_organic_tomorrow_man/snapshot.json b/packages/db/src/migrations/20261106201415_organic_tomorrow_man/snapshot.json
new file mode 100644
index 0000000..9848217
--- /dev/null
+++ b/packages/db/src/migrations/20261106201415_organic_tomorrow_man/snapshot.json
@@ -0,0 +1,1532 @@
+{
+ "version": "8",
+ "dialect": "postgres",
+ "id": "31829c0c-39bb-4545-ada1-2829bb29f26d",
+ "prevIds": [
+ "4f627249-c9fb-46cb-8f36-c4fa0305c360"
+ ],
+ "ddl": [
+ {
+ "values": [
+ "Redes sociales",
+ "Recomendación",
+ "Prospección",
+ "Teléfono",
+ "Correo",
+ "Página web",
+ "Díptico"
+ ],
+ "name": "acquisition",
+ "entityType": "enums",
+ "schema": "public"
+ },
+ {
+ "values": [
+ "Cliente",
+ "Asesor"
+ ],
+ "name": "customer_type",
+ "entityType": "enums",
+ "schema": "public"
+ },
+ {
+ "isRlsEnabled": false,
+ "name": "account",
+ "entityType": "tables",
+ "schema": "public"
+ },
+ {
+ "isRlsEnabled": false,
+ "name": "session",
+ "entityType": "tables",
+ "schema": "public"
+ },
+ {
+ "isRlsEnabled": false,
+ "name": "user",
+ "entityType": "tables",
+ "schema": "public"
+ },
+ {
+ "isRlsEnabled": false,
+ "name": "verification",
+ "entityType": "tables",
+ "schema": "public"
+ },
+ {
+ "isRlsEnabled": false,
+ "name": "customer_branches",
+ "entityType": "tables",
+ "schema": "public"
+ },
+ {
+ "isRlsEnabled": false,
+ "name": "contact",
+ "entityType": "tables",
+ "schema": "public"
+ },
+ {
+ "isRlsEnabled": false,
+ "name": "customer",
+ "entityType": "tables",
+ "schema": "public"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "account_id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "provider_id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "user_id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "access_token",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "refresh_token",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "id_token",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "access_token_expires_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "refresh_token_expires_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "scope",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "password",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "created_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "updated_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "expires_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "token",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "created_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "updated_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "ip_address",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "user_agent",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "user_id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "impersonated_by",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "name",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "email",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "boolean",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "false",
+ "generated": null,
+ "identity": null,
+ "name": "email_verified",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "image",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "created_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "updated_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "role",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "boolean",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": "false",
+ "generated": null,
+ "identity": null,
+ "name": "banned",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "ban_reason",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "ban_expires",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "user"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "verification"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "identifier",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "verification"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "value",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "verification"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "expires_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "verification"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "created_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "verification"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "updated_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "verification"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "name",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "street",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "int_number",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "ext_number",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "city",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "suburb",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "state",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "postal_code",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "phone",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "front_image_url",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "customer_id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "seller_id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "modified_by",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "archived",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "created_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "updated_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "name",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "email",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "phone",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "phone_extension",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "position",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "customer_id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "branch_id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "archived",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "modified_by",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "created_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "updated_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "name",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "rfc",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "street",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "int_number",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "ext_number",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "city",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "suburb",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "state",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "postal_code",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "phone",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "phone_extension",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "acquisition",
+ "typeSchema": "public",
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "acquisition",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "customer_type",
+ "typeSchema": "public",
+ "notNull": true,
+ "dimensions": 0,
+ "default": "'Cliente'",
+ "generated": null,
+ "identity": null,
+ "name": "type",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "seller_id",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "text",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "modified_by",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "created_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "name": "updated_at",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "name": "archived",
+ "entityType": "columns",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "nameExplicit": true,
+ "columns": [
+ {
+ "value": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ }
+ ],
+ "isUnique": false,
+ "where": null,
+ "with": "",
+ "method": "btree",
+ "concurrently": false,
+ "name": "account_userId_idx",
+ "entityType": "indexes",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "nameExplicit": true,
+ "columns": [
+ {
+ "value": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ }
+ ],
+ "isUnique": false,
+ "where": null,
+ "with": "",
+ "method": "btree",
+ "concurrently": false,
+ "name": "session_userId_idx",
+ "entityType": "indexes",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "nameExplicit": true,
+ "columns": [
+ {
+ "value": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ }
+ ],
+ "isUnique": false,
+ "where": null,
+ "with": "",
+ "method": "btree",
+ "concurrently": false,
+ "name": "verification_identifier_idx",
+ "entityType": "indexes",
+ "schema": "public",
+ "table": "verification"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "user_id"
+ ],
+ "schemaTo": "public",
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "CASCADE",
+ "name": "account_user_id_user_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "account"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "user_id"
+ ],
+ "schemaTo": "public",
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "CASCADE",
+ "name": "session_user_id_user_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "session"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "customer_id"
+ ],
+ "schemaTo": "public",
+ "tableTo": "customer",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "NO ACTION",
+ "name": "customer_branches_customer_id_customer_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "seller_id"
+ ],
+ "schemaTo": "public",
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "NO ACTION",
+ "name": "customer_branches_seller_id_user_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "modified_by"
+ ],
+ "schemaTo": "public",
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "NO ACTION",
+ "name": "customer_branches_modified_by_user_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "customer_branches"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "customer_id"
+ ],
+ "schemaTo": "public",
+ "tableTo": "customer",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "NO ACTION",
+ "name": "contact_customer_id_customer_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "branch_id"
+ ],
+ "schemaTo": "public",
+ "tableTo": "customer_branches",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "NO ACTION",
+ "name": "contact_branch_id_customer_branches_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "modified_by"
+ ],
+ "schemaTo": "public",
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "NO ACTION",
+ "name": "contact_modified_by_user_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "contact"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "seller_id"
+ ],
+ "schemaTo": "public",
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "NO ACTION",
+ "name": "customer_seller_id_user_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "modified_by"
+ ],
+ "schemaTo": "public",
+ "tableTo": "user",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "NO ACTION",
+ "name": "customer_modified_by_user_id_fkey",
+ "entityType": "fks",
+ "schema": "public",
+ "table": "customer"
+ },
+ {
+ "columns": [
+ "id"
+ ],
+ "nameExplicit": false,
+ "name": "account_pkey",
+ "schema": "public",
+ "table": "account",
+ "entityType": "pks"
+ },
+ {
+ "columns": [
+ "id"
+ ],
+ "nameExplicit": false,
+ "name": "session_pkey",
+ "schema": "public",
+ "table": "session",
+ "entityType": "pks"
+ },
+ {
+ "columns": [
+ "id"
+ ],
+ "nameExplicit": false,
+ "name": "user_pkey",
+ "schema": "public",
+ "table": "user",
+ "entityType": "pks"
+ },
+ {
+ "columns": [
+ "id"
+ ],
+ "nameExplicit": false,
+ "name": "verification_pkey",
+ "schema": "public",
+ "table": "verification",
+ "entityType": "pks"
+ },
+ {
+ "columns": [
+ "id"
+ ],
+ "nameExplicit": false,
+ "name": "customer_branches_pkey",
+ "schema": "public",
+ "table": "customer_branches",
+ "entityType": "pks"
+ },
+ {
+ "columns": [
+ "id"
+ ],
+ "nameExplicit": false,
+ "name": "contact_pkey",
+ "schema": "public",
+ "table": "contact",
+ "entityType": "pks"
+ },
+ {
+ "columns": [
+ "id"
+ ],
+ "nameExplicit": false,
+ "name": "customer_pkey",
+ "schema": "public",
+ "table": "customer",
+ "entityType": "pks"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "token"
+ ],
+ "nullsNotDistinct": false,
+ "name": "session_token_key",
+ "schema": "public",
+ "table": "session",
+ "entityType": "uniques"
+ },
+ {
+ "nameExplicit": false,
+ "columns": [
+ "email"
+ ],
+ "nullsNotDistinct": false,
+ "name": "user_email_key",
+ "schema": "public",
+ "table": "user",
+ "entityType": "uniques"
+ }
+ ],
+ "renames": []
+}
\ No newline at end of file
From 22b67b6fd592334cc328fe3ef3770a78fd971138 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 14:41:23 -0600
Subject: [PATCH 22/30] Crea branches page index y component select
---
.../customers/select-entity-button.tsx | 256 ++++++++++++++++++
apps/web/src/routes/_auth/branches/index.tsx | 150 ++++++++++
2 files changed, 406 insertions(+)
create mode 100644 apps/web/src/components/customers/select-entity-button.tsx
create mode 100644 apps/web/src/routes/_auth/branches/index.tsx
diff --git a/apps/web/src/components/customers/select-entity-button.tsx b/apps/web/src/components/customers/select-entity-button.tsx
new file mode 100644
index 0000000..9180c4b
--- /dev/null
+++ b/apps/web/src/components/customers/select-entity-button.tsx
@@ -0,0 +1,256 @@
+import { Button } from "@suni/ui/components/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@suni/ui/components/dialog";
+import { ReactSelect } from "@suni/ui/components/react-select";
+import { Plus } from "lucide-react";
+import { useMemo, useState } from "react";
+
+import { BranchFormDialog } from "@/components/customers/branches/branch-form-dialog";
+import { ContactFormDialog } from "@/components/customers/contacts/contact-form-dialog";
+import { useListBranches } from "@/hooks/use-branches";
+import { useListCustomers } from "@/hooks/use-customers";
+
+interface PickerProps {
+ value: string | null;
+ onValueChange: (value: string) => void;
+}
+
+function CustomerPicker({ value, onValueChange }: PickerProps) {
+ const { data: customers = [], isPending } = useListCustomers({
+ status: "active",
+ });
+
+ const options = useMemo(
+ () =>
+ customers
+ .toSorted((a, b) => a.name.localeCompare(b.name, "es"))
+ .map((customer) => ({ value: customer.id, label: customer.name })),
+ [customers]
+ );
+
+ return (
+ "Cargando…"}
+ noOptionsMessage={() => "Sin resultados"}
+ onChange={(option) => {
+ if (option) {
+ onValueChange(option.value);
+ }
+ }}
+ options={options}
+ placeholder="Selecciona un cliente"
+ value={options.find((option) => option.value === value) ?? null}
+ />
+ );
+}
+
+function BranchPicker({
+ customerId,
+ value,
+ onValueChange,
+}: PickerProps & { customerId: string | null }) {
+ const { data: branches = [], isPending } = useListBranches(
+ customerId ? { customerId } : {}
+ );
+
+ const options = useMemo(
+ () =>
+ branches
+ .filter((branch) => !branch.archived)
+ .toSorted((a, b) => a.name.localeCompare(b.name, "es"))
+ .map((branch) => ({ value: branch.id, label: branch.name })),
+ [branches]
+ );
+
+ return (
+ "Cargando…"}
+ noOptionsMessage={() => "Sin resultados"}
+ onChange={(option) => {
+ if (option) {
+ onValueChange(option.value);
+ }
+ }}
+ options={options}
+ placeholder="Selecciona una sucursal"
+ value={options.find((option) => option.value === value) ?? null}
+ />
+ );
+}
+
+interface EntityFormProps {
+ entity: "branch" | "contact";
+ customerId: string;
+ branchId: string | null;
+ onOpenChange: (open: boolean) => void;
+}
+
+function EntityForm({
+ entity,
+ customerId,
+ branchId,
+ onOpenChange,
+}: EntityFormProps) {
+ if (entity === "branch") {
+ return (
+
+ );
+ }
+
+ if (!branchId) {
+ return null;
+ }
+
+ return (
+
+ );
+}
+
+const COPY = {
+ branch: {
+ label: "Nueva Sucursal",
+ title: "Nueva sucursal",
+ description: "Selecciona el cliente al que pertenecerá la sucursal.",
+ },
+ contact: {
+ label: "Nuevo Contacto",
+ title: "Nuevo contacto",
+ description: "Selecciona a dónde pertenecerá el contacto.",
+ },
+} as const;
+
+interface NewEntityButtonProps {
+ entity: "branch" | "contact";
+ customerId?: string;
+ branchId?: string;
+ label?: string;
+ className?: string;
+}
+
+type Step = "closed" | "select" | "form";
+
+export function NewEntityButton({
+ entity,
+ customerId,
+ branchId,
+ label,
+ className,
+}: NewEntityButtonProps) {
+ const [step, setStep] = useState("closed");
+ const [pickedCustomerId, setPickedCustomerId] = useState(null);
+ const [pickedBranchId, setPickedBranchId] = useState(null);
+
+ const copy = COPY[entity];
+ const isContact = entity === "contact";
+
+ const effectiveCustomerId = customerId ?? pickedCustomerId;
+ const effectiveBranchId = branchId ?? pickedBranchId;
+
+ const needsCustomer = !customerId;
+ const needsBranch = isContact && !branchId;
+
+ const canContinue =
+ !!effectiveCustomerId && (!isContact || !!effectiveBranchId);
+
+ const close = () => {
+ setStep("closed");
+ setPickedCustomerId(null);
+ setPickedBranchId(null);
+ };
+
+ const handleFormOpenChange = (open: boolean) => {
+ if (!open) {
+ close();
+ }
+ };
+
+ return (
+ <>
+
+
+
+
+ {step === "form" && effectiveCustomerId ? (
+
+ ) : null}
+ >
+ );
+}
diff --git a/apps/web/src/routes/_auth/branches/index.tsx b/apps/web/src/routes/_auth/branches/index.tsx
new file mode 100644
index 0000000..7d8f3ec
--- /dev/null
+++ b/apps/web/src/routes/_auth/branches/index.tsx
@@ -0,0 +1,150 @@
+import { cn } from "@suni/ui/lib/utils";
+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
+import { Building2, SearchX } from "lucide-react";
+import { useMemo } from "react";
+import { z } from "zod";
+
+import BranchCard from "@/components/customers/branches/card";
+import { BranchesFilters } from "@/components/customers/branches/filters";
+import type { BranchFilters } from "@/components/customers/branches/filters";
+import { NewEntityButton } from "@/components/customers/select-entity-button";
+import { useListBranches } from "@/hooks/use-branches";
+import { stripAccents } from "@/lib/string-utils";
+
+/* oxlint-disable promise/prefer-await-to-then, github/no-then -- zod `.catch()` is not Promise.catch */
+const searchSchema = z.object({
+ name: z.string().default("").catch(""),
+ status: z.enum(["all", "active", "archived"]).default("all").catch("all"),
+ customerId: z.string().default("all").catch("all"),
+});
+/* oxlint-enable promise/prefer-await-to-then, github/no-then */
+
+const defaultFilters = searchSchema.parse({});
+
+export const Route = createFileRoute("/_auth/branches/")({
+ validateSearch: searchSchema,
+ search: { middlewares: [stripSearchParams(defaultFilters)] },
+ component: RouteComponent,
+});
+
+function RouteComponent() {
+ const filters = Route.useSearch();
+ const navigate = Route.useNavigate();
+
+ const {
+ data: branches = [],
+ isError,
+ isPending,
+ isPlaceholderData,
+ } = useListBranches(
+ filters.customerId === "all" ? {} : { customerId: filters.customerId }
+ );
+
+ const visibleBranches = useMemo(() => {
+ const term = stripAccents(filters.name.trim()).toLowerCase();
+
+ return branches
+ .filter((branch) => {
+ if (term && !stripAccents(branch.name).toLowerCase().includes(term)) {
+ return false;
+ }
+
+ if (filters.status === "active") {
+ return !branch.archived;
+ }
+
+ if (filters.status === "archived") {
+ return !!branch.archived;
+ }
+
+ return true;
+ })
+ .toSorted((a, b) => a.name.localeCompare(b.name, "es"));
+ }, [branches, filters.name, filters.status]);
+
+ const hasFilters =
+ filters.name.trim() !== "" ||
+ filters.status !== defaultFilters.status ||
+ filters.customerId !== defaultFilters.customerId;
+
+ const handleFiltersChange = (next: BranchFilters) =>
+ navigate({ search: next, replace: true });
+
+ return (
+
+
+
+
+
+ Gestiona las sucursales de los clientes
+
+
+
+
+
+
+
+
+
+ {isPending ? (
+
+ Cargando sucursales…
+
+ ) : null}
+
+ {isError ? (
+
+ No se pudieron cargar las sucursales.
+
+ ) : null}
+
+ {!(isPending || isError) && visibleBranches.length === 0 ? (
+
+ {hasFilters ? (
+
+ ) : (
+
+ )}
+
+ {hasFilters
+ ? "No se encontraron sucursales"
+ : "No hay sucursales para mostrar"}
+
+
+ {hasFilters
+ ? "Intenta con otros filtros de búsqueda"
+ : "Las sucursales aparecerán aquí"}
+
+
+ ) : null}
+
+ {visibleBranches.length > 0 ? (
+
+ {visibleBranches.map((branch) => (
+
+ ))}
+
+ ) : null}
+
+ );
+}
From 3aba253e0816caba58d3e5f9a6af73af5d1209ec Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 14:44:13 -0600
Subject: [PATCH 23/30] Integra select component a grid contacts
---
.../customers/contacts/contact-grid.tsx | 123 ++++++++----------
1 file changed, 54 insertions(+), 69 deletions(-)
diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx
index 173f6fe..b53a3e0 100644
--- a/apps/web/src/components/customers/contacts/contact-grid.tsx
+++ b/apps/web/src/components/customers/contacts/contact-grid.tsx
@@ -1,14 +1,13 @@
-import { Button } from "@suni/ui/components/button";
import { useQuery } from "@tanstack/react-query";
-import { Plus, SearchX, Users } from "lucide-react";
+import { SearchX, Users } from "lucide-react";
import { useMemo, useState } from "react";
+import { NewEntityButton } from "@/components/customers/select-entity-button";
import { orpc } from "@/utils/orpc";
import ContactCard from "./contact-card";
import { ContactsFilters } from "./contact-filters";
import type { ContactFilters } from "./contact-filters";
-import { ContactFormDialog } from "./contact-form-dialog";
interface ContactsGridProps {
customerId: string;
@@ -25,8 +24,6 @@ export function ContactsGrid({ customerId, branchId }: ContactsGridProps) {
DEFAULT_CONTACT_FILTERS
);
- const [isFormOpen, setIsFormOpen] = useState(false);
-
const {
data: contacts = [],
isPending,
@@ -59,75 +56,63 @@ export function ContactsGrid({ customerId, branchId }: ContactsGridProps) {
filters.name.trim() !== "" || filters.status !== "all";
return (
- <>
-
-
-
Contactos
- {branchId ? (
-
- ) : null}
-
+
+
+
Contactos
+
+
-
+
- {isPending ? (
-
- Cargando contactos…
-
- ) : null}
+ {isPending ? (
+
+ Cargando contactos…
+
+ ) : null}
+
+ {isError ? (
+
+ No se pudieron cargar los contactos.
+
+ ) : null}
- {isError ? (
-
- No se pudieron cargar los contactos.
+ {!(isPending || isError) && filtered.length === 0 ? (
+
+ {hasActiveFilters ? (
+
+ ) : (
+
+ )}
+
+ {hasActiveFilters
+ ? "No se encontraron contactos"
+ : "No hay contactos para mostrar"}
- ) : 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}
-
+
+ {hasActiveFilters
+ ? "Intenta con otros filtros de búsqueda"
+ : "Los contactos aparecerán aquí"}
+
+
+ ) : null}
- {branchId ? (
-
+ {filtered.length > 0 ? (
+
+ {filtered.map((contact) => (
+
+ ))}
+
) : null}
- >
+
);
}
From 1589a5ca02b8f949e3b3502cf9920946df9636e4 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 14:46:43 -0600
Subject: [PATCH 24/30] Crea contacts index
---
apps/web/src/routes/_auth/contacts/index.tsx | 145 +++++++++++++++++++
1 file changed, 145 insertions(+)
create mode 100644 apps/web/src/routes/_auth/contacts/index.tsx
diff --git a/apps/web/src/routes/_auth/contacts/index.tsx b/apps/web/src/routes/_auth/contacts/index.tsx
new file mode 100644
index 0000000..6b3d1b3
--- /dev/null
+++ b/apps/web/src/routes/_auth/contacts/index.tsx
@@ -0,0 +1,145 @@
+import { cn } from "@suni/ui/lib/utils";
+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
+import { SearchX, Users } from "lucide-react";
+import { useMemo } from "react";
+import { z } from "zod";
+
+import ContactCard from "@/components/customers/contacts/contact-card";
+import { ContactsFilters } from "@/components/customers/contacts/contact-filters";
+import type { ContactFilters } from "@/components/customers/contacts/contact-filters";
+import { NewEntityButton } from "@/components/customers/select-entity-button";
+import { useListContacts } from "@/hooks/use-contacts";
+import { stripAccents } from "@/lib/string-utils";
+
+/* oxlint-disable promise/prefer-await-to-then, github/no-then -- zod `.catch()` is not Promise.catch */
+const searchSchema = z.object({
+ name: z.string().default("").catch(""),
+ status: z.enum(["all", "active", "archived"]).default("all").catch("all"),
+});
+/* oxlint-enable promise/prefer-await-to-then, github/no-then */
+
+const defaultFilters = searchSchema.parse({});
+
+export const Route = createFileRoute("/_auth/contacts/")({
+ validateSearch: searchSchema,
+ search: { middlewares: [stripSearchParams(defaultFilters)] },
+ component: RouteComponent,
+});
+
+function RouteComponent() {
+ const filters = Route.useSearch();
+ const navigate = Route.useNavigate();
+
+ const {
+ data: contacts = [],
+ isError,
+ isPending,
+ isPlaceholderData,
+ } = useListContacts({});
+
+ const visibleContacts = useMemo(() => {
+ const term = stripAccents(filters.name.trim()).toLowerCase();
+
+ return contacts
+ .filter((contact) => {
+ if (term && !stripAccents(contact.name).toLowerCase().includes(term)) {
+ return false;
+ }
+
+ if (filters.status === "active") {
+ return !contact.archived;
+ }
+
+ if (filters.status === "archived") {
+ return !!contact.archived;
+ }
+
+ return true;
+ })
+ .toSorted((a, b) => a.name.localeCompare(b.name, "es"));
+ }, [contacts, filters.name, filters.status]);
+
+ const hasFilters =
+ filters.name.trim() !== "" || filters.status !== defaultFilters.status;
+
+ const handleFiltersChange = (next: ContactFilters) =>
+ navigate({ search: next, replace: true });
+
+ return (
+
+
+
+
+
+ Gestiona los contactos de las sucursales
+
+
+
+
+
+
+
+
+
+ {isPending ? (
+
+ Cargando contactos…
+
+ ) : null}
+
+ {isError ? (
+
+ No se pudieron cargar los contactos.
+
+ ) : null}
+
+ {!(isPending || isError) && visibleContacts.length === 0 ? (
+
+ {hasFilters ? (
+
+ ) : (
+
+ )}
+
+ {hasFilters
+ ? "No se encontraron contactos"
+ : "No hay contactos para mostrar"}
+
+
+ {hasFilters
+ ? "Intenta con otros filtros de búsqueda"
+ : "Los contactos aparecerán aquí"}
+
+
+ ) : null}
+
+ {visibleContacts.length > 0 ? (
+
+ {visibleContacts.map((contact) => (
+
+ ))}
+
+ ) : null}
+
+ );
+}
From 192c68f4ef09f1af25525fef375ec612bc1d4831 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Fri, 6 Nov 2026 14:50:25 -0600
Subject: [PATCH 25/30] Agrega sucursales y contactos a nav-bar
---
apps/web/src/components/nav-bar.tsx | 17 ++++++++++-------
1 file changed, 10 insertions(+), 7 deletions(-)
diff --git a/apps/web/src/components/nav-bar.tsx b/apps/web/src/components/nav-bar.tsx
index e080579..cb1f414 100644
--- a/apps/web/src/components/nav-bar.tsx
+++ b/apps/web/src/components/nav-bar.tsx
@@ -1,28 +1,31 @@
import { SidebarMenu, SidebarMenuItem } from "@suni/ui/components/sidebar";
import { cn } from "@suni/ui/lib/utils";
import { Link, useRouterState } from "@tanstack/react-router";
+import type { LinkProps } from "@tanstack/react-router";
import type { LucideIcon } from "lucide-react";
-import { Home, Users } from "lucide-react";
+import { Building2, Contact, ContactRound, Home, Users } from "lucide-react";
import { useIsAdmin } from "@/hooks/use-is-admin";
interface NavItem {
- to: "/dashboard" | "/users" | "/customers";
+ to: NonNullable;
label: string;
icon: LucideIcon;
adminOnly?: true;
}
-const NAV_ITEMS: NavItem[] = [
+const NAV_ITEMS = [
{ to: "/dashboard", label: "Inicio", icon: Home },
{ to: "/users", label: "Usuarios", icon: Users, adminOnly: true },
- { to: "/customers", label: "Clientes", icon: Users },
-];
+ { to: "/customers", label: "Clientes", icon: ContactRound },
+ { to: "/branches", label: "Sucursales", icon: Building2 },
+ { to: "/contacts", label: "Contactos", icon: Contact },
+] satisfies NavItem[];
export function NavMain() {
const pathname = useRouterState({ select: (s) => s.location.pathname });
const isAdmin = useIsAdmin();
- const items = NAV_ITEMS.filter((item) => isAdmin || !item.adminOnly);
+ const items = NAV_ITEMS.filter((item) => isAdmin || !("adminOnly" in item));
return (
@@ -32,12 +35,12 @@ export function NavMain() {
return (
{label}
From 1f39a84599c576a49d73fa67e3e173c240730d55 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Sun, 8 Nov 2026 15:49:02 -0600
Subject: [PATCH 26/30] Agrega hook ppara listar clientes en filtro branches
---
apps/web/src/routes/_auth/branches/index.tsx | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/apps/web/src/routes/_auth/branches/index.tsx b/apps/web/src/routes/_auth/branches/index.tsx
index 7d8f3ec..00496cd 100644
--- a/apps/web/src/routes/_auth/branches/index.tsx
+++ b/apps/web/src/routes/_auth/branches/index.tsx
@@ -9,6 +9,7 @@ import { BranchesFilters } from "@/components/customers/branches/filters";
import type { BranchFilters } from "@/components/customers/branches/filters";
import { NewEntityButton } from "@/components/customers/select-entity-button";
import { useListBranches } from "@/hooks/use-branches";
+import { useListCustomers } from "@/hooks/use-customers";
import { stripAccents } from "@/lib/string-utils";
/* oxlint-disable promise/prefer-await-to-then, github/no-then -- zod `.catch()` is not Promise.catch */
@@ -62,6 +63,8 @@ function RouteComponent() {
.toSorted((a, b) => a.name.localeCompare(b.name, "es"));
}, [branches, filters.name, filters.status]);
+ const { data: customers } = useListCustomers({});
+
const hasFilters =
filters.name.trim() !== "" ||
filters.status !== defaultFilters.status ||
@@ -90,6 +93,7 @@ function RouteComponent() {
From 3fc6ca3866293550ae6d0def2bc2941f59b86565 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Sun, 8 Nov 2026 16:56:24 -0600
Subject: [PATCH 27/30] Omite la consulta de la sucursal hasta que se
seleccione un cliente.
---
apps/web/src/components/customers/select-entity-button.tsx | 3 ++-
apps/web/src/hooks/use-branches.ts | 6 +++++-
2 files changed, 7 insertions(+), 2 deletions(-)
diff --git a/apps/web/src/components/customers/select-entity-button.tsx b/apps/web/src/components/customers/select-entity-button.tsx
index 9180c4b..6a06152 100644
--- a/apps/web/src/components/customers/select-entity-button.tsx
+++ b/apps/web/src/components/customers/select-entity-button.tsx
@@ -57,7 +57,8 @@ function BranchPicker({
onValueChange,
}: PickerProps & { customerId: string | null }) {
const { data: branches = [], isPending } = useListBranches(
- customerId ? { customerId } : {}
+ customerId ? { customerId } : {},
+ !!customerId
);
const options = useMemo(
diff --git a/apps/web/src/hooks/use-branches.ts b/apps/web/src/hooks/use-branches.ts
index 2a09553..a4ee52e 100644
--- a/apps/web/src/hooks/use-branches.ts
+++ b/apps/web/src/hooks/use-branches.ts
@@ -14,10 +14,14 @@ import { client, orpc } from "@/utils/orpc";
type BranchRow = AppRouterOutputs["branches"]["list"][number];
-export function useListBranches(params: AppRouterInputs["branches"]["list"]) {
+export function useListBranches(
+ params: AppRouterInputs["branches"]["list"],
+ enabled = true
+) {
return useQuery({
...orpc.branches.list.queryOptions({ input: params }),
placeholderData: keepPreviousData,
+ enabled,
});
}
From 651c3089bb1c7615ecbb88ac0f736c3292b4b7c9 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Sun, 8 Nov 2026 23:04:03 -0600
Subject: [PATCH 28/30] Agrega filtro de estado compartido (cliente > sucursal
> contacto)
---
packages/api/src/util/status.ts | 43 +++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+)
create mode 100644 packages/api/src/util/status.ts
diff --git a/packages/api/src/util/status.ts b/packages/api/src/util/status.ts
new file mode 100644
index 0000000..45b3245
--- /dev/null
+++ b/packages/api/src/util/status.ts
@@ -0,0 +1,43 @@
+const isNull = { isNull: true } as const;
+
+const isNotNull = { isNotNull: true } as const;
+
+const visible = {
+ customer: { archived: isNull },
+ branch: { archived: isNull, customer: { archived: isNull } },
+ contact: {
+ archived: isNull,
+ branch: { archived: isNull },
+ customer: { archived: isNull },
+ },
+} as const;
+
+const archived = {
+ customer: { archived: isNotNull },
+ branch: {
+ OR: [{ archived: isNotNull }, { customer: { archived: isNotNull } }],
+ },
+ contact: {
+ OR: [
+ { archived: isNotNull },
+ { branch: { archived: isNotNull } },
+ { customer: { archived: isNotNull } },
+ ],
+ },
+} as const;
+
+type Entity = keyof typeof visible;
+
+type Status = "active" | "archived" | "all";
+
+export function statusWhere(entity: Entity, status: Status) {
+ if (status === "all") {
+ return {};
+ }
+
+ if (status === "active") {
+ return visible[entity];
+ }
+
+ return archived[entity];
+}
From 3ae47a59c59970726863b8cb10924cf48ee53f2a Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Sun, 8 Nov 2026 23:05:32 -0600
Subject: [PATCH 29/30] Implementa helper statusWhere
---
packages/api/src/routers/branches/get.ts | 8 ++-----
packages/api/src/routers/branches/list.ts | 29 ++++++++++++++++++-----
packages/api/src/routers/contacts/get.ts | 4 ++--
packages/api/src/routers/contacts/list.ts | 16 +++++++++----
4 files changed, 39 insertions(+), 18 deletions(-)
diff --git a/packages/api/src/routers/branches/get.ts b/packages/api/src/routers/branches/get.ts
index 3ac6e25..c72e0f9 100644
--- a/packages/api/src/routers/branches/get.ts
+++ b/packages/api/src/routers/branches/get.ts
@@ -3,10 +3,6 @@ import { z } from "zod";
import { isAdmin, protectedProcedure } from "../../index";
-function notFound() {
- return new ORPCError("NOT_FOUND", { message: "Branch not found" });
-}
-
export const get = protectedProcedure
.route({ method: "GET", path: "/{id}" })
.input(z.object({ id: z.string() }))
@@ -19,14 +15,14 @@ export const get = protectedProcedure
: { id: input.id, sellerId: context.session.user.id },
columns: admin ? undefined : { sellerId: false, modifiedBy: false },
with: {
- customer: { columns: { id: true, name: true } },
+ customer: { columns: { id: true, name: true, archived: true } },
contacts: true,
...(admin && { seller: { columns: { id: true, name: true } } }),
},
});
if (!found) {
- throw notFound();
+ throw new ORPCError("NOT_FOUND", { message: "Branch not found" });
}
return admin ? found : { ...found, seller: null };
diff --git a/packages/api/src/routers/branches/list.ts b/packages/api/src/routers/branches/list.ts
index 1b8298f..cf4990c 100644
--- a/packages/api/src/routers/branches/list.ts
+++ b/packages/api/src/routers/branches/list.ts
@@ -1,18 +1,32 @@
+import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums";
import { z } from "zod";
import { isAdmin, protectedProcedure } from "../../index";
+import { statusWhere } from "../../util/status";
export const list = protectedProcedure
.route({ method: "GET", path: "/" })
- .input(z.object({ customerId: z.string().optional() }))
+ .input(
+ z.object({
+ customerId: z.string().optional(),
+ status: z.enum(CUSTOMER_STATUSES).default("active"),
+ })
+ )
.handler(async ({ input, context }) => {
- const where = input.customerId ? { customerId: input.customerId } : {};
+ const userId = context.session.user.id;
- if (await isAdmin(context, context.session.user.id)) {
+ const where = {
+ AND: [
+ statusWhere("branch", input.status),
+ ...(input.customerId ? [{ customerId: input.customerId }] : []),
+ ],
+ };
+
+ if (await isAdmin(context, userId)) {
return context.db.query.branch.findMany({
where,
with: {
- customer: { columns: { id: true, name: true } },
+ customer: { columns: { id: true, name: true, archived: true } },
seller: { columns: { id: true, name: true } },
contacts: true,
},
@@ -21,9 +35,12 @@ export const list = protectedProcedure
// Seller identity is admin-only.
const rows = await context.db.query.branch.findMany({
- where: { ...where, sellerId: context.session.user.id },
+ where: { AND: [where, { sellerId: userId }] },
columns: { sellerId: false, modifiedBy: false },
- with: { customer: { columns: { id: true, name: true } }, contacts: true },
+ with: {
+ customer: { columns: { id: true, name: true, archived: true } },
+ contacts: true,
+ },
});
return rows.map((row) => ({ ...row, seller: null }));
diff --git a/packages/api/src/routers/contacts/get.ts b/packages/api/src/routers/contacts/get.ts
index 233a196..4a2cc90 100644
--- a/packages/api/src/routers/contacts/get.ts
+++ b/packages/api/src/routers/contacts/get.ts
@@ -17,8 +17,8 @@ export const get = protectedProcedure
},
columns: admin ? undefined : { modifiedBy: false },
with: {
- branch: { columns: { id: true, name: true } },
- customer: { columns: { id: true, name: true } },
+ branch: { columns: { id: true, name: true, archived: true } },
+ customer: { 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 c6704e7..a81448d 100644
--- a/packages/api/src/routers/contacts/list.ts
+++ b/packages/api/src/routers/contacts/list.ts
@@ -1,6 +1,8 @@
+import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums";
import { z } from "zod";
import { isAdmin, protectedProcedure } from "../../index";
+import { statusWhere } from "../../util/status";
export const list = protectedProcedure
.route({ method: "GET", path: "/" })
@@ -8,6 +10,7 @@ export const list = protectedProcedure
z.object({
customerId: z.string().optional(),
branchId: z.string().optional(),
+ status: z.enum(CUSTOMER_STATUSES).default("active"),
})
)
.handler(async ({ input, context }) => {
@@ -16,11 +19,16 @@ export const list = protectedProcedure
return context.db.query.contact.findMany({
where: {
- customerId: input.customerId,
- branchId: input.branchId,
- branch: admin ? undefined : { sellerId: userId },
+ AND: [
+ statusWhere("contact", input.status),
+ { customerId: input.customerId, branchId: input.branchId },
+ ...(admin ? [] : [{ branch: { sellerId: userId } }]),
+ ],
},
columns: admin ? undefined : { modifiedBy: false },
- with: { branch: { columns: { id: true, name: true } } },
+ with: {
+ branch: { columns: { id: true, name: true, archived: true } },
+ customer: { columns: { id: true, name: true, archived: true } },
+ },
});
});
From a887b2b5009f73e947f8bb3217d7dba555a03686 Mon Sep 17 00:00:00 2001
From: YAHIR-1
Date: Sun, 8 Nov 2026 23:06:35 -0600
Subject: [PATCH 30/30] Implementa helper statusWhere en frontend agrega reglas
para mostrar badge de archivado asi como filtros en index
---
.../components/customers/branches/card.tsx | 36 +--
.../customers/contacts/contact-card.tsx | 216 ++++++++++++------
apps/web/src/routes/_auth/branches/index.tsx | 30 +--
apps/web/src/routes/_auth/contacts/index.tsx | 23 +-
4 files changed, 179 insertions(+), 126 deletions(-)
diff --git a/apps/web/src/components/customers/branches/card.tsx b/apps/web/src/components/customers/branches/card.tsx
index 005ec08..c790aea 100644
--- a/apps/web/src/components/customers/branches/card.tsx
+++ b/apps/web/src/components/customers/branches/card.tsx
@@ -1,3 +1,4 @@
+import type { AppRouterOutputs } from "@suni/api/routers/index";
import { Badge } from "@suni/ui/components/badge";
import { Button } from "@suni/ui/components/button";
import {
@@ -26,9 +27,10 @@ import { useState } from "react";
import { BranchFormDialog } from "./branch-form-dialog";
import { ChangeBranchStatusDialog } from "./change-branch-status-dialog";
-import type { Branch } from "./util/branch-address";
import { formatAddress } from "./util/branch-address";
+type Branch = AppRouterOutputs["branches"]["list"][number];
+
interface BranchCardProps {
branch: Branch;
customer?: { id: string; name: string };
@@ -94,7 +96,10 @@ function BranchImage({
}
export default function BranchCard({ branch, customer }: BranchCardProps) {
- const isArchived = !!branch.archived;
+ const isOwnArchived = !!branch.archived;
+ const isCustomerArchived = !!branch.customer?.archived;
+ const isArchived = isOwnArchived || isCustomerArchived;
+
const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false);
const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
const placeholder = "/placeholder.webp";
@@ -175,17 +180,20 @@ export default function BranchCard({ branch, customer }: BranchCardProps) {
Editar
)}
- setIsStatusDialogOpen(true)}
- >
- {isArchived ? (
-
- ) : (
-
- )}
- {isArchived ? "Desarchivar" : "Archivar"}
-
+ {/* Si el cliente es quien la archiva, desarchivarla no tendría efecto */}
+ {!isCustomerArchived && (
+ setIsStatusDialogOpen(true)}
+ >
+ {isOwnArchived ? (
+
+ ) : (
+
+ )}
+ {isOwnArchived ? "Desarchivar" : "Archivar"}
+
+ )}
@@ -217,7 +225,7 @@ export default function BranchCard({ branch, customer }: BranchCardProps) {
- Archivada
+ {isCustomerArchived ? "Cliente archivado" : "Archivada"}
)}
diff --git a/apps/web/src/components/customers/contacts/contact-card.tsx b/apps/web/src/components/customers/contacts/contact-card.tsx
index e0053b2..270380e 100644
--- a/apps/web/src/components/customers/contacts/contact-card.tsx
+++ b/apps/web/src/components/customers/contacts/contact-card.tsx
@@ -35,12 +35,141 @@ interface ContactCardProps {
readOnly?: boolean;
}
+function getArchiveState(contact: Contact) {
+ const isOwn = !!contact.archived;
+ const isCustomer = !!contact.customer?.archived;
+ const isBranch = !!contact.branch?.archived;
+ const isParent = isCustomer || isBranch;
+
+ let label = "Archivado";
+
+ if (isCustomer) {
+ label = "Cliente archivado";
+ } else if (isBranch) {
+ label = "Sucursal archivada";
+ }
+
+ return { isOwn, isParent, isArchived: isOwn || isParent, label };
+}
+
+interface ContactMenuProps {
+ isArchived: boolean;
+ isOwnArchived: boolean;
+ isParentArchived: boolean;
+ onEdit: () => void;
+ onToggleStatus: () => void;
+}
+
+function ContactMenu({
+ isArchived,
+ isOwnArchived,
+ isParentArchived,
+ onEdit,
+ onToggleStatus,
+}: ContactMenuProps) {
+ return (
+
+
+ }>
+ Abrir menú
+
+
+
+
+ Acciones
+ {!isArchived && (
+
+
+ Editar
+
+ )}
+
+ {/* Si un padre lo archiva, desarchivarlo no tendría efecto */}
+ {!isParentArchived && (
+
+ {isOwnArchived ? (
+
+ ) : (
+
+ )}
+ {isOwnArchived ? "Desarchivar" : "Archivar"}
+
+ )}
+
+
+
+
+ );
+}
+
+interface ContactParentsProps {
+ contact: Contact;
+ customer?: { id: string; name: string };
+}
+
+function ContactParents({ contact, customer }: ContactParentsProps) {
+ return (
+ <>
+ {customer && (
+
+
+
+ {customer.name}
+
+
+ )}
+
+ {contact.branch && (
+
+
+
+ {contact.branch.name}
+
+
+ )}
+ >
+ );
+}
+
+function ContactPhone({ contact }: { contact: Contact }) {
+ if (!contact.phone) {
+ return null;
+ }
+
+ return (
+
+
+
+ {contact.phone}
+ {contact.phoneExtension && ` ext. ${contact.phoneExtension}`}
+
+
+ );
+}
+
export default function ContactCard({
contact,
customer,
readOnly = false,
}: ContactCardProps) {
- const isArchived = !!contact.archived;
+ const { isOwn, isParent, isArchived, label } = getArchiveState(contact);
+
const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false);
const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
@@ -80,74 +209,17 @@ export default function ContactCard({
)}
- {customer && (
-
-
-
- {customer.name}
-
-
- )}
-
- {contact.branch && (
-
-
-
- {contact.branch.name}
-
-
- )}
+
{!readOnly && (
-
-
- }
- >
- Abrir menú
-
-
-
-
- Acciones
- {!isArchived && (
- setIsUpdateFormOpen(true)}
- >
-
- Editar
-
- )}
- setIsStatusDialogOpen(true)}
- >
- {isArchived ? (
-
- ) : (
-
- )}
- {isArchived ? "Desarchivar" : "Archivar"}
-
-
-
-
-
+ setIsUpdateFormOpen(true)}
+ onToggleStatus={() => setIsStatusDialogOpen(true)}
+ />
)}
@@ -167,15 +239,7 @@ export default function ContactCard({
{contact.email}
- {contact.phone && (
-
-
-
- {contact.phone}
- {contact.phoneExtension && ` ext. ${contact.phoneExtension}`}
-
-
- )}
+
{/* Archived badge */}
@@ -183,7 +247,7 @@ export default function ContactCard({
)}
diff --git a/apps/web/src/routes/_auth/branches/index.tsx b/apps/web/src/routes/_auth/branches/index.tsx
index 00496cd..c93f1d9 100644
--- a/apps/web/src/routes/_auth/branches/index.tsx
+++ b/apps/web/src/routes/_auth/branches/index.tsx
@@ -37,31 +37,23 @@ function RouteComponent() {
isError,
isPending,
isPlaceholderData,
- } = useListBranches(
- filters.customerId === "all" ? {} : { customerId: filters.customerId }
- );
+ } = 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) => {
- if (term && !stripAccents(branch.name).toLowerCase().includes(term)) {
- return false;
- }
-
- if (filters.status === "active") {
- return !branch.archived;
- }
-
- if (filters.status === "archived") {
- return !!branch.archived;
- }
-
- return true;
- })
+ .filter(
+ (branch) =>
+ !term || stripAccents(branch.name).toLowerCase().includes(term)
+ )
.toSorted((a, b) => a.name.localeCompare(b.name, "es"));
- }, [branches, filters.name, filters.status]);
+ }, [branches, filters.name]);
const { data: customers } = useListCustomers({});
diff --git a/apps/web/src/routes/_auth/contacts/index.tsx b/apps/web/src/routes/_auth/contacts/index.tsx
index 6b3d1b3..691eaaa 100644
--- a/apps/web/src/routes/_auth/contacts/index.tsx
+++ b/apps/web/src/routes/_auth/contacts/index.tsx
@@ -35,29 +35,18 @@ function RouteComponent() {
isError,
isPending,
isPlaceholderData,
- } = useListContacts({});
+ } = useListContacts({ status: filters.status });
const visibleContacts = useMemo(() => {
const term = stripAccents(filters.name.trim()).toLowerCase();
return contacts
- .filter((contact) => {
- if (term && !stripAccents(contact.name).toLowerCase().includes(term)) {
- return false;
- }
-
- if (filters.status === "active") {
- return !contact.archived;
- }
-
- if (filters.status === "archived") {
- return !!contact.archived;
- }
-
- return true;
- })
+ .filter(
+ (contact) =>
+ !term || stripAccents(contact.name).toLowerCase().includes(term)
+ )
.toSorted((a, b) => a.name.localeCompare(b.name, "es"));
- }, [contacts, filters.name, filters.status]);
+ }, [contacts, filters.name]);
const hasFilters =
filters.name.trim() !== "" || filters.status !== defaultFilters.status;