feat: enhance filtering across various pages

- Added filtering capabilities to the invoices estimates and recurring pages, displaying filtered list messages when applicable.
- Updated the leads page to include filtering for people and tags, ensuring the filter bar reflects the current state.
- Enhanced the pipeline page with filtering options, including support for board and list views, and improved the handling of parameters.
- Implemented filtering in the solutions page, ensuring the display of all articles regardless of filters applied.
- Improved task management pages to support filtering, including the ability to filter by priority and search terms.
- Updated ticket management to include filtering options for status, priority, and search, with appropriate messaging for filtered results.
- Introduced tests for board fields and presets to ensure compliance with backend filtering capabilities.
This commit is contained in:
Ashwin 2026-08-04 22:48:47 +05:30
parent 1ab7152376
commit 3faf6ee410
46 changed files with 2278 additions and 217 deletions

View file

@ -148,13 +148,35 @@ function toRow(account) {
};
}
/**
* Every filter param `listAccounts` will forward. See the note on
* FILTER_FIELDS in tickets.js: the descriptor in `$lib/v2/filters.js` must not
* name a key absent from this list, and `filters.test.js` enforces it.
*
* `industry` and `city` are `icontains` matches server-side, and `tags` and
* `assigned_to` are `getlist` (`AccountsListView.get_context_data`,
* `backend/accounts/views.py:213-226`), so more than one id can be sent for
* either.
*/
export const FILTER_FIELDS = ['assigned_to', 'tags', 'industry', 'city'];
/**
* Accounts in this org, largest lifetime value first.
*
* `active_accounts.open_accounts_count` is the size of the whole filtered
* queryset; `open_accounts` is one page of it. The header counts the former.
* Counting the rows you happen to hold is the mistake the pipeline header made
* before `totals` existed, and it under-reports silently.
* queryset; `open_accounts` is one page of it. `count` below reads the
* former, so it does not under-report the way a header that counted only the
* loaded page would.
*
* There is no `totals` envelope to prefer over this derivation here, unlike
* `invoices.js` and `tasks.js`: `AccountsListView.get_context_data`
* (`backend/accounts/views.py`) never puts a `totals` key on the response, so
* a `response.totals ?? {...}` fallback would always fall through to the
* `{...}` side, dead code pretending at a capability the API does not have.
* `customers` is still computed from `rows`, the one page actually loaded
* (`limit` defaults to 25), so it DOES under-report whenever the filtered set
* is bigger than that page. Fixing that needs a real aggregate from the API,
* which is not there to read yet.
*
* The API narrows this list for non-admins to accounts they created or are
* assigned to, so what comes back is already what this person may see.
@ -186,6 +208,30 @@ export async function listAccounts({ cookies }, params) {
};
}
/**
* Accounts as a flat `{id, name}` picker list, open accounts only.
*
* Same `/accounts/?limit=200` shape `contacts.js:342` already fetches for its
* own account picker, reused here rather than respelled a third time for the
* invoices and estimates filter bars, which both need an Account field.
*
* The 200 ceiling is real: an org with more open accounts than that gets a
* truncated picker, the same limit `contacts.js` already lives with.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @returns {Promise<{ accounts: {id: string, name: string}[] }>}
*/
export async function listAccountsPicker({ cookies }) {
const response = await apiRequest('/accounts/?limit=200', {}, { cookies });
const active = response.active_accounts ?? {};
return {
accounts: (active.open_accounts ?? []).map((/** @type {any} */ account) => ({
id: account.id,
name: account.name ?? ''
}))
};
}
/**
* One account and everything hanging off it.
*

View file

@ -43,6 +43,9 @@ import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/public';
import { apiRequest } from '$lib/api-helpers.js';
/** See the note on FILTER_FIELDS in tickets.js. */
export const FILTER_FIELDS = ['assigned_to', 'tags', 'city'];
/** DRF decimals arrive as strings. `null` stays `null`. It means "not recorded". */
function num(value) {
if (value === null || value === undefined || value === '') return null;

View file

@ -79,13 +79,18 @@ function toRow(deal) {
}
/**
* The open pipeline, largest first.
* The pipeline, largest first.
*
* `open=true` is applied by the API. The filter chip on the page says "Stage
* is not Closed", and a chip that describes a filter the query did not run is
* how v1 taught people the filter bar lies, the mock's own header comment
* made that point, so the query has to honour it rather than slicing the rows
* that happened to arrive.
* `open` is NOT forced here. `OpportunityListView`'s base queryset does not
* exclude closed stages (`opportunity_views.py:112-183`), so whether this call
* is scoped to the working pipeline is entirely up to whether the caller's
* `params` carries `?open=true`. That used to be hardcoded on every call,
* which meant the pipeline's own "All deals" preset (deliberately empty
* params, see `$lib/v2/filters.js`) could never show a closed deal no matter
* what the URL said, a chip and a preset that cannot change the result set is
* the exact failure this filter bar exists to remove. Callers that want the
* open pipeline specifically (the sidebar badge, the task-parent pickers) now
* set `open: 'true'` themselves.
*
* `totals` is computed server-side over the whole filtered queryset. Do not
* recompute it from `results`: `results` is one page.
@ -95,7 +100,6 @@ function toRow(deal) {
*/
export async function listDeals({ cookies }, params) {
const query = new URLSearchParams(params ?? undefined);
query.set('open', 'true');
if (!query.has('limit')) query.set('limit', '25');
const response = await apiRequest(`/opportunities/?${query}`, {}, { cookies });
@ -135,6 +139,41 @@ function normaliseTotals(totals, rows) {
};
}
/**
* Every filter param `listDeals` will forward. See the note on FILTER_FIELDS
* in tickets.js. `open` and `rotten` are deliberately absent: they are
* preset-only params `pipeline/+page.server.js` reads off the URL itself, the
* same way `all` works for tickets and tasks, not fields a person picks a
* value for.
*/
/**
* The filter fields and presets the BOARD can actually run.
*
* `kanban_views.py:122-137` reads only `search`, `account`, `assigned_to`,
* `tags` and the `closed_on` range, a narrower vocabulary than the list
* endpoint's. A chip for anything else would sit above cards it did not
* filter, while the header totals (which come from the list endpoint) DID
* apply it, so a number and the cards under it would describe different deals.
*
* These live here rather than in `pipeline/+page.server.js` because SvelteKit
* allows only a fixed set of named exports from a `+page.server.js` (`load`,
* `actions`, `prerender`, and a few more) and answers 500 for the whole route
* on any other one. Exporting them from there took the entire pipeline page
* down, and neither `pnpm run check` nor the unit tests noticed, because the
* tests import the module directly and never go through SvelteKit's router.
*/
export const BOARD_FIELDS = ['assigned_to', 'tags'];
export const BOARD_PRESETS = ['mine', 'all'];
export const FILTER_FIELDS = [
'assigned_to',
'stage',
'lead_source',
'amount__gte',
'amount__lte',
'tags'
];
/**
* The board.
*

View file

@ -56,6 +56,16 @@ const API_BASE_URL = `${env.PUBLIC_DJANGO_API_URL}/api`;
/** The two document states the backend accepts (Document.DOCUMENT_STATUS_CHOICE). */
export const STATUS_CHOICES = ['active', 'inactive'];
/**
* Every filter param `listDocuments` will forward. The descriptor in
* `$lib/v2/filters.js` must not name a key absent from this list; a test in
* `filters.test.js` enforces that. `status` is the only one: `tags` has no
* backing relation on `Document` at all, and `shared_to` is passed straight to
* `json.loads` by `DocumentListView.get`, so a plain `?shared_to=<uuid>` would
* 500 rather than filter.
*/
export const FILTER_FIELDS = ['status'];
/**
* The signed-in role and user id, decoded from the JWT. Display hints only:
* `role` decides whether the page offers Upload/Edit, and `user_id` is compared
@ -159,11 +169,19 @@ function computeTotals(docs) {
* scoped the rows to the org and, for a non-admin, to what `_visible_to`
* allows, so every row returned here is one the viewer may open.
*
* A `status` filter narrows both envelopes at once: `DocumentListView.get`
* applies it to the base queryset before splitting into
* `documents_active`/`documents_inactive`, so `?status=active` leaves the
* inactive envelope empty and the merge below still returns the right rows.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {URLSearchParams} [params]
*/
export async function listDocuments({ cookies }) {
export async function listDocuments({ cookies }, params) {
const viewer = viewerClaims(cookies);
const resp = await apiRequest('/documents/?limit=1000', {}, { cookies });
const query = new URLSearchParams(params ?? undefined);
if (!query.has('limit')) query.set('limit', '1000');
const resp = await apiRequest(`/documents/?${query}`, {}, { cookies });
const active = resp?.documents_active?.documents_active ?? [];
const inactive = resp?.documents_inactive?.documents_inactive ?? [];

View file

@ -42,6 +42,18 @@ import { apiRequest } from '$lib/api-helpers.js';
/** Statuses still awaiting the client's decision. The only ones with a live validity. */
const AWAITING = ['Sent', 'Viewed'];
/**
* Every filter param `listEstimates` will forward. See the note on
* FILTER_FIELDS in tickets.js: the descriptor in `$lib/v2/filters.js` must not
* name a key absent from this list, and `filters.test.js` enforces it.
*
* `EstimateListView.get` (`backend/invoices/api_views.py:1028-1036`) reads
* only `status` and `account`. There is no `assigned_to` filter on this
* endpoint, which is why the descriptor has no Owner field; this list must
* not grow one on its own either.
*/
export const FILTER_FIELDS = ['status', 'account'];
const num = (/** @type {any} */ value) => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
@ -120,13 +132,19 @@ function computeTotals(rows) {
* admin, own-and-assigned for a member, the endpoint scopes it), so the header
* figures and the table always describe the same set.
*
* `params` (built from FILTER_FIELDS: `status`, `account`) is applied by
* `EstimateListView.get` before pagination, and the header figures below are
* derived from the rows this call actually gets back, so a filter narrows
* both the table and the totals together, unlike `listInvoices`.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {URLSearchParams} [params]
*/
export async function listEstimates({ cookies }) {
const query = new URLSearchParams();
export async function listEstimates({ cookies }, params) {
const query = new URLSearchParams(params ?? undefined);
// One page covers every real org; totals are derived from what comes back,
// so anything past this ceiling would be uncounted. See the module note.
query.set('limit', '1000');
if (!query.has('limit')) query.set('limit', '1000');
const response = await apiRequest(`/invoices/estimates/?${query.toString()}`, {}, { cookies });
const rows = (response.results ?? []).map(toRow);

View file

@ -0,0 +1,96 @@
/**
* Reading filters off a URL, and turning them into an API query.
*
* Server-only: it is imported by `+page.server.js`, never by a component.
*
* Two allow-lists, deliberately, not one. `readFilters` drops anything the page
* descriptor does not declare, so a hand-typed param never becomes a variable
* this layer carries. `buildFilterQuery` then decides what reaches the API, the
* same shape `CREATE_FIELDS` / `buildBody` use in every other v2 module.
*
* Neither is the security boundary. The backend gates `include_deleted` on
* `is_org_admin` itself (`cases/views.py:176`). These exist so the UI does not
* silently inherit every param these endpoints grow.
*/
import { FILTERS } from '$lib/v2/filters.js';
const BOOLEANS = ['true', 'false'];
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
const NUMERIC = /^\d+(\.\d+)?$/;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** Field types whose value is an opaque id the API looks up by primary key. */
const ID_TYPES = ['person', 'tag', 'account'];
/**
* Validated filter params for one page.
*
* Enumerable types are checked and an unrecognised value is DROPPED rather than
* forwarded. Forwarding it would return an empty list with no error, which
* reads to a person as "there is nothing here" rather than "that filter was
* nonsense".
*
* Opaque ids (person, tag, account) are checked for UUID SHAPE only, not for
* existence, which would cost a fetch. Shape is enough to matter: every list
* endpoint answers 500 on a malformed id, because the value reaches Django as
* `id__in=['x']` and psycopg raises before any handler sees it. Verified
* against `/opportunities/`, `/opportunities/kanban/`, `/leads/`, `/cases/`,
* `/accounts/` and `/tasks/`, all six of which return 500 for `?tags=x`. This
* is not a security control, the backend remains the trust boundary; it stops
* a stale bookmark or an edited URL from taking a page down.
*
* Preset-only params such as `all`, `inactive` and `visibility` are NOT handled
* here. Each page's `load` already interprets its own, and this function
* deliberately does not duplicate that logic.
*
* @param {URL} url
* @param {string} pageKey
* @returns {Record<string, string>}
*/
export function readFilters(url, pageKey) {
const descriptor = FILTERS[pageKey];
if (!descriptor) return {};
/** @type {Record<string, string>} */
const out = {};
for (const field of descriptor.fields) {
if (field.type === 'date-range' || field.type === 'number-range') {
const valid = field.type === 'date-range' ? ISO_DATE : NUMERIC;
for (const key of [field.gteKey, field.lteKey]) {
const value = url.searchParams.get(/** @type {string} */ (key));
if (value && valid.test(value)) out[/** @type {string} */ (key)] = value;
}
continue;
}
const value = url.searchParams.get(field.key);
if (!value) continue;
if (field.type === 'select') {
if (field.options?.includes(value)) out[field.key] = value;
} else if (field.type === 'boolean') {
if (BOOLEANS.includes(value)) out[field.key] = value;
} else if (ID_TYPES.includes(field.type)) {
if (UUID.test(value)) out[field.key] = value;
} else {
out[field.key] = value;
}
}
return out;
}
/**
* The API query for a set of filters, restricted to the module's allow-list.
*
* @param {string[]} allowed
* @param {Record<string, string>} filters
* @returns {URLSearchParams}
*/
export function buildFilterQuery(allowed, filters) {
const query = new URLSearchParams();
for (const key of allowed) {
const value = filters[key];
if (value === undefined || value === null || value === '') continue;
query.set(key, value);
}
return query;
}

View file

@ -0,0 +1,134 @@
import { describe, it, expect } from 'vitest';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
const url = (/** @type {string} */ qs) => new URL(`http://x/tickets?${qs}`);
describe('readFilters', () => {
it('returns an empty object for a bare URL', () => {
expect(readFilters(url(''), 'tickets')).toEqual({});
});
it('keeps a valid select value', () => {
expect(readFilters(url('priority=High'), 'tickets')).toEqual({ priority: 'High' });
});
it('drops a select value that is not in the option list', () => {
// "Medium" is a Task priority, not a Case priority. Forwarding it would
// return an empty queue with no error, which reads as "no tickets".
expect(readFilters(url('priority=Medium'), 'tickets')).toEqual({});
});
it('drops a key the descriptor does not declare', () => {
// include_deleted is admin-gated server-side; the point here is that a
// hand-typed param never becomes a variable this layer carries.
expect(readFilters(url('include_deleted=true'), 'tickets')).toEqual({});
});
it('keeps an opaque id without checking that it exists', () => {
// Shape is checked, existence is not: proving the id exists would cost a
// fetch, and the API answering "no rows" for a real-looking id that was
// since deleted is the correct outcome.
const id = '11111111-2222-3333-4444-555555555555';
const out = readFilters(url(`assigned_to=${id}`), 'tickets');
expect(out).toEqual({ assigned_to: id });
});
it('normalises a boolean and drops a non-boolean', () => {
expect(readFilters(url('sla_breached=true'), 'tickets')).toEqual({ sla_breached: 'true' });
expect(readFilters(url('sla_breached=yes'), 'tickets')).toEqual({});
});
});
describe('text fields', () => {
it('passes a free-text value through unvalidated', () => {
const url = new URL('http://x/contacts?city=Hyderabad');
expect(readFilters(url, 'contacts')).toEqual({ city: 'Hyderabad' });
});
});
describe('buildFilterQuery', () => {
it('emits only allow-listed keys', () => {
const q = buildFilterQuery(['priority'], { priority: 'High', assigned_to: 'x' });
expect(q.get('priority')).toBe('High');
expect(q.has('assigned_to')).toBe(false);
});
it('skips empty values', () => {
const q = buildFilterQuery(['priority'], { priority: '' });
expect(q.has('priority')).toBe(false);
});
});
describe('range param names are exact, not derived', () => {
it('tasks emits a DOUBLE underscore due date range', () => {
const url = new URL('http://x/tasks?due_date__gte=2026-01-01&due_date__lte=2026-01-31');
expect(readFilters(url, 'tasks')).toEqual({
due_date__gte: '2026-01-01',
due_date__lte: '2026-01-31'
});
});
it('tasks ignores the single-underscore spelling', () => {
// Invoices uses due_date_gte. If a shared helper ever derives the key by
// concatenation, this is the test that fails instead of the filter
// silently returning an unfiltered list.
const url = new URL('http://x/tasks?due_date_gte=2026-01-01');
expect(readFilters(url, 'tasks')).toEqual({});
});
it('rejects a malformed date', () => {
const url = new URL('http://x/tasks?due_date__gte=01-01-2026');
expect(readFilters(url, 'tasks')).toEqual({});
});
it('accepts a half-open numeric range and rejects non-numeric', () => {
expect(readFilters(new URL('http://x/pipeline?amount__gte=5000'), 'pipeline')).toEqual({
amount__gte: '5000'
});
expect(readFilters(new URL('http://x/pipeline?amount__gte=lots'), 'pipeline')).toEqual({});
});
});
describe('invoices uses the single-underscore date convention', () => {
// Pinned against backend/invoices/api_views.py:149-152
// (`InvoiceListView.filter_queryset`), which reads `due_date_gte` /
// `due_date_lte`, one underscore. Every other v2 module's date range uses
// two (`due_date__gte`). Re-check that line before "correcting" either spelling.
it('accepts due_date_gte', () => {
const url = new URL('http://x/invoices?due_date_gte=2026-01-01');
expect(readFilters(url, 'invoices')).toEqual({ due_date_gte: '2026-01-01' });
});
it('ignores the double-underscore spelling that every other page uses', () => {
const url = new URL('http://x/invoices?due_date__gte=2026-01-01');
expect(readFilters(url, 'invoices')).toEqual({});
});
});
describe('opaque id fields: shape-checked before they reach the API', () => {
// Every list endpoint answers 500 on a malformed id, because the value
// reaches Django as `id__in=['x']` and psycopg raises before any handler
// runs. Confirmed against /opportunities/, /opportunities/kanban/, /leads/,
// /cases/, /accounts/ and /tasks/. A stale bookmark or an edited URL should
// cost the filter, not the page.
it('drops a tag id that is not a UUID', () => {
const url = new URL('http://x/tickets?tags=x');
expect(readFilters(url, 'tickets').tags).toBeUndefined();
});
it('drops an owner id that is not a UUID', () => {
const url = new URL('http://x/tickets?assigned_to=not-an-id');
expect(readFilters(url, 'tickets').assigned_to).toBeUndefined();
});
it('keeps a well formed UUID', () => {
const id = '868f58fd-f783-4472-baac-216f5e22484c';
const url = new URL(`http://x/tickets?tags=${id}`);
expect(readFilters(url, 'tickets').tags).toBe(id);
});
it('drops an account id that is not a UUID', () => {
const url = new URL('http://x/invoices?account=12345');
expect(readFilters(url, 'invoices').account).toBeUndefined();
});
});

View file

@ -56,6 +56,20 @@ export const INVOICE_STATUSES = [
/** Statuses a settled invoice can be in: the due date stops meaning anything. */
const SETTLED = ['Paid', 'Cancelled'];
/**
* Every filter param `listInvoices` will forward. See the note on
* FILTER_FIELDS in tickets.js: the descriptor in `$lib/v2/filters.js` must not
* name a key absent from this list, and `filters.test.js` enforces it.
*
* `due_date_gte` / `due_date_lte`: SINGLE underscore.
* `InvoiceListView.filter_queryset` (`backend/invoices/api_views.py:149-152`)
* reads exactly these two spellings. Every other v2 module's date-range field
* uses a DOUBLE underscore (`due_date__gte`); forwarding that spelling here
* would silently return the unfiltered list rather than erroring, which is
* why `filter-params.test.js` pins this one explicitly.
*/
export const FILTER_FIELDS = ['status', 'account', 'assigned_to', 'due_date_gte', 'due_date_lte'];
const num = (/** @type {any} */ value) => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
@ -151,6 +165,17 @@ function toDetail(inv) {
* invoices they made or were assigned. The rows follow the same rule, which is
* the point: v1 summed the loaded page and the pills disagreed with the list.
*
* `params` (built from FILTER_FIELDS) narrows `invoices` but NOT `totals`.
* `InvoiceListView.get` (`backend/invoices/api_views.py:177-193`) computes
* `_totals` over `base`, the role-scoped queryset, deliberately BEFORE
* `filter_queryset` runs, with a comment reading "not just this page or the
* current filter". So applying a Status or Account filter changes the rows
* this function returns and leaves every number in `totals` exactly as it
* was. `invoices/+page.svelte` does not claim otherwise: unlike
* tasks/tickets/pipeline/accounts/estimates, it has no "these numbers
* describe the filtered list" line, because for this endpoint that sentence
* would be false.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {URLSearchParams} [params]
*/

View file

@ -0,0 +1,117 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { listInvoices, FILTER_FIELDS } = await import('$lib/server/v2/invoices.js');
const { readFilters, buildFilterQuery } = await import('$lib/server/v2/filter-params.js');
// Cast rather than shaping a full Cookies mock: listInvoices only ever calls
// `cookies.get` (through the mocked apiRequest), so nothing here touches
// `getAll`/`set`/`delete`/`serialize`. See the same note in leads.test.js.
const event = /** @type {any} */ ({ cookies: { get: () => 'token' } });
/** The querystring `listInvoices` actually sent to `apiRequest`. */
function sentQuery() {
const [endpoint] = apiRequest.mock.calls[0];
return new URL(`http://x${endpoint}`).searchParams;
}
describe('listInvoices', () => {
beforeEach(() => {
apiRequest.mockReset();
});
it('defaults limit to 100 and sorts by due_date when no params are given', async () => {
apiRequest.mockResolvedValue({ results: [], totals: {} });
await listInvoices(event, undefined);
expect(apiRequest).toHaveBeenCalledOnce();
const query = sentQuery();
expect(query.get('limit')).toBe('100');
expect(query.get('sort')).toBe('due_date');
});
it('forwards a caller-supplied due_date_gte/due_date_lte through to the API querystring', async () => {
// Pinned against backend/invoices/api_views.py:149-152
// (InvoiceListView.filter_queryset), which reads the SINGLE-underscore
// due_date_gte / due_date_lte. Every other v2 module's date-range field
// uses two underscores (due_date__gte). If this regresses to the
// double-underscore spelling, the endpoint silently ignores the filter
// and returns every invoice rather than erroring, which is why this is
// pinned at both the readFilters layer (filter-params.test.js) and here,
// end to end through the URL this module actually sends.
apiRequest.mockResolvedValue({ results: [], totals: {} });
const url = new URL('http://x/invoices?due_date_gte=2026-01-01&due_date_lte=2026-01-31');
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'invoices'));
await listInvoices(event, params);
const query = sentQuery();
expect(query.get('due_date_gte')).toBe('2026-01-01');
expect(query.get('due_date_lte')).toBe('2026-01-31');
expect(query.has('due_date__gte')).toBe(false);
expect(query.has('due_date__lte')).toBe(false);
});
it('forwards status, account and assigned_to unmodified', async () => {
apiRequest.mockResolvedValue({ results: [], totals: {} });
const acc = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa';
const who = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb';
const url = new URL(`http://x/invoices?status=Overdue&account=${acc}&assigned_to=${who}`);
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'invoices'));
await listInvoices(event, params);
const query = sentQuery();
expect(query.get('status')).toBe('Overdue');
expect(query.get('account')).toBe(acc);
expect(query.get('assigned_to')).toBe(who);
});
it('drops a param the descriptor does not declare, e.g. a hand-typed contact filter', async () => {
apiRequest.mockResolvedValue({ results: [], totals: {} });
const url = new URL('http://x/invoices?contact=con-1');
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'invoices'));
await listInvoices(event, params);
expect(sentQuery().has('contact')).toBe(false);
});
it('falls back to response.count when totals.count is absent', async () => {
apiRequest.mockResolvedValue({ results: [{ id: '1' }], count: 7, totals: {} });
const { totals } = await listInvoices(event, new URLSearchParams());
expect(totals.count).toBe(7);
});
it('coerces every money figure in totals to a number', async () => {
apiRequest.mockResolvedValue({
results: [],
totals: { count: 2, outstanding: '150.50', overdue: '0', draft: null }
});
const { totals } = await listInvoices(event, new URLSearchParams());
expect(totals.outstanding).toBe(150.5);
expect(totals.overdue).toBe(0);
expect(totals.draft).toBe(0);
});
it('maps a result row through toRow, rebuilding the nested account shape', async () => {
apiRequest.mockResolvedValue({
results: [
{
id: 'inv-1',
invoice_number: 'INV-0001',
status: 'Draft',
account: 'acc-1',
account_name: 'Northwind',
total_amount: '500.00'
}
],
totals: {}
});
const { invoices } = await listInvoices(event, new URLSearchParams());
expect(invoices[0].account).toEqual({ id: 'acc-1', name: 'Northwind' });
expect(invoices[0].total_amount).toBe(500);
});
});

View file

@ -31,6 +31,9 @@ import {
pairForEdit
} from '$lib/server/v2/lead-custom-fields.js';
/** See the note on FILTER_FIELDS in tickets.js. */
export const FILTER_FIELDS = ['assigned_to', 'status', 'source', 'tags'];
/**
* Attachments serialise with a storage-relative `file_path` (`/media/…`) on
* local dev and an absolute URL behind object storage in prod. Resolve it

View file

@ -36,7 +36,7 @@ function personName(profile) {
/**
* @param {import('@sveltejs/kit').Cookies} cookies
* @returns {Promise<{ people: { id: string, name: string }[], teams: { id: string, name: string }[] }>}
* @returns {Promise<{ people: { id: string, name: string, email: string }[], teams: { id: string, name: string }[] }>}
*/
export async function getOrgPeopleAndTeams(cookies) {
try {
@ -44,7 +44,8 @@ export async function getOrgPeopleAndTeams(cookies) {
return {
people: (resp?.profiles ?? []).map((/** @type {any} */ p) => ({
id: p.id,
name: personName(p)
name: personName(p),
email: p.user_details?.email ?? ''
})),
teams: (resp?.teams ?? []).map((/** @type {any} */ t) => ({ id: t.id, name: t.name }))
};
@ -52,3 +53,24 @@ export async function getOrgPeopleAndTeams(cookies) {
return { people: [], teams: [] };
}
}
/**
* The viewer's own PROFILE id, for the "Mine" presets.
*
* Matched by email because no id is available any other way: the JWT carries
* `user_email` but no profile id, and `locals.user.id` is the User id, not the
* Profile id that `assigned_to` filters on. Those are different tables and
* mixing them has silently broken checks in this codebase before.
*
* Returns null when nothing matches, and callers must then hide the preset
* rather than render a link that filters to nobody.
*
* @param {{id: string, email?: string}[]} people
* @param {string | undefined} viewerEmail
* @returns {string | null}
*/
export function resolveMe(people, viewerEmail) {
if (!viewerEmail) return null;
const wanted = viewerEmail.toLowerCase();
return people.find((p) => (p.email ?? '').toLowerCase() === wanted)?.id ?? null;
}

View file

@ -8,7 +8,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const apiRequest = vi.fn();
vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) }));
const { getOrgPeopleAndTeams } = await import('./org-people.js');
const { getOrgPeopleAndTeams, resolveMe } = await import('./org-people.js');
const cookies = /** @type {any} */ ({});
@ -17,13 +17,13 @@ describe('getOrgPeopleAndTeams', () => {
apiRequest.mockReset();
});
it('labels a person by name when there is one', async () => {
it('labels a person by name when there is one, and carries the email through so @me can be resolved', async () => {
apiRequest.mockResolvedValue({
profiles: [{ id: 'p1', user_details: { name: 'Ada Lovelace', email: 'ada@x.io' } }],
teams: []
});
const { people } = await getOrgPeopleAndTeams(cookies);
expect(people).toEqual([{ id: 'p1', name: 'Ada Lovelace' }]);
expect(people).toEqual([{ id: 'p1', name: 'Ada Lovelace', email: 'ada@x.io' }]);
});
it('falls back to the email, then to Unnamed', async () => {
@ -60,3 +60,24 @@ describe('getOrgPeopleAndTeams', () => {
await expect(getOrgPeopleAndTeams(cookies)).resolves.toEqual({ people: [], teams: [] });
});
});
describe('resolveMe', () => {
const people = [
{ id: 'p1', name: 'Ada', email: 'ada@x.com' },
{ id: 'p2', name: 'Bo', email: 'bo@x.com' }
];
it('matches on email, case insensitively', () => {
expect(resolveMe(people, 'ADA@x.com')).toBe('p1');
});
it('returns null when nobody matches, so the caller can hide the preset', () => {
// A "Mine" link that filters to nobody is worse than no link: it looks
// like the viewer owns nothing.
expect(resolveMe(people, 'nobody@x.com')).toBe(null);
});
it('returns null for a missing viewer email', () => {
expect(resolveMe(people, undefined)).toBe(null);
});
});

View file

@ -129,17 +129,26 @@ function bySchedulePriority(/** @type {any} */ a, /** @type {any} */ b) {
return da - db;
}
/**
* Every filter param `listRecurringInvoices` will forward. The descriptor in
* `$lib/v2/filters.js` must not name a key absent from this list; a test in
* `filters.test.js` enforces that.
*/
export const FILTER_FIELDS = ['is_active'];
/**
* The schedules worklist. Rows follow whatever the API returns for the requester
* (the endpoint scopes non-admins to their own and assigned), so the pills and
* the table cover the same set.
* the table cover the same set. An `is_active` filter narrows the same rows the
* totals are derived from, so the header figures and the table always agree.
*
* @param {{ cookies: import('@sveltejs/kit').Cookies }} event
* @param {URLSearchParams} [params]
*/
export async function listRecurringInvoices({ cookies }) {
const query = new URLSearchParams();
export async function listRecurringInvoices({ cookies }, params) {
const query = new URLSearchParams(params ?? undefined);
// One page covers every real org; totals derive from what comes back.
query.set('limit', '1000');
if (!query.has('limit')) query.set('limit', '1000');
const response = await apiRequest(`/invoices/recurring/?${query.toString()}`, {}, { cookies });
const rows = (response.results ?? []).map(toRow);

View file

@ -44,6 +44,15 @@ import { apiRequest } from '$lib/api-helpers.js';
/** `Solution.STATUS_CHOICES`, in workflow order. */
export const SOLUTION_STATUSES = ['draft', 'reviewed', 'approved'];
/**
* Every filter param `listArticles` will forward. The descriptor in
* `$lib/v2/filters.js` must not name a key absent from this list; a test in
* `filters.test.js` enforces that. `visibility` is not here: it is a view
* param the page's own load translates to `is_published` before the query
* ever reaches this module, the same way contacts translates `inactive`.
*/
export const FILTER_FIELDS = ['status'];
/**
* The subset of a Django solution the v2 pages read.
*

View file

@ -46,6 +46,15 @@ import { apiRequest } from '$lib/api-helpers.js';
export const TASK_STATUSES = ['New', 'In Progress', 'Completed'];
export const TASK_PRIORITIES = ['Low', 'Medium', 'High'];
/** See the note on FILTER_FIELDS in tickets.js. */
export const FILTER_FIELDS = [
'assigned_to',
'priority',
'status',
'due_date__gte',
'due_date__lte'
];
/**
* Attachments serialise with a storage-relative `file_path` (`/media/…`) on
* local dev and an absolute URL behind object storage in prod. Resolve it

View file

@ -125,6 +125,14 @@ function toRow(row) {
};
}
/**
* Every filter param `listTickets` will forward. The descriptor in
* `$lib/v2/filters.js` must not name a key absent from this list; a test in
* `filters.test.js` enforces that, because the failure mode otherwise is a chip
* on screen and an unfiltered list underneath it.
*/
export const FILTER_FIELDS = ['assigned_to', 'priority', 'case_type', 'sla_breached', 'tags'];
/**
* The queue, newest first.
*

View file

@ -1,50 +1,332 @@
<script>
import { X, Plus, ChevronDown } from '@lucide/svelte';
/**
* One filter system. A saved view, then one removable chip per active
* filter, then Add. Nothing hidden in a dropdown that the row of chips
* does not already show.
* One filter system, for every v2 list page.
*
* Replaces the three overlapping systems in v1 (segment pills + view tabs
* + inline dropdowns), where you could not tell what was actually applied.
* A preset picker, then one removable chip per active filter, then Add.
* Nothing hidden in a dropdown that the row of chips does not already show.
*
* Everything here is a link or a `method="GET"` form, which is the browser's
* native way to write URL params. So the filter bar works on a cold page and
* survives a failed hydration, and there is no state to keep in sync with the
* address bar.
*
* The component derives its own chips from the URL rather than taking a
* prebuilt list. That is what makes every chip removable: a chip exists only
* when its param is actually set. The previous version took a `filters` array
* that pages built by hand, and several passed chips describing an implicit
* default, so the X had nothing to remove and did nothing.
*
* @type {{
* view?: string,
* filters?: Array<{ key: string, label: string, value: string }>,
* meta?: string,
* onremove?: (key: string) => void
* page: string,
* url: URL,
* people?: {id: string, name: string}[],
* tags?: {id: string, name: string}[],
* accounts?: {id: string, name: string}[],
* meId?: string | null,
* meta?: string | null,
* onlyFields?: string[],
* onlyPresets?: string[]
* }}
*/
let { view = 'All', filters = [], meta = null, onremove = () => {} } = $props();
import { X, Plus, ChevronDown } from '@lucide/svelte';
import { FILTERS, activeChips, activePresetKey, withParams } from '$lib/v2/filters.js';
import { invoiceStatusLabel } from '$lib/v2/enums.js';
let {
page,
url,
people = [],
tags = [],
accounts = [],
meId = null,
meta = null,
onlyFields = undefined,
onlyPresets = undefined
} = $props();
let descriptor = $derived(FILTERS[page] ?? { presets: [], fields: [] });
/**
* Some pages run a second query engine alongside the main one, with a
* narrower filter vocabulary than the page's own descriptor. Pipeline's
* board is the first: it renders from `/opportunities/kanban/`, which reads
* only a few of the params `/opportunities/` does. `onlyFields`/
* `onlyPresets` name the subset that view can actually run; when passed,
* the bar offers, and only offers, controls and chips for that subset. A
* chip for a param the current view cannot honour would sit above rows it
* did not filter, while a header total computed with the full param set
* would disagree with what the rows show.
*/
let visibleFields = $derived(
onlyFields ? descriptor.fields.filter((f) => onlyFields.includes(f.key)) : descriptor.fields
);
let visiblePresets = $derived(
onlyPresets ? descriptor.presets.filter((p) => onlyPresets.includes(p.key)) : descriptor.presets
);
let chips = $derived(
activeChips(page, url, { people, tags, accounts }).filter(
(chip) => !onlyFields || onlyFields.includes(chip.key)
)
);
// meId is passed so a "@me" preset matches only the viewer's own id. Without
// it, filtering by a colleague would light up "Mine".
let activeKey = $derived(activePresetKey(page, url, meId));
let activeLabel = $derived(
descriptor.presets.find((/** @type {any} */ p) => p.key === activeKey)?.label ?? 'All'
);
/**
* A preset's href. Every param the preset does not set is cleared, so
* switching view is a fresh start rather than a merge with whatever chips
* were up.
*
* A preset naming `@me` is dropped entirely when the viewer's profile could
* not be resolved: a "Mine" link that filters to nobody looks like the viewer
* owns nothing.
*/
const presetHref = (/** @type {any} */ preset) => {
/** @type {Record<string, string|null>} */
const params = {};
for (const field of descriptor.fields) {
if (field.type === 'date-range' || field.type === 'number-range') {
params[field.gteKey] = null;
params[field.lteKey] = null;
} else params[field.key] = null;
}
for (const other of descriptor.presets) {
for (const key of Object.keys(other.params)) params[key] = null;
}
for (const [key, value] of Object.entries(preset.params)) {
params[key] = value === '@me' ? meId : /** @type {string} */ (value);
}
return withParams(url, params);
};
const usable = (/** @type {any} */ preset) =>
!Object.values(preset.params).includes('@me') || Boolean(meId);
const optionsFor = (/** @type {any} */ field) => {
if (field.type === 'person') return people;
if (field.type === 'tag') return tags;
if (field.type === 'account') return accounts;
return (field.options ?? []).map((/** @type {string} */ v) => ({
id: v,
name: field.labelFor ? field.labelFor(v) : invoiceStatusLabel(v)
}));
};
</script>
<div class="v2-filters">
<button class="v2-view" type="button">
{view}
<ChevronDown size={13} style="color:var(--v2-slate)" />
</button>
<details class="v2-view-menu">
<summary class="v2-view">
{activeLabel}
<ChevronDown size={13} style="color:var(--v2-slate)" />
</summary>
<div class="v2-menu">
{#each visiblePresets.filter(usable) as preset (preset.key)}
<a
class="v2-menu-item"
class:v2-menu-item-on={preset.key === activeKey}
href={presetHref(preset)}
>
{preset.label}
</a>
{/each}
</div>
</details>
{#each filters as f (f.key)}
{#each chips as chip (chip.key)}
<span class="v2-chip">
<b>{f.label}</b>
{f.value}
<button
type="button"
aria-label="Remove the {f.label} filter"
onclick={() => onremove(f.key)}
>
<X size={12} />
</button>
<b>{chip.label}</b>
{chip.value}
<a href={chip.href} aria-label="Remove the {chip.label} filter"><X size={12} /></a>
</span>
{/each}
<button class="v2-chip v2-chip-add" type="button">
<Plus size={12} />
Filter
</button>
{#if visibleFields.length > 0}
<details class="v2-filter-menu">
<summary class="v2-chip v2-chip-add">
<Plus size={12} />
Filter
</summary>
<form class="v2-menu v2-filter-form" method="GET">
<!-- Params the form does not own (the preset's own, plus paging) would
be dropped by a GET submit, which resets the whole URL. Carrying
them as hidden inputs keeps the active view when a filter is
added.
This checks against the FULL descriptor, not `visibleFields`, on
purpose: a param that belongs to a field this view is not
offering (a Stage value left over on the board, say) is exactly
the kind of param this view cannot honour, so submitting Apply
here drops it rather than carrying it along as a hidden input. -->
{#each [...url.searchParams] as [key, value] (key)}
{#if !descriptor.fields.some((/** @type {any} */ f) => f.key === key || f.gteKey === key || f.lteKey === key)}
<input type="hidden" name={key} {value} />
{/if}
{/each}
{#each visibleFields as field (field.key)}
<label class="v2-filter-row">
<span class="v2-label">{field.label}</span>
{#if field.type === 'date-range'}
<span class="v2-filter-dates">
<input
class="v2-input"
type="date"
name={field.gteKey}
value={url.searchParams.get(field.gteKey) ?? ''}
/>
<input
class="v2-input"
type="date"
name={field.lteKey}
value={url.searchParams.get(field.lteKey) ?? ''}
/>
</span>
{:else if field.type === 'number-range'}
<span class="v2-filter-dates">
<input
class="v2-input"
type="number"
min="0"
name={field.gteKey}
value={url.searchParams.get(field.gteKey) ?? ''}
placeholder="Min"
/>
<input
class="v2-input"
type="number"
min="0"
name={field.lteKey}
value={url.searchParams.get(field.lteKey) ?? ''}
placeholder="Max"
/>
</span>
{:else if field.type === 'boolean'}
<select class="v2-input" name={field.key}>
<option value="">Any</option>
<option value="true" selected={url.searchParams.get(field.key) === 'true'}
>Yes</option
>
<option value="false" selected={url.searchParams.get(field.key) === 'false'}
>No</option
>
</select>
{:else if field.type === 'text'}
<input
class="v2-input"
type="text"
name={field.key}
value={url.searchParams.get(field.key) ?? ''}
placeholder="Any"
/>
{:else}
<select class="v2-input" name={field.key}>
<option value="">Any</option>
{#each optionsFor(field) as option (option.id)}
<option
value={option.id}
selected={url.searchParams.get(field.key) === option.id}
>
{option.name}
</option>
{/each}
</select>
{/if}
</label>
{/each}
<div class="v2-filter-actions">
<button class="v2-btn v2-btn-primary v2-btn-sm" type="submit">Apply</button>
<a class="v2-btn v2-btn-sm" href={url.pathname}>Clear all</a>
</div>
</form>
</details>
{/if}
{#if meta}
<span class="v2-sub" style="margin-left:auto">{meta}</span>
{/if}
</div>
<style>
.v2-view-menu,
.v2-filter-menu {
position: relative;
}
.v2-view-menu summary,
.v2-filter-menu summary {
list-style: none;
cursor: pointer;
}
.v2-view-menu summary::-webkit-details-marker,
.v2-filter-menu summary::-webkit-details-marker {
display: none;
}
.v2-menu {
position: absolute;
top: calc(100% + 5px);
left: 0;
z-index: 20;
min-width: 190px;
padding: 5px;
border: 1px solid var(--v2-line);
border-radius: var(--v2-radius);
background: var(--v2-card);
box-shadow: 0 6px 18px rgb(0 0 0 / 8%);
}
.v2-menu-item {
display: block;
padding: 6px 9px;
border-radius: 5px;
color: inherit;
font-size: 12.5px;
text-decoration: none;
}
.v2-menu-item:hover {
background: var(--v2-wash);
}
.v2-menu-item-on {
font-weight: 600;
}
.v2-filter-form {
display: flex;
min-width: 260px;
flex-direction: column;
gap: 9px;
padding: 11px;
}
.v2-filter-row {
display: flex;
flex-direction: column;
gap: 4px;
}
.v2-filter-dates {
display: flex;
gap: 6px;
}
.v2-filter-actions {
display: flex;
gap: 6px;
padding-top: 3px;
}
.v2-chip a {
display: inline-flex;
color: inherit;
}
/* The lists switch to cards below 768px and the header actions go full
width, but an absolutely positioned menu does not: at 260px min-width it
runs off a 320px viewport when its trigger sits mid-row. Anchoring it to
the left edge and letting it use the full width keeps it on screen. */
@media (max-width: 768px) {
.v2-menu {
position: fixed;
left: 8px;
right: 8px;
min-width: 0;
}
}
</style>

View file

@ -89,6 +89,15 @@ export const LEAD_STATUS_LABEL = {
closed: 'Closed'
};
/**
* The statuses the leads LIST can display. `LeadListView` excludes `converted`
* outright and splits `closed` into a `close_leads` block the frontend never
* reads, so offering either as a filter option gives a permanently empty page
* that reads as "you have none" rather than "this page cannot show them".
* The full set stays in LEAD_STATUSES for the detail page's status select.
*/
export const LEAD_LIST_STATUSES = ['assigned', 'in process', 'recycled'];
export const LEAD_SOURCES = [
'call',
'email',
@ -419,3 +428,27 @@ export const BOARD_PRIORITY_TONE = {
/** tasks.BoardMember.ROLE_CHOICES, board-local, unrelated to Profile.role. */
export const BOARD_ROLE_LABEL = { owner: 'Owner', admin: 'Admin', member: 'Member' };
/**
* Option lists for the list-page filters. Values are what goes on the wire;
* labels are derived where they differ.
*
* CASE_PRIORITIES is not TASK_PRIORITY. A Case is Low/Normal/High/Urgent and a
* Task is Low/Medium/High: "Medium" is not a valid case priority and "Normal"
* is not a valid task priority. See the note at TASK_STATUS above.
*/
export const CASE_PRIORITIES = ['Low', 'Normal', 'High', 'Urgent'];
export const CASE_TYPES = ['Question', 'Incident', 'Problem'];
export const CASE_STATUSES = ['New', 'Assigned', 'Pending', 'Closed', 'Rejected', 'Duplicate'];
export const INVOICE_STATUSES = [
'Draft',
'Sent',
'Viewed',
'Paid',
'Partially_Paid',
'Overdue',
'Pending',
'Cancelled'
];
export const ESTIMATE_STATUSES = ['Draft', 'Sent', 'Viewed', 'Accepted', 'Declined', 'Expired'];
export const DOCUMENT_STATUSES = ['active', 'inactive'];

View file

@ -0,0 +1,406 @@
/**
* What each list page can be filtered by, and how those filters are drawn.
*
* Client-safe on purpose: `.svelte` files import this, and SvelteKit hard-blocks
* importing `$lib/server/` into a component. The server-side counterpart is
* `$lib/server/v2/filter-params.js`.
*
* Filter state lives in the URL and nowhere else, so a filtered list is
* shareable and the back button works without any state to synchronise.
*
* A descriptor has two parts:
*
* - `presets`: named views. Each writes the params the page's `load` ALREADY
* reads. Never invent a new spelling: tickets and tasks use `all=1`, not
* `all=true`, and a preset writing the wrong one changes the URL and shows
* the same rows, which is the failure this whole phase exists to remove.
* - `fields`: what `+ Filter` offers. Each becomes one removable chip.
*
* A `date-range` field names BOTH emitted params explicitly, because the
* convention is not uniform: invoices uses `due_date_gte` (one underscore)
* while every other endpoint uses `due_date__gte` (two). Never build a date key
* by concatenation. A `number-range` field (`amount` on pipeline) is the same
* shape, two named params and no derived key, only the value it validates is
* numeric rather than an ISO date.
*/
import {
CASE_PRIORITIES,
CASE_TYPES,
DOCUMENT_STATUSES,
ESTIMATE_STATUSES,
INDUSTRIES,
INVOICE_STATUSES,
LEAD_LIST_STATUSES,
LEAD_STATUS_LABEL,
LEAD_SOURCES,
LEAD_SOURCE_LABEL,
SOLUTION_STATUS,
SOLUTION_STATUS_LABEL,
STAGES,
STAGE_LABEL,
TASK_PRIORITY,
TASK_STATUS,
industryLabel,
invoiceStatusLabel
} from './enums.js';
/** @typedef {{ key: string, label: string, params: Record<string, string> }} Preset */
/** @typedef {{ key: string, label: string, type: string, options?: string[], labelFor?: (v: string) => string, gteKey?: string, lteKey?: string }} Field */
/** @typedef {{ presets: Preset[], fields: Field[] }} Descriptor */
/** @type {Record<string, Descriptor>} */
export const FILTERS = {
tickets: {
presets: [
{ key: 'open', label: 'Open, newest first', params: {} },
{ key: 'mine', label: 'Mine', params: { assigned_to: '@me' } },
{ key: 'breaching', label: 'Breaching SLA', params: { sla_breached: 'true' } },
{ key: 'all', label: 'Everything', params: { all: '1' } }
],
fields: [
{ key: 'assigned_to', label: 'Owner', type: 'person' },
{ key: 'priority', label: 'Priority', type: 'select', options: CASE_PRIORITIES },
{ key: 'case_type', label: 'Type', type: 'select', options: CASE_TYPES },
{ key: 'sla_breached', label: 'Breaching SLA', type: 'boolean' },
{ key: 'tags', label: 'Tag', type: 'tag' }
]
},
leads: {
presets: [
{ key: 'open', label: 'Open leads', params: {} },
{ key: 'mine', label: 'Mine', params: { assigned_to: '@me' } }
],
fields: [
{ key: 'assigned_to', label: 'Owner', type: 'person' },
{
key: 'status',
label: 'Status',
type: 'select',
options: LEAD_LIST_STATUSES,
labelFor: (v) => LEAD_STATUS_LABEL[v] ?? v
},
{
key: 'source',
label: 'Source',
type: 'select',
options: LEAD_SOURCES,
labelFor: (v) => LEAD_SOURCE_LABEL[v] ?? v
},
{ key: 'tags', label: 'Tag', type: 'tag' }
]
},
contacts: {
presets: [
{ key: 'mine', label: 'Mine', params: { assigned_to: '@me' } },
{ key: 'inactive', label: 'Including inactive', params: { inactive: '1' } },
{ key: 'active', label: 'Active contacts', params: {} }
],
fields: [
{ key: 'assigned_to', label: 'Owner', type: 'person' },
{ key: 'tags', label: 'Tag', type: 'tag' },
{ key: 'city', label: 'City', type: 'text' }
]
},
pipeline: {
presets: [
{ key: 'open', label: 'Open deals', params: { open: 'true' } },
{ key: 'mine', label: 'Mine', params: { assigned_to: '@me' } },
{ key: 'stalled', label: 'Stalled', params: { rotten: 'true' } },
{ key: 'all', label: 'All deals', params: {} }
],
fields: [
{ key: 'assigned_to', label: 'Owner', type: 'person' },
{
key: 'stage',
label: 'Stage',
type: 'select',
options: STAGES,
labelFor: (v) => STAGE_LABEL[v] ?? v
},
{
key: 'lead_source',
label: 'Source',
type: 'select',
options: LEAD_SOURCES,
labelFor: (v) => LEAD_SOURCE_LABEL[v] ?? v
},
{
key: 'amount',
label: 'Value',
type: 'number-range',
gteKey: 'amount__gte',
lteKey: 'amount__lte'
},
{ key: 'tags', label: 'Tag', type: 'tag' }
]
},
tasks: {
presets: [
{ key: 'open', label: 'Open tasks', params: {} },
{ key: 'mine', label: 'My tasks', params: { assigned_to: '@me' } },
{ key: 'all', label: 'All tasks', params: { all: '1' } }
],
fields: [
{ key: 'assigned_to', label: 'Owner', type: 'person' },
{ key: 'priority', label: 'Priority', type: 'select', options: TASK_PRIORITY },
{ key: 'status', label: 'Status', type: 'select', options: TASK_STATUS },
{
key: 'due_date',
label: 'Due date',
type: 'date-range',
gteKey: 'due_date__gte',
lteKey: 'due_date__lte'
}
]
},
accounts: {
presets: [
{ key: 'mine', label: 'Mine', params: { assigned_to: '@me' } },
{ key: 'all', label: 'All accounts', params: {} }
],
fields: [
{ key: 'assigned_to', label: 'Owner', type: 'person' },
{ key: 'tags', label: 'Tag', type: 'tag' },
{
key: 'industry',
label: 'Industry',
type: 'select',
options: INDUSTRIES,
labelFor: industryLabel
},
{ key: 'city', label: 'City', type: 'text' }
]
},
invoices: {
presets: [
{ key: 'overdue', label: 'Overdue', params: { status: 'Overdue' } },
{ key: 'draft', label: 'Draft', params: { status: 'Draft' } },
{ key: 'all', label: 'All invoices', params: {} }
],
fields: [
{
key: 'status',
label: 'Status',
type: 'select',
options: INVOICE_STATUSES,
labelFor: invoiceStatusLabel
},
{ key: 'account', label: 'Account', type: 'account' },
{ key: 'assigned_to', label: 'Owner', type: 'person' },
// Invoices uses a SINGLE underscore (`due_date_gte`/`due_date_lte`,
// `backend/invoices/api_views.py:149-152`). Every other date-range field
// in this file uses a DOUBLE underscore. Never build this key by
// concatenation; a shared helper that did would silently return an
// unfiltered list here while working everywhere else.
{
key: 'due_date',
label: 'Due date',
type: 'date-range',
gteKey: 'due_date_gte',
lteKey: 'due_date_lte'
}
]
},
estimates: {
presets: [
{ key: 'accepted', label: 'Accepted', params: { status: 'Accepted' } },
{ key: 'all', label: 'All estimates', params: {} }
],
fields: [
{ key: 'status', label: 'Status', type: 'select', options: ESTIMATE_STATUSES },
{ key: 'account', label: 'Account', type: 'account' }
// No Owner field: `EstimateListView.get` (backend/invoices/api_views.py
// :1028-1036) reads only `status` and `account`, never `assigned_to`.
// Offering one here would draw a chip that filters nothing underneath it.
]
},
solutions: {
presets: [
{ key: 'published', label: 'Published', params: { visibility: 'published' } },
{ key: 'drafts', label: 'Drafts', params: { status: 'draft' } },
{ key: 'all', label: 'All articles, last edited first', params: {} }
],
fields: [
{
key: 'status',
label: 'Status',
type: 'select',
options: SOLUTION_STATUS,
labelFor: (v) => SOLUTION_STATUS_LABEL[v] ?? v
}
]
},
documents: {
// `active` is the empty-params default, and `all` opts in with
// `archived=1`, the same shape `/contacts` uses for `inactive`. The load
// applies `status=active` unless that opt-in or an explicit Status choice
// is present. Written the other way round, with `all` as the default,
// archived documents come back alongside the live ones on a bare URL,
// which undoes the only thing archiving does.
presets: [
{ key: 'active', label: 'Active documents', params: {} },
{ key: 'all', label: 'Including archived', params: { archived: '1' } }
],
// `tags` and `created_by` are deliberately absent: `DocumentListView.get`
// (backend/common/views/document_views.py:71-79) reads only `title`,
// `status` and `shared_to`, `Document` has no `tags` relation at all, and
// `shared_to` is passed straight to `json.loads`, so a plain
// `?shared_to=<uuid>` throws `JSONDecodeError` and answers 500. Status is
// the only filter this endpoint actually honours.
fields: [{ key: 'status', label: 'Status', type: 'select', options: DOCUMENT_STATUSES }]
},
recurring: {
presets: [
{ key: 'active', label: 'Active schedules', params: { is_active: 'true' } },
{ key: 'all', label: 'All schedules', params: {} }
],
fields: [{ key: 'is_active', label: 'Active', type: 'boolean' }]
}
};
/** Every param key a descriptor's fields can emit, date ranges expanded. */
export function fieldKeys(/** @type {Descriptor} */ descriptor) {
const keys = [];
for (const field of descriptor.fields) {
if (field.type === 'date-range' || field.type === 'number-range') {
keys.push(field.gteKey, field.lteKey);
} else keys.push(field.key);
}
return /** @type {string[]} */ (keys.filter(Boolean));
}
/** The same URL with `key` removed. Returns a path plus query, never absolute. */
export function withoutParam(/** @type {URL} */ url, /** @type {string} */ key) {
const next = new URLSearchParams(url.search);
next.delete(key);
const qs = next.toString();
return qs ? `${url.pathname}?${qs}` : url.pathname;
}
/**
* The same URL with `params` applied. A null or empty value removes the key, so
* one helper covers both adding a filter and clearing one.
*/
export function withParams(
/** @type {URL} */ url,
/** @type {Record<string, string|null>} */ params
) {
const next = new URLSearchParams(url.search);
for (const [key, value] of Object.entries(params)) {
if (value === null || value === '') next.delete(key);
else next.set(key, value);
}
const qs = next.toString();
return qs ? `${url.pathname}?${qs}` : url.pathname;
}
/**
* Which preset the current URL represents.
*
* A preset matches when every param it sets is present with that value. The
* empty-params preset is the fallback, so it is checked last and only wins when
* nothing else does. Presets are ordered most-specific-first in each descriptor
* for this reason.
*
* `meId` is the resolved viewer's profile id. A preset param of `@me` is
* substituted with `meId` before comparing, so `mine` only matches the
* viewer's own id, never any other value of the same key. When `meId` is not
* resolved (null), an `@me` param can never match: labelling an unowned or
* someone-else's-owned view as "Mine" would assert something false about
* what is on screen.
*/
export function activePresetKey(
/** @type {string} */ pageKey,
/** @type {URL} */ url,
/** @type {string | null} */ meId = null
) {
const descriptor = FILTERS[pageKey];
if (!descriptor) return '';
const withParamsSet = descriptor.presets.filter((p) => Object.keys(p.params).length > 0);
for (const preset of withParamsSet) {
const hit = Object.entries(preset.params).every(([k, v]) => {
const wanted = v === '@me' ? meId : v;
// An unresolved viewer cannot match a "@me" preset. Returning true here
// would label any owner-filtered view as "Mine".
return wanted !== null && url.searchParams.get(k) === wanted;
});
if (hit) return preset.key;
}
return descriptor.presets.find((p) => Object.keys(p.params).length === 0)?.key ?? '';
}
/**
* One chip per explicitly-set filter param.
*
* A chip only ever represents a param that is actually in the URL, which is
* what makes every chip removable. The old bar rendered chips describing
* implicit defaults, and their X had nothing to remove, so it did nothing. An
* implicit default belongs in the preset name, not in a chip.
*
* `lookups` resolves opaque ids to names: `{ people: [{id,name}], tags: [...],
* accounts: [...] }`. A missing lookup falls back to the raw value rather than
* rendering an empty chip.
*/
export function activeChips(
/** @type {string} */ pageKey,
/** @type {URL} */ url,
/** @type {{people?: any[], tags?: any[], accounts?: any[]}} */ lookups = {}
) {
const descriptor = FILTERS[pageKey];
if (!descriptor) return [];
const nameFrom = (/** @type {any[]} */ list, /** @type {string} */ id) =>
list?.find((o) => o.id === id)?.name ?? id;
const chips = [];
for (const field of descriptor.fields) {
if (field.type === 'date-range' || field.type === 'number-range') {
const from = url.searchParams.get(/** @type {string} */ (field.gteKey));
const to = url.searchParams.get(/** @type {string} */ (field.lteKey));
if (!from && !to) continue;
const value =
field.type === 'number-range'
? from && to
? `${from} to ${to}`
: from
? `over ${from}`
: `under ${to}`
: from && to
? `${from} to ${to}`
: from
? `from ${from}`
: `up to ${to}`;
chips.push({
key: field.key,
label: field.label,
value,
href: withParams(url, {
[/** @type {string} */ (field.gteKey)]: null,
[/** @type {string} */ (field.lteKey)]: null
})
});
continue;
}
const raw = url.searchParams.get(field.key);
if (!raw) continue;
let value = raw;
if (field.type === 'person') value = nameFrom(lookups.people ?? [], raw);
else if (field.type === 'tag') value = nameFrom(lookups.tags ?? [], raw);
else if (field.type === 'account') value = nameFrom(lookups.accounts ?? [], raw);
else if (field.type === 'boolean') value = raw === 'true' ? 'Yes' : 'No';
else if (field.labelFor) value = field.labelFor(raw);
chips.push({ key: field.key, label: field.label, value, href: withoutParam(url, field.key) });
}
return chips;
}

View file

@ -0,0 +1,282 @@
import { describe, it, expect } from 'vitest';
import {
FILTERS,
fieldKeys,
withoutParam,
withParams,
activeChips,
activePresetKey
} from '$lib/v2/filters.js';
/**
* Each page's module exports the allow-list its list function forwards. As
* descriptors are added by later tasks this map grows with them, and the loop
* below covers whatever is present.
*/
const MODULES = {
tickets: () => import('$lib/server/v2/tickets.js'),
leads: () => import('$lib/server/v2/leads.js'),
contacts: () => import('$lib/server/v2/contacts.js'),
pipeline: () => import('$lib/server/v2/deals.js'),
tasks: () => import('$lib/server/v2/tasks.js'),
accounts: () => import('$lib/server/v2/accounts.js'),
invoices: () => import('$lib/server/v2/invoices.js'),
estimates: () => import('$lib/server/v2/estimates.js'),
solutions: () => import('$lib/server/v2/solutions.js'),
documents: () => import('$lib/server/v2/documents.js'),
recurring: () => import('$lib/server/v2/recurring.js')
};
describe('every descriptor agrees with its module allow-list', () => {
for (const pageKey of Object.keys(FILTERS)) {
it(`${pageKey}: every field key is forwarded by the module`, async () => {
// A descriptor with no MODULES entry must fail here with a sentence,
// not a bare TypeError on `MODULES[pageKey] is not a function`. Adding a
// descriptor without registering its module is the expected mistake.
expect(MODULES[pageKey], `add "${pageKey}" to MODULES in this file`).toBeDefined();
const mod = await MODULES[pageKey]();
expect(mod.FILTER_FIELDS, `${pageKey}.js must export FILTER_FIELDS`).toBeDefined();
for (const key of fieldKeys(FILTERS[pageKey])) {
expect(mod.FILTER_FIELDS, `${pageKey} field "${key}"`).toContain(key);
}
});
it(`${pageKey}: exactly one preset is the default`, () => {
const empty = FILTERS[pageKey].presets.filter((p) => Object.keys(p.params).length === 0);
expect(empty.length).toBe(1);
});
it(`${pageKey}: every preset param is forwarded or is a page-local view param`, async () => {
const mod = await MODULES[pageKey]();
// Params a page's own load interprets rather than forwarding to the API.
// `open` and `rotten` are pipeline's version of `all`: `?open=true` and
// `?rotten=true` (opportunity_views.py:183,186) are read directly by
// pipeline's load, the same way tickets and tasks read `all` themselves,
// so neither belongs on deals.js's FILTER_FIELDS allow-list.
// Params a page's own `load` interprets rather than forwarding to the
// API. `archived` is documents' opt-in to seeing archived rows, the
// same shape as contacts' `inactive`.
const VIEW_PARAMS = [
'all',
'inactive',
'archived',
'visibility',
'view',
'open',
'rotten'
];
for (const preset of FILTERS[pageKey].presets) {
for (const key of Object.keys(preset.params)) {
if (VIEW_PARAMS.includes(key)) continue;
expect(mod.FILTER_FIELDS, `${pageKey} preset "${preset.key}" param "${key}"`).toContain(
key
);
}
}
});
}
});
describe('leads: only statuses the list endpoint can actually show', () => {
// backend/leads/views/lead_views.py:92 excludes status="converted" from the
// base queryset unconditionally, before any query param is read, and :166
// splits what remains into `open_leads` and a `close_leads` block that
// `listLeads` (lib/server/v2/leads.js) never reads. So the leads list can
// only ever render "assigned", "in process" or "recycled". Offering
// "Converted" or "Closed" as a filter option would submit a value the page
// can never return a row for, which reads as "you have none" rather than
// "this page cannot show them".
it('offers neither "converted" nor "closed" as a status option', () => {
const statusField = FILTERS.leads.fields.find((f) => f.key === 'status');
expect(statusField.options).not.toContain('converted');
expect(statusField.options).not.toContain('closed');
});
it('writes no preset param the list endpoint does not read', () => {
// `is_converted` is read only by the PATCH/conversion action, never by
// the list GET, so no preset may promise a view built on it.
for (const preset of FILTERS.leads.presets) {
expect(Object.keys(preset.params)).not.toContain('is_converted');
}
});
});
describe('documents: exactly one filter field', () => {
// `DocumentListView.get` (backend/common/views/document_views.py:71-79) reads
// only `title`, `status` and `shared_to`. `Document` has no `tags` relation
// at all, and `shared_to` is passed straight to `json.loads`, so an ordinary
// `?shared_to=<uuid>` throws `JSONDecodeError` and answers 500. If a future
// change adds a field here, re-check the backend view before doing it; do
// not "helpfully" restore `tags` or `created_by`.
it('offers only "status"', () => {
expect(FILTERS.documents.fields.map((f) => f.key)).toEqual(['status']);
});
});
describe('documents: archived rows stay out of the default view', () => {
// Archiving a document is how you get it out of the way. If the empty-params
// preset were the "all" one, a bare /documents would show archived rows back
// alongside the live ones and undo the only thing archiving does. So `active`
// is the default and `all` opts in through `archived=1`, which
// `documents/+page.server.js` reads. Same shape as contacts' `inactive`.
it('makes "active" the empty-params default', () => {
const active = FILTERS.documents.presets.find((p) => p.key === 'active');
expect(Object.keys(active.params)).toEqual([]);
});
it('makes seeing archived rows an explicit opt-in', () => {
const all = FILTERS.documents.presets.find((p) => p.key === 'all');
expect(all.params).toEqual({ archived: '1' });
});
it('never lets a preset send status=active, which the load owns', () => {
// The default narrowing lives in the load, not the descriptor, so that an
// explicit Status choice can override it. A preset writing status=active
// would put a second, competing source of truth in the URL.
for (const preset of FILTERS.documents.presets) {
expect(preset.params.status).toBeUndefined();
}
});
});
describe('URL helpers', () => {
const url = new URL('http://x/tickets?priority=High&all=1');
it('withoutParam drops one key and keeps the rest', () => {
expect(withoutParam(url, 'priority')).toBe('/tickets?all=1');
});
it('withoutParam returns a bare path when nothing is left', () => {
expect(withoutParam(new URL('http://x/tickets?a=1'), 'a')).toBe('/tickets');
});
it('withParams treats an empty value as a removal', () => {
expect(withParams(url, { priority: '' })).toBe('/tickets?all=1');
});
});
describe('activePresetKey', () => {
it('returns the default preset key for a bare URL', () => {
expect(activePresetKey('tickets', new URL('http://x/tickets'))).toBe('open');
});
it('matches a non-@me preset on its literal param value', () => {
expect(activePresetKey('tickets', new URL('http://x/tickets?sla_breached=true'))).toBe(
'breaching'
);
});
it('matches the "mine" preset when assigned_to equals the resolved viewer id', () => {
expect(activePresetKey('tickets', new URL('http://x/tickets?assigned_to=p1'), 'p1')).toBe(
'mine'
);
});
it('does not match "mine" when assigned_to names someone other than the viewer', () => {
// Regression test: the old matcher accepted "@me" against ANY assigned_to
// value, so filtering by a colleague's id was mislabelled as "Mine".
expect(activePresetKey('tickets', new URL('http://x/tickets?assigned_to=p2'), 'p1')).toBe(
'open'
);
});
it('does not match "mine" when the viewer id is unresolved', () => {
expect(activePresetKey('tickets', new URL('http://x/tickets?assigned_to=p1'), null)).toBe(
'open'
);
});
});
describe('activeChips', () => {
it('renders a chip only for params that are actually set', () => {
const chips = activeChips('tickets', new URL('http://x/tickets?priority=High'));
expect(chips).toHaveLength(1);
expect(chips[0]).toMatchObject({ key: 'priority', label: 'Priority', value: 'High' });
});
it('resolves a person id to a name and still removes by id', () => {
const chips = activeChips('tickets', new URL('http://x/tickets?assigned_to=p1'), {
people: [{ id: 'p1', name: 'Ada' }]
});
expect(chips[0].value).toBe('Ada');
expect(chips[0].href).toBe('/tickets');
});
it('falls back to the raw id when the lookup misses', () => {
const chips = activeChips('tickets', new URL('http://x/tickets?assigned_to=p9'), {
people: []
});
expect(chips[0].value).toBe('p9');
});
});
describe('pipeline presets', () => {
// The pipeline base queryset does not exclude closed stages
// (opportunity_views.py), so the empty-params preset is "All deals", not
// "Open". A bare URL must resolve to that preset, not to "open", or the
// preset menu would highlight a view the query is not actually running.
it('returns "all" for a bare URL, not "open"', () => {
expect(activePresetKey('pipeline', new URL('http://x/pipeline'))).toBe('all');
});
it('matches "open" only when ?open=true is actually set', () => {
expect(activePresetKey('pipeline', new URL('http://x/pipeline?open=true'))).toBe('open');
});
it('matches "stalled" on ?rotten=true', () => {
expect(activePresetKey('pipeline', new URL('http://x/pipeline?rotten=true'))).toBe('stalled');
});
it('matches "mine" against the resolved viewer id only', () => {
expect(activePresetKey('pipeline', new URL('http://x/pipeline?assigned_to=p1'), 'p1')).toBe(
'mine'
);
expect(activePresetKey('pipeline', new URL('http://x/pipeline?assigned_to=p1'), 'p2')).toBe(
'all'
);
});
});
describe('tasks presets', () => {
it('returns "open" for a bare URL', () => {
expect(activePresetKey('tasks', new URL('http://x/tasks'))).toBe('open');
});
it('matches "all" on ?all=1, the same spelling tickets uses', () => {
expect(activePresetKey('tasks', new URL('http://x/tasks?all=1'))).toBe('all');
});
it('matches "mine" against the resolved viewer id only', () => {
expect(activePresetKey('tasks', new URL('http://x/tasks?assigned_to=p1'), 'p1')).toBe('mine');
});
});
describe('number-range chips (pipeline "Value")', () => {
it('renders a half-open floor as "over X"', () => {
const chips = activeChips('pipeline', new URL('http://x/pipeline?amount__gte=5000'));
expect(chips).toHaveLength(1);
expect(chips[0]).toMatchObject({ key: 'amount', label: 'Value', value: 'over 5000' });
});
it('renders a half-open ceiling as "under X"', () => {
const chips = activeChips('pipeline', new URL('http://x/pipeline?amount__lte=10000'));
expect(chips[0].value).toBe('under 10000');
});
it('renders a closed range as "X to Y"', () => {
const chips = activeChips(
'pipeline',
new URL('http://x/pipeline?amount__gte=5000&amount__lte=10000')
);
expect(chips[0].value).toBe('5000 to 10000');
});
it('removes both bounds through one href', () => {
const chips = activeChips(
'pipeline',
new URL('http://x/pipeline?amount__gte=5000&amount__lte=10000&stage=PROSPECTING')
);
const valueChip = chips.find((c) => c.key === 'amount');
expect(valueChip.href).toBe('/pipeline?stage=PROSPECTING');
});
});

View file

@ -20,9 +20,16 @@ const LIVE_COUNTS = {
/** @param {any} event */
leads: async (event) =>
(await listLeads(event, new URLSearchParams({ limit: '1' }))).totals.count,
/** @param {any} event */
/**
* Open deals only, same rule as tickets and tasks below: a badge counting
* closed deals would never go down. `listDeals` no longer assumes this on
* its own (`$lib/server/v2/deals.js`'s FILTER_FIELDS note), so it is spelled
* out here.
*
* @param {any} event
*/
pipeline: async (event) =>
(await listDeals(event, new URLSearchParams({ limit: '1' }))).totals.count,
(await listDeals(event, new URLSearchParams({ open: 'true', limit: '1' }))).totals.count,
/**
* Open tickets only. A support badge counting closed ones would never go
* down, which is the same objection as the accounts note below.

View file

@ -1,18 +1,44 @@
import { listAccounts } from '$lib/server/v2/accounts.js';
import { listAccounts, FILTER_FIELDS } from '$lib/server/v2/accounts.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { getOrgPeopleAndTeams, resolveMe } from '$lib/server/v2/org-people.js';
import { getTags } from '$lib/server/v2/tags.js';
/**
* Only filters the API actually applies are forwarded. A parameter that
* changes the URL and nothing else teaches people the filter bar is decorative.
*
* `city` and `industry` used to be forwarded straight off the URL, unvalidated
* as anything the API happened to read; they now go through `readFilters`
* like every other v2 list, so a hand-typed param never becomes a variable
* this layer carries and an `industry` value outside the option list gets
* dropped rather than returning a silent empty page.
*
* The pickers are fetched here rather than inside `listAccounts` for the same
* reason as `leads.js`: folding them into the list read would cost every
* other caller of that function a request it never renders.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load({ cookies, url }) {
const params = new URLSearchParams();
for (const key of ['search', 'name', 'city', 'industry', 'assigned_to', 'tags', 'limit']) {
export async function load({ cookies, url, locals }) {
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'accounts'));
for (const key of ['search', 'name', 'limit']) {
const value = url.searchParams.get(key);
if (value) params.set(key, value);
}
const { results, totals } = await listAccounts({ cookies }, params);
return { accounts: results, totals };
const [{ results, totals }, orgPeople, tagList] = await Promise.all([
listAccounts({ cookies }, params),
getOrgPeopleAndTeams(cookies),
// A failed tag fetch should cost the Tag dropdown in the filter bar, not
// the whole list. Same pattern as leads.js and pipeline's deals.js.
getTags({ cookies }).catch(() => ({ tags: [] }))
]);
return {
accounts: results,
totals,
people: orgPeople.people,
tags: tagList.tags ?? [],
meId: resolveMe(orgPeople.people, /** @type {any} */ (locals).user?.email)
};
}

View file

@ -1,9 +1,11 @@
<script>
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
import EmptyState from '$lib/v2/components/EmptyState.svelte';
import { money, count } from '$lib/v2/format.js';
import { activeChips, activePresetKey } from '$lib/v2/filters.js';
import { Plus, Building2 } from '@lucide/svelte';
/** @type {{ data: any }} */
@ -11,20 +13,53 @@
let accounts = $derived(data.accounts);
let totals = $derived(data.totals);
/**
* Whether the view is actually narrowed, rather than merely carrying a query
* string. `page.url.search` alone is the wrong test: it fires on any param,
* including ones that are not filters at all. `'all'` is this page's
* empty-params preset, its declared default, so any other preset counts as
* filtered even when it sets no field a chip would show.
*/
let isFiltered = $derived(
activeChips('accounts', page.url, { people: data.people, tags: data.tags }).length > 0 ||
activePresetKey('accounts', page.url, data.meId) !== 'all'
);
</script>
<PageHeader title="Accounts">
{#snippet sub()}
<!-- The count is the size of the whole result set, not of this page. -->
<span class="v2-num">{count(totals.count)}</span> accounts ·
<span class="v2-num">{count(totals.customers)}</span> with a deal won
<span class="v2-num">{count(totals.count)}</span> accounts
<!-- `customers` is counted from the rows actually loaded, because the
accounts endpoint returns no aggregate for it (see the note in
`lib/server/v2/accounts.js`). Printing it beside a whole-set count
when only one page is loaded states a smaller number as though it
covered everything, so it is shown only when this page IS the whole
set. A figure that disappears beats a figure that is wrong. -->
{#if (totals.shown ?? 0) >= (totals.count ?? 0)}
· <span class="v2-num">{count(totals.customers)}</span> with a deal won
{/if}
{/snippet}
{#snippet actions()}
<a class="v2-btn v2-btn-primary" href="/accounts/new"><Plus />New account</a>
{/snippet}
</PageHeader>
<FilterBar view="All accounts" filters={[]} meta="Sorted by revenue won" />
{#if isFiltered}
<p class="v2-sub" style="font-size:11.5px;margin:8px 0 0">
These numbers describe the filtered list.
</p>
{/if}
<FilterBar
page="accounts"
url={page.url}
people={data.people}
tags={data.tags}
meId={data.meId}
meta="Sorted by revenue won"
/>
<div class="v2-scroll">
{#if accounts.length === 0}

View file

@ -1,4 +1,7 @@
import { listContacts } from '$lib/server/v2/contacts.js';
import { listContacts, FILTER_FIELDS } from '$lib/server/v2/contacts.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { getOrgPeopleAndTeams, resolveMe } from '$lib/server/v2/org-people.js';
import { getTags } from '$lib/server/v2/tags.js';
/**
* Only filters the API actually applies are forwarded. A parameter that
@ -9,11 +12,16 @@ import { listContacts } from '$lib/server/v2/contacts.js';
* rather than by discarding rows after they arrive, which was only ever right
* on the first page.
*
* The pickers are fetched here rather than inside `listContacts` for the same
* reason as `tickets.js`: a picker fetch folded into the list read would cost
* a redundant request on every caller that reads contacts for their totals
* alone.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load({ cookies, url }) {
const params = new URLSearchParams();
for (const key of ['search', 'name', 'city', 'email', 'phone', 'assigned_to', 'tags', 'limit']) {
export async function load({ cookies, url, locals }) {
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'contacts'));
for (const key of ['search', 'name', 'email', 'phone', 'limit']) {
const value = url.searchParams.get(key);
if (value) params.set(key, value);
}
@ -21,6 +29,21 @@ export async function load({ cookies, url }) {
const includeInactive = url.searchParams.get('inactive') === '1';
if (!includeInactive) params.set('is_active', 'true');
const { results, totals } = await listContacts({ cookies }, params);
return { contacts: results, totals, includeInactive, search: params.get('search') ?? '' };
const [{ results, totals }, orgPeople, tagList] = await Promise.all([
listContacts({ cookies }, params),
getOrgPeopleAndTeams(cookies),
// A failed tag fetch should cost the Tag dropdown in the filter bar, not
// the whole list. Follows the tickets.js pattern; see the note there.
getTags({ cookies }).catch(() => ({ tags: [] }))
]);
return {
contacts: results,
totals,
includeInactive,
search: params.get('search') ?? '',
people: orgPeople.people,
tags: tagList.tags ?? [],
meId: resolveMe(orgPeople.people, /** @type {any} */ (locals).user?.email)
};
}

View file

@ -1,4 +1,5 @@
<script>
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
import Avatar from '$lib/v2/components/Avatar.svelte';
@ -12,12 +13,6 @@
let contacts = $derived(data.contacts);
let totals = $derived(data.totals);
// A chip may only claim a filter the API actually applied. `is_active=true`
// is sent unless the URL asks for everybody, so this one is honest.
let filters = $derived(
data.includeInactive ? [] : [{ key: 'active', label: 'Status', value: 'active' }]
);
</script>
<PageHeader title="Contacts">
@ -40,7 +35,14 @@
{/snippet}
</PageHeader>
<FilterBar view="All contacts" {filters} meta="Most recently added first" />
<FilterBar
page="contacts"
url={page.url}
people={data.people}
tags={data.tags}
meId={data.meId}
meta="Most recently added first"
/>
<div class="v2-scroll">
{#if contacts.length === 0}

View file

@ -1,4 +1,5 @@
import { listDocuments } from '$lib/server/v2/documents.js';
import { listDocuments, FILTER_FIELDS } from '$lib/server/v2/documents.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
/**
* The documents list.
@ -9,8 +10,26 @@ import { listDocuments } from '$lib/server/v2/documents.js';
* deleting live on their own routes (`/new`, `/[id]/edit`) so the destructive
* paths are deliberate, never a mis-click in a table.
*
* `status` is the only filter this endpoint honours; see the note on
* `FILTER_FIELDS` in `documents.js`. The old page fetched every document and
* filtered archived ones out client-side, which is wrong once pagination is
* in play: it returns fewer rows than the page size and understates the count.
* The API narrows the set now.
*
* Active-only is the default, applied here rather than by an empty-params
* preset, which is the same shape `/contacts` uses for `inactive` and
* `/tasks` uses for `all`. Archiving a document is how you get it out of the
* way, so a default that showed archived ones back alongside the live ones
* would undo the only thing archiving does. `?archived=1` opts in, and an
* explicit `?status=` from the Status field beats the default outright, the
* same rule the tasks queue follows.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load(event) {
return await listDocuments(event);
export async function load({ cookies, url }) {
const filters = readFilters(url, 'documents');
const params = buildFilterQuery(FILTER_FIELDS, filters);
const includeArchived = url.searchParams.get('archived') === '1';
if (!includeArchived && !params.has('status')) params.set('status', 'active');
return await listDocuments({ cookies }, params);
}

View file

@ -20,6 +20,7 @@
* everyone else. The row only offers Delete where the server would allow
* it, rather than offering it to everyone and failing on press.
*/
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
@ -36,9 +37,6 @@
// the Upload button shows for everyone. Editing/deleting are the narrow writes
//. Those are gated per row by `can_write` (creator or admin) below.
let showInactive = $state(false);
let visible = $derived(documents.filter((d) => showInactive || d.status === 'active'));
const ICON = { pdf: FileText, sheet: FileSpreadsheet, text: FileText };
const iconFor = (kind) => ICON[kind] ?? File;
@ -73,13 +71,16 @@
<span class="v2-num">{count(totals.inactive)}</span> archived
{/snippet}
{#snippet actions()}
<button class="v2-btn" type="button" onclick={() => (showInactive = !showInactive)}>
{showInactive ? 'Hide archived' : 'Show archived'}
</button>
<a class="v2-btn v2-btn-primary" href="/documents/new"><Upload />Upload</a>
{/snippet}
</PageHeader>
{#if page.url.search}
<p class="v2-sub" style="font-size:11.5px;margin:8px 0 0">
These numbers describe the filtered list.
</p>
{/if}
<div class="v2-pad" style="padding-top:14px;flex:none">
<div class="v2-stats">
<StatCard
@ -94,15 +95,10 @@
</div>
</div>
<FilterBar
view={showInactive ? 'All documents' : 'Active documents'}
filters={showInactive ? [] : [{ key: 'status', label: 'Status', value: 'Active' }]}
onremove={() => (showInactive = true)}
meta="Newest first"
/>
<FilterBar page="documents" url={page.url} meta="Newest first" />
<div class="v2-scroll">
{#if visible.length === 0}
{#if documents.length === 0}
<EmptyState
title="No documents yet"
body="Contracts, runbooks, price sheets. The things you send people often enough to stop hunting for. Share each one with the people or the team who need it; an unshared upload is visible only to you and to admins."
@ -126,7 +122,7 @@
</tr>
</thead>
<tbody>
{#each visible as d (d.id)}
{#each documents as d (d.id)}
{@const Icon = iconFor(d.file_kind)}
<tr class:archived={d.status === 'inactive'}>
<td style="white-space:normal;max-width:420px">
@ -184,7 +180,7 @@
</div>
<p class="v2-sub v2-pad" style="font-size:12px;padding-bottom:24px">
Showing <span class="v2-num">{visible.length}</span> of
Showing <span class="v2-num">{documents.length}</span> of
<span class="v2-num">{count(totals.count)}</span>
</p>
{/if}

View file

@ -1,18 +1,47 @@
import { fail } from '@sveltejs/kit';
import { listInvoices, sendInvoice } from '$lib/server/v2/invoices.js';
import { listInvoices, sendInvoice, FILTER_FIELDS } from '$lib/server/v2/invoices.js';
import { listAccountsPicker } from '$lib/server/v2/accounts.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { getOrgPeopleAndTeams, resolveMe } from '$lib/server/v2/org-people.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/**
* The invoice list.
*
* Server load, so the JWT cookie stays server-side. Rows and the header pills
* arrive from one API call. The totals are the API's job now, aggregated over
* the whole visible queryset rather than summed from the page.
* Server load, so the JWT cookie stays server-side. Rows arrive from one API
* call, filtered by whatever `FILTER_FIELDS` params are on the URL. The
* header pills do NOT narrow with them, see the note on `totals` in
* `listInvoices` (`$lib/server/v2/invoices.js`): the API computes them over
* the role-scoped queryset before filtering, by design, so this page has no
* "these numbers describe the filtered list" line the way accounts, estimates,
* tasks, tickets and pipeline do. Adding one here would describe something
* that is not true for this endpoint.
*
* The owner and account pickers are separate fetches, same reasoning as
* leads.js and pipeline's deals.js: folding them into `listInvoices` would
* cost every other caller of that function (the shell's nav badge, for one) a
* request it never renders.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load({ cookies }) {
return await listInvoices({ cookies });
export async function load({ cookies, url, locals }) {
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'invoices'));
const [{ invoices, totals }, orgPeople, accountList] = await Promise.all([
listInvoices({ cookies }, params),
getOrgPeopleAndTeams(cookies),
// A failed account fetch should cost the Account dropdown in the filter
// bar, not the whole list. Same pattern as the Tag fetch in leads.js.
listAccountsPicker({ cookies }).catch(() => ({ accounts: [] }))
]);
return {
invoices,
totals,
people: orgPeople.people,
accounts: accountList.accounts ?? [],
meId: resolveMe(orgPeople.people, /** @type {any} */ (locals).user?.email)
};
}
/** @type {import('./$types').Actions} */

View file

@ -1,4 +1,5 @@
<script>
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SectionTabs from '$lib/v2/components/SectionTabs.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
@ -72,7 +73,19 @@
</div>
</div>
<FilterBar view="All invoices" filters={[]} meta="Oldest due first" />
<!-- No "filtered list" line here, unlike the other v2 list pages: the pills
above come from `totals`, which the API deliberately computes over the
whole role-scoped queryset regardless of the active filter (see the note
on `listInvoices` in `$lib/server/v2/invoices.js`). Saying "these numbers
describe the filtered list" would be false for this page. -->
<FilterBar
page="invoices"
url={page.url}
people={data.people}
accounts={data.accounts}
meId={data.meId}
meta="Oldest due first"
/>
{#if form?.error}
<p class="v2-sub v2-pad" style="color:var(--v2-rust);font-size:12.5px;padding-top:10px">

View file

@ -1,16 +1,31 @@
import { fail, redirect } from '@sveltejs/kit';
import { listEstimates, convertEstimate } from '$lib/server/v2/estimates.js';
import { listEstimates, convertEstimate, FILTER_FIELDS } from '$lib/server/v2/estimates.js';
import { listAccountsPicker } from '$lib/server/v2/accounts.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/**
* The estimates worklist. `load` returns `{ estimates, totals }`. The exact
* names the page reads; the data layer's own field is `estimates`, so there is
* no rename to get wrong here.
* The estimates worklist. `load` returns `{ estimates, totals, accounts }`.
* `estimates`/`totals` are the exact names the page reads; the data layer's
* own field is `estimates`, so there is no rename to get wrong here.
*
* The account picker is a separate fetch, same reasoning as every other v2
* list: folding it into `listEstimates` would cost every other caller of that
* function a request it never renders.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load({ cookies }) {
return await listEstimates({ cookies });
export async function load({ cookies, url }) {
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'estimates'));
const [{ estimates, totals }, accountList] = await Promise.all([
listEstimates({ cookies }, params),
// A failed account fetch should cost the Account dropdown in the filter
// bar, not the whole worklist. Same pattern as the Tag fetch in leads.js.
listAccountsPicker({ cookies }).catch(() => ({ accounts: [] }))
]);
return { estimates, totals, accounts: accountList.accounts ?? [] };
}
/** @type {import('./$types').Actions} */

View file

@ -8,6 +8,7 @@
* indistinguishable and the gap only surfaced at month end. Status and
* "has it been billed" are two separate facts and get two separate columns.
*/
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SectionTabs from '$lib/v2/components/SectionTabs.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
@ -52,6 +53,12 @@
{/snippet}
</PageHeader>
{#if page.url.search}
<p class="v2-sub" style="font-size:11.5px;margin:8px 0 0">
These numbers describe the filtered list.
</p>
{/if}
<SectionTabs set="invoices" />
{#if form?.error}
@ -79,8 +86,9 @@
</div>
<FilterBar
view="All estimates"
filters={[]}
page="estimates"
url={page.url}
accounts={data.accounts}
meta="Accepted but unbilled first, then most recently sent"
/>

View file

@ -1,15 +1,21 @@
import { fail } from '@sveltejs/kit';
import { listRecurringInvoices, toggleRecurring } from '$lib/server/v2/recurring.js';
import { listRecurringInvoices, toggleRecurring, FILTER_FIELDS } from '$lib/server/v2/recurring.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/**
* The schedules worklist. `load` returns `{ schedules, totals }`. The names the
* page reads; the data layer's own field is `schedules`, so no rename here.
*
* `is_active` is forwarded to the API rather than derived from the rows after
* the fact, so the four header figures (all computed from what comes back)
* agree with the table underneath them.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load({ cookies }) {
return await listRecurringInvoices({ cookies });
export async function load({ cookies, url }) {
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'recurring'));
return await listRecurringInvoices({ cookies }, params);
}
/** @type {import('./$types').Actions} */

View file

@ -8,6 +8,7 @@
* unless somebody remembers, the customer never gets billed. The failure is
* silent and looks exactly like success. It is a column here.
*/
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SectionTabs from '$lib/v2/components/SectionTabs.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
@ -59,6 +60,12 @@
<SectionTabs set="invoices" />
{#if page.url.search}
<p class="v2-sub" style="font-size:11.5px;margin:8px 0 0">
These numbers describe the filtered list.
</p>
{/if}
{#if form?.error}
<div class="v2-pad" style="padding-top:12px;flex:none">
<p class="rec-error" role="alert">{form.error}</p>
@ -84,7 +91,7 @@
</div>
</div>
<FilterBar view="All schedules" filters={[]} meta="Active first, then soonest to generate" />
<FilterBar page="recurring" url={page.url} meta="Active first, then soonest to generate" />
<div class="v2-scroll">
{#if data.schedules.length === 0}

View file

@ -1,21 +1,44 @@
import { listLeads } from '$lib/server/v2/leads.js';
import { listLeads, FILTER_FIELDS } from '$lib/server/v2/leads.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { getOrgPeopleAndTeams, resolveMe } from '$lib/server/v2/org-people.js';
import { getTags } from '$lib/server/v2/tags.js';
/**
* Server load, not a universal one. The access token is an httpOnly cookie;
* a `+page.js` would have to run this fetch in the browser too, where that
* cookie is deliberately unreadable.
*
* Only filters the API actually applies are forwarded. A parameter that
* changes the URL and nothing else teaches people the filter bar is decorative.
*
* The pickers are fetched here rather than inside `listLeads` for the same
* reason as `tickets.js`: a picker fetch folded into the list read would cost
* a redundant request on every caller that reads leads for their totals alone.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load({ cookies, url }) {
// Forward the filter params the API already understands, so a filtered list
// and its totals are produced by one query with one WHERE clause.
const params = new URLSearchParams();
for (const key of ['search', 'status', 'source', 'rating', 'limit']) {
export async function load({ cookies, url, locals }) {
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'leads'));
for (const key of ['search', 'rating', 'limit']) {
const value = url.searchParams.get(key);
if (value) params.set(key, value);
}
const { results, totals } = await listLeads({ cookies }, params);
return { leads: results, totals };
const [{ results, totals }, orgPeople, tagList] = await Promise.all([
listLeads({ cookies }, params),
getOrgPeopleAndTeams(cookies),
// A failed tag fetch should cost the Tag dropdown in the filter bar, not
// the whole list. Follows the tickets.js pattern; see the note there.
getTags({ cookies }).catch(() => ({ tags: [] }))
]);
return {
// `listLeads` returns `{ results, totals }`; the page reads `data.leads`,
// so this renames rather than spreading `list` verbatim.
leads: results,
totals,
people: orgPeople.people,
tags: tagList.tags ?? [],
meId: resolveMe(orgPeople.people, /** @type {any} */ (locals).user?.email)
};
}

View file

@ -1,4 +1,5 @@
<script>
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
@ -24,8 +25,6 @@
let plural = $derived(t(terms, 'lead.plural', 'Leads'));
let singular = $derived(t(terms, 'lead.singular', 'lead'));
const FILTERS = [];
/**
* The same rule the API counts with, so the highlighted rows and the
* "unworked for more than a week" figure in the header agree. If one moves,
@ -50,7 +49,14 @@
{/snippet}
</PageHeader>
<FilterBar view="All leads" filters={FILTERS} meta="Least recently touched first" />
<FilterBar
page="leads"
url={page.url}
people={data.people}
tags={data.tags}
meId={data.meId}
meta="Least recently touched first"
/>
<div class="v2-scroll">
{#if leads.length === 0}

View file

@ -1,31 +1,108 @@
import { listBoard, listDeals } from '$lib/server/v2/deals.js';
import {
listBoard,
listDeals,
FILTER_FIELDS,
BOARD_FIELDS,
BOARD_PRESETS
} from '$lib/server/v2/deals.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { getOrgPeopleAndTeams, resolveMe } from '$lib/server/v2/org-people.js';
import { getTags } from '$lib/server/v2/tags.js';
/**
* The list and the board are two different queries, not two renderings of one
* result: the table is paginated and the board is grouped and capped per
* column. Only the one being shown is fetched.
*
* `view` is read and forwarded untouched. It is the board/list layout toggle,
* not a filter, and must survive every preset and chip link the same way it
* did before this page grew a filter bar.
*
* `open` and `rotten` are preset-only params, the same shape as `all` on
* /tickets and /tasks: `?open=true` narrows to the working pipeline and
* `?rotten=true` to the stalled subset (`opportunity_views.py:183,186`), and
* neither is one of the descriptor's `fields`, only its `presets`, so
* `readFilters` does not carry them and this load reads them off the URL
* itself. Neither is offered on the board (see BOARD_PRESETS below): the
* kanban endpoint does not read either one.
*
* `BOARD_FIELDS` and `BOARD_PRESETS` say what the board can actually run, and
* live in `deals.js` rather than here. A `+page.server.js` may export only a
* fixed set of names, and SvelteKit answers 500 for the whole route on any
* other one.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load(event) {
const view = event.url.searchParams.get('view') === 'board' ? 'board' : 'list';
const { cookies, url, locals } = event;
const view = url.searchParams.get('view') === 'board' ? 'board' : 'list';
const boardMode = view === 'board';
// Forward only the filters the API implements. An unknown key silently
// doing nothing is how a filter bar starts lying.
const params = new URLSearchParams();
for (const key of ['search', 'account', 'assigned_to', 'tags', 'limit']) {
const value = event.url.searchParams.get(key);
const filters = readFilters(url, 'pipeline');
const params = buildFilterQuery(boardMode ? BOARD_FIELDS : FILTER_FIELDS, filters);
// `search` is the one non-field param the board can also run
// (`kanban_views.py:123`). `limit` and `rotten` are list-only: the board is
// not paginated the same way, and `rotten` is never offered while
// `boardMode` is true (BOARD_PRESETS excludes it). `open` is not forwarded
// from the URL either, but for the opposite reason: board mode sets it
// unconditionally below, because the board can only ever show open stages.
const extraKeys = boardMode ? ['search'] : ['search', 'limit', 'open', 'rotten'];
for (const key of extraKeys) {
const value = url.searchParams.get(key);
if (value) params.set(key, value);
}
if (view === 'board') {
const [orgPeople, tagList] = await Promise.all([
getOrgPeopleAndTeams(cookies),
// A failed tag fetch should cost the Tag dropdown in the filter bar, not
// the whole pipeline. Same pattern as tickets.js and leads.js.
getTags({ cookies }).catch(() => ({ tags: [] }))
]);
const shared = {
people: orgPeople.people,
tags: tagList.tags ?? [],
meId: resolveMe(orgPeople.people, /** @type {any} */ (locals).user?.email),
// Handed to the page even in list mode, so the List<->Board toggle can
// build a board-safe link without a `.svelte` file importing anything
// from this `.server.js` module (SvelteKit forbids that, the same
// protection as `$lib/server/`); the toggle just needs to know which of
// the CURRENT params survive the switch.
boardFields: BOARD_FIELDS
};
if (boardMode) {
// The board renders open stages only: `listBoard` drops every `CLOSED_*`
// column (`deals.js`). So the honest total beside it counts open deals
// too. Without this, the default preset's header would add up won and
// lost deals that no lane on screen displays, which is the same
// number-disagrees-with-rows defect BOARD_FIELDS exists to prevent, just
// arriving by a different route.
params.set('open', 'true');
const { lanes } = await listBoard(event, params);
// The header totals stay the table's: they describe the whole open
// pipeline, which is the same claim on either view.
// Same param set the board itself just ran (see BOARD_FIELDS above), not
// the full FILTER_FIELDS set: a header total narrowed by a filter the
// board ignored would disagree with the cards under it, the exact
// mismatch this restriction exists to remove.
const { totals } = await listDeals(event, new URLSearchParams(params));
return { view, lanes, totals, deals: [] };
return {
view,
lanes,
totals,
deals: [],
onlyFields: BOARD_FIELDS,
onlyPresets: BOARD_PRESETS,
...shared
};
}
const { results, totals } = await listDeals(event, params);
return { view, deals: results, totals, lanes: [] };
return {
view,
deals: results,
totals,
lanes: [],
onlyFields: undefined,
onlyPresets: undefined,
...shared
};
}

View file

@ -1,4 +1,5 @@
<script>
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
import Pill from '$lib/v2/components/Pill.svelte';
@ -7,6 +8,7 @@
import EmptyState from '$lib/v2/components/EmptyState.svelte';
import { money, count, shortDate } from '$lib/v2/format.js';
import { STAGE_LABEL, AGING_TONE, AGING_LABEL } from '$lib/v2/enums.js';
import { activeChips, activePresetKey, withoutParam } from '$lib/v2/filters.js';
import { Columns3, List, Plus } from '@lucide/svelte';
/** @type {{ data: any }} */
@ -23,38 +25,92 @@
render, each is just short. */
let lanes = $derived(data.lanes);
// Only filters actually applied by the query appear as chips.
const FILTERS = [{ key: 'stage', label: 'Stage', value: 'is not Closed' }];
/**
* Whether the current view is actually narrowed, as opposed to merely
* carrying a query string. `page.url.search` alone is the wrong test: on
* this page `?view=board` is a layout toggle, not a filter, so a bare
* "Board" click from the unfiltered list would otherwise claim these
* numbers are filtered when nothing was. `'all'` is pipeline's own
* empty-params preset (see `$lib/v2/filters.js`), its declared default, so
* being on any other preset counts as filtered even when that preset
* (`open`, `stalled`) sets no field a chip would represent.
*/
let isFiltered = $derived(
activeChips('pipeline', page.url, { people: data.people, tags: data.tags }).length > 0 ||
activePresetKey('pipeline', page.url, data.meId) !== 'all'
);
/**
* The List<->Board toggle used to be two static hrefs, `/pipeline` and
* `/pipeline?view=board`, so switching layout silently dropped every active
* filter. Board to List keeps every param and drops only `view`: the list
* can run everything the board could and more. List to Board keeps
* `view=board` plus only the params the board can actually honour
* (`data.boardFields`, always returned by `load` regardless of the current
* view, see the note in `+page.server.js`); the rest are deliberately
* dropped, and it is visible rather than silent, since the chips for them
* disappear along with the params.
*/
let listHref = $derived(withoutParam(page.url, 'view'));
let boardHref = $derived.by(() => {
const next = new URLSearchParams();
next.set('view', 'board');
// `search` mirrors what `+page.server.js` forwards to the board itself
// (`kanban_views.py:123` reads it); it is not one of `boardFields`
// because it is not a descriptor field, just like on the list view.
for (const key of [...(data.boardFields ?? []), 'search']) {
const value = page.url.searchParams.get(key);
if (value) next.set(key, value);
}
return `/pipeline?${next}`;
});
</script>
<PageHeader title="Pipeline">
{#snippet sub()}
<!-- Totals come from the API aggregate, never from the rows on screen. -->
<span class="v2-num">{count(totals.count)}</span> open deals ·
<!-- Totals come from the API aggregate, never from the rows on screen.
Not "open deals": the default view is now the pipeline's own "All
deals" preset (empty params), which includes closed stages, so a word
that was only ever true under the old hardcoded ?open=true would lie
here as soon as somebody switched presets. -->
<span class="v2-num">{count(totals.count)}</span> deals ·
<span class="v2-num">{money(totals.amount_sum)}</span> ·
<span class="v2-num">{money(totals.weighted_sum)}</span> weighted ·
<span class="v2-num" style="color:var(--v2-rust)">{totals.stalled_count}</span> stalled
{/snippet}
{#snippet actions()}
{#if view === 'board'}
<a class="v2-btn v2-btn-quiet" href="/pipeline"><List />List</a>
<a class="v2-btn v2-btn-quiet" href={listHref}><List />List</a>
<span class="v2-btn" aria-current="true"><Columns3 />Board</span>
{:else}
<span class="v2-btn" aria-current="true"><List />List</span>
<a class="v2-btn v2-btn-quiet" href="/pipeline?view=board"><Columns3 />Board</a>
<a class="v2-btn v2-btn-quiet" href={boardHref}><Columns3 />Board</a>
{/if}
<a class="v2-btn v2-btn-primary" href="/pipeline/new"><Plus />New deal</a>
{/snippet}
</PageHeader>
{#if isFiltered}
<p class="v2-sub" style="font-size:11.5px;margin:8px 0 0">
These numbers describe the filtered pipeline.
</p>
{/if}
<!-- The board meta used to read "Drag a card to move a stage". There is a real
move endpoint, but nothing here is draggable, and an interface that names
a gesture it does not support is the specific habit this redesign exists
to break. It says where the stage is actually changed instead. -->
<FilterBar
view="All open deals"
filters={FILTERS}
meta={view === 'board' ? 'Open a deal to change its stage' : 'Sorted by value'}
page="pipeline"
url={page.url}
people={data.people}
tags={data.tags}
meId={data.meId}
onlyFields={data.onlyFields}
onlyPresets={data.onlyPresets}
meta={view === 'board'
? 'Open stages only. Open a deal to change its stage'
: 'Sorted by value'}
/>
{#if view === 'board'}
@ -103,8 +159,8 @@
{:else if deals.length === 0}
<div class="v2-scroll">
<EmptyState
title="No open deals"
body="Every deal is either closed or not created yet. Start one from an account you are already talking to, or convert a lead that is ready."
title="No deals here"
body="Nothing matches this view. Start a deal from an account you are already talking to, convert a lead that is ready, or clear a filter to see more."
>
{#snippet icon()}<Columns3 size={21} />{/snippet}
{#snippet actions()}

View file

@ -0,0 +1,95 @@
import { describe, it, expect } from 'vitest';
// Imported from `deals.js`, not from `+page.server.js`. SvelteKit permits only
// a fixed set of named exports on a `+page.server.js` and answers 500 for the
// whole route on any other one, so these constants cannot live there. This
// test passed while the pipeline page was returning 500 for every request,
// because vitest imports the module directly and never goes through the
// router. Do not "simplify" this back to a route import.
import { BOARD_FIELDS, BOARD_PRESETS } from '$lib/server/v2/deals.js';
import { FILTERS, fieldKeys } from '$lib/v2/filters.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
/**
* The board renders from `/opportunities/kanban/`, a different endpoint from
* the list's `/opportunities/`, with a narrower filter vocabulary:
* `backend/opportunity/views/kanban_views.py:122-137` (`_apply_filters`)
* reads only `search`, `account`, `assigned_to`, `tags`, `closed_on__gte` and
* `closed_on__lte`. `BOARD_FIELDS` names the subset of pipeline's OWN
* descriptor fields that also appear in that list, so the board never offers
* a chip for a param it cannot actually run. Re-check this list against the
* backend file above if either side ever changes; nothing enforces the
* agreement except this test.
*/
const KANBAN_SUPPORTED_PARAMS = [
'search',
'account',
'assigned_to',
'tags',
'closed_on__gte',
'closed_on__lte'
];
describe('BOARD_FIELDS', () => {
it('is a subset of the pipeline descriptor field keys', () => {
const pipelineKeys = fieldKeys(FILTERS.pipeline);
for (const key of BOARD_FIELDS) {
expect(pipelineKeys, `"${key}" is not a pipeline descriptor field`).toContain(key);
}
});
it('names only params the kanban endpoint actually reads', () => {
for (const key of BOARD_FIELDS) {
expect(
KANBAN_SUPPORTED_PARAMS,
`"${key}" is not read by OpportunityKanbanView._apply_filters`
).toContain(key);
}
});
it('excludes stage, lead_source and amount, which the kanban endpoint drops silently', () => {
// These three are real pipeline filters, and real list filters, but the
// kanban view does not read them at all: a chip for one of them on the
// board would sit above cards it never actually filtered.
expect(BOARD_FIELDS).not.toContain('stage');
expect(BOARD_FIELDS).not.toContain('lead_source');
expect(BOARD_FIELDS).not.toContain('amount');
});
});
describe('BOARD_PRESETS', () => {
it('is a subset of the pipeline descriptor preset keys', () => {
const presetKeys = FILTERS.pipeline.presets.map((p) => p.key);
for (const key of BOARD_PRESETS) {
expect(presetKeys, `"${key}" is not a pipeline preset`).toContain(key);
}
});
it('excludes "open" and "stalled", which need params the kanban endpoint ignores', () => {
// "open" writes ?open=true and "stalled" writes ?rotten=true
// (opportunity_views.py:183,186 on the LIST endpoint); the kanban view
// reads neither, so offering either preset on the board would change the
// URL without changing a single card.
expect(BOARD_PRESETS).not.toContain('open');
expect(BOARD_PRESETS).not.toContain('stalled');
});
});
describe('the board-safe param builder', () => {
const url = new URL(
'http://x/pipeline?stage=NEGOTIATION&lead_source=call&amount__gte=5000&amount__lte=10000&assigned_to=aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa&tags=bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
);
it('drops stage, lead_source and the amount range', () => {
const params = buildFilterQuery(BOARD_FIELDS, readFilters(url, 'pipeline'));
expect(params.has('stage')).toBe(false);
expect(params.has('lead_source')).toBe(false);
expect(params.has('amount__gte')).toBe(false);
expect(params.has('amount__lte')).toBe(false);
});
it('keeps assigned_to and tags', () => {
const params = buildFilterQuery(BOARD_FIELDS, readFilters(url, 'pipeline'));
expect(params.get('assigned_to')).toBe('aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa');
expect(params.get('tags')).toBe('bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb');
});
});

View file

@ -1,5 +1,6 @@
import { fail } from '@sveltejs/kit';
import { listArticles, setPublished } from '$lib/server/v2/solutions.js';
import { listArticles, setPublished, FILTER_FIELDS } from '$lib/server/v2/solutions.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { readableError } from '$lib/server/v2/form-errors.js';
/**
@ -9,8 +10,8 @@ import { readableError } from '$lib/server/v2/form-errors.js';
* @type {import('./$types').PageServerLoad}
*/
export async function load({ cookies, locals, url }) {
const params = new URLSearchParams();
for (const key of ['search', 'status', 'limit']) {
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'solutions'));
for (const key of ['search', 'limit']) {
const value = url.searchParams.get(key);
if (value) params.set(key, value);
}

View file

@ -9,6 +9,7 @@
* information rather than a button. It still says so. Knowing a colleague
* has to release it is worth more than a control that answers 403.
*/
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
@ -24,17 +25,6 @@
let articles = $derived(data.articles);
let totals = $derived(data.totals);
let filters = $derived(
[
data.status ? { key: 'status', label: 'Status', value: data.status } : null,
data.visibility ? { key: 'visibility', label: 'Visibility', value: data.visibility } : null,
data.search ? { key: 'search', label: 'Search', value: data.search } : null
].filter(Boolean)
);
/** Whether any filter is on, which decides what an empty result means. */
let filtered = $derived(filters.length > 0);
</script>
<PageHeader title="Knowledge base">
@ -51,6 +41,16 @@
{/snippet}
</PageHeader>
<!-- Unconditional, unlike every other v2 list page's "filtered list" caption:
`solution_views.py:122-132` counts the five cards over the whole base on
purpose, never the filtered page, because they partition the knowledge
base and recomputing them inside `?status=draft` would leave the other
four reading zero. True whether or not a filter is applied, so it always
renders. -->
<p class="v2-sub" style="font-size:11.5px;margin:8px 0 0">
These numbers cover every article, not just the ones shown.
</p>
<div class="v2-pad" style="padding-top:14px;flex:none">
<div class="v2-stats">
<StatCard
@ -70,8 +70,8 @@
</div>
<FilterBar
view={filtered ? 'Filtered, last edited first' : 'All articles, last edited first'}
{filters}
page="solutions"
url={page.url}
meta="Published means customers can be shown it. Approving it is a separate step"
/>
@ -82,14 +82,14 @@
<div class="v2-scroll">
{#if articles.length === 0}
<EmptyState
title={filtered ? 'No articles match that' : 'No articles yet'}
body={filtered
title={page.url.search ? 'No articles match that' : 'No articles yet'}
body={page.url.search
? 'Nothing in the knowledge base matches those filters. Clearing them shows everything.'
: 'Write the answer once, link it from the tickets that ask for it, and stop retyping it. The first one usually comes straight out of a ticket you just resolved.'}
>
{#snippet icon()}<BookOpen size={21} />{/snippet}
{#snippet actions()}
{#if filtered}
{#if page.url.search}
<a class="v2-btn" href="/solutions">Clear filters</a>
{/if}
<a class="v2-btn v2-btn-primary" href="/solutions/new">New article</a>
@ -168,7 +168,7 @@
<p class="v2-sub v2-pad" style="font-size:12px;padding-bottom:24px">
Showing <span class="v2-num">{articles.length}</span> of
<span class="v2-num">{count(totals.matched)}</span>
{#if filtered}
{#if page.url.search}
· <a href="/solutions" style="color:inherit">clear filters</a>
{/if}
</p>

View file

@ -1,5 +1,7 @@
import { fail } from '@sveltejs/kit';
import { listTasks, setTaskDone } from '$lib/server/v2/tasks.js';
import { listTasks, setTaskDone, FILTER_FIELDS } from '$lib/server/v2/tasks.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { getOrgPeopleAndTeams, resolveMe } from '$lib/server/v2/org-people.js';
/**
* The task queue.
@ -12,24 +14,35 @@ import { listTasks, setTaskDone } from '$lib/server/v2/tasks.js';
* @type {import('./$types').PageServerLoad}
*/
export async function load(event) {
const showAll = event.url.searchParams.get('all') === '1';
const params = new URLSearchParams();
const search = event.url.searchParams.get('q');
if (search) params.set('search', search);
const priority = event.url.searchParams.get('priority');
if (priority) params.set('priority', priority);
const { url, locals } = event;
const showAll = url.searchParams.get('all') === '1';
const { results, totals, owners } = await listTasks(event, params);
const filters = readFilters(url, 'tasks');
const params = buildFilterQuery(FILTER_FIELDS, filters);
const search = url.searchParams.get('q');
if (search) params.set('search', search);
const [{ results, totals, owners }, orgPeople] = await Promise.all([
listTasks(event, params),
getOrgPeopleAndTeams(event.cookies)
]);
// `all=1` and an explicit `?status=` both mean the viewer asked for something
// other than the to-do list, so the open-only strip stands down for either.
// Without this, `status=Completed` fetches the completed tasks and then
// drops all of them, and the page reads as "you have none".
const explicitStatus = Boolean(filters.status);
return {
// Filtered here rather than with `?status=`, because the totals the header
// reads have to cover both; "3 of 11 open" needs the 11.
tasks: showAll ? results : results.filter((task) => !task.is_done),
// Filtered here rather than with `?status=` alone, because the totals the
// header reads have to cover both; "3 of 11 open" needs the 11.
tasks: showAll || explicitStatus ? results : results.filter((task) => !task.is_done),
totals,
owners,
showAll,
filters: { q: search ?? '', priority: priority ?? '' },
canDelete: event.locals.profile?.role === 'ADMIN'
people: orgPeople.people,
meId: resolveMe(orgPeople.people, /** @type {any} */ (locals).user?.email),
canDelete: locals.profile?.role === 'ADMIN'
};
}

View file

@ -9,6 +9,7 @@
* shows a pending state while the request is in flight and takes whatever
* the server says, rather than assuming it worked.
*/
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SectionTabs from '$lib/v2/components/SectionTabs.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
@ -48,6 +49,12 @@
{/snippet}
</PageHeader>
{#if page.url.search}
<p class="v2-sub" style="font-size:11.5px;margin:8px 0 0">
These numbers describe the filtered list.
</p>
{/if}
<SectionTabs set="tasks" />
<div class="v2-pad" style="padding-top:14px;flex:none">
@ -75,16 +82,7 @@
</div>
</div>
<FilterBar
view={data.showAll ? 'All tasks' : 'Open tasks'}
filters={[
data.showAll ? null : { key: 'status', label: 'Status', value: 'is not Completed' },
data.filters.priority
? { key: 'priority', label: 'Priority', value: data.filters.priority }
: null
].filter(Boolean)}
meta="Newest first"
/>
<FilterBar page="tasks" url={page.url} people={data.people} meId={data.meId} meta="Newest first" />
{#if form?.error}
<p class="v2-pad v2-form-error" role="alert">{form.error}</p>

View file

@ -12,7 +12,10 @@ export async function load(event) {
const [options, tickets, deals, leads] = await Promise.allSettled([
getTaskFormOptions(event),
listTickets(event, new URLSearchParams({ limit: '100' })),
listDeals(event, new URLSearchParams({ limit: '100' })),
// Open deals only, matching what this picker offered before `listDeals`
// stopped assuming it: attaching a task to a deal you already closed is
// an edge case the picker does not need to carry by default.
listDeals(event, new URLSearchParams({ open: 'true', limit: '100' })),
listLeads(event, new URLSearchParams({ limit: '100' }))
]);
const settled = options.status === 'fulfilled' ? options.value : { owners: [], accounts: [] };

View file

@ -21,7 +21,10 @@ export async function load(event) {
const [options, tickets, deals, leads] = await Promise.allSettled([
getTaskFormOptions(event),
listTickets(event, new URLSearchParams({ limit: '100' })),
listDeals(event, new URLSearchParams({ limit: '100' })),
// Open deals only, matching what this picker offered before `listDeals`
// stopped assuming it: attaching a task to a deal you already closed is
// an edge case the picker does not need to carry by default.
listDeals(event, new URLSearchParams({ open: 'true', limit: '100' })),
listLeads(event, new URLSearchParams({ limit: '100' }))
]);

View file

@ -1,22 +1,29 @@
import { listTickets, OPEN_STATUSES } from '$lib/server/v2/tickets.js';
import { listTickets, OPEN_STATUSES, FILTER_FIELDS } from '$lib/server/v2/tickets.js';
import { readFilters, buildFilterQuery } from '$lib/server/v2/filter-params.js';
import { getOrgPeopleAndTeams, resolveMe } from '$lib/server/v2/org-people.js';
import { getTags } from '$lib/server/v2/tags.js';
/**
* Only filters the API actually applies are forwarded. A parameter that
* changes the URL and nothing else teaches people the filter bar is decorative.
*
* The queue defaults to open tickets, which is what the mock page claimed in a
* chip it could not act on. `status` is repeatable and the API switches to
* `status__in` when more than one arrives, so "open" is three values rather
* than a fourth definition of the word.
* The queue defaults to open tickets. `status` is repeatable and the API
* switches to `status__in` when more than one arrives, so "open" is three
* values rather than a fourth definition of the word.
*
* The pickers are fetched here rather than inside `listTickets` because
* `getSettingsHub` calls read functions for their totals alone, and a picker
* fetch folded into one costs a redundant request on every hub load.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load({ cookies, url }) {
const params = new URLSearchParams();
for (const key of ['search', 'priority', 'case_type', 'account', 'assigned_to', 'limit']) {
const value = url.searchParams.get(key);
if (value) params.set(key, value);
}
export async function load({ cookies, url, locals }) {
const params = buildFilterQuery(FILTER_FIELDS, readFilters(url, 'tickets'));
const search = url.searchParams.get('search');
if (search) params.set('search', search);
const limit = url.searchParams.get('limit');
if (limit) params.set('limit', limit);
const status = url.searchParams.get('status') ?? '';
const showAll = url.searchParams.get('all') === '1';
@ -26,13 +33,26 @@ export async function load({ cookies, url }) {
for (const open of OPEN_STATUSES) params.append('status', open);
}
const { results, totals } = await listTickets({ cookies }, params);
const [{ results, totals }, orgPeople, tagList] = await Promise.all([
listTickets({ cookies }, params),
getOrgPeopleAndTeams(cookies),
// getTags has no fallback of its own: on /settings/tags a failed fetch is
// meant to surface as an error. Here the tag list is just one picker in
// the filter bar, so the degradation belongs to this caller, not to the
// shared function. Losing the picker should cost the Tag dropdown, not
// the whole queue.
getTags({ cookies }).catch(() => ({ tags: [] }))
]);
return {
tickets: results,
totals,
showAll,
status,
search: params.get('search') ?? '',
priority: params.get('priority') ?? ''
priority: params.get('priority') ?? '',
people: orgPeople.people,
tags: tagList.tags ?? [],
meId: resolveMe(orgPeople.people, /** @type {any} */ (locals).user?.email)
};
}

View file

@ -1,4 +1,5 @@
<script>
import { page } from '$app/state';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import SectionTabs from '$lib/v2/components/SectionTabs.svelte';
import FilterBar from '$lib/v2/components/FilterBar.svelte';
@ -68,14 +69,6 @@
clay: 'var(--v2-clay)',
slate: 'var(--v2-slate)'
};
let filters = $derived(
[
{ key: 'status', label: 'Status', value: data.showAll ? 'any' : 'open' },
data.priority ? { key: 'priority', label: 'Priority', value: data.priority } : null,
data.search ? { key: 'search', label: 'Search', value: data.search } : null
].filter(Boolean)
);
</script>
<PageHeader title="Tickets">
@ -92,14 +85,21 @@
{/snippet}
</PageHeader>
{#if page.url.search}
<p class="v2-sub" style="font-size:11.5px;margin:8px 0 0">These numbers describe the filtered queue.</p>
{/if}
<!-- Approvals and Analytics were buttons in this header that went nowhere.
They are sibling pages, so they belong in a tab strip that also tells you
which one you are on. -->
<SectionTabs set="tickets" />
<FilterBar
view={data.showAll ? 'Everything, newest first' : 'Open, newest first'}
{filters}
page="tickets"
url={page.url}
people={data.people}
tags={data.tags}
meId={data.meId}
meta="First-reply targets come from each ticket's SLA hours"
/>