|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * Empty-group fill (#4708, objectui#3136). |
| 5 | + * |
| 6 | + * A measure carrying its own `filter` runs as a separate grouped sub-query and |
| 7 | + * is merged back by dimension key. A `GROUP BY` over a filtered row set emits |
| 8 | + * NO group for a dimension value the filter excludes entirely, so the measure |
| 9 | + * comes back ABSENT rather than `0` — and a derived ratio over an absent |
| 10 | + * operand goes null, so the cell renders blank: visually identical to "no data |
| 11 | + * for this row", which is the opposite of what the row means. |
| 12 | + * |
| 13 | + * The bias is what makes it worth a dedicated suite: the rows that blank are |
| 14 | + * exactly the WORST-performing ones (nothing matched the numerator's filter), |
| 15 | + * while a row that matched everything renders fine. A dashboard that hides its |
| 16 | + * worst rows and shows its best is the least acceptable direction for the |
| 17 | + * error to run, so `renders the worst row …` below asserts the asymmetry |
| 18 | + * directly rather than only the individual cells. |
| 19 | + * |
| 20 | + * The fill is strictly by aggregate kind — over-filling would trade this lie |
| 21 | + * for its mirror image (an `avg` of nothing reported as 0 is a measurement |
| 22 | + * nobody made), so `does NOT fill avg/min/max` pins the other side. |
| 23 | + */ |
| 24 | + |
| 25 | +import { describe, it, expect, vi } from 'vitest'; |
| 26 | +import type { IAnalyticsService, AnalyticsQuery, AnalyticsResult } from '@objectstack/spec/contracts'; |
| 27 | +import { DatasetSchema } from '@objectstack/spec/ui'; |
| 28 | +import { compileDataset } from '../dataset-compiler.js'; |
| 29 | +import { DatasetExecutor, fillEmptyGroups } from '../dataset-executor.js'; |
| 30 | + |
| 31 | +function fakeService(handler: (q: AnalyticsQuery) => AnalyticsResult): IAnalyticsService { |
| 32 | + return { query: vi.fn(async (q: AnalyticsQuery) => handler(q)), getMeta: async () => [] }; |
| 33 | +} |
| 34 | + |
| 35 | +// ── the issue's reproduction, verbatim (hotcrm#593 / hotcrm#656) ───────────── |
| 36 | + |
| 37 | +const winRate = DatasetSchema.parse({ |
| 38 | + name: 'pipeline', label: 'Pipeline', object: 'opportunity', |
| 39 | + dimensions: [{ name: 'lead_source', field: 'lead_source', type: 'string' }], |
| 40 | + measures: [ |
| 41 | + { name: 'won_count', aggregate: 'count', filter: { stage: 'closed_won' } }, |
| 42 | + { name: 'lost_count', aggregate: 'count', filter: { stage: 'closed_lost' } }, |
| 43 | + { name: 'decided_count', aggregate: 'count', filter: { stage: { $in: ['closed_won', 'closed_lost'] } } }, |
| 44 | + { name: 'win_rate', derived: { op: 'ratio', of: ['won_count', 'decided_count'] } }, |
| 45 | + ], |
| 46 | +}); |
| 47 | + |
| 48 | +/** |
| 49 | + * The four lead sources of the issue's table. Each sub-query returns only the |
| 50 | + * groups its filter left non-empty — which is what a real `GROUP BY` does: |
| 51 | + * - `partner` won everything → absent from the `lost_count` result |
| 52 | + * - `cold_call` won nothing → absent from the `won_count` result |
| 53 | + */ |
| 54 | +const winRateService = fakeService((q) => { |
| 55 | + switch (q.measures[0]) { |
| 56 | + case 'won_count': |
| 57 | + return { rows: [ |
| 58 | + { lead_source: 'content', won_count: 2 }, |
| 59 | + { lead_source: 'referral', won_count: 1 }, |
| 60 | + { lead_source: 'partner', won_count: 1 }, |
| 61 | + ], fields: [] }; |
| 62 | + case 'lost_count': |
| 63 | + return { rows: [ |
| 64 | + { lead_source: 'content', lost_count: 1 }, |
| 65 | + { lead_source: 'referral', lost_count: 1 }, |
| 66 | + { lead_source: 'cold_call', lost_count: 1 }, |
| 67 | + ], fields: [] }; |
| 68 | + case 'decided_count': |
| 69 | + return { rows: [ |
| 70 | + { lead_source: 'content', decided_count: 3 }, |
| 71 | + { lead_source: 'referral', decided_count: 2 }, |
| 72 | + { lead_source: 'partner', decided_count: 1 }, |
| 73 | + { lead_source: 'cold_call', decided_count: 1 }, |
| 74 | + ], fields: [] }; |
| 75 | + default: |
| 76 | + return { rows: [], fields: [] }; |
| 77 | + } |
| 78 | +}); |
| 79 | + |
| 80 | +const runWinRate = () => |
| 81 | + new DatasetExecutor(winRateService).execute(compileDataset(winRate), { |
| 82 | + dimensions: ['lead_source'], |
| 83 | + measures: ['won_count', 'lost_count', 'decided_count', 'win_rate'], |
| 84 | + }); |
| 85 | + |
| 86 | +describe('empty-group fill — a filtered count that matched nothing (#4708)', () => { |
| 87 | + it('reports 0 (not blank) for the group its filter excluded, so the ratio computes', async () => { |
| 88 | + const rows = (await runWinRate()).rows; |
| 89 | + const cold = rows.find((r) => r.lead_source === 'cold_call')!; |
| 90 | + // cold_call won nothing and lost one. The correct answer is 0%, not blank. |
| 91 | + expect(cold.won_count).toBe(0); |
| 92 | + expect(cold.decided_count).toBe(1); |
| 93 | + expect(cold.win_rate).toBe(0); |
| 94 | + }); |
| 95 | + |
| 96 | + it('fills the mirror gap too — a source that never lost reads 0 losses', async () => { |
| 97 | + const rows = (await runWinRate()).rows; |
| 98 | + expect(rows.find((r) => r.lead_source === 'partner')).toMatchObject({ |
| 99 | + won_count: 1, lost_count: 0, decided_count: 1, win_rate: 1, |
| 100 | + }); |
| 101 | + }); |
| 102 | + |
| 103 | + it('renders the worst row exactly as legibly as the best one (the asymmetry)', async () => { |
| 104 | + const rows = (await runWinRate()).rows; |
| 105 | + // The defect's signature: `partner` (won everything) rendered fine while |
| 106 | + // `cold_call` (won nothing) rendered blank — the dashboard hid its worst |
| 107 | + // row. No row may come back with an unmeasured cell. |
| 108 | + for (const row of rows) { |
| 109 | + expect(row.win_rate, `win_rate blank for ${row.lead_source}`).not.toBeNull(); |
| 110 | + expect(row.win_rate).toEqual(expect.any(Number)); |
| 111 | + for (const m of ['won_count', 'lost_count', 'decided_count']) { |
| 112 | + expect(row[m], `${m} blank for ${row.lead_source}`).toEqual(expect.any(Number)); |
| 113 | + } |
| 114 | + } |
| 115 | + // …and the worst row is the one the reader must be able to act on. |
| 116 | + const byRate = [...rows].sort((a, b) => Number(a.win_rate) - Number(b.win_rate)); |
| 117 | + expect(byRate[0]).toMatchObject({ lead_source: 'cold_call', win_rate: 0 }); |
| 118 | + expect(byRate[byRate.length - 1]).toMatchObject({ lead_source: 'partner', win_rate: 1 }); |
| 119 | + }); |
| 120 | + |
| 121 | + it('invents no group — a dimension value no query reported stays out of the grid', async () => { |
| 122 | + const rows = (await runWinRate()).rows; |
| 123 | + // Only the four sources some sub-query actually returned. `webinar` has no |
| 124 | + // opportunities at all, so it is absent from every result and must not be |
| 125 | + // materialised as a row of zeroes. |
| 126 | + expect(rows.map((r) => r.lead_source).sort()).toEqual(['cold_call', 'content', 'partner', 'referral']); |
| 127 | + }); |
| 128 | +}); |
| 129 | + |
| 130 | +// ── the other side: aggregates with no answer over an empty set ────────────── |
| 131 | + |
| 132 | +const amounts = DatasetSchema.parse({ |
| 133 | + name: 'deals', label: 'Deals', object: 'opportunity', |
| 134 | + dimensions: [{ name: 'lead_source', field: 'lead_source', type: 'string' }], |
| 135 | + measures: [ |
| 136 | + { name: 'won_count', aggregate: 'count', filter: { stage: 'closed_won' } }, |
| 137 | + { name: 'won_total', aggregate: 'sum', field: 'amount', filter: { stage: 'closed_won' } }, |
| 138 | + { name: 'won_avg', aggregate: 'avg', field: 'amount', filter: { stage: 'closed_won' } }, |
| 139 | + { name: 'won_min', aggregate: 'min', field: 'amount', filter: { stage: 'closed_won' } }, |
| 140 | + { name: 'won_max', aggregate: 'max', field: 'amount', filter: { stage: 'closed_won' } }, |
| 141 | + { name: 'all_count', aggregate: 'count' }, |
| 142 | + ], |
| 143 | +}); |
| 144 | + |
| 145 | +describe('empty-group fill — strictly by aggregate kind (#4708)', () => { |
| 146 | + it('does NOT fill avg/min/max: nothing to average over an empty group', async () => { |
| 147 | + const svc = fakeService((q) => { |
| 148 | + if (q.measures.includes('all_count')) { |
| 149 | + return { rows: [ |
| 150 | + { lead_source: 'content', all_count: 4 }, |
| 151 | + { lead_source: 'cold_call', all_count: 1 }, |
| 152 | + ], fields: [] }; |
| 153 | + } |
| 154 | + // every won_* sub-query: cold_call won nothing, so no group for it |
| 155 | + const m = q.measures[0]; |
| 156 | + return { rows: [{ lead_source: 'content', [m]: 7 }], fields: [] }; |
| 157 | + }); |
| 158 | + const res = await new DatasetExecutor(svc).execute(compileDataset(amounts), { |
| 159 | + dimensions: ['lead_source'], |
| 160 | + measures: ['all_count', 'won_count', 'won_total', 'won_avg', 'won_min', 'won_max'], |
| 161 | + }); |
| 162 | + const cold = res.rows.find((r) => r.lead_source === 'cold_call')!; |
| 163 | + // Measured facts: no rows matched, so the count is 0 and the sum is 0. |
| 164 | + expect(cold.won_count).toBe(0); |
| 165 | + expect(cold.won_total).toBe(0); |
| 166 | + // Genuinely unknown — filling these would report a measurement nobody made |
| 167 | + // ("average deal size 0" is a different claim from "no deals"). |
| 168 | + for (const m of ['won_avg', 'won_min', 'won_max']) { |
| 169 | + expect(cold[m] ?? null, `${m} must stay null`).toBeNull(); |
| 170 | + expect(cold[m], `${m} must not be flattened to 0`).not.toBe(0); |
| 171 | + } |
| 172 | + // The group that did have data is untouched. |
| 173 | + expect(res.rows.find((r) => r.lead_source === 'content')).toMatchObject({ |
| 174 | + won_count: 7, won_total: 7, won_avg: 7, won_min: 7, won_max: 7, |
| 175 | + }); |
| 176 | + }); |
| 177 | +}); |
| 178 | + |
| 179 | +// ── the compareTo seam: rows APPENDED by the comparison merge ──────────────── |
| 180 | + |
| 181 | +const compareDs = DatasetSchema.parse({ |
| 182 | + name: 'trend', label: 'Trend', object: 'opportunity', |
| 183 | + dimensions: [ |
| 184 | + { name: 'lead_source', field: 'lead_source', type: 'string' }, |
| 185 | + { name: 'close_date', field: 'close_date', type: 'date' }, |
| 186 | + ], |
| 187 | + measures: [ |
| 188 | + { name: 'revenue', aggregate: 'sum', field: 'amount' }, |
| 189 | + { name: 'avg_deal', aggregate: 'avg', field: 'amount' }, |
| 190 | + { name: 'won_count', aggregate: 'count', filter: { stage: 'closed_won' } }, |
| 191 | + ], |
| 192 | +}); |
| 193 | + |
| 194 | +describe('empty-group fill — buckets the comparison window added (#4708)', () => { |
| 195 | + it('fills every base measure on a row only the previous period produced', async () => { |
| 196 | + const svc = fakeService((q) => { |
| 197 | + const shifted = JSON.stringify(q.timeDimensions ?? []).includes('2025-12'); |
| 198 | + if (shifted) { |
| 199 | + return { rows: [ |
| 200 | + { lead_source: 'content', revenue: 80, avg_deal: 40, won_count: 2 }, |
| 201 | + { lead_source: 'cold_call', revenue: 10, avg_deal: 10, won_count: 1 }, |
| 202 | + ], fields: [] }; |
| 203 | + } |
| 204 | + if (q.measures.includes('won_count')) { |
| 205 | + return { rows: [{ lead_source: 'content', won_count: 3 }], fields: [] }; |
| 206 | + } |
| 207 | + // this period, `cold_call` has no opportunities at all |
| 208 | + return { rows: [{ lead_source: 'content', revenue: 100, avg_deal: 50 }], fields: [] }; |
| 209 | + }); |
| 210 | + const res = await new DatasetExecutor(svc).execute(compileDataset(compareDs), { |
| 211 | + dimensions: ['lead_source'], |
| 212 | + measures: ['revenue', 'avg_deal', 'won_count'], |
| 213 | + timeDimensions: [{ dimension: 'close_date', dateRange: ['2026-01-01', '2026-01-31'] }], |
| 214 | + compareTo: { kind: 'previousPeriod', dimension: 'close_date' }, |
| 215 | + }); |
| 216 | + const cold = res.rows.find((r) => r.lead_source === 'cold_call')!; |
| 217 | + // The row exists because the comparison window had data for it; "how much |
| 218 | + // did cold_call sell this period" therefore has an exact answer — none. |
| 219 | + // Before #4708 the fill ran BEFORE this merge, so all three read blank. |
| 220 | + expect(cold.revenue).toBe(0); |
| 221 | + expect(cold.won_count).toBe(0); |
| 222 | + expect(cold.avg_deal ?? null).toBeNull(); |
| 223 | + // the comparison columns are untouched — they were reported |
| 224 | + expect(cold).toMatchObject({ revenue__compare: 10, won_count__compare: 1 }); |
| 225 | + }); |
| 226 | + |
| 227 | + it('fills a comparison column the previous window never reported', async () => { |
| 228 | + const svc = fakeService((q) => { |
| 229 | + const shifted = JSON.stringify(q.timeDimensions ?? []).includes('2025-12'); |
| 230 | + // the previous period knew nothing of `content` |
| 231 | + if (shifted) return { rows: [], fields: [] }; |
| 232 | + if (q.measures.includes('won_count')) { |
| 233 | + return { rows: [{ lead_source: 'content', won_count: 3 }], fields: [] }; |
| 234 | + } |
| 235 | + return { rows: [{ lead_source: 'content', revenue: 100, avg_deal: 50 }], fields: [] }; |
| 236 | + }); |
| 237 | + const res = await new DatasetExecutor(svc).execute(compileDataset(compareDs), { |
| 238 | + dimensions: ['lead_source'], |
| 239 | + measures: ['revenue', 'avg_deal', 'won_count'], |
| 240 | + timeDimensions: [{ dimension: 'close_date', dateRange: ['2026-01-01', '2026-01-31'] }], |
| 241 | + compareTo: { kind: 'previousPeriod', dimension: 'close_date' }, |
| 242 | + }); |
| 243 | + expect(res.rows[0]).toMatchObject({ |
| 244 | + revenue: 100, won_count: 3, |
| 245 | + // "sold nothing last month" — a fact, not a gap |
| 246 | + revenue__compare: 0, won_count__compare: 0, |
| 247 | + }); |
| 248 | + expect(res.rows[0].avg_deal__compare ?? null).toBeNull(); |
| 249 | + }); |
| 250 | +}); |
| 251 | + |
| 252 | +// ── the helper in isolation ───────────────────────────────────────────────── |
| 253 | + |
| 254 | +describe('fillEmptyGroups', () => { |
| 255 | + it('fills count/count_distinct/sum, leaves avg/min/max and reported values alone', () => { |
| 256 | + const rows = [ |
| 257 | + { g: 'a', c: 2, d: 1, s: 5, avg: 2.5, min: 1, max: 4 }, |
| 258 | + { g: 'b' }, |
| 259 | + ]; |
| 260 | + fillEmptyGroups(rows, { |
| 261 | + c: 'count', d: 'count_distinct', s: 'sum', avg: 'avg', min: 'min', max: 'max', |
| 262 | + unknown: undefined, |
| 263 | + }); |
| 264 | + expect(rows[0]).toEqual({ g: 'a', c: 2, d: 1, s: 5, avg: 2.5, min: 1, max: 4 }); |
| 265 | + expect(rows[1]).toEqual({ g: 'b', c: 0, d: 0, s: 0 }); |
| 266 | + }); |
| 267 | + |
| 268 | + it('touches only the columns it is given, and never adds rows', () => { |
| 269 | + const rows = [{ g: 'a' }]; |
| 270 | + expect(fillEmptyGroups(rows, { c: 'count' })).toHaveLength(1); |
| 271 | + expect(rows[0]).toEqual({ g: 'a', c: 0 }); |
| 272 | + }); |
| 273 | +}); |
0 commit comments