Skip to content
Merged
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
2 changes: 2 additions & 0 deletions docs/de/platform/knowledge/structured-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Zum Pflegen der Organisationsdatensätze brauchst du die Rolle Redakteur oder h

Vor dem Speichern prüft das Formular jedes Feld gegen das, was Tale speichert: **Name** bis 300 Zeichen, **Telefon** bis 50, **Sprache** bis 20 und bei der **E-Mail** höchstens 64 Zeichen vor dem `@`. Ein Wert über einer Grenze wird unter seinem Feld genannt, und gespeichert wird erst, wenn du ihn korrigiert hast.

Um nur die Kontakte einer Sprache zu sehen, wähle über der Kontaktliste **Filter** und unter **Sprache** die gewünschte Sprache. Eine Sprache schließt ihre regionalen Varianten ein: **FR** zeigt Kontakte mit der Sprache `fr`, `fr-CH` oder `fr_CA`. Ein Kontakt ohne Sprache erscheint nur, solange keine Sprache gewählt ist.

Du kannst einen Kontakt auch beim Schreiben anlegen. Wähle im Bereich **Start** in der Ansicht **Inbox** die Schaltfläche **Neue E-Mail** und tippe eine Adresse in **An**: Trägt sie kein Kontakt, bietet die Liste **„…“ als Kontakt hinzufügen** an und öffnet dasselbe Formular mit bereits ausgefüllter **E-Mail**. Nach dem Speichern ist dieser Kontakt der Empfänger – du verlässt die begonnene Nachricht also nie.

Ist die E-Mail-Adresse bereits vorhanden, suche den bestehenden Kontakt und bearbeite ihn über sein Zeilenmenü; aus **Neue E-Mail** heraus wählt Tale den vorhandenen Kontakt für dich aus. Beim Speichern wird nur der Datensatz angelegt; Tale sendet dem Kontakt dabei keine E-Mail.
Expand Down
2 changes: 2 additions & 0 deletions docs/en/platform/knowledge/structured-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ You need an Editor role or higher to maintain organization records. Open **Knowl

The form holds each field to what Tale stores before it saves: a **Name** of up to 300 characters, a **Phone** of up to 50, a **Locale** of up to 20, and an **Email** with at most 64 characters before the `@`. A value past a limit is named under its field, and nothing is saved until you fix it.

To see only the contacts in one language, choose **Filter** above the Contacts list and pick the language under **Locale**. A language includes its regional variants: **FR** lists contacts whose locale is `fr`, `fr-CH`, or `fr_CA`. A contact without a locale appears only while no language is picked.

You can also add a contact while writing to them. In the **Inbox** view in Home, choose **New email** and type an address into **To**: if no contact carries it, the list offers **Add “…” as a contact**, which opens this same form with the **Email** already filled. Saving makes that contact the recipient, so you never leave the message you are writing.

If the email address already exists, find the existing contact and update it through the row menu instead of creating a duplicate; from **New email**, Tale selects the existing contact for you. Saving a contact creates a record; it does not send that person an email.
Expand Down
2 changes: 2 additions & 0 deletions docs/fr/platform/knowledge/structured-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Le rôle Rédacteur ou un rôle supérieur est nécessaire pour modifier les fic

Avant d’enregistrer, le formulaire vérifie chaque champ selon ce que Tale conserve : un **Nom** de 300 caractères au plus, un **Téléphone** de 50 au plus, une **Langue** de 20 au plus et un **Courriel** d’au plus 64 caractères avant le `@`. Une valeur qui dépasse une limite est signalée sous son champ, et rien n’est enregistré tant que tu ne l’as pas corrigée.

Pour n’afficher que les contacts d’une langue, choisis **Filtre** au-dessus de la liste des contacts, puis la langue sous **Langue**. Une langue inclut ses variantes régionales : **FR** affiche les contacts dont la langue est `fr`, `fr-CH` ou `fr_CA`. Un contact sans langue n’apparaît que tant qu’aucune langue n’est choisie.

Tu peux aussi créer une fiche au moment d’écrire. Dans la vue **Réception** d’**Accueil**, choisis **Nouvel e-mail** et saisis une adresse dans **À** : si aucun contact ne la porte, la liste propose **Ajouter « … » comme contact**, ce qui ouvre ce même formulaire avec le **Courriel** déjà renseigné. Une fois la fiche enregistrée, ce contact devient le destinataire : tu ne quittes jamais le message en cours.

