Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions .agents/skills/verify-suni/features/customers.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
# Customers

Customers (`Clientes`) is the reference domain module. A signed-in user lists customers and filters them by name, type and status. They create a customer with an address filled from the postal code, open its detail page, edit it, and archive or unarchive it. There is no delete.
Customers (`Clientes`) is the reference domain module. A signed-in user lists customers and filters them by name and status. They create a customer with an address filled from the postal code, open its detail page, edit it, and archive or unarchive it. There is no delete.

## Sub-features

- `customers-list` shows active customers as cards, with loading, empty and error states.
- `customers-filter` filters by name (`?name=`, accents ignored), type (`?type=`) and status (`?status=active|archived|all`).
- `customers-filter` filters by name (`?name=`, accents ignored) and status (`?status=active|archived|all`).
- `customers-create` validates with the shared Zod schema, looks up the postal code, saves, and opens the detail page.
- `customers-detail` shows the name, RFC, type, acquisition, seller (admins only), address and phone.
- `customers-detail` shows the name, RFC, acquisition, seller (admins only), address and phone.
- `customers-edit` changes a customer and returns to its detail page.
- `customers-archive` archives from the card menu after a confirmation dialog, and unarchives the same way.

Expand All @@ -30,7 +30,7 @@ Preconditions:
- **General data.** Run `$V ab find label "Razón social" fill "$N"`, `$V ab find label "RFC" fill "VSU010101AB1"` and `$V ab find label "Teléfono" fill "8112345678"`. Then pick the acquisition channel by keyboard: `$V ab find label "Medio de adquisición" click`, `$V ab keyboard type "Página web"` and `$V ab press Enter`.
- **Postal code lookup.** Run `$V ab find label "Código postal" fill "64000"` and `$V ab wait --fn 'document.querySelector("#city")?.value !== ""'`. `Municipio` is `Monterrey`, `Estado` is `Nuevo León`, both read-only, and a `Colonia *` combobox appears. Run `$V ab find label "Colonia" click`, `$V ab keyboard type "Monterrey Centro"` and `$V ab press Enter`.
- **Street.** Run `$V ab find label "Calle" fill "Av. Constitución"` and `$V ab find label "Número exterior" fill "100"`. Run `$V shot customers create-filled`.
- **Save.** Run `$V ab find role button click --name "Crear"` and `$V ab wait --text "VSU010101AB1"`. `$V ab get url` is `/customers/<uuid>`, and the page shows `$N`, `Cliente`, `Página web` and `Av. Constitución, No. Ext. 100, Colonia Monterrey Centro`. Run `$V shot customers create-detail`.
- **Save.** Run `$V ab find role button click --name "Crear"` and `$V ab wait --text "VSU010101AB1"`. `$V ab get url` is `/customers/<uuid>`, and the page shows `$N`, `Página web` and `Av. Constitución, No. Ext. 100, Colonia Monterrey Centro`. Run `$V shot customers create-detail`.
- **Stored row.** `$V sql "select count(*), max(postal_code), max(suburb) from customer where name = '$N'"` returns `1 | 64000 | Monterrey Centro`.
- **Filter.** Run `$V ab find role link click --name "Clientes"` and `$V ab find label "Buscar por nombre" fill "$N"`. The URL gains `?name=` and exactly one card has the heading `$N`. Run `$V shot customers list-after`.
- **Archive.** Run `$V ab find role button click --name "Abrir menú"`, `$V ab find role menuitem click --name "Archivar"` and `$V ab wait --text "Esto archivará"`. Run `$V shot customers archive-dialog`, then `$V ab find role button click --name "Archivar"`. With the name filter still applied, `No se encontraron clientes` appears. `$V sql "select archived is not null from customer where name = '$N'"` returns `t`.
Expand All @@ -41,11 +41,11 @@ Preconditions:

## Gotchas

