From 3faf6ee41011999ec3c500d7a797fff3bece80b4 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Tue, 4 Aug 2026 22:48:47 +0530 Subject: [PATCH] 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. --- frontend/src/lib/server/v2/accounts.js | 52 ++- frontend/src/lib/server/v2/contacts.js | 3 + frontend/src/lib/server/v2/deals.js | 53 ++- frontend/src/lib/server/v2/documents.js | 22 +- frontend/src/lib/server/v2/estimates.js | 24 +- frontend/src/lib/server/v2/filter-params.js | 96 +++++ .../src/lib/server/v2/filter-params.test.js | 134 ++++++ frontend/src/lib/server/v2/invoices.js | 25 ++ frontend/src/lib/server/v2/invoices.test.js | 117 +++++ frontend/src/lib/server/v2/leads.js | 3 + frontend/src/lib/server/v2/org-people.js | 26 +- frontend/src/lib/server/v2/org-people.test.js | 27 +- frontend/src/lib/server/v2/recurring.js | 17 +- frontend/src/lib/server/v2/solutions.js | 9 + frontend/src/lib/server/v2/tasks.js | 9 + frontend/src/lib/server/v2/tickets.js | 8 + .../src/lib/v2/components/FilterBar.svelte | 342 +++++++++++++-- frontend/src/lib/v2/enums.js | 33 ++ frontend/src/lib/v2/filters.js | 406 ++++++++++++++++++ frontend/src/lib/v2/filters.test.js | 282 ++++++++++++ frontend/src/routes/(app)/+layout.server.js | 11 +- .../src/routes/(app)/accounts/+page.server.js | 38 +- .../src/routes/(app)/accounts/+page.svelte | 41 +- .../src/routes/(app)/contacts/+page.server.js | 35 +- .../src/routes/(app)/contacts/+page.svelte | 16 +- .../routes/(app)/documents/+page.server.js | 25 +- .../src/routes/(app)/documents/+page.svelte | 26 +- .../src/routes/(app)/invoices/+page.server.js | 41 +- .../src/routes/(app)/invoices/+page.svelte | 15 +- .../(app)/invoices/estimates/+page.server.js | 27 +- .../(app)/invoices/estimates/+page.svelte | 12 +- .../(app)/invoices/recurring/+page.server.js | 12 +- .../(app)/invoices/recurring/+page.svelte | 9 +- .../src/routes/(app)/leads/+page.server.js | 39 +- frontend/src/routes/(app)/leads/+page.svelte | 12 +- .../src/routes/(app)/pipeline/+page.server.js | 101 ++++- .../src/routes/(app)/pipeline/+page.svelte | 78 +++- .../(app)/pipeline/board-fields.test.js | 95 ++++ .../routes/(app)/solutions/+page.server.js | 7 +- .../src/routes/(app)/solutions/+page.svelte | 34 +- .../src/routes/(app)/tasks/+page.server.js | 39 +- frontend/src/routes/(app)/tasks/+page.svelte | 18 +- .../(app)/tasks/[id]/edit/+page.server.js | 5 +- .../routes/(app)/tasks/new/+page.server.js | 5 +- .../src/routes/(app)/tickets/+page.server.js | 46 +- .../src/routes/(app)/tickets/+page.svelte | 20 +- 46 files changed, 2278 insertions(+), 217 deletions(-) create mode 100644 frontend/src/lib/server/v2/filter-params.js create mode 100644 frontend/src/lib/server/v2/filter-params.test.js create mode 100644 frontend/src/lib/server/v2/invoices.test.js create mode 100644 frontend/src/lib/v2/filters.js create mode 100644 frontend/src/lib/v2/filters.test.js create mode 100644 frontend/src/routes/(app)/pipeline/board-fields.test.js diff --git a/frontend/src/lib/server/v2/accounts.js b/frontend/src/lib/server/v2/accounts.js index 031d726a..824bd7b3 100644 --- a/frontend/src/lib/server/v2/accounts.js +++ b/frontend/src/lib/server/v2/accounts.js @@ -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. * diff --git a/frontend/src/lib/server/v2/contacts.js b/frontend/src/lib/server/v2/contacts.js index afa1c516..13317a6e 100644 --- a/frontend/src/lib/server/v2/contacts.js +++ b/frontend/src/lib/server/v2/contacts.js @@ -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; diff --git a/frontend/src/lib/server/v2/deals.js b/frontend/src/lib/server/v2/deals.js index 1f638ae6..e027b08a 100644 --- a/frontend/src/lib/server/v2/deals.js +++ b/frontend/src/lib/server/v2/deals.js @@ -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. * diff --git a/frontend/src/lib/server/v2/documents.js b/frontend/src/lib/server/v2/documents.js index ba04fbd4..ed9779bb 100644 --- a/frontend/src/lib/server/v2/documents.js +++ b/frontend/src/lib/server/v2/documents.js @@ -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=` 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 ?? []; diff --git a/frontend/src/lib/server/v2/estimates.js b/frontend/src/lib/server/v2/estimates.js index c194661f..6d7b093e 100644 --- a/frontend/src/lib/server/v2/estimates.js +++ b/frontend/src/lib/server/v2/estimates.js @@ -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); diff --git a/frontend/src/lib/server/v2/filter-params.js b/frontend/src/lib/server/v2/filter-params.js new file mode 100644 index 00000000..10d7a22d --- /dev/null +++ b/frontend/src/lib/server/v2/filter-params.js @@ -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} + */ +export function readFilters(url, pageKey) { + const descriptor = FILTERS[pageKey]; + if (!descriptor) return {}; + + /** @type {Record} */ + 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} 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; +} diff --git a/frontend/src/lib/server/v2/filter-params.test.js b/frontend/src/lib/server/v2/filter-params.test.js new file mode 100644 index 00000000..a67983d7 --- /dev/null +++ b/frontend/src/lib/server/v2/filter-params.test.js @@ -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(); + }); +}); diff --git a/frontend/src/lib/server/v2/invoices.js b/frontend/src/lib/server/v2/invoices.js index 04283733..8ddf3bca 100644 --- a/frontend/src/lib/server/v2/invoices.js +++ b/frontend/src/lib/server/v2/invoices.js @@ -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] */ diff --git a/frontend/src/lib/server/v2/invoices.test.js b/frontend/src/lib/server/v2/invoices.test.js new file mode 100644 index 00000000..af0bf388 --- /dev/null +++ b/frontend/src/lib/server/v2/invoices.test.js @@ -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); + }); +}); diff --git a/frontend/src/lib/server/v2/leads.js b/frontend/src/lib/server/v2/leads.js index b2338a48..63ff2786 100644 --- a/frontend/src/lib/server/v2/leads.js +++ b/frontend/src/lib/server/v2/leads.js @@ -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 diff --git a/frontend/src/lib/server/v2/org-people.js b/frontend/src/lib/server/v2/org-people.js index e38adc79..9961c0d3 100644 --- a/frontend/src/lib/server/v2/org-people.js +++ b/frontend/src/lib/server/v2/org-people.js @@ -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; +} diff --git a/frontend/src/lib/server/v2/org-people.test.js b/frontend/src/lib/server/v2/org-people.test.js index d4738c86..80f89c49 100644 --- a/frontend/src/lib/server/v2/org-people.test.js +++ b/frontend/src/lib/server/v2/org-people.test.js @@ -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); + }); +}); diff --git a/frontend/src/lib/server/v2/recurring.js b/frontend/src/lib/server/v2/recurring.js index 3354efce..ae1a8f7c 100644 --- a/frontend/src/lib/server/v2/recurring.js +++ b/frontend/src/lib/server/v2/recurring.js @@ -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); diff --git a/frontend/src/lib/server/v2/solutions.js b/frontend/src/lib/server/v2/solutions.js index 2b8beca0..be960b38 100644 --- a/frontend/src/lib/server/v2/solutions.js +++ b/frontend/src/lib/server/v2/solutions.js @@ -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. * diff --git a/frontend/src/lib/server/v2/tasks.js b/frontend/src/lib/server/v2/tasks.js index 368c4ad9..aadc0e81 100644 --- a/frontend/src/lib/server/v2/tasks.js +++ b/frontend/src/lib/server/v2/tasks.js @@ -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 diff --git a/frontend/src/lib/server/v2/tickets.js b/frontend/src/lib/server/v2/tickets.js index 59c9a13e..f30f7cda 100644 --- a/frontend/src/lib/server/v2/tickets.js +++ b/frontend/src/lib/server/v2/tickets.js @@ -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. * diff --git a/frontend/src/lib/v2/components/FilterBar.svelte b/frontend/src/lib/v2/components/FilterBar.svelte index 9383030d..1ca052f8 100644 --- a/frontend/src/lib/v2/components/FilterBar.svelte +++ b/frontend/src/lib/v2/components/FilterBar.svelte @@ -1,50 +1,332 @@
- +
+ + {activeLabel} + + +
+ {#each visiblePresets.filter(usable) as preset (preset.key)} + + {preset.label} + + {/each} +
+
- {#each filters as f (f.key)} + {#each chips as chip (chip.key)} - {f.label} - {f.value} - + {chip.label} + {chip.value} + {/each} - + {#if visibleFields.length > 0} +
+ + + Filter + +
+ + {#each [...url.searchParams] as [key, value] (key)} + {#if !descriptor.fields.some((/** @type {any} */ f) => f.key === key || f.gteKey === key || f.lteKey === key)} + + {/if} + {/each} + + {#each visibleFields as field (field.key)} + + {/each} + +
+ + Clear all +
+
+
+ {/if} {#if meta} {meta} {/if}
+ + diff --git a/frontend/src/lib/v2/enums.js b/frontend/src/lib/v2/enums.js index d83edd22..0fe8c673 100644 --- a/frontend/src/lib/v2/enums.js +++ b/frontend/src/lib/v2/enums.js @@ -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']; diff --git a/frontend/src/lib/v2/filters.js b/frontend/src/lib/v2/filters.js new file mode 100644 index 00000000..0f645749 --- /dev/null +++ b/frontend/src/lib/v2/filters.js @@ -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 }} 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} */ +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=` 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} */ 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; +} diff --git a/frontend/src/lib/v2/filters.test.js b/frontend/src/lib/v2/filters.test.js new file mode 100644 index 00000000..178a1c2e --- /dev/null +++ b/frontend/src/lib/v2/filters.test.js @@ -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=` 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'); + }); +}); diff --git a/frontend/src/routes/(app)/+layout.server.js b/frontend/src/routes/(app)/+layout.server.js index 1644d589..46a988cc 100644 --- a/frontend/src/routes/(app)/+layout.server.js +++ b/frontend/src/routes/(app)/+layout.server.js @@ -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. diff --git a/frontend/src/routes/(app)/accounts/+page.server.js b/frontend/src/routes/(app)/accounts/+page.server.js index 708724cf..838242c5 100644 --- a/frontend/src/routes/(app)/accounts/+page.server.js +++ b/frontend/src/routes/(app)/accounts/+page.server.js @@ -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) + }; } diff --git a/frontend/src/routes/(app)/accounts/+page.svelte b/frontend/src/routes/(app)/accounts/+page.svelte index 3ef42a41..f3e930fc 100644 --- a/frontend/src/routes/(app)/accounts/+page.svelte +++ b/frontend/src/routes/(app)/accounts/+page.svelte @@ -1,9 +1,11 @@ {#snippet sub()} - {count(totals.count)} accounts · - {count(totals.customers)} with a deal won + {count(totals.count)} accounts + + {#if (totals.shown ?? 0) >= (totals.count ?? 0)} + · {count(totals.customers)} with a deal won + {/if} {/snippet} {#snippet actions()} New account {/snippet} - +{#if isFiltered} +

+ These numbers describe the filtered list. +

+{/if} + +
{#if accounts.length === 0} diff --git a/frontend/src/routes/(app)/contacts/+page.server.js b/frontend/src/routes/(app)/contacts/+page.server.js index e9fc4e2c..1d3d277d 100644 --- a/frontend/src/routes/(app)/contacts/+page.server.js +++ b/frontend/src/routes/(app)/contacts/+page.server.js @@ -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) + }; } diff --git a/frontend/src/routes/(app)/contacts/+page.svelte b/frontend/src/routes/(app)/contacts/+page.svelte index c7407269..59ee4e5a 100644 --- a/frontend/src/routes/(app)/contacts/+page.svelte +++ b/frontend/src/routes/(app)/contacts/+page.svelte @@ -1,4 +1,5 @@ @@ -40,7 +35,14 @@ {/snippet} - +
{#if contacts.length === 0} diff --git a/frontend/src/routes/(app)/documents/+page.server.js b/frontend/src/routes/(app)/documents/+page.server.js index 0cbdedb3..7af50998 100644 --- a/frontend/src/routes/(app)/documents/+page.server.js +++ b/frontend/src/routes/(app)/documents/+page.server.js @@ -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); } diff --git a/frontend/src/routes/(app)/documents/+page.svelte b/frontend/src/routes/(app)/documents/+page.svelte index e4f0303f..883165c8 100644 --- a/frontend/src/routes/(app)/documents/+page.svelte +++ b/frontend/src/routes/(app)/documents/+page.svelte @@ -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 @@ {count(totals.inactive)} archived {/snippet} {#snippet actions()} - Upload {/snippet} +{#if page.url.search} +

+ These numbers describe the filtered list. +

+{/if} +
- (showInactive = true)} - meta="Newest first" -/> +
- {#if visible.length === 0} + {#if documents.length === 0} - {#each visible as d (d.id)} + {#each documents as d (d.id)} {@const Icon = iconFor(d.file_kind)} @@ -184,7 +180,7 @@

- Showing {visible.length} of + Showing {documents.length} of {count(totals.count)}

{/if} diff --git a/frontend/src/routes/(app)/invoices/+page.server.js b/frontend/src/routes/(app)/invoices/+page.server.js index 0db82b0a..77f5335e 100644 --- a/frontend/src/routes/(app)/invoices/+page.server.js +++ b/frontend/src/routes/(app)/invoices/+page.server.js @@ -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} */ diff --git a/frontend/src/routes/(app)/invoices/+page.svelte b/frontend/src/routes/(app)/invoices/+page.svelte index 0e8a2108..8f1e21fc 100644 --- a/frontend/src/routes/(app)/invoices/+page.svelte +++ b/frontend/src/routes/(app)/invoices/+page.svelte @@ -1,4 +1,5 @@ {#snippet sub()} - - {count(totals.count)} open deals · + + {count(totals.count)} deals · {money(totals.amount_sum)} · {money(totals.weighted_sum)} weighted · {totals.stalled_count} stalled {/snippet} {#snippet actions()} {#if view === 'board'} - List + List Board {:else} List - Board + Board {/if} New deal {/snippet} +{#if isFiltered} +

+ These numbers describe the filtered pipeline. +

+{/if} + {#if view === 'board'} @@ -103,8 +159,8 @@ {:else if deals.length === 0}
{#snippet icon()}{/snippet} {#snippet actions()} diff --git a/frontend/src/routes/(app)/pipeline/board-fields.test.js b/frontend/src/routes/(app)/pipeline/board-fields.test.js new file mode 100644 index 00000000..413ab4ff --- /dev/null +++ b/frontend/src/routes/(app)/pipeline/board-fields.test.js @@ -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'); + }); +}); diff --git a/frontend/src/routes/(app)/solutions/+page.server.js b/frontend/src/routes/(app)/solutions/+page.server.js index cf6dbd2e..6221ba53 100644 --- a/frontend/src/routes/(app)/solutions/+page.server.js +++ b/frontend/src/routes/(app)/solutions/+page.server.js @@ -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); } diff --git a/frontend/src/routes/(app)/solutions/+page.svelte b/frontend/src/routes/(app)/solutions/+page.svelte index bdc41667..db3cc420 100644 --- a/frontend/src/routes/(app)/solutions/+page.svelte +++ b/frontend/src/routes/(app)/solutions/+page.svelte @@ -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); @@ -51,6 +41,16 @@ {/snippet} + +

+ These numbers cover every article, not just the ones shown. +

+
@@ -82,14 +82,14 @@
{#if articles.length === 0} {#snippet icon()}{/snippet} {#snippet actions()} - {#if filtered} + {#if page.url.search} Clear filters {/if} New article @@ -168,7 +168,7 @@

Showing {articles.length} of {count(totals.matched)} - {#if filtered} + {#if page.url.search} · clear filters {/if}

diff --git a/frontend/src/routes/(app)/tasks/+page.server.js b/frontend/src/routes/(app)/tasks/+page.server.js index c9204f72..29a79f77 100644 --- a/frontend/src/routes/(app)/tasks/+page.server.js +++ b/frontend/src/routes/(app)/tasks/+page.server.js @@ -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' }; } diff --git a/frontend/src/routes/(app)/tasks/+page.svelte b/frontend/src/routes/(app)/tasks/+page.svelte index bb2a0e36..f6a64aaa 100644 --- a/frontend/src/routes/(app)/tasks/+page.svelte +++ b/frontend/src/routes/(app)/tasks/+page.svelte @@ -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} +{#if page.url.search} +

+ These numbers describe the filtered list. +

+{/if} +
@@ -75,16 +82,7 @@
- + {#if form?.error} diff --git a/frontend/src/routes/(app)/tasks/[id]/edit/+page.server.js b/frontend/src/routes/(app)/tasks/[id]/edit/+page.server.js index a39f7ff4..acebf598 100644 --- a/frontend/src/routes/(app)/tasks/[id]/edit/+page.server.js +++ b/frontend/src/routes/(app)/tasks/[id]/edit/+page.server.js @@ -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: [] }; diff --git a/frontend/src/routes/(app)/tasks/new/+page.server.js b/frontend/src/routes/(app)/tasks/new/+page.server.js index cbfd34bc..5947a8c9 100644 --- a/frontend/src/routes/(app)/tasks/new/+page.server.js +++ b/frontend/src/routes/(app)/tasks/new/+page.server.js @@ -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' })) ]); diff --git a/frontend/src/routes/(app)/tickets/+page.server.js b/frontend/src/routes/(app)/tickets/+page.server.js index c64cabd0..d7218a67 100644 --- a/frontend/src/routes/(app)/tickets/+page.server.js +++ b/frontend/src/routes/(app)/tickets/+page.server.js @@ -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) }; } diff --git a/frontend/src/routes/(app)/tickets/+page.svelte b/frontend/src/routes/(app)/tickets/+page.svelte index a5de64c0..0156e09d 100644 --- a/frontend/src/routes/(app)/tickets/+page.svelte +++ b/frontend/src/routes/(app)/tickets/+page.svelte @@ -1,4 +1,5 @@ @@ -92,14 +85,21 @@ {/snippet} +{#if page.url.search} +

These numbers describe the filtered queue.

+{/if} +