Si cette adresse existe déjà, retrouve la fiche et modifie-la depuis le menu de sa ligne ; depuis **Nouvel e-mail**, Tale sélectionne pour toi le contact existant. Enregistrer un contact crée uniquement une fiche ; cette opération ne lui envoie aucun e-mail.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/**
* The Contacts list over its real paginated read: `useListContactsPaginated`,
* the adapter row and `backendFetch` run unchanged, and only `fetch` is
* answered here, by a small model of the contacts door that narrows by the
* facets its address names. The router, the abilities and the column config
* are stubbed as in `contact-table.test.tsx`.
*/
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ColumnDef } from '@tanstack/react-table';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import type { ContactDoc } from '@/app/lib/backend/contract/docs';
import { render, screen, waitFor, within } from '@/tests/utils/render';
import {
syntheticBackend,
type SyntheticBackend,
} from '@/tests/utils/synthetic-backend';

import { ContactsTable } from './contact-table';

vi.mock('@tanstack/react-router', () => ({
useNavigate: () => vi.fn(),
}));
vi.mock('@/app/hooks/use-ability', () => ({
useAbility: () => ({ can: () => true, cannot: () => false }),
}));
vi.mock('../hooks/mutations', () => ({
useBulkCreateContacts: () => ({ mutateAsync: vi.fn() }),
useCreateContact: () => ({ mutateAsync: vi.fn() }),
useDeleteContact: () => ({ mutateAsync: vi.fn() }),
useUpdateContact: () => ({ mutateAsync: vi.fn() }),
}));

const columns: ColumnDef<ContactDoc>[] = [
{ accessorKey: 'name', header: 'Name', size: 200 },
{ accessorKey: 'locale', header: 'Locale', size: 120 },
];

vi.mock('../hooks/use-contacts-table-config', () => ({
useContactsTableConfig: () => ({
columns,
searchPlaceholder: 'Search contacts',
pageSize: 20,
}),
}));

const ORG = 'org-1';

function wireContact(name: string, locale: string, source: string) {
return {
id: `contact-${name.toLowerCase().replaceAll(' ', '-')}`,
organizationId: ORG,
name,
email: `${name.toLowerCase().replaceAll(' ', '.')}@example.test`,
phone: null,
externalId: null,
source,
locale,
address: null,
tags: [],
metadata: null,
notes: null,
lifecycleStatus: null,
createdAt: 1770000000000,
updatedAt: 1770000000000,
};
}

const directory = [
wireContact('Audit en', 'en', 'manual_import'),
wireContact('Audit fr', 'fr', 'manual_import'),
wireContact('Audit fr-CH', 'fr-CH', 'manual_import'),
wireContact('Upload en', 'en', 'file_upload'),
];

/** The contacts door as the list reaches it: each facet its address names
* narrows the rows, a language listing its regional tags. */
function contactsDoor(url: URL): Response {
const source = url.searchParams.get('source');
const locale = url.searchParams.get('locale')?.toLowerCase();
const items = directory.filter(
(row) =>
(source === null || row.source === source) &&
(locale === undefined ||
row.locale.toLowerCase() === locale ||
row.locale.toLowerCase().startsWith(`${locale}-`)),
);
return Response.json({ items, nextCursor: null });
}

let backend: SyntheticBackend;

beforeEach(() => {
// The adapters resolve the active organization from the page's address.
window.history.pushState({}, '', `/dashboard/${ORG}/contacts`);
backend = syntheticBackend();
backend.on(/^GET \/api\/app\/contacts\/count\?/, () =>
Response.json({ count: directory.length }),
);
backend.on(/^GET \/api\/app\/contacts\?/, contactsDoor);
});

afterEach(() => {
vi.restoreAllMocks();
});

function contactsTable(props: { source?: string; locale?: string }) {
return <ContactsTable organizationId={ORG} {...props} />;
}

function renderTable(props: { source?: string; locale?: string } = {}) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const view = render(
<QueryClientProvider client={client}>
{contactsTable(props)}
</QueryClientProvider>,
);
return {
rerender: (next: { source?: string; locale?: string }) =>
view.rerender(
<QueryClientProvider client={client}>
{contactsTable(next)}
</QueryClientProvider>,
),
};
}

/** The names of the data rows the table renders, in order: each row's first
* cell with text (the selection checkbox has none, Name precedes Locale). */
function listedNames(): string[] {
return screen
.getAllByRole('row')
.map((row) =>
within(row)
.queryAllByRole('cell')
.map((cell) => cell.textContent?.trim() ?? '')
.find((text) => text !== ''),
)
.filter((name): name is string => name !== undefined);
}