- `Medio de adquisición`, `Tipo` and `Colonia` are react-select comboboxes. Pick options by typing and pressing `Enter`. `find role option click` can report success without selecting anything, and then `Crear` silently stays on `/customers/new` with `Selecciona un medio de adquisición`. Always assert that the URL left `/customers/new`.
- `Medio de adquisición` and `Colonia` are react-select comboboxes. Pick options by typing and pressing `Enter`. `find role option click` can report success without selecting anything, and then `Crear` silently stays on `/customers/new` with `Selecciona un medio de adquisición`. Always assert that the URL left `/customers/new`.
- The postal code lookup calls the real SEPOMEX service. On a miss or an error, the status says `No encontramos ese código postal` or `No se pudo consultar el código postal`, and `Municipio` and `Estado` unlock for manual entry.
- `Tipo` only renders for admins. A user-role customer always gets `Cliente`, and the seller line on cards only appears for admins.
- The seller line on cards only appears for admins.
- The RFC must match `^[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}$` and is not unique, so reusing `VSU010101AB1` is fine.
- Card menus are hidden until hover on pointer devices. `find role button --name "Abrir menú"` still reaches them. With several cards, filter by name first so only one menu matches.
- The name search is bound to `?name=`. A second `fill` appends to the current value instead of replacing it. Click `Limpiar` first, which also resets the type and status filters.
- The name search is bound to `?name=`. A second `fill` appends to the current value instead of replacing it. Click `Limpiar búsqueda` first.
- On the detail page `Editar` is a `link`. In a card's menu it is a `menuitem`.
- Archived customers stay in the shared database. Report the names you left.
46 changes: 9 additions & 37 deletions apps/web/src/components/customers/customer-filters.tsx
Original file line number Diff line number Diff line change
@@ -1,51 +1,23 @@
import type { AppRouterOutputs } from "@suni/api/routers/index";
import { CUSTOMER_TYPES } from "@suni/db/schema/customer-enums";
import { getRouteApi } from "@tanstack/react-router";

import { FilterBar } from "@/components/customers/shared/filter-bar";
import { SegmentedControl } from "@/components/customers/shared/segmented-control";

const routeApi = getRouteApi("/_auth/customers/");

type TypeFilter = "all" | (typeof CUSTOMER_TYPES)[number];

const TYPE_OPTIONS: { value: TypeFilter; label: string }[] = [
{ value: "all", label: "Todos" },
...CUSTOMER_TYPES.map((value) => ({ value, label: value })),
];

interface CustomerFiltersProps {
/** Customers in the current tab and search, before the type filter, for the counts. */
customers: AppRouterOutputs["customers"]["list"][number][];
}

