@@ -28,6 +28,7 @@ import {
2828 compileListViewGroupRowsQuery ,
2929 deriveColumnSummary ,
3030 listViewGroupKeyPredicate ,
31+ listViewGroupOrderColumn ,
3132} from './view-grouping-query' ;
3233import type { ListViewGroupHeaderRow } from './view-grouping-query' ;
3334
@@ -137,14 +138,22 @@ function reduceHeaderQuery(rows: Row[], query: EngineAggregateOptions): ListView
137138 case 'count_distinct' : out [ agg . alias ] = new Set ( values . filter ( ( v ) => v != null ) ) . size ; break ;
138139 case 'sum' : out [ agg . alias ] = nums . reduce ( ( a , b ) => a + b , 0 ) ; break ;
139140 case 'avg' : out [ agg . alias ] = nums . length ? nums . reduce ( ( a , b ) => a + b , 0 ) / nums . length : null ; break ;
140- case 'min' : out [ agg . alias ] = nums . length ? Math . min ( ...nums ) : null ; break ;
141- case 'max' : out [ agg . alias ] = nums . length ? Math . max ( ...nums ) : null ; break ;
141+ // Raw comparison, as the in-memory face does: a `YYYY-MM-DD` string
142+ // orders chronologically, and a number orders as itself.
143+ case 'min' : out [ agg . alias ] = orderStatistic ( values , ( a , b ) => a < b ) ; break ;
144+ case 'max' : out [ agg . alias ] = orderStatistic ( values , ( a , b ) => a > b ) ; break ;
142145 }
143146 }
144147 return out as ListViewGroupHeaderRow ;
145148 } ) ;
146149}
147150
151+ /** `min` / `max` over the non-null values, `null` over none. */
152+ function orderStatistic ( values : unknown [ ] , better : ( a : never , b : never ) => boolean ) : unknown {
153+ const defined = values . filter ( ( v ) => v != null ) ;
154+ return defined . length === 0 ? null : defined . reduce ( ( a , b ) => ( better ( a as never , b as never ) ? a : b ) ) ;
155+ }
156+
148157/** Header rows → `{ unit: count }`, the shape a reader compares. */
149158function countsByUnit ( headers : ListViewGroupHeaderRow [ ] ) : Record < string , number > {
150159 return Object . fromEntries ( headers . map ( ( h ) => [ String ( h . business_unit ) , h [ LIST_VIEW_GROUP_COUNT_ALIAS ] ] ) ) ;
@@ -519,6 +528,229 @@ describe('compileListViewGroupQuery — refuses what the contract cannot mean',
519528 } ) ;
520529} ) ;
521530
531+ // ─── [#25786] Ordering a level by another field ──────────────────────────────
532+ //
533+ // The HotCRM forecast shape: periods grouped by their LABEL, which sorts as
534+ // text ("Nov 2026" < "Oct 2026" < "Q1 2027" < "Q4 2025" …), ordered by their
535+ // period START. Two labels share a start on purpose (the tie arm) and one
536+ // period has no start at all (the null arm).
537+
538+ interface Forecast {
539+ id : string ;
540+ period_label : string ;
541+ period_start : string | null ;
542+ amount : number ;
543+ }
544+
545+ const FORECAST_PERIODS : ReadonlyArray < readonly [ label : string , start : string | null , rows : number ] > = [
546+ [ 'Q4 2025' , '2025-10-01' , 2 ] ,
547+ [ 'Sep 2026' , '2026-09-01' , 1 ] ,
548+ [ 'Oct 2026' , '2026-10-01' , 3 ] ,
549+ [ 'Q4 2026' , '2026-10-01' , 1 ] ,
550+ [ 'Nov 2026' , '2026-11-01' , 2 ] ,
551+ [ 'Q1 2027' , '2027-01-01' , 2 ] ,
552+ [ 'Unscheduled' , null , 1 ] ,
553+ ] ;
554+
555+ /** Interleaved on purpose, so no group order can fall out of the row order. */
556+ const FORECASTS : Forecast [ ] = ( ( ) => {
557+ const queues = FORECAST_PERIODS . map ( ( [ label , start , rows ] ) =>
558+ Array . from ( { length : rows } , ( _ , i ) => ( { id : `${ label } -${ i } ` , period_label : label , period_start : start , amount : i + 1 } ) ) ) ;
559+ const out : Forecast [ ] = [ ] ;
560+ while ( queues . some ( ( q ) => q . length > 0 ) ) {
561+ for ( const q of [ ...queues ] . reverse ( ) ) {
562+ const next = q . shift ( ) ;
563+ if ( next ) out . push ( next ) ;
564+ }
565+ }
566+ return out ;
567+ } ) ( ) ;
568+
569+ /**
570+ * The CONSUMER's sort, written out as `GroupingFieldSchema.orderBy` states it
571+ * — test-local, because the sort is the consumer's and not this module's: by
572+ * the header-row column {@link listViewGroupOrderColumn} names, a `null` value
573+ * last in both directions, equal values by the group key in the same direction.
574+ */
575+ function sortHeaders (
576+ headers : ListViewGroupHeaderRow [ ] ,
577+ column : string ,
578+ key : string ,
579+ order : 'asc' | 'desc' ,
580+ ) : string [ ] {
581+ const sign = order === 'desc' ? - 1 : 1 ;
582+ const cmp = ( a : unknown , b : unknown ) => ( a === b ? 0 : ( a as string ) < ( b as string ) ? - 1 : 1 ) ;
583+ return [ ...headers ]
584+ . sort ( ( a , b ) => {
585+ const av = a [ column ] ;
586+ const bv = b [ column ] ;
587+ if ( av == null || bv == null ) return av == null && bv == null ? 0 : av == null ? 1 : - 1 ;
588+ return sign * ( cmp ( av , bv ) || cmp ( a [ key ] , b [ key ] ) ) ;
589+ } )
590+ . map ( ( h ) => String ( h [ key ] ) ) ;
591+ }
592+
593+ describe ( '[#25786] a level ordered by another field — the header query carries the value to sort by' , ( ) => {
594+ const byStart = ( order ?: 'asc' | 'desc' ) => ( {
595+ grouping : { fields : [ { field : 'period_label' , orderBy : 'period_start' , ...( order ? { order } : { } ) } ] } ,
596+ } ) ;
597+
598+ it ( 'compiles ONE `min` node for `asc` (the default) and ONE `max` node for `desc`, named by listViewGroupOrderColumn' , ( ) => {
599+ expect ( compileListViewGroupQuery ( byStart ( ) ) . aggregations ) . toEqual ( [
600+ { function : 'count' , alias : LIST_VIEW_GROUP_COUNT_ALIAS } ,
601+ { function : 'min' , field : 'period_start' , alias : 'min_period_start' } ,
602+ ] ) ;
603+ expect ( compileListViewGroupQuery ( byStart ( 'desc' ) ) . aggregations ) . toEqual ( [
604+ { function : 'count' , alias : LIST_VIEW_GROUP_COUNT_ALIAS } ,
605+ { function : 'max' , field : 'period_start' , alias : 'max_period_start' } ,
606+ ] ) ;
607+ // The grouping key never leaves `groupBy`: one header per LABEL.
608+ expect ( compileListViewGroupQuery ( byStart ( ) ) . groupBy ) . toEqual ( [ 'period_label' ] ) ;
609+ expect ( listViewGroupOrderColumn ( byStart ( ) . grouping , 0 ) ) . toBe ( 'min_period_start' ) ;
610+ expect ( listViewGroupOrderColumn ( byStart ( 'desc' ) . grouping , 0 ) ) . toBe ( 'max_period_start' ) ;
611+ } ) ;
612+
613+ it ( 'sorting the header rows by that column puts the periods in TIME order, where the key alone gives text order' , ( ) => {
614+ const asc = byStart ( ) ;
615+ const headers = reduceHeaderQuery ( FORECASTS as unknown as Row [ ] , compileListViewGroupQuery ( asc ) ) ;
616+ expect ( headers ) . toHaveLength ( FORECAST_PERIODS . length ) ;
617+ expect ( sortHeaders ( headers , listViewGroupOrderColumn ( asc . grouping , 0 ) , 'period_label' , 'asc' ) ) . toEqual ( [
618+ 'Q4 2025' , 'Sep 2026' , 'Oct 2026' , 'Q4 2026' , 'Nov 2026' , 'Q1 2027' , 'Unscheduled' ,
619+ ] ) ;
620+ // CONTROL — the same rows by the group key: what the forecast list showed.
621+ expect ( sortHeaders ( headers , 'period_label' , 'period_label' , 'asc' ) ) . toEqual ( [
622+ 'Nov 2026' , 'Oct 2026' , 'Q1 2027' , 'Q4 2025' , 'Q4 2026' , 'Sep 2026' , 'Unscheduled' ,
623+ ] ) ;
624+
625+ const desc = byStart ( 'desc' ) ;
626+ const descHeaders = reduceHeaderQuery ( FORECASTS as unknown as Row [ ] , compileListViewGroupQuery ( desc ) ) ;
627+ // The null-start period is LAST in this direction too, and the tie keeps
628+ // the key order in the same direction.
629+ expect ( sortHeaders ( descHeaders , listViewGroupOrderColumn ( desc . grouping , 0 ) , 'period_label' , 'desc' ) ) . toEqual ( [
630+ 'Q1 2027' , 'Nov 2026' , 'Q4 2026' , 'Oct 2026' , 'Sep 2026' , 'Q4 2025' , 'Unscheduled' ,
631+ ] ) ;
632+ // Every count still rides the same row.
633+ expect ( Object . fromEntries ( headers . map ( ( h ) => [ h . period_label , h . count ] ) ) )
634+ . toEqual ( Object . fromEntries ( FORECAST_PERIODS . map ( ( [ label , , rows ] ) => [ label , rows ] ) ) ) ;
635+ } ) ;
636+
637+ it ( '`min` ascending and `max` descending are one rule: each group sits where its FIRST row would, rows sorted by `orderBy`' , ( ) => {
638+ // An order field that is NOT a function of the group key: owners ordered
639+ // by the dates of their deals.
640+ const deals = [
641+ { id : 'a1' , owner : 'avery' , closed_on : '2026-01-05' } ,
642+ { id : 'a2' , owner : 'avery' , closed_on : '2026-06-01' } ,
643+ { id : 'b1' , owner : 'blake' , closed_on : '2026-03-01' } ,
644+ { id : 'c1' , owner : 'casey' , closed_on : '2026-02-01' } ,
645+ { id : 'c2' , owner : 'casey' , closed_on : '2026-07-01' } ,
646+ ] ;
647+ for ( const order of [ 'asc' , 'desc' ] as const ) {
648+ const grouping = { fields : [ { field : 'owner' , orderBy : 'closed_on' , order } ] } ;
649+ const headers = reduceHeaderQuery ( deals as unknown as Row [ ] , compileListViewGroupQuery ( { grouping } ) ) ;
650+ const sorted = [ ...deals ] . sort ( ( a , b ) => ( order === 'asc' ? 1 : - 1 ) * a . closed_on . localeCompare ( b . closed_on ) ) ;
651+ const firstAppearance = [ ...new Set ( sorted . map ( ( d ) => d . owner ) ) ] ;
652+ expect ( sortHeaders ( headers , listViewGroupOrderColumn ( grouping , 0 ) , 'owner' , order ) , order ) . toEqual ( firstAppearance ) ;
653+ }
654+ expect ( [ 'avery' , 'casey' , 'blake' ] ) . toEqual (
655+ [ ...new Set ( [ ...deals ] . sort ( ( a , b ) => a . closed_on . localeCompare ( b . closed_on ) ) . map ( ( d ) => d . owner ) ) ] ,
656+ ) ;
657+ } ) ;
658+
659+ it ( 'a level that orders by its own key compiles no node, and its sort column is the key itself' , ( ) => {
660+ for ( const fields of [ [ { field : 'period_label' } ] , [ { field : 'period_label' , orderBy : 'period_label' , order : 'desc' as const } ] ] ) {
661+ const grouping = { fields } ;
662+ expect ( compileListViewGroupQuery ( { grouping } ) . aggregations ) . toEqual ( [
663+ { function : 'count' , alias : LIST_VIEW_GROUP_COUNT_ALIAS } ,
664+ ] ) ;
665+ expect ( listViewGroupOrderColumn ( grouping , 0 ) ) . toBe ( 'period_label' ) ;
666+ }
667+ } ) ;
668+
669+ it ( 'a column summary `min` over the same field IS the order node — one node, one column' , ( ) => {
670+ const query = compileListViewGroupQuery ( {
671+ ...byStart ( ) ,
672+ columns : [ { field : 'period_start' , summary : 'min' } , { field : 'amount' , summary : 'sum' } ] ,
673+ } ) ;
674+ expect ( query . aggregations ) . toEqual ( [
675+ { function : 'count' , alias : LIST_VIEW_GROUP_COUNT_ALIAS } ,
676+ { function : 'min' , field : 'period_start' , alias : 'min_period_start' } ,
677+ { function : 'sum' , field : 'amount' , alias : 'sum_amount' } ,
678+ ] ) ;
679+ } ) ;
680+
681+ it ( 'per level, in nesting order; `depth` carries only the grouped levels\' nodes, and an outer level folds exactly' , ( ) => {
682+ const rows = FORECASTS . map ( ( f , i ) => ( { ...f , region : i % 2 === 0 ? 'north' : 'south' , region_rank : i % 2 === 0 ? 2 : 1 } ) ) ;
683+ const view = {
684+ grouping : {
685+ fields : [
686+ { field : 'region' , orderBy : 'region_rank' } ,
687+ { field : 'period_label' , orderBy : 'period_start' , order : 'desc' as const } ,
688+ ] ,
689+ } ,
690+ } ;
691+ const leaves = compileListViewGroupQuery ( view ) ;
692+ expect ( leaves . aggregations ) . toEqual ( [
693+ { function : 'count' , alias : LIST_VIEW_GROUP_COUNT_ALIAS } ,
694+ { function : 'min' , field : 'region_rank' , alias : 'min_region_rank' } ,
695+ { function : 'max' , field : 'period_start' , alias : 'max_period_start' } ,
696+ ] ) ;
697+ const outer = compileListViewGroupQuery ( view , { depth : 1 } ) ;
698+ expect ( outer . aggregations ) . toEqual ( [
699+ { function : 'count' , alias : LIST_VIEW_GROUP_COUNT_ALIAS } ,
700+ { function : 'min' , field : 'region_rank' , alias : 'min_region_rank' } ,
701+ ] ) ;
702+ expect ( listViewGroupOrderColumn ( view . grouping , 1 ) ) . toBe ( 'max_period_start' ) ;
703+
704+ // The outer level's value, folded from the leaves (`min` of mins), equals
705+ // the outer level's own query.
706+ const leafRows = reduceHeaderQuery ( rows as unknown as Row [ ] , leaves ) ;
707+ const outerRows = reduceHeaderQuery ( rows as unknown as Row [ ] , outer ) ;
708+ for ( const region of [ 'north' , 'south' ] ) {
709+ const folded = orderStatistic ( leafRows . filter ( ( r ) => r . region === region ) . map ( ( r ) => r . min_region_rank ) , ( a , b ) => a < b ) ;
710+ expect ( folded , region ) . toBe ( outerRows . find ( ( r ) => r . region === region ) ! . min_region_rank ) ;
711+ }
712+ expect ( sortHeaders ( outerRows , listViewGroupOrderColumn ( view . grouping , 0 ) , 'region' , 'asc' ) ) . toEqual ( [ 'south' , 'north' ] ) ;
713+ } ) ;
714+
715+ it ( 'refuses a blank `orderBy` — INVALID_QUERY / 400 at the level\'s `orderBy`' , ( ) => {
716+ for ( const orderBy of [ '' , ' ' ] ) {
717+ const grouping = { fields : [ { field : 'status' } , { field : 'period_label' , orderBy } ] } ;
718+ const err = refusal ( ( ) => compileListViewGroupQuery ( { grouping } ) ) ;
719+ expect ( err ) . toBeInstanceOf ( ListViewGroupQueryError ) ;
720+ expect ( err . reason ) . toBe ( 'grouping_order_by_blank' ) ;
721+ expect ( err . code ) . toBe ( 'INVALID_QUERY' ) ;
722+ expect ( err . status ) . toBe ( 400 ) ;
723+ expect ( err . path ) . toEqual ( [ 'grouping' , 'fields' , 1 , 'orderBy' ] ) ;
724+ // The same refusal from the column helper, and past the compiled depth too.
725+ expect ( refusal ( ( ) => listViewGroupOrderColumn ( grouping , 1 ) ) . reason ) . toBe ( 'grouping_order_by_blank' ) ;
726+ expect ( refusal ( ( ) => compileListViewGroupQuery ( { grouping } , { depth : 1 } ) ) . reason ) . toBe ( 'grouping_order_by_blank' ) ;
727+ }
728+ } ) ;
729+
730+ it ( 'refuses an order value landing on a grouped field\'s own column' , ( ) => {
731+ const err = refusal ( ( ) => compileListViewGroupQuery ( {
732+ grouping : { fields : [ { field : 'min_period_start' } , { field : 'period_label' , orderBy : 'period_start' } ] } ,
733+ } ) ) ;
734+ expect ( err . reason ) . toBe ( 'alias_collision' ) ;
735+ expect ( err . code ) . toBe ( 'INVALID_QUERY' ) ;
736+ expect ( err . status ) . toBe ( 400 ) ;
737+ expect ( err . path ) . toEqual ( [ 'grouping' , 'fields' , 1 , 'orderBy' ] ) ;
738+ } ) ;
739+
740+ it . each ( [ - 1 , 1 , 0.5 ] ) ( 'listViewGroupOrderColumn refuses level %s of a one-level grouping' , ( level ) => {
741+ const err = refusal ( ( ) => listViewGroupOrderColumn ( byStart ( ) . grouping , level ) ) ;
742+ expect ( err . reason ) . toBe ( 'depth_out_of_range' ) ;
743+ expect ( err . code ) . toBe ( 'INVALID_QUERY' ) ;
744+ expect ( err . status ) . toBe ( 400 ) ;
745+ } ) ;
746+
747+ it ( 'compiles from a grouping the schema accepts' , ( ) => {
748+ const parsed = ListViewSchema . parse ( { columns : [ 'period_label' ] , grouping : byStart ( 'desc' ) . grouping } ) ;
749+ expect ( compileListViewGroupQuery ( { grouping : parsed . grouping ! } ) . aggregations )
750+ . toContainEqual ( { function : 'max' , field : 'period_start' , alias : 'max_period_start' } ) ;
751+ } ) ;
752+ } ) ;
753+
522754// ─── The per-group row page ──────────────────────────────────────────────────
523755
524756describe ( 'compileListViewGroupRowsQuery — rows inside a group are the EXISTING paged find' , ( ) => {
0 commit comments