const listReads = () =>
backend.calls.filter((call) => call.startsWith('GET /api/app/contacts?'));

describe('the Contacts facets over the real list read', () => {
// #3618: the Locale facet showed as active while the list asked for, cached
// and rendered every contact.
it('lists only the French contacts under the French Locale', async () => {
renderTable({ locale: 'fr' });

await waitFor(() =>
expect(listedNames()).toEqual(['Audit fr', 'Audit fr-CH']),
);
expect(listReads()).toEqual([
`GET /api/app/contacts?limit=20&locale=fr&orgId=${ORG}`,
]);
});

it('reads the list again when the Locale changes, and back', async () => {
const view = renderTable();
await waitFor(() => expect(listedNames()).toHaveLength(4));

view.rerender({ locale: 'fr' });
await waitFor(() =>
expect(listedNames()).toEqual(['Audit fr', 'Audit fr-CH']),
);

view.rerender({});
await waitFor(() => expect(listedNames()).toHaveLength(4));
expect(listReads().slice(0, 2)).toEqual([
`GET /api/app/contacts?limit=20&orgId=${ORG}`,
`GET /api/app/contacts?limit=20&locale=fr&orgId=${ORG}`,
]);
});

it('still narrows by Source, alone and beside the Locale', async () => {
const view = renderTable({ source: 'file_upload' });
await waitFor(() => expect(listedNames()).toEqual(['Upload en']));

view.rerender({ source: 'manual_import', locale: 'en' });
await waitFor(() => expect(listedNames()).toEqual(['Audit en']));
expect(listReads()).toEqual([
`GET /api/app/contacts?limit=20&source=file_upload&orgId=${ORG}`,
`GET /api/app/contacts?limit=20&source=manual_import&locale=en&orgId=${ORG}`,
]);
});
});
68 changes: 68 additions & 0 deletions services/platform/app/lib/backend/engagement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,74 @@ describe.each([
});
});

describe('the contacts listing facets', () => {
const listing = (args: Record<string, unknown>) =>
engagementPaginatedAdapters['contacts/queries:listContactsPaginated']?.(
args,
ctx,
);

/** The address of every page the adapter asked for, origin stripped. */
async function requested(
args: Record<string, unknown>,
cursor: string | null = null,
): Promise<string> {
const fetchSpy = vi
.spyOn(window, 'fetch')
.mockResolvedValue(
new Response(JSON.stringify({ items: [], nextCursor: null })),
);
await listing(args)?.fetchPage(cursor, 20);
const input = fetchSpy.mock.calls[0]?.[0];
fetchSpy.mockRestore();
return typeof input === 'string' ? input : '';
}

// #3618: the Locale facet changed neither the request nor the cache key,
// so the list kept every contact under an active filter.
it('asks for the selected Locale and keys its pages apart', async () => {
expect(await requested({ locale: 'fr' })).toBe(
'/api/app/contacts?limit=20&locale=fr&orgId=org1',
);
expect(listing({ locale: 'fr' })?.queryKey).not.toEqual(
listing({})?.queryKey,
);
expect(listing({ locale: 'fr' })?.queryKey).not.toEqual(
listing({ locale: 'de' })?.queryKey,
);
});

it('keeps the Locale on every later page', async () => {
expect(await requested({ locale: 'fr' }, '1770003600000|record-1')).toBe(
'/api/app/contacts?limit=20&locale=fr&cursorUpdatedAt=1770003600000&cursorId=record-1&orgId=org1',
);
});

it('still asks for the Source, alone and beside the Locale', async () => {
expect(await requested({ source: 'file_upload' })).toBe(
'/api/app/contacts?limit=20&source=file_upload&orgId=org1',
);
expect(await requested({ source: 'file_upload', locale: 'fr' })).toBe(
'/api/app/contacts?limit=20&source=file_upload&locale=fr&orgId=org1',
);
const keys = [
listing({}),
listing({ source: 'file_upload' }),
listing({ locale: 'file_upload' }),
listing({ source: 'file_upload', locale: 'fr' }),
].map((adapter) => JSON.stringify(adapter?.queryKey));
expect(new Set(keys).size).toBe(keys.length);
});

it('keys every facet under the contact entity a write invalidates', () => {
expect(listing({ locale: 'fr' })?.queryKey.slice(0, 3)).toEqual([
'backend',
'org1',
'contact',
]);
});
});

