Skip to content

Commit e6980d6

Browse files
authored
fix(dashboard): readable customer profile and working branch filters (#311)
The customer profile printed the tier's id when the tier list was unavailable, raw event codes such as customer.checked_in, the start date as ISO, and labelled the earn base with the sale-amount label although the base is the sale over the tenant's unit. It now shows the tier name or a dash, activity in words, dates as es-CL, and the base in its own unit. The branch list's search box did nothing, "Incluir inactivas" did nothing because the identity worker returns every branch, and the address column showed city and country. The page now filters and searches the list it already has, accent-insensitively, and shows the street address.
1 parent f11d6fb commit e6980d6

7 files changed

Lines changed: 263 additions & 55 deletions

File tree

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// @vitest-environment jsdom
2+
3+
/**
4+
* The customer profile, read for what it prints: names and words, never the
5+
* ids and event codes the API hands over.
6+
*/
7+
8+
import { cleanup, render, screen } from '@testing-library/react';
9+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
10+
11+
import CustomerDetailPage from '../app/dashboard/customers/[id]/page';
12+
import type { CustomerDetail } from '../lib/api';
13+
14+
const TIER_ID = 'b0000000-0000-4000-8000-00000000000b';
15+
16+
const mocks = vi.hoisted(() => ({
17+
customer: {} as Record<string, unknown>,
18+
tiers: [] as Array<{ id: string; name: string; multiplier: number }>,
19+
}));
20+
21+
vi.mock('next/navigation', () => ({
22+
useParams: () => ({ id: 'a0000000-0000-4000-8000-000000000001' }),
23+
useRouter: () => ({ push: vi.fn(), back: vi.fn() }),
24+
}));
25+
26+
vi.mock('../lib/api', async (importOriginal) => {
27+
const actual = await importOriginal<typeof import('../lib/api')>();
28+
return {
29+
...actual,
30+
api: {
31+
getCustomer: vi.fn(async () => mocks.customer as unknown as CustomerDetail),
32+
getTiers: vi.fn(async () => mocks.tiers),
33+
getLoyaltyConfig: vi.fn(async () => ({ earnRate: 1, programName: 'Puntos' })),
34+
updateCustomer: vi.fn(),
35+
},
36+
};
37+
});
38+
39+
beforeEach(() => {
40+
mocks.customer = {
41+
id: 'a0000000-0000-4000-8000-000000000001',
42+
fullName: 'Ana Ruiz',
43+
phone: '+56911112222',
44+
points: 320,
45+
totalPointsEarned: 900,
46+
currentTier: TIER_ID,
47+
currentTierId: TIER_ID,
48+
createdAt: '2025-11-02',
49+
customer_events: [
50+
{
51+
id: 'e1',
52+
eventType: 'customer.checked_in',
53+
payload: {},
54+
createdAt: new Date().toISOString(),
55+
},
56+
],
57+
recent_transactions: [
58+
{ id: 't1', type: 'adjust', points: 50, note: null, createdAt: new Date().toISOString() },
59+
],
60+
consents: [],
61+
};
62+
mocks.tiers = [];
63+
});
64+
65+
afterEach(() => {
66+
cleanup();
67+
vi.clearAllMocks();
68+
});
69+
70+
describe('the customer profile', () => {
71+
it('never prints the tier id when the tier list is unavailable', async () => {
72+
render(<CustomerDetailPage />);
73+
await screen.findAllByText('Ana Ruiz');
74+
75+
expect(screen.queryByText(new RegExp(TIER_ID))).toBeNull();
76+
});
77+
78+
it('shows the tier by name when it is known', async () => {
79+
mocks.tiers = [{ id: TIER_ID, name: 'Plata', multiplier: 1.2 }];
80+
render(<CustomerDetailPage />);
81+
82+
expect((await screen.findAllByText('Plata')).length).toBeGreaterThan(0);
83+
});
84+
85+
it('describes activity in words, not event codes', async () => {
86+
render(<CustomerDetailPage />);
87+
await screen.findAllByText('Ana Ruiz');
88+
89+
expect(screen.getByText('Visitó el local')).toBeTruthy();
90+
expect(screen.getByText('Ajuste de puntos')).toBeTruthy();
91+
expect(screen.queryByText('customer.checked_in')).toBeNull();
92+
expect(screen.queryByText('adjust')).toBeNull();
93+
});
94+
95+
it('dates the customer’s start in the Chilean format', async () => {
96+
render(<CustomerDetailPage />);
97+
await screen.findAllByText('Ana Ruiz');
98+
99+
expect(screen.getAllByText(/02-11-2025/).length).toBeGreaterThan(0);
100+
expect(screen.queryByText(/2025-11-02/)).toBeNull();
101+
});
102+
});

‎apps/dashboard/src/__tests__/loyalty-points.contract.test.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -423,9 +423,11 @@ describe('the customer page points breakdown', () => {
423423
});
424424

425425
it('labels the base in the mechanic’s own unit', () => {
426-
// `pts` next to a visit count told the operator the field was money. The unit
427-
// comes from the same label the input uses, so the field and the equation agree.
428-
expect(block).toMatch(/<span>[^<]*Base:[^<]*\{\s*earn\.base\s*\}[^<]*\{\s*saleAmountLabel\s*\}/);
426+
// `pts` next to a visit count told the operator the field was money, and the
427+
// input's own label ("Monto de venta") called the base the sale when it is the
428+
// sale over the tenant's unit. The unit is derived from the earn mechanic.
429+
expect(block).toMatch(/<span>[^<]*Base:[^<]*\{\s*earn\.base\s*\}[^<]*\{\s*baseUnitLabel\s*\}/);
430+
expect(customerSource).toMatch(/const baseUnitLabel\s*=\s*earnRule\.earnBy === 'purchase'/);
429431
});
430432

431433
it('shows every factor the total multiplies', () => {
@@ -458,18 +460,18 @@ describe('the customer page points breakdown', () => {
458460
//
459461
// Only `{interpolations}` count. The surrounding prose — "Base", "Multiplicador",
460462
// "pts" — is wording, not an operand, and reading it as one made this test
461-
// report the fix as the defect. `saleAmountLabel` is wording too: it names the
463+
// report the fix as the defect. `baseUnitLabel` is wording too: it names the
462464
// unit of a factor already displayed, it is not an operand of its own.
463465
const displayed = [...block.matchAll(/<span>([^<]*)<\/span>/g)].flatMap((match) =>
464466
[...match[1]!.matchAll(/\{\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)\s*\}/g)].map(
465467
(inner) => inner[1]!,
466468
),
467469
);
468470

469-
expect(displayed.filter((name) => name !== 'saleAmountLabel')).not.toEqual([]);
471+
expect(displayed.filter((name) => name !== 'baseUnitLabel')).not.toEqual([]);
470472

471473
for (const factor of displayed) {
472-
if (factor === 'saleAmountLabel') continue;
474+
if (factor === 'baseUnitLabel') continue;
473475
expect(SHOWN_FACTORS, `"${factor}" is displayed but never multiplied`).toContain(factor);
474476
}
475477
});
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// @vitest-environment jsdom
2+
3+
/**
4+
* The branch list, as a merchant uses it: the search finds a branch, the
5+
* address column shows the address, and "Incluir inactivas" decides whether
6+
* deactivated branches appear.
7+
*
8+
* The identity worker returns every branch, active or not, in one list, so
9+
* the page filters and searches what it already has.
10+
*/
11+
12+
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
13+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
14+
15+
const mocks = vi.hoisted(() => ({ getVenues: vi.fn() }));
16+
17+
vi.mock('@/lib/api', () => ({ api: { getVenues: mocks.getVenues } }));
18+
19+
import VenuesPage from '../app/dashboard/settings/venues/page';
20+
21+
function branch(overrides: Record<string, unknown>) {
22+
return {
23+
id: 'b1',
24+
name: 'Providencia',
25+
address: 'Av. Providencia 1234',
26+
city: 'Santiago',
27+
country: 'CL',
28+
timezone: 'America/Santiago',
29+
latitude: null,
30+
longitude: null,
31+
is_active: true,
32+
...overrides,
33+
};
34+
}
35+
36+
beforeEach(() => {
37+
mocks.getVenues.mockResolvedValue({
38+
branches: [
39+
branch({}),
40+
branch({ id: 'b2', name: 'Ñuñoa', address: 'Irarrázaval 3000' }),
41+
branch({ id: 'b3', name: 'Las Condes', address: 'Apoquindo 5000', is_active: false }),
42+
],
43+
total: 3,
44+
});
45+
});
46+
47+
afterEach(() => {
48+
cleanup();
49+
vi.clearAllMocks();
50+
});
51+
52+
describe('the branch list', () => {
53+
it('hides deactivated branches until asked to include them', async () => {
54+
render(<VenuesPage />);
55+
await screen.findByText('Providencia');
56+
57+
expect(screen.queryByText('Las Condes')).toBeNull();
58+
59+
fireEvent.click(screen.getByLabelText('Incluir inactivas'));
60+
61+
expect(await screen.findByText('Las Condes')).toBeTruthy();
62+
});
63+
64+
it('finds a branch by name or address', async () => {
65+
render(<VenuesPage />);
66+
await screen.findByText('Providencia');
67+
68+
const search = screen.getByPlaceholderText('Buscar por nombre o dirección…');
69+
fireEvent.change(search, { target: { value: 'irarra' } });
70+
71+
expect(screen.getByText('Ñuñoa')).toBeTruthy();
72+
expect(screen.queryByText('Providencia')).toBeNull();
73+
74+
fireEvent.change(search, { target: { value: 'nunoa' } });
75+
expect(screen.getByText('Ñuñoa')).toBeTruthy();
76+
});
77+
78+
it('shows the street address in the address column', async () => {
79+
render(<VenuesPage />);
80+
await screen.findByText('Providencia');
81+
82+
expect(screen.getByText('Av. Providencia 1234, Santiago')).toBeTruthy();
83+
});
84+
85+
it('says so when no branch matches the search', async () => {
86+
render(<VenuesPage />);
87+
await screen.findByText('Providencia');
88+
89+
fireEvent.change(screen.getByPlaceholderText('Buscar por nombre o dirección…'), {
90+
target: { value: 'valparaíso' },
91+
});
92+
93+
expect(screen.getByText('Ninguna sede coincide con la búsqueda.')).toBeTruthy();
94+
});
95+
});

‎apps/dashboard/src/app/dashboard/customers/[id]/page.tsx‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
buildCustomerPatch,
1010
draftFromCustomer,
1111
formatBirthDate,
12+
formatCalendarDate,
1213
patchErrorFor,
1314
type CustomerDraft,
1415
} from '@/lib/customer-edit';
@@ -209,7 +210,7 @@ export default function CustomerDetailPage() {
209210
setCustomer(cust);
210211
if (cust.currentTierId) {
211212
const match = tiers.find((t) => t.id === cust.currentTierId);
212-
setTierName(match?.name || cust.currentTier || '—');
213+
setTierName(match?.name ?? '—');
213214
setTierMultiplier(match?.multiplier || 1);
214215
} else {
215216
setTierName(cust.currentTier || 'Bronce');
@@ -270,7 +271,7 @@ export default function CustomerDetailPage() {
270271
// Map tier ID to name + multiplier
271272
if (cust.currentTierId) {
272273
const match = tiers.find((t) => t.id === cust.currentTierId);
273-
setTierName(match?.name || cust.currentTier || '—');
274+
setTierName(match?.name ?? '—');
274275
setTierMultiplier(match?.multiplier || 1);
275276
} else {
276277
setTierName(cust.currentTier || 'Bronce');
@@ -312,6 +313,12 @@ export default function CustomerDetailPage() {
312313
const earn = resolveEarn(earnRule, { pesos: amount, visits: amount }, tierMultiplier);
313314
const earnRate = earnRule.earnRate;
314315
const saleAmountLabel = earnRule.earnBy === 'purchase' ? 'Monto de venta ($)' : 'Visitas / conteos';
316+
// What one unit of the base is. Under `purchase` the base is the sale over the
317+
// tenant's unit, not the sale itself, so the input's label would misname it.
318+
const baseUnitLabel =
319+
earnRule.earnBy === 'purchase'
320+
? `× $${earnRule.earnUnitAmount.toLocaleString('es-CL')} de compra`
321+
: 'visitas';
315322
const saleAmountStep = earnRule.earnBy === 'purchase' ? '0.01' : '1';
316323
const saleAmountPlaceholder = earnRule.earnBy === 'purchase' ? 'Ej: 1500' : 'Ej: 1';
317324

@@ -349,7 +356,7 @@ export default function CustomerDetailPage() {
349356
id: t.id,
350357
kind: 'tx' as const,
351358
eventType: t.type === 'earn' || t.type === 'earned' ? 'points.earned'
352-
: t.type === 'redeem' ? 'points.redeemed' : t.type,
359+
: t.type === 'redeem' ? 'points.redeemed' : 'points.adjusted',
353360
points: t.points,
354361
note: t.note ?? null,
355362
createdAt: t.createdAt,
@@ -364,15 +371,19 @@ export default function CustomerDetailPage() {
364371
const labels: Record<string, string> = {
365372
'points.earned': 'Puntos ganados',
366373
'points.redeemed': 'Puntos canjeados',
374+
'points.adjusted': 'Ajuste de puntos',
367375
'customer.registered': 'Registro',
376+
'customer.checked_in': 'Visitó el local',
368377
'visit': 'Visita al local',
369378
'CUSTOMER_REGISTERED': 'Registro',
370379
'POINTS_EARNED': 'Puntos ganados',
371380
'POINTS_REDEEMED': 'Puntos canjeados',
372381
'TIER_CHANGED': 'Cambio de nivel',
373382
'VISIT_RECORDED': 'Visita registrada',
374383
};
375-
return labels[item.eventType] || item.eventType;
384+
// An event this page does not know yet is still activity; its code is not
385+
// something to show a merchant.
386+
return labels[item.eventType] ?? 'Actividad';
376387
}
377388

378389
function timelineColor(type: string): string {
@@ -411,7 +422,7 @@ export default function CustomerDetailPage() {
411422
</p>
412423
)}
413424
<p className="customer-hero-since">
414-
Cliente desde {customer.createdAt}
425+
Cliente desde {formatCalendarDate(customer.createdAt)}
415426
</p>
416427
</div>
417428

@@ -519,7 +530,7 @@ export default function CustomerDetailPage() {
519530
<dt>Puntos</dt>
520531
<dd style={{ margin: 0 }}>{customer.points.toLocaleString()}</dd>
521532
<dt>Miembro desde</dt>
522-
<dd style={{ margin: 0 }}>{customer.createdAt}</dd>
533+
<dd style={{ margin: 0 }}>{formatCalendarDate(customer.createdAt)}</dd>
523534
</dl>
524535

525536
<div style={{ display: 'flex', gap: '0.5rem' }}>
@@ -611,7 +622,7 @@ export default function CustomerDetailPage() {
611622
call a visit count "pts". The total is `earn.preview`, the same
612623
derivation the charge uses, rather than a second floor here. */}
613624
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.875rem' }}>
614-
<span>Base: {earn.base} {saleAmountLabel}</span>
625+
<span>Base: {earn.base} {baseUnitLabel}</span>
615626
<span>&times; Tasa ({earnRate}x)</span>
616627
<span>&times; Multiplicador ({tierMultiplier}x)</span>
617628
<span><strong>= {earn.preview} pts</strong></span>

0 commit comments

Comments
 (0)