export default function CustomerFilters({ customers }: CustomerFiltersProps) {
const { name, type } = routeApi.useSearch();
export default function CustomerFilters() {
const { name } = routeApi.useSearch();
const navigate = routeApi.useNavigate();

const setFilters = (filters: { name?: string; type?: TypeFilter }) =>
navigate({ search: (prev) => ({ ...prev, ...filters }), replace: true });

const countOf = (value: TypeFilter) =>
value === "all"
? customers.length
: customers.filter((customer) => customer.type === value).length;

return (
<FilterBar
onSearchChange={(value) => setFilters({ name: value })}
onSearchChange={(next) =>
navigate({
search: (prev) => ({ ...prev, name: next }),
replace: true,
})
}
search={name}
searchLabel="Buscar por nombre"
>
<SegmentedControl
legend="Tipo de cliente"
onValueChange={(value) => setFilters({ type: value })}
options={TYPE_OPTIONS.map((option) => ({
...option,
count: countOf(option.value),
}))}
value={type}
/>
</FilterBar>
/>
);
}
22 changes: 1 addition & 21 deletions apps/web/src/components/customers/customer-form.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import type { AppRouterOutputs } from "@suni/api/routers/index";
import {
ACQUISITION_CHANNELS,
CUSTOMER_TYPES,
} from "@suni/db/schema/customer-enums";
import { ACQUISITION_CHANNELS } from "@suni/db/schema/customer-enums";
import { customerSchema } from "@suni/db/validation/customers";
import { Button } from "@suni/ui/components/button";
import { revalidateLogic, useSelector } from "@tanstack/react-form";
Expand All @@ -12,7 +9,6 @@ import type { z } from "zod";

import { useAppForm } from "@/components/form/use-app-form";
import { useCreateCustomer, useUpdateCustomer } from "@/hooks/use-customers";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { POSTAL_CODE_LENGTH, useAddressLookup } from "@/hooks/use-postal-code";

type FormValues = Omit<z.input<typeof customerSchema>, "acquisition"> & {
Expand All @@ -35,7 +31,6 @@ const EMPTY_VALUES: FormValues = {
phone: "",
phoneExtension: "",
acquisition: "",
type: "Cliente",
postalCode: "",
suburb: "",
city: "",
Expand All @@ -56,7 +51,6 @@ function toFormValues(customer?: CustomerFormProps["customer"]): FormValues {
phone: customer.phone,
phoneExtension: customer.phoneExtension,
acquisition: customer.acquisition,
type: customer.type,
postalCode: customer.postalCode,
suburb: customer.suburb,
city: customer.city,
Expand All @@ -72,11 +66,8 @@ const ACQUISITION_OPTIONS = ACQUISITION_CHANNELS.map((value) => ({
label: value,
}));

const TYPE_OPTIONS = CUSTOMER_TYPES.map((value) => ({ value, label: value }));

export function CustomerForm({ customer }: CustomerFormProps) {
const navigate = useNavigate();
const isAdmin = useIsAdmin();
const createCustomer = useCreateCustomer();
const updateCustomer = useUpdateCustomer();

Expand Down Expand Up @@ -166,17 +157,6 @@ export function CustomerForm({ customer }: CustomerFormProps) {
/>
)}
</form.AppField>
{isAdmin ? (
<form.AppField name="type">
{(field) => (
<field.SelectField
label="Tipo"
options={TYPE_OPTIONS}
required
/>
)}
</form.AppField>
) : null}
</div>
</fieldset>

Expand Down
9 changes: 1 addition & 8 deletions apps/web/src/routes/_auth/customers/$customerId/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,7 @@ function RouteComponent() {
</Button>
</>
}
description={
<div className="flex flex-wrap items-center gap-2">
<span className="tabular-nums">{customer.rfc}</span>
<Badge variant={customer.type === "Asesor" ? "outline" : "default"}>
{customer.type}
</Badge>
</div>
}
description={<span className="tabular-nums">{customer.rfc}</span>}
icon={ContactRound}
title={customer.name}
/>
Expand Down
22 changes: 5 additions & 17 deletions apps/web/src/routes/_auth/customers/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
CUSTOMER_STATUSES,
CUSTOMER_TYPES,
} from "@suni/db/schema/customer-enums";
import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums";
import { Button } from "@suni/ui/components/button";
import {
Link,
Expand All @@ -25,10 +22,6 @@ import { useListCustomers } from "@/hooks/use-customers";
/* 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(""),
type: z
.enum(["all", ...CUSTOMER_TYPES])
.default("all")
.catch("all"),
status: z.enum(CUSTOMER_STATUSES).default("active").catch("active"),
});
/* oxlint-enable promise/prefer-await-to-then, github/no-then */
Expand All @@ -42,7 +35,7 @@ export const Route = createFileRoute("/_auth/customers/")({
});

function RouteComponent() {
const { name, type, status } = Route.useSearch();
const { name, status } = Route.useSearch();
const navigate = Route.useNavigate();

// Fetch every status once so each tab shows its count and switching is instant.
Expand All @@ -54,12 +47,7 @@ function RouteComponent() {

const rowsByStatus = byStatus(matchingName(customers ?? [], name));

const inTab = rowsByStatus[status];

const visibleCustomers =
type === "all" ? inTab : inTab.filter((customer) => customer.type === type);

const hasFilters = name.trim() !== "" || type !== "all";
const hasFilters = name.trim() !== "";

return (
<div className="flex flex-col gap-6">
Expand Down Expand Up @@ -89,9 +77,9 @@ function RouteComponent() {
}
value={status}
>
<CustomerFilters customers={inTab} />
<CustomerFilters />
<CustomerList
customers={visibleCustomers}
customers={rowsByStatus[status]}
hasFilters={hasFilters}
isError={isError}
isPending={isPending}
Expand Down
4 changes: 1 addition & 3 deletions packages/api/src/routers/customers/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,9 @@ export const create = scopedProcedure
.handler(async ({ input, context }) => {
const { userId } = context;

const type = context.admin ? input.type : "Cliente";

const [created] = await context.db
.insert(customer)
.values({ ...input, type, sellerId: userId, modifiedBy: userId })
.values({ ...input, sellerId: userId, modifiedBy: userId })
.returning({ id: customer.id });

return created;
Expand Down
6 changes: 2 additions & 4 deletions packages/api/src/routers/customers/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,13 @@ export const update = scopedProcedure
.route({ method: "PATCH", path: "/{id}" })
.input(customerSchema.extend({ id: z.string() }))
.handler(async ({ input, context, errors }) => {
const { id, type, ...fields } = input;
const { id, ...fields } = input;

const { userId } = context;

const data = context.admin ? { ...fields, type } : fields;

const [updated] = await context.db
.update(customer)
.set({ ...data, modifiedBy: userId })
.set({ ...fields, modifiedBy: userId })
// Archived customers are read-only until restored.
.where(
and(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE "customer" DROP COLUMN "type";--> statement-breakpoint
DROP TYPE "customer_type";
Loading
Loading