describe('website creation dates', () => {
const wireRow = {
id: 'website-1',
Expand Down
3 changes: 2 additions & 1 deletion services/platform/app/lib/backend/engagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,14 +370,15 @@ export const engagementPaginatedAdapters: Record<string, PaginatedAdapter> = {
typeof args[key] === 'string' && args[key] !== ''
? `&${key}=${encodeURIComponent(args[key])}`
: '';
const qs = qsOf('search') + qsOf('source');
const qs = qsOf('search') + qsOf('source') + qsOf('locale');
return {
queryKey: backendKey(
orgId,
'contact',
'page',
keyPart(args.search),
keyPart(args.source),
keyPart(args.locale),
),
fetchPage: (cursor, numItems) => {
const split = splitCursor(cursor);
Expand Down
43 changes: 41 additions & 2 deletions services/platform/backend/domains/contacts/routes.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import type { Context } from 'hono';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { CONTACT_IMPORT_ROWS_MAX } from '../../../lib/shared/schemas/common.ts';
import {
CONTACT_IMPORT_ROWS_MAX,
CONTACT_LOCALE_MAX,
} from '../../../lib/shared/schemas/common.ts';
import type { OrgEnv } from '../../auth/org.ts';

const { bulkCreateContacts, updateContact } = vi.hoisted(() => ({
const { bulkCreateContacts, listContacts, updateContact } = vi.hoisted(() => ({
bulkCreateContacts: vi.fn(),
listContacts: vi.fn(),
updateContact: vi.fn(),
}));

vi.mock('./service.ts', async (importOriginal) => ({
...(await importOriginal<typeof import('./service.ts')>()),
bulkCreateContacts,
listContacts,
updateContact,
}));
vi.mock('@tale/shared/db/serializable', () => ({
Expand Down Expand Up @@ -203,3 +208,37 @@ describe('contact edit', () => {
);
});
});

describe('contact listing filters', () => {
beforeEach(() => {
vi.clearAllMocks();
listContacts.mockResolvedValue({ items: [], nextCursor: null });
});

const list = (query: string) => app.request(`/?orgId=o1&${query}`);

// #3618: the door never read `locale`, so the Contacts Locale facet listed
// every contact.
it('hands the Locale facet to the listing beside the Source', async () => {
expect((await list('limit=20&locale=fr')).status).toBe(200);
expect(listContacts).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ organizationId: 'o1' }),
{ limit: 20, locale: 'fr', cursor: null },
);
expect((await list('source=file_upload&locale=fr')).status).toBe(200);
expect(listContacts).toHaveBeenLastCalledWith(
expect.anything(),
expect.anything(),
{ source: 'file_upload', locale: 'fr', cursor: null },
);
});

it('refuses a Locale longer than any contact stores, as it does a Source', async () => {
expect(
(await list(`locale=${'x'.repeat(CONTACT_LOCALE_MAX + 1)}`)).status,
).toBe(400);
expect((await list('source=fax')).status).toBe(400);
expect(listContacts).not.toHaveBeenCalled();
});
});
5 changes: 5 additions & 0 deletions services/platform/backend/domains/contacts/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { z } from 'zod';
import {
CONTACT_EXTERNAL_ID_MAX,
CONTACT_IMPORT_ROWS_MAX,
CONTACT_LOCALE_MAX,
CONTACT_LOCALE_PATTERN,
} from '../../../lib/shared/schemas/common.ts';
import type { Auth } from '../../auth/auth.ts';
Expand Down Expand Up @@ -84,6 +85,9 @@ export function createContactRoutes(deps: {
.object({
search: z.string().max(200).optional(),
source: sourceSchema.optional(),
// An open set, like `search` and `tag`: the REST door stores any
// locale up to the cap, so an unknown one lists nothing.
locale: z.string().max(CONTACT_LOCALE_MAX).optional(),
tag: z.string().max(60).optional(),
limit: z.coerce.number().int().min(1).max(200).optional(),
cursorUpdatedAt: z.coerce.number().int().positive().optional(),
Expand All @@ -92,6 +96,7 @@ export function createContactRoutes(deps: {
.safeParse({
search: c.req.query('search'),
source: c.req.query('source'),
locale: c.req.query('locale'),
tag: c.req.query('tag'),
limit: c.req.query('limit'),
cursorUpdatedAt: c.req.query('cursorUpdatedAt'),
Expand Down
Loading