feat: Stripe-style filter bar for freight backoffice (pilot: contracts)

Replace the ad-hoc filter controls with a URL-linkable pill filter bar:
each filter is a pill that opens a type-aware popover (text/enum/date/
number/boolean, each with the right operator set), overflow filters live
behind a searchable "More filters" menu, sorting is a separate control,
and filter state round-trips through the URL query string (shareable,
back/forward-safe, backward compatible with existing ?statuses=A,B links).

Frontend (apps/edr-freight-web/backoffice/src/components/filters/):
- FilterDef schema + a pure url.ts codec (parse/serialize/toApiParams),
  with a 24-case round-trip + malformed-input test suite
- useFilters hook driving react-query params straight from useSearchParams,
  debounced search, saved views in localStorage (@mantine/hooks
  useLocalStorage), page-reset-on-filter-change baked into one
  setSearchParams call instead of a separate effect
- FilterBar/FilterPill/OperatorSelect/MoreFiltersMenu/SortControl +
  per-type popover bodies (Mantine)
- ContractRequestsPage migrated end to end as the pilot

Backend (apps/edr-freight-api):
- pagination.util: applySort() — whitelisted sortBy resolved against a
  per-module column map (never interpolated), with a mandatory `id ASC`
  tiebreaker so paginating a non-unique sort can't drop/duplicate rows
- facets.util: computeFacets() — one GROUP BY per enum column, each
  omitting its own predicate, so picking a value doesn't hide its siblings
