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

@@ -12,6 +12,7 @@ import {
SelectQueryBuilder,
} from 'typeorm';
import { computeFacets, FacetBucket } from '../../common/utils/facets.util';
import { wagonsPerUnitForSize } from '../rule-engine/container-type.util';
import { ContainerType } from '../rule-engine/entities/container-type.entity';
import { Contract } from '../contracts/entities/contract.entity';
@@ -857,6 +858,29 @@ export class BookingsRepository extends BaseRepository<Booking> {
};
}
/**
* Facet counts for the filter bar's enum popovers: one `GROUP BY` per
* column, each with every OTHER active filter applied but its own
* predicate omitted (see `applyListFilters`'s `omit` param). `bookingType`
* is derived from `contract_kind` (see the comment in `applyListFilters`),
* not a plain column, so it facets on the same CASE expression the filter
* itself applies.
*/
async getFacets(options: BookingListFilterOptions): Promise<Record<string, FacetBucket[]>> {
return computeFacets(
() => this.repository.createQueryBuilder('booking').where('booking.deleted_at IS NULL'),
(qb, omit) => this.applyListFilters(qb, options, omit as keyof BookingListFilterOptions),
{
status: 'booking.status',
freightType: 'booking.freight_type',
tradeDirection: 'booking.trade_direction',
paymentStatus: 'booking.payment_status',
bookingType:
"CASE WHEN booking.contract_kind = 'GENERAL' THEN 'GENERAL_CONTRACT' ELSE 'ONE_TIME' END",
},
);
}
async getStatusCounts(): Promise<Record<string, number>> {
const rows = await this.repository
.createQueryBuilder('booking')
@@ -915,16 +939,24 @@ export class BookingsRepository extends BaseRepository<Booking> {
return { inQueue, onThisPage, needsAction, urgent };
}
/**
* @param omit skip this one predicate — used by `getFacets` so a facet's
* own filter doesn't hide its own sibling values. Every other caller
* (list, summary metrics) passes nothing.
*/
private applyListFilters(
qb: SelectQueryBuilder<Booking>,
options: BookingListFilterOptions,
omit?: keyof BookingListFilterOptions | 'status',
): void {
if (options.statuses?.length) {
qb.andWhere('booking.status IN (:...statuses)', {
statuses: options.statuses,
});
} else if (options.status) {
qb.andWhere('booking.status = :status', { status: options.status });
if (omit !== 'status') {
if (options.statuses?.length) {
qb.andWhere('booking.status IN (:...statuses)', {
statuses: options.statuses,
});
} else if (options.status) {
qb.andWhere('booking.status = :status', { status: options.status });
}
}
if (options.companyId) {
@@ -957,12 +989,12 @@ export class BookingsRepository extends BaseRepository<Booking> {
cargoTypeId: options.cargoTypeId,
});
}
if (options.freightType) {
if (omit !== 'freightType' && options.freightType) {
qb.andWhere('booking.freight_type = :freightType', {
freightType: options.freightType,
});
}
if (options.bookingType) {
if (omit !== 'bookingType' && options.bookingType) {
// The stored booking_type column is 'ONE_TIME' for every row (contract
// drawdowns included — see contract-booking.service create), so the
// one-time vs general split keys on the denormalized contract_kind:
@@ -1011,12 +1043,12 @@ export class BookingsRepository extends BaseRepository<Booking> {
} else if (options.isGovernment === 'false') {
qb.andWhere('booking.is_government = FALSE');
}
if (options.tradeDirection) {
if (omit !== 'tradeDirection' && options.tradeDirection) {
qb.andWhere('booking.trade_direction = :tradeDirection', {
tradeDirection: options.tradeDirection,
});
}
if (options.tradeDirections) {
if (omit !== 'tradeDirection' && options.tradeDirections) {
applyDirectionScope(qb, 'booking.trade_direction', options.tradeDirections);
}
if (options.paymentCurrency) {
@@ -1024,7 +1056,7 @@ export class BookingsRepository extends BaseRepository<Booking> {
paymentCurrency: options.paymentCurrency,
});
}
if (options.paymentStatus) {
if (omit !== 'paymentStatus' && options.paymentStatus) {
qb.andWhere('booking.payment_status = :paymentStatus', {
paymentStatus: options.paymentStatus,
});

View File

@@ -2051,8 +2051,9 @@ export class BookingsService {
consolidationPaired: filter.consolidationPaired,
};
const [statusCounts, metrics] = await Promise.all([
const [statusCounts, facets, metrics] = await Promise.all([
this.bookingsRepository.getStatusCounts(),
this.bookingsRepository.getFacets(listFilter),
this.bookingsRepository.getListSummaryMetrics({
...listFilter,
page,
@@ -2064,7 +2065,9 @@ export class BookingsService {
return {
metrics,
// Tabs stay unfiltered (whole-set) on purpose — see the DTO comment.
tabs: mapStatusCountsToTabs(statusCounts),
facets,
};
}

View File

@@ -1,4 +1,5 @@
import { ApiProperty } from '@nestjs/swagger';
import { FacetBucket } from '../../../common/utils/facets.util';
export class BookingListSummaryMetricsDto {
@ApiProperty({ example: 42 })
@@ -31,4 +32,18 @@ export class BookingListSummaryDto {
@ApiProperty({ type: BookingListSummaryTabsDto })
tabs!: BookingListSummaryTabsDto;
/**
* Per-column value counts for the filter bar's enum popovers, scoped to
* every OTHER currently-active filter (own predicate omitted per column —
* see `BookingsRepository.getFacets`). Unlike `tabs`, which is
* deliberately unfiltered so tab counts stay stable while you filter
* within a tab, these move with the filter set.
*/
@ApiProperty({
description: 'Facet counts keyed by filter field, for the pill filter bar',
type: 'object',
additionalProperties: { type: 'array', items: { type: 'object' } },
})
facets!: Record<string, FacetBucket[]>;
}