- contracts/bookings: list-summary now returns real filter-scoped facet
  counts (contracts' getStatusCounts was unfiltered/global; superseded)
- deleted drivers/vehicles findAllWithFilters — dead code that
  interpolated an unwhitelisted sortBy straight into orderBy()
- migration: missing bookings(status)/wagons(status) indexes +
  (created_at DESC, id ASC) partials on the hot list tables

UI polish pass: inactive pill uses the opaque "default" variant instead
of a faint tinted outline, active pill uses "light" not "filled", larger
X hit target, applied filters sort first, sort control separated behind
a divider on the right and wraps independently from the filter row,
popover option rows are fully clickable (count moved inside the native
label) with bigger hit area and font, fixed a real date-filter bug where
the calendar's own portal falsely registered as an "outside click" and
closed the popover, and fixed a timezone bug where bare YYYY-MM-DD
strings were parsed as UTC instead of local time (shifts a day for EAT).

Not in this commit: rollout to the other ~59 list pages, the Ethiopian-
calendar DateBody branch, and the Family-B (client-side) bridge mode —
tracked in the filter-bar plan.
This commit is contained in:
Nathnael
2026-08-14 13:18:46 +00:00
parent ab5a4117df
commit 4a4d3077d7
32 changed files with 1879 additions and 376 deletions

View File

@@ -41,4 +41,16 @@ export class PaginationQueryDto {
@Transform(({ value }) => String(value).toUpperCase())
@IsIn(['ASC', 'DESC'])
sortOrder?: 'ASC' | 'DESC';
/**
* Column to sort by, as a public field name (not a raw SQL column). The
* actual whitelist lives in `applySort`'s `sortable` map at each call site,
* not here — a per-DTO `@IsIn` is opt-in and has been forgotten before.
* An unrecognized value falls back silently rather than 400ing, so a stale
* bookmark or shared link never breaks.
*/
@ApiPropertyOptional({ description: 'Public field name; unknown values fall back to the endpoint default.' })
@IsOptional()
@Transform(({ value }) => (typeof value === 'string' && value.trim() ? value.trim() : undefined))
sortBy?: string;
}

View File

@@ -0,0 +1,48 @@
import { ObjectLiteral, SelectQueryBuilder } from 'typeorm';
export interface FacetBucket {
value: string;
count: number;
}
/**
* One `GROUP BY` query per faceted column, each with every OTHER active
* filter applied but its OWN predicate omitted. That omission is the point:
* with `status=SUBMITTED` selected, the status facet still reports
* `APPROVED: 8` so the user can switch, while the freightType facet reflects
* only the SUBMITTED-scoped set. Omit `search` from nothing — it's a scope,
* not a pill, and stays applied in every facet.
*
* Capped at 50 buckets per column — FK-id facets (warehouseId, yardId) can
* have real cardinality; beyond 50 the frontend should fall back to a
* typeahead instead of a checkbox list. Never facet a column whose popover
* would need its own search box (references, plate numbers, free text).
*
* @param base builds a FRESH query builder (soft-delete guard only,
* no filters) — called once per facet column.
* @param applyFilters applies every filter to `qb`, using `omit` to skip
* one column's own predicate.
* @param columns facet key -> "alias.column" SQL reference.
*/
export async function computeFacets<T extends ObjectLiteral>(
base: () => SelectQueryBuilder<T>,
applyFilters: (qb: SelectQueryBuilder<T>, omit?: string) => void,
columns: Record<string, string>,
): Promise<Record<string, FacetBucket[]>> {
const entries = await Promise.all(
Object.entries(columns).map(async ([key, column]) => {
const qb = base();
applyFilters(qb, key);
const rows = await qb
.select(column, 'value')
.addSelect('COUNT(*)::int', 'count')
.andWhere(`${column} IS NOT NULL`)
.groupBy(column)
.orderBy('count', 'DESC')
.limit(50)
.getRawMany<{ value: string; count: number }>();
return [key, rows.map((r) => ({ value: String(r.value), count: Number(r.count) }))] as const;
}),
);
return Object.fromEntries(entries);
}

View File

@@ -0,0 +1,76 @@
import { SelectQueryBuilder } from 'typeorm';
import { applySort, buildPaginationMeta, normalizePagination } from './pagination.util';
/** Minimal fake — just enough of the SelectQueryBuilder chain applySort touches. */
function fakeQb() {
const calls: Array<{ method: string; args: unknown[] }> = [];
const qb = {
alias: 'contract',
orderBy(...args: unknown[]) {
calls.push({ method: 'orderBy', args });
return qb;
},
addOrderBy(...args: unknown[]) {
calls.push({ method: 'addOrderBy', args });
return qb;
},
};
return { qb: qb as unknown as SelectQueryBuilder<any>, calls };
}
const SORTABLE = {
createdAt: 'contract.createdAt',
contractValidUntil: 'contract.contractValidUntil',
};
describe('applySort', () => {
it('resolves a whitelisted sortBy to its column', () => {
const { qb, calls } = fakeQb();
applySort(qb, { sortBy: 'contractValidUntil', sortOrder: 'ASC' }, SORTABLE, 'createdAt');
expect(calls[0]).toEqual({
method: 'orderBy',
args: ['contract.contractValidUntil', 'ASC'],
});
});
it('falls back to the default column for an unknown sortBy instead of throwing', () => {
const { qb, calls } = fakeQb();
// A stale bookmark or shared link naming a removed/renamed column must
// never 400 — it should silently behave as if sortBy were absent.
expect(() =>
applySort(qb, { sortBy: "id; DROP TABLE contracts; --" }, SORTABLE, 'createdAt'),
).not.toThrow();
expect(calls[0]).toEqual({ method: 'orderBy', args: ['contract.createdAt', 'DESC'] });
});
it('defaults sortOrder to DESC when absent or not ASC', () => {
const { qb, calls } = fakeQb();
applySort(qb, {}, SORTABLE, 'createdAt');
expect(calls[0]).toEqual({ method: 'orderBy', args: ['contract.createdAt', 'DESC'] });
});
it('always appends an id ASC tiebreaker', () => {
const { qb, calls } = fakeQb();
applySort(qb, { sortBy: 'createdAt' }, SORTABLE, 'createdAt');
expect(calls[1]).toEqual({ method: 'addOrderBy', args: ['contract.id', 'ASC'] });
});
});
describe('normalizePagination / buildPaginationMeta', () => {
it('clamps page to >= 1 and pageSize to the configured max', () => {
const p = normalizePagination({ page: 0, pageSize: 999 }, { maxPageSize: 100 });
expect(p).toEqual({ page: 1, pageSize: 100, skip: 0, take: 100 });
});
it('computes hasNextPage/hasPreviousPage from total', () => {
const meta = buildPaginationMeta(45, 2, 20);
expect(meta).toEqual({
page: 2,
pageSize: 20,
total: 45,
totalPages: 3,
hasNextPage: true,
hasPreviousPage: true,
});
});
});

View File

@@ -83,3 +83,32 @@ export function paginateArray<T>(
meta: buildPaginationMeta(rows.length, page, pageSize),
};
}
/**
* Apply `ORDER BY` from a query DTO's `sortBy`/`sortOrder`, resolved against a
* whitelist — never interpolate `sortBy` into a query builder directly, it is
* unvalidated user input and an unwhitelisted `orderBy(\`alias.${sortBy}\`)`
* is a SQL-injection primitive (see the deleted `findAllWithFilters` methods
* on drivers/vehicles repositories, which had exactly that bug).
*
* An unknown `sortBy` falls back to `fallback` instead of throwing — a stale
* bookmark or shared link should never 400.
*
* Always appends `id ASC` as a tiebreaker: sorting by a non-unique column
* (status, createdAt on bulk-imported rows) without one can drop or
* duplicate rows across pages once LIMIT/OFFSET is involved.
*
* @param sortable public sort key -> "alias.column" SQL reference. Also
* doubles as the Swagger enum / frontend's sortable-column list.
* @param fallback a key that must exist in `sortable`.
*/
export function applySort<T extends ObjectLiteral>(
qb: SelectQueryBuilder<T>,
query: { sortBy?: string; sortOrder?: 'ASC' | 'DESC' },
sortable: Record<string, string>,
fallback: string,
): SelectQueryBuilder<T> {
const column = (query.sortBy && sortable[query.sortBy]) || sortable[fallback];
qb.orderBy(column, query.sortOrder === 'ASC' ? 'ASC' : 'DESC');
return qb.addOrderBy(`${qb.alias}.id`, 'ASC');
}