@kivacore/ui-pro-shared 0.0.9 → 0.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +167 -1
- package/src/.kiva/config.json +27 -0
- package/src/components/avatar-group.tsx +222 -0
- package/src/components/kiva/bulk-update-dialog/bulk-update-dialog.tsx +240 -0
- package/src/components/kiva/bulk-update-dialog/index.tsx +6 -0
- package/src/components/kiva/bulk-update-dialog/types.ts +33 -0
- package/src/components/kiva/calendar/animations.ts +40 -0
- package/src/components/kiva/calendar/calendar-body.tsx +106 -0
- package/src/components/kiva/calendar/calendar-sidebar.tsx +103 -0
- package/src/components/kiva/calendar/calendar.tsx +243 -0
- package/src/components/kiva/calendar/constants.ts +12 -0
- package/src/components/kiva/calendar/contexts/calendar-context.tsx +696 -0
- package/src/components/kiva/calendar/contexts/dnd-context.tsx +173 -0
- package/src/components/kiva/calendar/dialogs/add-edit-event-dialog.tsx +287 -0
- package/src/components/kiva/calendar/dialogs/delete-event-dialog.tsx +73 -0
- package/src/components/kiva/calendar/dialogs/event-details-dialog.tsx +163 -0
- package/src/components/kiva/calendar/dialogs/events-list-dialog.tsx +122 -0
- package/src/components/kiva/calendar/dnd/draggable-event.tsx +66 -0
- package/src/components/kiva/calendar/dnd/droppable-area.tsx +53 -0
- package/src/components/kiva/calendar/dnd/resizable-event.tsx +190 -0
- package/src/components/kiva/calendar/header/calendar-header.tsx +84 -0
- package/src/components/kiva/calendar/header/date-navigator.tsx +188 -0
- package/src/components/kiva/calendar/header/filter.tsx +80 -0
- package/src/components/kiva/calendar/header/today-button.tsx +49 -0
- package/src/components/kiva/calendar/header/user-select.tsx +111 -0
- package/src/components/kiva/calendar/header/view-tabs.tsx +144 -0
- package/src/components/kiva/calendar/helpers.ts +617 -0
- package/src/components/kiva/calendar/hooks/use-disclosure.ts +19 -0
- package/src/components/kiva/calendar/hooks/use-local-storage.ts +40 -0
- package/src/components/kiva/calendar/hooks/use-media-query.ts +25 -0
- package/src/components/kiva/calendar/hooks.ts +5 -0
- package/src/components/kiva/calendar/index.tsx +27 -0
- package/src/components/kiva/calendar/interfaces.ts +35 -0
- package/src/components/kiva/calendar/schemas.ts +20 -0
- package/src/components/kiva/calendar/settings/settings.tsx +116 -0
- package/src/components/kiva/calendar/skeletons/calendar-header-skeleton.tsx +27 -0
- package/src/components/kiva/calendar/skeletons/calendar-skeleton.tsx +19 -0
- package/src/components/kiva/calendar/skeletons/day-view-skeleton.tsx +40 -0
- package/src/components/kiva/calendar/skeletons/month-view-skeleton.tsx +36 -0
- package/src/components/kiva/calendar/skeletons/week-view-skeleton.tsx +48 -0
- package/src/components/kiva/calendar/skeletons/year-view-skeleton.tsx +42 -0
- package/src/components/kiva/calendar/types.ts +25 -0
- package/src/components/kiva/calendar/views/agenda-view/agenda-events.tsx +150 -0
- package/src/components/kiva/calendar/views/month-view/calendar-month-view.tsx +82 -0
- package/src/components/kiva/calendar/views/month-view/day-cell.tsx +218 -0
- package/src/components/kiva/calendar/views/month-view/event-bullet.tsx +46 -0
- package/src/components/kiva/calendar/views/month-view/month-event-badge.tsx +154 -0
- package/src/components/kiva/calendar/views/timeline/calendar-timeline-view.tsx +100 -0
- package/src/components/kiva/calendar/views/timeline/lib/timeline-layout.ts +130 -0
- package/src/components/kiva/calendar/views/timeline/lib/timeline-model.ts +504 -0
- package/src/components/kiva/calendar/views/timeline/timeline-event-bar.tsx +68 -0
- package/src/components/kiva/calendar/views/timeline/timeline-grid-header.tsx +125 -0
- package/src/components/kiva/calendar/views/timeline/timeline-row.tsx +159 -0
- package/src/components/kiva/calendar/views/timeline/timeline-section.tsx +61 -0
- package/src/components/kiva/calendar/views/timeline/use-timeline-sections.ts +278 -0
- package/src/components/kiva/calendar/views/week-and-day-view/calendar-day-view.tsx +277 -0
- package/src/components/kiva/calendar/views/week-and-day-view/calendar-time-line.tsx +47 -0
- package/src/components/kiva/calendar/views/week-and-day-view/calendar-week-view.tsx +229 -0
- package/src/components/kiva/calendar/views/week-and-day-view/day-view-multi-day-events-row.tsx +79 -0
- package/src/components/kiva/calendar/views/week-and-day-view/event-block.tsx +116 -0
- package/src/components/kiva/calendar/views/week-and-day-view/render-grouped-events.tsx +54 -0
- package/src/components/kiva/calendar/views/week-and-day-view/week-view-multi-day-events-row.tsx +159 -0
- package/src/components/kiva/calendar/views/year-view/calendar-year-view.tsx +159 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-active-chips.tsx +137 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-clear.tsx +34 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-search.tsx +67 -0
- package/src/components/kiva/data-table-side-filters/components/side-filter-section.tsx +77 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-async-options.tsx +354 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-boolean.tsx +66 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-checkbox-list.tsx +137 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-date-range.tsx +204 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-numeric-range.tsx +162 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-options-dropdown.tsx +191 -0
- package/src/components/kiva/data-table-side-filters/controllers/side-filter-text.tsx +53 -0
- package/src/components/kiva/data-table-side-filters/core/query-translator.ts +367 -0
- package/src/components/kiva/data-table-side-filters/core/types.ts +81 -0
- package/src/components/kiva/data-table-side-filters/data-table-side-filters.tsx +483 -0
- package/src/components/kiva/data-table-side-filters/hooks/use-data-table-side-filters.tsx +160 -0
- package/src/components/kiva/data-table-side-filters/hooks/use-show-more.tsx +62 -0
- package/src/components/kiva/data-table-side-filters/index.tsx +44 -0
- package/src/components/kiva/data-table-side-filters/lib/render-mode.ts +62 -0
- package/src/components/kiva/date-time-picker.tsx +163 -0
- package/src/components/kiva/editable-record-detail.tsx +809 -0
- package/src/components/kiva/enum-option-editor/enum-option-editor.tsx +891 -0
- package/src/components/kiva/enum-option-editor/index.tsx +26 -0
- package/src/components/kiva/enum-option-editor/kiva-enum-option-editor.tsx +320 -0
- package/src/components/kiva/enum-option-editor/types.ts +90 -0
- package/src/components/kiva/kanban.tsx +1376 -0
- package/src/components/kiva/kiva-data-export-menu.tsx +543 -0
- package/src/components/kiva/map.tsx +1631 -0
- package/src/components/kiva/pivot-calendar/components/group-sidebar.tsx +95 -0
- package/src/components/kiva/pivot-calendar/components/pivot-calendar-toolbar.tsx +113 -0
- package/src/components/kiva/pivot-calendar/components/stats-cell.tsx +126 -0
- package/src/components/kiva/pivot-calendar/helpers.ts +374 -0
- package/src/components/kiva/pivot-calendar/hooks/use-pivot-calendar.ts +222 -0
- package/src/components/kiva/pivot-calendar/index.tsx +32 -0
- package/src/components/kiva/pivot-calendar/pivot-calendar.tsx +107 -0
- package/src/components/kiva/pivot-calendar/types.ts +154 -0
- package/src/components/kiva/pivot-calendar/views/days-of-month-view.tsx +37 -0
- package/src/components/kiva/pivot-calendar/views/days-of-week-view.tsx +37 -0
- package/src/components/kiva/pivot-calendar/views/month-calendar-view.tsx +154 -0
- package/src/components/kiva/pivot-calendar/views/months-of-year-view.tsx +40 -0
- package/src/components/kiva/pivot-calendar/views/pivot-grid-view.tsx +251 -0
- package/src/components/kiva/pivot-filter/index.tsx +9 -0
- package/src/components/kiva/pivot-filter/pivot-filter-item.tsx +159 -0
- package/src/components/kiva/pivot-filter/pivot-filter-settings.tsx +161 -0
- package/src/components/kiva/pivot-filter/pivot-filter.tsx +187 -0
- package/src/components/kiva/pivot-filter/types.ts +82 -0
- package/src/components/kiva/pivot-grid/hooks/use-pivot-grid.ts +683 -0
- package/src/components/kiva/pivot-grid/index.tsx +23 -0
- package/src/components/kiva/pivot-grid/lib/pivot-grid-color-rules.ts +98 -0
- package/src/components/kiva/pivot-grid/lib/pivot-grid-export.ts +265 -0
- package/src/components/kiva/pivot-grid/lib/pivot-grid-model.ts +1110 -0
- package/src/components/kiva/pivot-grid/pivot-grid-demo-data.ts +200 -0
- package/src/components/kiva/pivot-grid/pivot-grid-export-menu.tsx +66 -0
- package/src/components/kiva/pivot-grid/pivot-grid-toolbar.tsx +85 -0
- package/src/components/kiva/pivot-grid/pivot-grid.tsx +601 -0
- package/src/components/kiva/pivot-grid/types.ts +195 -0
- package/src/components/kiva/place-autocomplete.tsx +484 -0
- package/src/components/kiva/record-delete-confirm-dialog/index.tsx +10 -0
- package/src/components/kiva/record-delete-confirm-dialog/record-delete-confirm-dialog.tsx +266 -0
- package/src/components/kiva/record-delete-confirm-dialog/types.ts +25 -0
- package/src/hooks/kiva/_internal/autonumber-setting.ts +112 -0
- package/src/hooks/kiva/_internal/form-layout-to-view.ts +665 -0
- package/src/hooks/kiva/_internal/kiva-hook-utils.ts +143 -0
- package/src/hooks/kiva/_internal/use-computed-field-evaluator.tsx +310 -0
- package/src/hooks/kiva/_internal/use-field-actions-evaluator.tsx +398 -0
- package/src/hooks/kiva/_internal/use-form-actions-evaluator.tsx +363 -0
- package/src/hooks/kiva/_internal/use-form-view-engine.tsx +2200 -0
- package/src/hooks/kiva/_internal/use-kiva-form-view-fields.tsx +190 -0
- package/src/hooks/kiva/_internal/use-kiva-kanban-cards.tsx +311 -0
- package/src/hooks/kiva/use-data-export.tsx +265 -0
- package/src/hooks/kiva/use-kiva-calendar.tsx +992 -0
- package/src/hooks/kiva/use-kiva-data-export.tsx +173 -0
- package/src/hooks/kiva/use-kiva-data-grid.tsx +4750 -0
- package/src/hooks/kiva/use-kiva-data-view-select.tsx +1273 -0
- package/src/hooks/kiva/use-kiva-form-view.tsx +1581 -0
- package/src/hooks/kiva/use-kiva-inventory.tsx +184 -0
- package/src/hooks/kiva/use-kiva-kanban.tsx +1750 -0
- package/src/hooks/kiva/use-kiva-map-view.tsx +2255 -0
- package/src/hooks/kiva/use-kiva-pivot-calendar.tsx +759 -0
- package/src/hooks/kiva/use-kiva-pivot-filter.tsx +1523 -0
- package/src/hooks/kiva/use-kiva-pivot-grid.tsx +543 -0
- package/src/hooks/kiva/use-kiva-tenant.tsx +313 -0
- package/src/hooks/kiva/use-parameter-persistence.ts +191 -0
|
@@ -0,0 +1,1523 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
// @ts-nocheck
|
|
4
|
+
/* eslint-disable */
|
|
5
|
+
import {
|
|
6
|
+
useCallback,
|
|
7
|
+
useEffect,
|
|
8
|
+
useMemo,
|
|
9
|
+
useRef,
|
|
10
|
+
useState,
|
|
11
|
+
type ReactNode
|
|
12
|
+
} from 'react';
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
addDays,
|
|
16
|
+
addHours,
|
|
17
|
+
addQuarters,
|
|
18
|
+
eachDayOfInterval,
|
|
19
|
+
eachHourOfInterval,
|
|
20
|
+
eachMonthOfInterval,
|
|
21
|
+
eachQuarterOfInterval,
|
|
22
|
+
eachWeekOfInterval,
|
|
23
|
+
endOfDay,
|
|
24
|
+
endOfMonth,
|
|
25
|
+
endOfQuarter,
|
|
26
|
+
endOfWeek,
|
|
27
|
+
endOfYear,
|
|
28
|
+
format,
|
|
29
|
+
formatISO,
|
|
30
|
+
startOfDay,
|
|
31
|
+
startOfMonth,
|
|
32
|
+
startOfQuarter,
|
|
33
|
+
startOfWeek,
|
|
34
|
+
startOfYear
|
|
35
|
+
} from 'date-fns';
|
|
36
|
+
|
|
37
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
38
|
+
import {
|
|
39
|
+
createDataSourceClient,
|
|
40
|
+
type DataSource,
|
|
41
|
+
type DataSourceField
|
|
42
|
+
} from '@kivacore/app-utils';
|
|
43
|
+
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
|
44
|
+
|
|
45
|
+
import {
|
|
46
|
+
PivotFilter,
|
|
47
|
+
type PivotFilterItem,
|
|
48
|
+
type PivotFilterProps,
|
|
49
|
+
type PivotFilterUser
|
|
50
|
+
} from '@kivacore/ui-pro-shared/components/kiva/pivot-filter';
|
|
51
|
+
import { cn } from '@kivacore/ui-pro-shared/lib/utils';
|
|
52
|
+
|
|
53
|
+
import { useUiTranslation } from '@kivacore/ui-pro-shared/hooks/kiva/use-ui-translation';
|
|
54
|
+
|
|
55
|
+
import { PivotFilterSettings } from '@kivacore/ui-pro-shared/components/kiva/pivot-filter/pivot-filter-settings';
|
|
56
|
+
|
|
57
|
+
/*
|
|
58
|
+
* -------------------------------------------------------------------------
|
|
59
|
+
* Public types
|
|
60
|
+
* -------------------------------------------------------------------------
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
export type PivotFilterAggregateFunc = 'count' | 'sum' | 'avg' | 'min' | 'max';
|
|
64
|
+
|
|
65
|
+
export interface PivotFilterCalculation {
|
|
66
|
+
/** Aggregate function. */
|
|
67
|
+
func: PivotFilterAggregateFunc;
|
|
68
|
+
/** Field slug used by the aggregate (e.g. `id`, `amount`). */
|
|
69
|
+
field: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type PivotFilterDateBucket
|
|
73
|
+
= | 'hours_of_today'
|
|
74
|
+
| 'days_of_week'
|
|
75
|
+
| 'days_of_month'
|
|
76
|
+
| 'weeks_of_month'
|
|
77
|
+
| 'weeks_of_quarter'
|
|
78
|
+
| 'months_of_quarter'
|
|
79
|
+
| 'months_of_year'
|
|
80
|
+
| 'quarters_of_year';
|
|
81
|
+
|
|
82
|
+
export type PivotFilterFieldType = 'list' | 'user' | 'user-multi' | 'date' | 'unsupported';
|
|
83
|
+
|
|
84
|
+
export interface PivotFilterRule {
|
|
85
|
+
field: string;
|
|
86
|
+
operator: string;
|
|
87
|
+
value: unknown;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface UseKivaPivotFilterOptions {
|
|
91
|
+
client: RestApiClient;
|
|
92
|
+
appSlug: string;
|
|
93
|
+
dataSourceSlug: string;
|
|
94
|
+
/** Slug of the field to pivot on. */
|
|
95
|
+
fieldSlug: string;
|
|
96
|
+
/** Aggregate. `null` (default) computes `count` of `id`. */
|
|
97
|
+
calculation?: PivotFilterCalculation | null;
|
|
98
|
+
/** Initial date bucket — only used when the field is a date / dateTime. */
|
|
99
|
+
defaultDateBucket?: PivotFilterDateBucket;
|
|
100
|
+
/** Base filter merged into every query (e.g. saved view's filter). */
|
|
101
|
+
defaultFilters?: unknown;
|
|
102
|
+
/**
|
|
103
|
+
* Filter currently active on the consumer (e.g. the data grid). Merged in
|
|
104
|
+
* on top of `defaultFilters`. Use this so the pill counts react to the
|
|
105
|
+
* user's other filtering.
|
|
106
|
+
*/
|
|
107
|
+
activeFilters?: unknown;
|
|
108
|
+
/**
|
|
109
|
+
* Filter contributed by a parent pivot filter. Merged in for nested
|
|
110
|
+
* "drill-down" pivot filter setups (e.g. filter by status, then by user).
|
|
111
|
+
*/
|
|
112
|
+
parentPivotFilters?: unknown;
|
|
113
|
+
/** Hide items whose `stat === 0` (except the currently selected one). */
|
|
114
|
+
hideZeroValues?: boolean;
|
|
115
|
+
/** Initially selected item id, or `null`. */
|
|
116
|
+
defaultSelectedItemId?: string | null;
|
|
117
|
+
/** Override the items query reference date — used for date buckets. */
|
|
118
|
+
referenceDate?: Date;
|
|
119
|
+
/** Disable the settings popover entirely. */
|
|
120
|
+
disableSettings?: boolean;
|
|
121
|
+
/**
|
|
122
|
+
* Fired whenever the user changes the date bucket or calculation through
|
|
123
|
+
* the settings popover (or via `setDateBucket` / `setCalculation`). Use it
|
|
124
|
+
* to persist the user's preference back to a saved view / preferences API.
|
|
125
|
+
*/
|
|
126
|
+
onConfigurationChange?: (config: {
|
|
127
|
+
dateBucket: PivotFilterDateBucket;
|
|
128
|
+
calculation: PivotFilterCalculation | null;
|
|
129
|
+
}) => void;
|
|
130
|
+
/** TanStack Query `staleTime` in ms. Defaults to 30s. */
|
|
131
|
+
staleTime?: number;
|
|
132
|
+
/** Skip fetching when `false`. */
|
|
133
|
+
enabled?: boolean;
|
|
134
|
+
/**
|
|
135
|
+
* `expand` query param sent with the data-source schema fetch. Defaults to
|
|
136
|
+
* `'enums'` (so select/status fields carry their option metadata). Pass
|
|
137
|
+
* `false` (or `''`) to omit `expand` entirely for backends that don't
|
|
138
|
+
* support it (e.g. core/tenant system data sources).
|
|
139
|
+
*/
|
|
140
|
+
dataSourceExpand?: string | false;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface UseKivaPivotFilterResult {
|
|
144
|
+
/** Props ready to spread on `<PivotFilter {...result.pivotFilterProps} />`. */
|
|
145
|
+
pivotFilterProps: PivotFilterProps;
|
|
146
|
+
/** All items derived from the API response. */
|
|
147
|
+
items: Array<PivotFilterItem>;
|
|
148
|
+
/** Aggregated stat across all items. */
|
|
149
|
+
total: number;
|
|
150
|
+
/** Currently selected item id (`null` = "All" pill). */
|
|
151
|
+
selectedItemId: string | null;
|
|
152
|
+
/** Update the selection programmatically (e.g. from external chips). */
|
|
153
|
+
setSelectedItemId: (id: string | null) => void;
|
|
154
|
+
/** Currently selected item (`null` for "All"). */
|
|
155
|
+
selectedItem: PivotFilterItem | null;
|
|
156
|
+
/**
|
|
157
|
+
* Filter rule(s) corresponding to the current selection — feed this back to
|
|
158
|
+
* the data source (e.g. as an additional rule on the active grid filter).
|
|
159
|
+
* `null` when "All" is selected.
|
|
160
|
+
*/
|
|
161
|
+
filterRule: Array<PivotFilterRule> | null;
|
|
162
|
+
/** Resolved field definition. */
|
|
163
|
+
field: DataSourceField | null;
|
|
164
|
+
/** Field strategy derived from `field.type`. */
|
|
165
|
+
fieldType: PivotFilterFieldType;
|
|
166
|
+
/** Current date bucket. Date buckets are FE-generated, not from the API. */
|
|
167
|
+
dateBucket: PivotFilterDateBucket;
|
|
168
|
+
/** Change the date bucket (also resets the selection). */
|
|
169
|
+
setDateBucket: (bucket: PivotFilterDateBucket) => void;
|
|
170
|
+
/** Current calculation (`null` = count of id). */
|
|
171
|
+
calculation: PivotFilterCalculation | null;
|
|
172
|
+
/** Change the calculation. */
|
|
173
|
+
setCalculation: (calc: PivotFilterCalculation | null) => void;
|
|
174
|
+
/** Refetch the data source and the items. */
|
|
175
|
+
reload: () => void;
|
|
176
|
+
isLoading: boolean;
|
|
177
|
+
isFetching: boolean;
|
|
178
|
+
error: Error | null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/*
|
|
182
|
+
* -------------------------------------------------------------------------
|
|
183
|
+
* Constants
|
|
184
|
+
* -------------------------------------------------------------------------
|
|
185
|
+
*/
|
|
186
|
+
|
|
187
|
+
const DEFAULT_DATE_BUCKET: PivotFilterDateBucket = 'days_of_week';
|
|
188
|
+
|
|
189
|
+
const DEFAULT_CALCULATION: PivotFilterCalculation = { func: 'count', field: 'id' };
|
|
190
|
+
|
|
191
|
+
/*
|
|
192
|
+
* Backend support for the native pivot syntax `columns: '<field>(...)'`
|
|
193
|
+
* combined with `calculations`:
|
|
194
|
+
*
|
|
195
|
+
* - `field-select`, `field-status`, `field-radioGroup`: joined enum table
|
|
196
|
+
* surfaces `id, name, color, icon`.
|
|
197
|
+
* - `field-relation`: joined related data source. `id` and `name` are
|
|
198
|
+
* guaranteed; `icon` / `color` are silently dropped when absent.
|
|
199
|
+
* - `field-userSelect`: joined tenant_user. `id` and `name` (computed).
|
|
200
|
+
* - `field-date` / `field-dateTime`: pivot via the native bucket function
|
|
201
|
+
* syntax `<bucket>@<field>` (no nested select).
|
|
202
|
+
* - `field-multiSelect`, `field-tagSelect`, `field-userMultiSelect`:
|
|
203
|
+
* backend's `applyPivot` rejects these as axis fields — surfaced as
|
|
204
|
+
* `fieldType: 'unsupported'` and the query is skipped.
|
|
205
|
+
*/
|
|
206
|
+
const LIST_FIELD_TYPES = new Set([
|
|
207
|
+
'field-select',
|
|
208
|
+
'field-status',
|
|
209
|
+
'field-radioGroup',
|
|
210
|
+
'field-relation'
|
|
211
|
+
]);
|
|
212
|
+
|
|
213
|
+
const USER_FIELD_TYPE = 'field-userSelect';
|
|
214
|
+
|
|
215
|
+
const DATE_FIELD_TYPES = new Set(['field-date', 'field-dateTime']);
|
|
216
|
+
|
|
217
|
+
/*
|
|
218
|
+
* -------------------------------------------------------------------------
|
|
219
|
+
* Hook
|
|
220
|
+
* -------------------------------------------------------------------------
|
|
221
|
+
*/
|
|
222
|
+
|
|
223
|
+
export function useKivaPivotFilter(
|
|
224
|
+
options: UseKivaPivotFilterOptions
|
|
225
|
+
): UseKivaPivotFilterResult {
|
|
226
|
+
const {
|
|
227
|
+
client,
|
|
228
|
+
appSlug,
|
|
229
|
+
dataSourceSlug,
|
|
230
|
+
fieldSlug,
|
|
231
|
+
calculation: calculationProp,
|
|
232
|
+
defaultDateBucket = DEFAULT_DATE_BUCKET,
|
|
233
|
+
defaultFilters,
|
|
234
|
+
activeFilters,
|
|
235
|
+
parentPivotFilters,
|
|
236
|
+
hideZeroValues = false,
|
|
237
|
+
defaultSelectedItemId = null,
|
|
238
|
+
referenceDate,
|
|
239
|
+
disableSettings = false,
|
|
240
|
+
onConfigurationChange,
|
|
241
|
+
staleTime = 30_000,
|
|
242
|
+
enabled = true,
|
|
243
|
+
dataSourceExpand = 'enums'
|
|
244
|
+
} = options;
|
|
245
|
+
|
|
246
|
+
const { t } = useUiTranslation();
|
|
247
|
+
const queryClient = useQueryClient();
|
|
248
|
+
|
|
249
|
+
const dataSourcesClient = useMemo(
|
|
250
|
+
() => createDataSourceClient(client),
|
|
251
|
+
[client]
|
|
252
|
+
);
|
|
253
|
+
|
|
254
|
+
const [selectedItemId, setSelectedItemId] = useState<string | null>(defaultSelectedItemId);
|
|
255
|
+
const [internalDateBucket, setInternalDateBucket] = useState<PivotFilterDateBucket>(defaultDateBucket);
|
|
256
|
+
const [internalCalculation, setInternalCalculation] = useState<PivotFilterCalculation | null>(
|
|
257
|
+
calculationProp ?? null
|
|
258
|
+
);
|
|
259
|
+
|
|
260
|
+
const dateBucket = internalDateBucket;
|
|
261
|
+
const calculation = internalCalculation;
|
|
262
|
+
|
|
263
|
+
/* ---- data source metadata -------------------------------------------- */
|
|
264
|
+
|
|
265
|
+
const dataSourceKey = useMemo(
|
|
266
|
+
() => [
|
|
267
|
+
'kiva',
|
|
268
|
+
'dataSource',
|
|
269
|
+
appSlug,
|
|
270
|
+
dataSourceSlug,
|
|
271
|
+
dataSourceExpand || 'none'
|
|
272
|
+
] as const,
|
|
273
|
+
[appSlug, dataSourceSlug, dataSourceExpand]
|
|
274
|
+
);
|
|
275
|
+
|
|
276
|
+
const dataSourceQuery = useQuery<DataSource>({
|
|
277
|
+
queryKey: dataSourceKey,
|
|
278
|
+
queryFn: () => dataSourcesClient.getBySlug(
|
|
279
|
+
appSlug,
|
|
280
|
+
dataSourceSlug,
|
|
281
|
+
dataSourceExpand ? { expand: dataSourceExpand } : undefined
|
|
282
|
+
),
|
|
283
|
+
enabled: enabled && Boolean(appSlug) && Boolean(dataSourceSlug),
|
|
284
|
+
staleTime
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
const dataSource = dataSourceQuery.data ?? null;
|
|
288
|
+
|
|
289
|
+
/* ---- field resolution ------------------------------------------------ */
|
|
290
|
+
|
|
291
|
+
const field = useMemo(() => {
|
|
292
|
+
if (!dataSource?.fields) return null;
|
|
293
|
+
|
|
294
|
+
return dataSource.fields.find(f => f.slug === fieldSlug) ?? null;
|
|
295
|
+
}, [dataSource?.fields, fieldSlug]);
|
|
296
|
+
|
|
297
|
+
const fieldType = useMemo<PivotFilterFieldType>(() => {
|
|
298
|
+
if (!field) return 'unsupported';
|
|
299
|
+
if (LIST_FIELD_TYPES.has(field.type)) return 'list';
|
|
300
|
+
if (field.type === USER_FIELD_TYPE) return 'user';
|
|
301
|
+
if (DATE_FIELD_TYPES.has(field.type)) return 'date';
|
|
302
|
+
|
|
303
|
+
return 'unsupported';
|
|
304
|
+
}, [field]);
|
|
305
|
+
|
|
306
|
+
/* ---- numeric / aggregate-target field list --------------------------- */
|
|
307
|
+
|
|
308
|
+
const aggregateTargetFields = useMemo(() => {
|
|
309
|
+
if (!dataSource?.fields) return [];
|
|
310
|
+
|
|
311
|
+
return dataSource.fields.filter(f => f.type === 'field-number' || f.type === 'field-money' || f.type === 'field-duration');
|
|
312
|
+
}, [dataSource?.fields]);
|
|
313
|
+
|
|
314
|
+
/* ---- query payload --------------------------------------------------- */
|
|
315
|
+
|
|
316
|
+
const referenceDateValue = useMemo(() => referenceDate ?? new Date(), [referenceDate]);
|
|
317
|
+
|
|
318
|
+
const dateRange = useMemo(() => {
|
|
319
|
+
if (fieldType !== 'date') return null;
|
|
320
|
+
|
|
321
|
+
return getDateRangeForBucket(dateBucket, referenceDateValue);
|
|
322
|
+
}, [fieldType, dateBucket, referenceDateValue]);
|
|
323
|
+
|
|
324
|
+
const mergedFilters = useMemo(() => mergeFilters([defaultFilters, activeFilters, parentPivotFilters]), [defaultFilters, activeFilters, parentPivotFilters]);
|
|
325
|
+
|
|
326
|
+
const calculationPayload = useMemo(() => buildCalculationPayload(calculation ?? DEFAULT_CALCULATION), [calculation]);
|
|
327
|
+
|
|
328
|
+
const payload = useMemo(() => {
|
|
329
|
+
if (!field) return null;
|
|
330
|
+
|
|
331
|
+
if (fieldType === 'date' && dateRange) {
|
|
332
|
+
return buildDatePayload(field.slug, dateRange, calculationPayload, mergedFilters);
|
|
333
|
+
}
|
|
334
|
+
if (fieldType === 'list') {
|
|
335
|
+
return buildListPayload(field.slug, calculationPayload, mergedFilters);
|
|
336
|
+
}
|
|
337
|
+
if (fieldType === 'user' || fieldType === 'user-multi') {
|
|
338
|
+
return buildUserPayload(field.slug, calculationPayload, mergedFilters);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
return null;
|
|
342
|
+
}, [
|
|
343
|
+
field,
|
|
344
|
+
fieldType,
|
|
345
|
+
dateRange,
|
|
346
|
+
calculationPayload,
|
|
347
|
+
mergedFilters
|
|
348
|
+
]);
|
|
349
|
+
|
|
350
|
+
/* ---- items query ----------------------------------------------------- */
|
|
351
|
+
|
|
352
|
+
const itemsQueryKey = useMemo(
|
|
353
|
+
() => [
|
|
354
|
+
'kiva',
|
|
355
|
+
'pivotFilter',
|
|
356
|
+
appSlug,
|
|
357
|
+
dataSourceSlug,
|
|
358
|
+
fieldSlug,
|
|
359
|
+
fieldType,
|
|
360
|
+
dateBucket,
|
|
361
|
+
calculationPayload.name,
|
|
362
|
+
payload
|
|
363
|
+
] as const,
|
|
364
|
+
[
|
|
365
|
+
appSlug,
|
|
366
|
+
dataSourceSlug,
|
|
367
|
+
fieldSlug,
|
|
368
|
+
fieldType,
|
|
369
|
+
dateBucket,
|
|
370
|
+
calculationPayload.name,
|
|
371
|
+
payload
|
|
372
|
+
]
|
|
373
|
+
);
|
|
374
|
+
|
|
375
|
+
const itemsQuery = useQuery<Array<Record<string, unknown>>>({
|
|
376
|
+
queryKey: itemsQueryKey,
|
|
377
|
+
queryFn: async () => {
|
|
378
|
+
if (!payload) return [];
|
|
379
|
+
|
|
380
|
+
const response = await client.get<Array<Record<string, unknown>> | { data: Array<Record<string, unknown>> }>(
|
|
381
|
+
`/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/items`,
|
|
382
|
+
payload as Parameters<typeof client.get>[1]
|
|
383
|
+
);
|
|
384
|
+
|
|
385
|
+
if (Array.isArray(response)) return response;
|
|
386
|
+
if (response && typeof response === 'object' && Array.isArray((response as { data?: unknown }).data)) {
|
|
387
|
+
return (response as { data: Array<Record<string, unknown>> }).data;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
return [];
|
|
391
|
+
},
|
|
392
|
+
enabled: enabled && Boolean(field) && Boolean(payload) && fieldType !== 'unsupported',
|
|
393
|
+
staleTime
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
/* ---- item transformation -------------------------------------------- */
|
|
397
|
+
|
|
398
|
+
const fieldOptions = useMemo(() => {
|
|
399
|
+
if (!field) return [];
|
|
400
|
+
|
|
401
|
+
return extractFieldOptions(field);
|
|
402
|
+
}, [field]);
|
|
403
|
+
|
|
404
|
+
const items = useMemo<Array<PivotFilterItem>>(() => {
|
|
405
|
+
const apiRows = itemsQuery.data ?? [];
|
|
406
|
+
const statName = calculationPayload.name;
|
|
407
|
+
let built: Array<PivotFilterItem> = [];
|
|
408
|
+
|
|
409
|
+
if (fieldType === 'list' && field) {
|
|
410
|
+
built = buildListItems(apiRows, statName, fieldOptions, field.slug, t('ui.pivotFilter.notSet', 'Not Set'));
|
|
411
|
+
} else if (fieldType === 'user' && field) {
|
|
412
|
+
built = buildUserItems(apiRows, statName, field.slug, t('ui.pivotFilter.notSet', 'Not Set'));
|
|
413
|
+
} else if (fieldType === 'user-multi' && field) {
|
|
414
|
+
built = buildUserMultiItems(apiRows, statName, field.slug, t('ui.pivotFilter.notSet', 'Not Set'));
|
|
415
|
+
} else if (fieldType === 'date' && dateRange && field) {
|
|
416
|
+
built = buildDateItems(
|
|
417
|
+
apiRows,
|
|
418
|
+
statName,
|
|
419
|
+
field.slug,
|
|
420
|
+
dateBucket,
|
|
421
|
+
referenceDateValue,
|
|
422
|
+
t('ui.pivotFilter.notSet', 'Not Set'),
|
|
423
|
+
t('ui.pivotFilter.before', 'Before'),
|
|
424
|
+
t('ui.pivotFilter.upcoming', 'Upcoming')
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/*
|
|
429
|
+
* Sort pivot items so the strip is deterministic across loads:
|
|
430
|
+
* - list/enum → preserve the schema's option order (status progressions
|
|
431
|
+
* like Open → In Progress → Done stay meaningful). Items
|
|
432
|
+
* not found in the schema fall to the end, stat-descending.
|
|
433
|
+
* - user/user-multi → stat-descending with locale-aware name tiebreak.
|
|
434
|
+
* - date → template order (already meaningful — calendar buckets).
|
|
435
|
+
* - "Not Set" → always last, regardless of type.
|
|
436
|
+
*/
|
|
437
|
+
if (fieldType === 'list' && fieldOptions.length > 0) {
|
|
438
|
+
const optionOrder = new Map(fieldOptions.map((o, i) => [o.id, i]));
|
|
439
|
+
|
|
440
|
+
built = [...built].sort((a, b) => {
|
|
441
|
+
if (a.isEmpty && !b.isEmpty) return 1;
|
|
442
|
+
if (!a.isEmpty && b.isEmpty) return -1;
|
|
443
|
+
|
|
444
|
+
const ai = optionOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER;
|
|
445
|
+
const bi = optionOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER;
|
|
446
|
+
|
|
447
|
+
if (ai !== bi) return ai - bi;
|
|
448
|
+
|
|
449
|
+
return (b.stat ?? 0) - (a.stat ?? 0);
|
|
450
|
+
});
|
|
451
|
+
} else if (fieldType === 'user' || fieldType === 'user-multi') {
|
|
452
|
+
built = [...built].sort((a, b) => {
|
|
453
|
+
if (a.isEmpty && !b.isEmpty) return 1;
|
|
454
|
+
if (!a.isEmpty && b.isEmpty) return -1;
|
|
455
|
+
|
|
456
|
+
const statDiff = (b.stat ?? 0) - (a.stat ?? 0);
|
|
457
|
+
|
|
458
|
+
if (statDiff !== 0) return statDiff;
|
|
459
|
+
|
|
460
|
+
return a.name.localeCompare(b.name);
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
return built;
|
|
465
|
+
}, [
|
|
466
|
+
itemsQuery.data,
|
|
467
|
+
field,
|
|
468
|
+
fieldType,
|
|
469
|
+
fieldOptions,
|
|
470
|
+
calculationPayload.name,
|
|
471
|
+
dateBucket,
|
|
472
|
+
dateRange,
|
|
473
|
+
referenceDateValue,
|
|
474
|
+
t
|
|
475
|
+
]);
|
|
476
|
+
|
|
477
|
+
const total = useMemo(() => items.reduce((sum, item) => sum + item.stat, 0), [items]);
|
|
478
|
+
|
|
479
|
+
/* ---- filter rule emission ------------------------------------------- */
|
|
480
|
+
|
|
481
|
+
const selectedItem = useMemo(
|
|
482
|
+
() => items.find(item => item.id === selectedItemId) ?? null,
|
|
483
|
+
[items, selectedItemId]
|
|
484
|
+
);
|
|
485
|
+
|
|
486
|
+
const filterRule = useMemo<Array<PivotFilterRule> | null>(() => {
|
|
487
|
+
if (!field || selectedItem === null) return null;
|
|
488
|
+
|
|
489
|
+
const isDateOnly = field.type === 'field-date';
|
|
490
|
+
|
|
491
|
+
return buildFilterRule(field.slug, fieldType, isDateOnly, selectedItem);
|
|
492
|
+
}, [field, fieldType, selectedItem]);
|
|
493
|
+
|
|
494
|
+
const handleSelect = useCallback((item: PivotFilterItem | null) => {
|
|
495
|
+
setSelectedItemId(item ? item.id : null);
|
|
496
|
+
}, []);
|
|
497
|
+
|
|
498
|
+
const handleSetDateBucket = useCallback((next: PivotFilterDateBucket) => {
|
|
499
|
+
setInternalDateBucket(next);
|
|
500
|
+
setSelectedItemId(null);
|
|
501
|
+
onConfigurationChange?.({ dateBucket: next, calculation: internalCalculation });
|
|
502
|
+
}, [onConfigurationChange, internalCalculation]);
|
|
503
|
+
|
|
504
|
+
const handleSetCalculation = useCallback((next: PivotFilterCalculation | null) => {
|
|
505
|
+
setInternalCalculation(next);
|
|
506
|
+
onConfigurationChange?.({ dateBucket: internalDateBucket, calculation: next });
|
|
507
|
+
}, [onConfigurationChange, internalDateBucket]);
|
|
508
|
+
|
|
509
|
+
/*
|
|
510
|
+
* When the parent pivot's filter changes, the current selection may point
|
|
511
|
+
* to a bucket that no longer exists in the new result set. Reset it so the
|
|
512
|
+
* UI stays in a coherent state (matches Vue's `KvPivotFilter` behavior).
|
|
513
|
+
*/
|
|
514
|
+
const previousParentFiltersRef = useRef(parentPivotFilters);
|
|
515
|
+
|
|
516
|
+
useEffect(() => {
|
|
517
|
+
if (previousParentFiltersRef.current !== parentPivotFilters) {
|
|
518
|
+
previousParentFiltersRef.current = parentPivotFilters;
|
|
519
|
+
setSelectedItemId(null);
|
|
520
|
+
}
|
|
521
|
+
}, [parentPivotFilters]);
|
|
522
|
+
|
|
523
|
+
/* ---- refresh + settings ---------------------------------------------- */
|
|
524
|
+
|
|
525
|
+
const reload = useCallback(() => {
|
|
526
|
+
void queryClient.invalidateQueries({ queryKey: dataSourceKey });
|
|
527
|
+
void itemsQuery.refetch();
|
|
528
|
+
}, [queryClient, dataSourceKey, itemsQuery]);
|
|
529
|
+
|
|
530
|
+
const settingsContent = useMemo<ReactNode>(() => {
|
|
531
|
+
if (disableSettings) return undefined;
|
|
532
|
+
if (!field) return undefined;
|
|
533
|
+
|
|
534
|
+
return (
|
|
535
|
+
<PivotFilterSettings
|
|
536
|
+
fieldType={fieldType}
|
|
537
|
+
dateBucket={dateBucket}
|
|
538
|
+
onDateBucketChange={handleSetDateBucket}
|
|
539
|
+
calculation={calculation}
|
|
540
|
+
onCalculationChange={handleSetCalculation}
|
|
541
|
+
aggregateFields={aggregateTargetFields} />
|
|
542
|
+
);
|
|
543
|
+
}, [
|
|
544
|
+
disableSettings,
|
|
545
|
+
field,
|
|
546
|
+
fieldType,
|
|
547
|
+
dateBucket,
|
|
548
|
+
handleSetDateBucket,
|
|
549
|
+
calculation,
|
|
550
|
+
handleSetCalculation,
|
|
551
|
+
aggregateTargetFields
|
|
552
|
+
]);
|
|
553
|
+
|
|
554
|
+
/* ---- pivotFilterProps ----------------------------------------------- */
|
|
555
|
+
|
|
556
|
+
const pivotFilterProps = useMemo<PivotFilterProps>(() => ({
|
|
557
|
+
items,
|
|
558
|
+
selectedItemId,
|
|
559
|
+
onSelect: handleSelect,
|
|
560
|
+
total,
|
|
561
|
+
loading: itemsQuery.isLoading,
|
|
562
|
+
hideZeroValues,
|
|
563
|
+
onRefresh: reload,
|
|
564
|
+
settingsContent
|
|
565
|
+
}), [
|
|
566
|
+
items,
|
|
567
|
+
selectedItemId,
|
|
568
|
+
handleSelect,
|
|
569
|
+
total,
|
|
570
|
+
itemsQuery.isLoading,
|
|
571
|
+
hideZeroValues,
|
|
572
|
+
reload,
|
|
573
|
+
settingsContent
|
|
574
|
+
]);
|
|
575
|
+
|
|
576
|
+
const isLoading = dataSourceQuery.isLoading || itemsQuery.isLoading;
|
|
577
|
+
const isFetching = dataSourceQuery.isFetching || itemsQuery.isFetching;
|
|
578
|
+
const error = (dataSourceQuery.error ?? itemsQuery.error) as Error | null;
|
|
579
|
+
|
|
580
|
+
return {
|
|
581
|
+
pivotFilterProps,
|
|
582
|
+
items,
|
|
583
|
+
total,
|
|
584
|
+
selectedItemId,
|
|
585
|
+
setSelectedItemId,
|
|
586
|
+
selectedItem,
|
|
587
|
+
filterRule,
|
|
588
|
+
field,
|
|
589
|
+
fieldType,
|
|
590
|
+
dateBucket,
|
|
591
|
+
setDateBucket: handleSetDateBucket,
|
|
592
|
+
calculation,
|
|
593
|
+
setCalculation: handleSetCalculation,
|
|
594
|
+
reload,
|
|
595
|
+
isLoading,
|
|
596
|
+
isFetching,
|
|
597
|
+
error
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/*
|
|
602
|
+
* -------------------------------------------------------------------------
|
|
603
|
+
* Payload builders
|
|
604
|
+
* -------------------------------------------------------------------------
|
|
605
|
+
*/
|
|
606
|
+
|
|
607
|
+
function buildCalculationPayload(calc: PivotFilterCalculation) {
|
|
608
|
+
const name = `${calc.func.toUpperCase()}_OF_${calc.field}`;
|
|
609
|
+
|
|
610
|
+
return {
|
|
611
|
+
field: calc.field,
|
|
612
|
+
func: calc.func,
|
|
613
|
+
name
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function buildListPayload(
|
|
618
|
+
fieldSlug: string,
|
|
619
|
+
calc: { field: string; func: string; name: string },
|
|
620
|
+
filters: unknown
|
|
621
|
+
): Record<string, unknown> {
|
|
622
|
+
/*
|
|
623
|
+
* Use native Kiva column-with-nested-select syntax:
|
|
624
|
+
*
|
|
625
|
+
* columns: 'status(id, name, icon, color)'
|
|
626
|
+
*
|
|
627
|
+
* Combined with `calculations`, the backend joins the related table
|
|
628
|
+
* (`tenant_enum` for select/status/radioGroup, the related data source
|
|
629
|
+
* for relation fields) and auto-groups by the joined keys. The response
|
|
630
|
+
* row carries the sub-object directly:
|
|
631
|
+
*
|
|
632
|
+
* `[{ status: { id, name, icon, color }, COUNT_OF_id: 5 }, ...]`
|
|
633
|
+
*
|
|
634
|
+
* This avoids the `pivot.matrix` alias quirks: the matrix path uses
|
|
635
|
+
* `cte0.<alias>` (left side of `:`) as a real column name on the CTE,
|
|
636
|
+
* AND auto-pushes `cte0.id as cte0__id` — so any user-provided `id`
|
|
637
|
+
* collided. The native column syntax has none of that.
|
|
638
|
+
*/
|
|
639
|
+
return {
|
|
640
|
+
columns: `${fieldSlug}(id, name, icon, color)`,
|
|
641
|
+
...(filters ? { filters } : {}),
|
|
642
|
+
calculations: [calc]
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function buildUserPayload(
|
|
647
|
+
fieldSlug: string,
|
|
648
|
+
calc: { field: string; func: string; name: string },
|
|
649
|
+
filters: unknown
|
|
650
|
+
): Record<string, unknown> {
|
|
651
|
+
/*
|
|
652
|
+
* `field-userSelect` resolves to the tenant users data source. The
|
|
653
|
+
* `name` subfield is the backend-computed display name. Avatar URLs are
|
|
654
|
+
* not surfaced today; resolve them in the FE from the consumer's users
|
|
655
|
+
* list when needed.
|
|
656
|
+
*/
|
|
657
|
+
return {
|
|
658
|
+
columns: `${fieldSlug}(id, name)`,
|
|
659
|
+
...(filters ? { filters } : {}),
|
|
660
|
+
calculations: [calc]
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
function buildDatePayload(
|
|
665
|
+
fieldSlug: string,
|
|
666
|
+
range: DateRange,
|
|
667
|
+
calc: { field: string; func: string; name: string },
|
|
668
|
+
filters: unknown
|
|
669
|
+
): Record<string, unknown> {
|
|
670
|
+
/*
|
|
671
|
+
* Native Kiva date-bucket function syntax: `<bucket>@<dateField>`.
|
|
672
|
+
* Supported buckets include `days_of_week`, `days_of_month`,
|
|
673
|
+
* `weeks_of_month`, `weeks_of_quarter`, `months_of_quarter`,
|
|
674
|
+
* `months_of_year`, `quarters_of_year`, `hours_of_today`. The backend
|
|
675
|
+
* SQL emits a CASE expression with `OLDER` / `UPCOMING` sentinels for
|
|
676
|
+
* out-of-range dates plus `to_char` for the in-range bucket key, and
|
|
677
|
+
* auto-groups by the result.
|
|
678
|
+
*
|
|
679
|
+
* Response row: `{ '<bucket>@<dateField>': '2024-03-15' | 'OLDER' | 'UPCOMING', COUNT_OF_id }`.
|
|
680
|
+
*/
|
|
681
|
+
void range;
|
|
682
|
+
|
|
683
|
+
return {
|
|
684
|
+
columns: `${range.bucketFunc}@${fieldSlug}`,
|
|
685
|
+
...(filters ? { filters } : {}),
|
|
686
|
+
calculations: [calc]
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function mergeFilters(parts: Array<unknown>): unknown {
|
|
691
|
+
const rules: Array<unknown> = [];
|
|
692
|
+
|
|
693
|
+
for (const part of parts) {
|
|
694
|
+
if (!part) continue;
|
|
695
|
+
|
|
696
|
+
if (Array.isArray(part)) {
|
|
697
|
+
rules.push(...part);
|
|
698
|
+
continue;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
if (typeof part === 'object') {
|
|
702
|
+
const obj = part as { rules?: unknown; combinator?: string };
|
|
703
|
+
|
|
704
|
+
if (Array.isArray(obj.rules)) {
|
|
705
|
+
/*
|
|
706
|
+
* Only inline the child group's rules when it is an AND group — an AND
|
|
707
|
+
* group is semantically equivalent to its rules being siblings in the
|
|
708
|
+
* parent AND container. An OR group must stay as a nested group so its
|
|
709
|
+
* OR combinator is preserved; flattening it into the parent AND would
|
|
710
|
+
* turn OR(A, B) into AND(A, B), changing the query meaning entirely.
|
|
711
|
+
*/
|
|
712
|
+
if ((obj.combinator ?? 'and') === 'and') {
|
|
713
|
+
rules.push(...obj.rules);
|
|
714
|
+
} else {
|
|
715
|
+
rules.push(obj);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
if (rules.length === 0) return null;
|
|
722
|
+
|
|
723
|
+
return { combinator: 'and', rules };
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/*
|
|
727
|
+
* -------------------------------------------------------------------------
|
|
728
|
+
* Date bucket generators
|
|
729
|
+
* -------------------------------------------------------------------------
|
|
730
|
+
*/
|
|
731
|
+
|
|
732
|
+
interface DateRange {
|
|
733
|
+
/** The bucket-function id; also the backend `<bucket>@<field>` function name. */
|
|
734
|
+
bucketFunc: PivotFilterDateBucket;
|
|
735
|
+
/** Window start — drives FE template generation. */
|
|
736
|
+
start: Date;
|
|
737
|
+
/** Window end — drives FE template generation. */
|
|
738
|
+
end: Date;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
function getDateRangeForBucket(bucket: PivotFilterDateBucket, refDate: Date): DateRange {
|
|
742
|
+
const window = (() => {
|
|
743
|
+
switch (bucket) {
|
|
744
|
+
case 'hours_of_today': return { start: startOfDay(refDate), end: endOfDay(refDate) };
|
|
745
|
+
|
|
746
|
+
case 'days_of_week': return {
|
|
747
|
+
start: startOfWeek(refDate, { weekStartsOn: 1 }),
|
|
748
|
+
end: endOfWeek(refDate, { weekStartsOn: 1 })
|
|
749
|
+
};
|
|
750
|
+
|
|
751
|
+
case 'days_of_month': return { start: startOfMonth(refDate), end: endOfMonth(refDate) };
|
|
752
|
+
|
|
753
|
+
case 'weeks_of_month': return { start: startOfMonth(refDate), end: endOfMonth(refDate) };
|
|
754
|
+
|
|
755
|
+
case 'weeks_of_quarter': return { start: startOfQuarter(refDate), end: endOfQuarter(refDate) };
|
|
756
|
+
|
|
757
|
+
case 'months_of_quarter': return { start: startOfQuarter(refDate), end: endOfQuarter(refDate) };
|
|
758
|
+
|
|
759
|
+
case 'months_of_year': return { start: startOfYear(refDate), end: endOfYear(refDate) };
|
|
760
|
+
|
|
761
|
+
case 'quarters_of_year': return { start: startOfYear(refDate), end: endOfYear(refDate) };
|
|
762
|
+
}
|
|
763
|
+
})();
|
|
764
|
+
|
|
765
|
+
return {
|
|
766
|
+
bucketFunc: bucket,
|
|
767
|
+
start: window.start,
|
|
768
|
+
end: window.end
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/*
|
|
773
|
+
* -------------------------------------------------------------------------
|
|
774
|
+
* Item builders
|
|
775
|
+
* -------------------------------------------------------------------------
|
|
776
|
+
*/
|
|
777
|
+
|
|
778
|
+
function readStat(row: Record<string, unknown>, name: string): number {
|
|
779
|
+
const value = row[name];
|
|
780
|
+
|
|
781
|
+
if (typeof value === 'number') return value;
|
|
782
|
+
if (typeof value === 'string') {
|
|
783
|
+
const parsed = Number.parseFloat(value);
|
|
784
|
+
|
|
785
|
+
return Number.isNaN(parsed) ? 0 : parsed;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
return 0;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
interface KivaEnumOption {
|
|
792
|
+
id: string;
|
|
793
|
+
slug?: string;
|
|
794
|
+
name: string;
|
|
795
|
+
icon?: string;
|
|
796
|
+
color?: string;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
function extractFieldOptions(field: DataSourceField): Array<KivaEnumOption> {
|
|
800
|
+
const raw = field as Record<string, unknown>;
|
|
801
|
+
const source = Array.isArray(raw.enums) ? raw.enums : Array.isArray(raw.options) ? raw.options : [];
|
|
802
|
+
|
|
803
|
+
const result: Array<KivaEnumOption> = [];
|
|
804
|
+
|
|
805
|
+
for (const entry of source) {
|
|
806
|
+
if (!entry || typeof entry !== 'object') continue;
|
|
807
|
+
|
|
808
|
+
const option = entry as Record<string, unknown>;
|
|
809
|
+
const id = typeof option.id === 'string' ? option.id : undefined;
|
|
810
|
+
const slug = typeof option.slug === 'string' ? option.slug : typeof option.value === 'string' ? option.value : undefined;
|
|
811
|
+
const identifier = id ?? slug;
|
|
812
|
+
const name = typeof option.name === 'string' ? option.name : typeof option.label === 'string' ? option.label : slug ?? identifier;
|
|
813
|
+
const icon = typeof option.icon === 'string' ? option.icon : undefined;
|
|
814
|
+
const color = typeof option.color === 'string' ? option.color : undefined;
|
|
815
|
+
|
|
816
|
+
if (!identifier || !name) continue;
|
|
817
|
+
|
|
818
|
+
result.push({
|
|
819
|
+
id: identifier,
|
|
820
|
+
slug,
|
|
821
|
+
name,
|
|
822
|
+
icon,
|
|
823
|
+
color
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
return result;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
function buildListItems(
|
|
831
|
+
rows: Array<Record<string, unknown>>,
|
|
832
|
+
statName: string,
|
|
833
|
+
options: Array<KivaEnumOption>,
|
|
834
|
+
fieldSlug: string,
|
|
835
|
+
emptyLabel: string
|
|
836
|
+
): Array<PivotFilterItem> {
|
|
837
|
+
/*
|
|
838
|
+
* Response shape (with `columns: '<fieldSlug>(id, name, icon, color)'`):
|
|
839
|
+
* { [fieldSlug]: { id, name, icon?, color? } | null, [statName]: <number> }
|
|
840
|
+
*
|
|
841
|
+
* Icon / color come back inline for enum-style fields. For relation
|
|
842
|
+
* fields they're typically `null`; fallback to the data source's enum
|
|
843
|
+
* metadata when present.
|
|
844
|
+
*/
|
|
845
|
+
const optionsById = new Map(options.map(opt => [opt.id, opt]));
|
|
846
|
+
|
|
847
|
+
return rows.map<PivotFilterItem>((row) => {
|
|
848
|
+
const stat = readStat(row, statName);
|
|
849
|
+
const nested = row[fieldSlug] as Record<string, unknown> | null | undefined;
|
|
850
|
+
|
|
851
|
+
if (!nested) {
|
|
852
|
+
return {
|
|
853
|
+
id: 'EMPTY',
|
|
854
|
+
name: emptyLabel,
|
|
855
|
+
stat,
|
|
856
|
+
isEmpty: true
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
const id = typeof nested.id === 'string' ? nested.id : String(nested.id ?? '');
|
|
861
|
+
|
|
862
|
+
if (!id) {
|
|
863
|
+
return {
|
|
864
|
+
id: 'EMPTY',
|
|
865
|
+
name: emptyLabel,
|
|
866
|
+
stat,
|
|
867
|
+
isEmpty: true
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
const inlineName = typeof nested.name === 'string' ? nested.name : null;
|
|
872
|
+
const inlineIcon = typeof nested.icon === 'string' ? nested.icon : null;
|
|
873
|
+
const inlineColor = typeof nested.color === 'string' ? nested.color : null;
|
|
874
|
+
const option = optionsById.get(id);
|
|
875
|
+
|
|
876
|
+
return {
|
|
877
|
+
id,
|
|
878
|
+
name: inlineName ?? option?.name ?? id,
|
|
879
|
+
stat,
|
|
880
|
+
icon: inlineIcon ?? option?.icon,
|
|
881
|
+
color: inlineColor ?? option?.color
|
|
882
|
+
};
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
function buildUserItems(
|
|
887
|
+
rows: Array<Record<string, unknown>>,
|
|
888
|
+
statName: string,
|
|
889
|
+
fieldSlug: string,
|
|
890
|
+
emptyLabel: string
|
|
891
|
+
): Array<PivotFilterItem> {
|
|
892
|
+
/* Response shape: `{ [fieldSlug]: { id, name } | null, [statName] }`. */
|
|
893
|
+
return rows.map<PivotFilterItem>((row) => {
|
|
894
|
+
const stat = readStat(row, statName);
|
|
895
|
+
const nested = row[fieldSlug] as Record<string, unknown> | null | undefined;
|
|
896
|
+
const userId = nested && typeof nested.id === 'string' ? nested.id : null;
|
|
897
|
+
const name = nested && typeof nested.name === 'string' ? nested.name : null;
|
|
898
|
+
|
|
899
|
+
if (!userId) {
|
|
900
|
+
return {
|
|
901
|
+
id: 'EMPTY',
|
|
902
|
+
name: emptyLabel,
|
|
903
|
+
stat,
|
|
904
|
+
isEmpty: true
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
const user: PivotFilterUser = {
|
|
909
|
+
id: userId,
|
|
910
|
+
name: name ?? userId,
|
|
911
|
+
picturePath: null
|
|
912
|
+
};
|
|
913
|
+
|
|
914
|
+
return {
|
|
915
|
+
id: userId,
|
|
916
|
+
name: user.name,
|
|
917
|
+
stat,
|
|
918
|
+
user
|
|
919
|
+
};
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function buildUserMultiItems(
|
|
924
|
+
rows: Array<Record<string, unknown>>,
|
|
925
|
+
statName: string,
|
|
926
|
+
fieldSlug: string,
|
|
927
|
+
emptyLabel: string
|
|
928
|
+
): Array<PivotFilterItem> {
|
|
929
|
+
/*
|
|
930
|
+
* Currently routed through `fieldType: 'unsupported'` at the strategy
|
|
931
|
+
* detection step (backend rejects `userMultiSelect` for pivots). Kept here
|
|
932
|
+
* for symmetry and a future backend fix — assumes `[fieldSlug]` carries a
|
|
933
|
+
* `{ id, name }` per row.
|
|
934
|
+
*/
|
|
935
|
+
const bucket = new Map<string, PivotFilterItem>();
|
|
936
|
+
|
|
937
|
+
for (const row of rows) {
|
|
938
|
+
const stat = readStat(row, statName);
|
|
939
|
+
const nested = row[fieldSlug] as Record<string, unknown> | null | undefined;
|
|
940
|
+
const userId = nested && typeof nested.id === 'string' ? nested.id : null;
|
|
941
|
+
|
|
942
|
+
if (!userId) {
|
|
943
|
+
const existing = bucket.get('EMPTY');
|
|
944
|
+
|
|
945
|
+
if (existing) {
|
|
946
|
+
existing.stat += stat;
|
|
947
|
+
} else {
|
|
948
|
+
bucket.set('EMPTY', {
|
|
949
|
+
id: 'EMPTY',
|
|
950
|
+
name: emptyLabel,
|
|
951
|
+
stat,
|
|
952
|
+
isEmpty: true
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
continue;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
const name = nested && typeof nested.name === 'string' ? nested.name : userId;
|
|
959
|
+
const existing = bucket.get(userId);
|
|
960
|
+
|
|
961
|
+
if (existing) {
|
|
962
|
+
existing.stat += stat;
|
|
963
|
+
} else {
|
|
964
|
+
bucket.set(userId, {
|
|
965
|
+
id: userId,
|
|
966
|
+
name,
|
|
967
|
+
stat,
|
|
968
|
+
user: { id: userId, name, picturePath: null }
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
return Array.from(bucket.values());
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
interface DateBucketTemplate {
|
|
977
|
+
id: string;
|
|
978
|
+
name: string;
|
|
979
|
+
secondary?: string;
|
|
980
|
+
interval: [Date, Date] | null;
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
function buildDateItems(
|
|
984
|
+
rows: Array<Record<string, unknown>>,
|
|
985
|
+
statName: string,
|
|
986
|
+
fieldSlug: string,
|
|
987
|
+
bucket: PivotFilterDateBucket,
|
|
988
|
+
refDate: Date,
|
|
989
|
+
emptyLabel: string,
|
|
990
|
+
beforeLabel: string,
|
|
991
|
+
upcomingLabel: string
|
|
992
|
+
): Array<PivotFilterItem> {
|
|
993
|
+
/*
|
|
994
|
+
* Backend `<bucket>@<field>` CASE expression returns one of:
|
|
995
|
+
* - `'OLDER'` — record's date is before the window
|
|
996
|
+
* - `'UPCOMING'` — record's date is after the window
|
|
997
|
+
* - `'<formatted bucket key>'` — in-range, formatted via `to_char`
|
|
998
|
+
* - `null` — record has no date (only when `field-date` allows nulls)
|
|
999
|
+
*
|
|
1000
|
+
* The response row's bucket value is keyed by `<bucket>@<fieldSlug>` (the
|
|
1001
|
+
* raw column expression, since we didn't alias it).
|
|
1002
|
+
*/
|
|
1003
|
+
const templates = buildDateTemplates(bucket, refDate, beforeLabel, upcomingLabel);
|
|
1004
|
+
const statByBucket = new Map<string, number>();
|
|
1005
|
+
let beforeStat = 0;
|
|
1006
|
+
let upcomingStat = 0;
|
|
1007
|
+
let emptyStat = 0;
|
|
1008
|
+
const responseKey = `${bucket}@${fieldSlug}`;
|
|
1009
|
+
|
|
1010
|
+
for (const row of rows) {
|
|
1011
|
+
const stat = readStat(row, statName);
|
|
1012
|
+
const rawBucket = row[responseKey];
|
|
1013
|
+
|
|
1014
|
+
if (rawBucket == null) {
|
|
1015
|
+
emptyStat += stat;
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
const bucketKey = String(rawBucket);
|
|
1020
|
+
|
|
1021
|
+
if (bucketKey === 'OLDER') {
|
|
1022
|
+
beforeStat += stat;
|
|
1023
|
+
continue;
|
|
1024
|
+
}
|
|
1025
|
+
if (bucketKey === 'UPCOMING') {
|
|
1026
|
+
upcomingStat += stat;
|
|
1027
|
+
continue;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
statByBucket.set(bucketKey, (statByBucket.get(bucketKey) ?? 0) + stat);
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
return templates.map<PivotFilterItem>((template) => {
|
|
1034
|
+
if (template.id === 'BEFORE') {
|
|
1035
|
+
return {
|
|
1036
|
+
id: 'BEFORE',
|
|
1037
|
+
name: template.name,
|
|
1038
|
+
stat: beforeStat,
|
|
1039
|
+
meta: { interval: template.interval }
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
if (template.id === 'UPCOMING') {
|
|
1043
|
+
return {
|
|
1044
|
+
id: 'UPCOMING',
|
|
1045
|
+
name: template.name,
|
|
1046
|
+
stat: upcomingStat,
|
|
1047
|
+
meta: { interval: template.interval }
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
if (template.id === 'EMPTY') {
|
|
1051
|
+
return {
|
|
1052
|
+
id: 'EMPTY',
|
|
1053
|
+
name: emptyLabel,
|
|
1054
|
+
stat: emptyStat,
|
|
1055
|
+
isEmpty: true
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
return {
|
|
1060
|
+
id: template.id,
|
|
1061
|
+
name: template.name,
|
|
1062
|
+
secondary: template.secondary,
|
|
1063
|
+
stat: statByBucket.get(template.id) ?? 0,
|
|
1064
|
+
meta: { interval: template.interval }
|
|
1065
|
+
};
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
function buildDateTemplates(
|
|
1070
|
+
bucket: PivotFilterDateBucket,
|
|
1071
|
+
refDate: Date,
|
|
1072
|
+
beforeLabel: string,
|
|
1073
|
+
upcomingLabel: string
|
|
1074
|
+
): Array<DateBucketTemplate> {
|
|
1075
|
+
const before: DateBucketTemplate = {
|
|
1076
|
+
id: 'BEFORE',
|
|
1077
|
+
name: beforeLabel,
|
|
1078
|
+
interval: null
|
|
1079
|
+
};
|
|
1080
|
+
const upcoming: DateBucketTemplate = {
|
|
1081
|
+
id: 'UPCOMING',
|
|
1082
|
+
name: upcomingLabel,
|
|
1083
|
+
interval: null
|
|
1084
|
+
};
|
|
1085
|
+
const empty: DateBucketTemplate = {
|
|
1086
|
+
id: 'EMPTY',
|
|
1087
|
+
name: 'EMPTY',
|
|
1088
|
+
interval: null
|
|
1089
|
+
};
|
|
1090
|
+
|
|
1091
|
+
let inner: Array<DateBucketTemplate> = [];
|
|
1092
|
+
|
|
1093
|
+
switch (bucket) {
|
|
1094
|
+
case 'hours_of_today': {
|
|
1095
|
+
const start = startOfDay(refDate);
|
|
1096
|
+
const end = endOfDay(refDate);
|
|
1097
|
+
|
|
1098
|
+
before.interval = [new Date(0), start];
|
|
1099
|
+
upcoming.interval = [end, new Date(8640000000000000)];
|
|
1100
|
+
inner = eachHourOfInterval({ start, end }).map(day => ({
|
|
1101
|
+
id: format(day, 'yyyy-MM-dd-HH'),
|
|
1102
|
+
name: format(day, 'HH'),
|
|
1103
|
+
secondary: `→ ${format(addHours(day, 1), 'HH')}`,
|
|
1104
|
+
interval: [day, addHours(day, 1)]
|
|
1105
|
+
}));
|
|
1106
|
+
break;
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
case 'days_of_week': {
|
|
1110
|
+
const start = startOfWeek(refDate, { weekStartsOn: 1 });
|
|
1111
|
+
const end = endOfWeek(refDate, { weekStartsOn: 1 });
|
|
1112
|
+
|
|
1113
|
+
before.interval = [new Date(0), start];
|
|
1114
|
+
upcoming.interval = [end, new Date(8640000000000000)];
|
|
1115
|
+
inner = eachDayOfInterval({ start, end }).map(day => ({
|
|
1116
|
+
id: format(day, 'yyyy-MM-dd'),
|
|
1117
|
+
name: format(day, 'EEE').toUpperCase(),
|
|
1118
|
+
secondary: format(day, 'd MMM'),
|
|
1119
|
+
interval: [day, endOfDay(day)]
|
|
1120
|
+
}));
|
|
1121
|
+
break;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
case 'days_of_month': {
|
|
1125
|
+
const start = startOfMonth(refDate);
|
|
1126
|
+
const end = endOfMonth(refDate);
|
|
1127
|
+
|
|
1128
|
+
before.interval = [new Date(0), start];
|
|
1129
|
+
upcoming.interval = [end, new Date(8640000000000000)];
|
|
1130
|
+
inner = eachDayOfInterval({ start, end }).map(day => ({
|
|
1131
|
+
id: format(day, 'yyyy-MM-dd'),
|
|
1132
|
+
name: format(day, 'd'),
|
|
1133
|
+
secondary: format(day, 'MMM, EEE'),
|
|
1134
|
+
interval: [day, endOfDay(day)]
|
|
1135
|
+
}));
|
|
1136
|
+
break;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
case 'weeks_of_month': {
|
|
1140
|
+
const start = startOfMonth(refDate);
|
|
1141
|
+
const end = endOfMonth(refDate);
|
|
1142
|
+
|
|
1143
|
+
before.interval = [new Date(0), start];
|
|
1144
|
+
upcoming.interval = [end, new Date(8640000000000000)];
|
|
1145
|
+
inner = eachWeekOfInterval({ start, end }, { weekStartsOn: 1 }).map((day, index) => ({
|
|
1146
|
+
id: format(day, 'RRRR-II'),
|
|
1147
|
+
name: `W${String(index + 1).padStart(2, '0')}`,
|
|
1148
|
+
secondary: `${format(day, 'dd.MM')} – ${format(addDays(day, 6), 'dd.MM')}`,
|
|
1149
|
+
interval: [day, endOfWeek(day, { weekStartsOn: 1 })]
|
|
1150
|
+
}));
|
|
1151
|
+
break;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
case 'weeks_of_quarter': {
|
|
1155
|
+
const start = startOfQuarter(refDate);
|
|
1156
|
+
const end = endOfQuarter(refDate);
|
|
1157
|
+
|
|
1158
|
+
before.interval = [new Date(0), start];
|
|
1159
|
+
upcoming.interval = [end, new Date(8640000000000000)];
|
|
1160
|
+
inner = eachWeekOfInterval({ start, end }, { weekStartsOn: 1 }).map((day, index) => ({
|
|
1161
|
+
id: format(day, 'RRRR-II'),
|
|
1162
|
+
name: `W${String(index + 1).padStart(2, '0')}`,
|
|
1163
|
+
secondary: `${format(day, 'dd.MM')} – ${format(addDays(day, 6), 'dd.MM')}`,
|
|
1164
|
+
interval: [day, endOfWeek(day, { weekStartsOn: 1 })]
|
|
1165
|
+
}));
|
|
1166
|
+
break;
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
case 'months_of_quarter': {
|
|
1170
|
+
const start = startOfQuarter(refDate);
|
|
1171
|
+
const end = endOfQuarter(refDate);
|
|
1172
|
+
|
|
1173
|
+
before.interval = [new Date(0), start];
|
|
1174
|
+
upcoming.interval = [end, new Date(8640000000000000)];
|
|
1175
|
+
inner = eachMonthOfInterval({ start, end }).map(day => ({
|
|
1176
|
+
id: format(day, 'yyyy-MM'),
|
|
1177
|
+
name: format(day, 'MMM'),
|
|
1178
|
+
secondary: format(day, 'yyyy'),
|
|
1179
|
+
interval: [day, endOfMonth(day)]
|
|
1180
|
+
}));
|
|
1181
|
+
break;
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
case 'months_of_year': {
|
|
1185
|
+
const start = startOfYear(refDate);
|
|
1186
|
+
const end = endOfYear(refDate);
|
|
1187
|
+
|
|
1188
|
+
before.interval = [new Date(0), start];
|
|
1189
|
+
upcoming.interval = [end, new Date(8640000000000000)];
|
|
1190
|
+
inner = eachMonthOfInterval({ start, end }).map(day => ({
|
|
1191
|
+
id: format(day, 'yyyy-MM'),
|
|
1192
|
+
name: format(day, 'MMM'),
|
|
1193
|
+
secondary: format(day, 'yyyy'),
|
|
1194
|
+
interval: [day, endOfMonth(day)]
|
|
1195
|
+
}));
|
|
1196
|
+
break;
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
case 'quarters_of_year': {
|
|
1200
|
+
const start = startOfYear(refDate);
|
|
1201
|
+
const end = endOfYear(refDate);
|
|
1202
|
+
|
|
1203
|
+
before.interval = [new Date(0), start];
|
|
1204
|
+
upcoming.interval = [end, new Date(8640000000000000)];
|
|
1205
|
+
inner = eachQuarterOfInterval({ start, end }).map(day => ({
|
|
1206
|
+
id: format(day, 'yyyy-Q'),
|
|
1207
|
+
name: format(day, 'QQQ'),
|
|
1208
|
+
secondary: format(day, 'yyyy'),
|
|
1209
|
+
interval: [day, addQuarters(day, 1)]
|
|
1210
|
+
}));
|
|
1211
|
+
break;
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
return [
|
|
1216
|
+
before,
|
|
1217
|
+
...inner,
|
|
1218
|
+
upcoming,
|
|
1219
|
+
empty
|
|
1220
|
+
];
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
/*
|
|
1224
|
+
* -------------------------------------------------------------------------
|
|
1225
|
+
* Filter rule emission
|
|
1226
|
+
* -------------------------------------------------------------------------
|
|
1227
|
+
*/
|
|
1228
|
+
|
|
1229
|
+
function buildFilterRule(
|
|
1230
|
+
fieldSlug: string,
|
|
1231
|
+
fieldType: PivotFilterFieldType,
|
|
1232
|
+
isDateOnly: boolean,
|
|
1233
|
+
item: PivotFilterItem
|
|
1234
|
+
): Array<PivotFilterRule> {
|
|
1235
|
+
if (item.isEmpty || item.id === 'EMPTY') {
|
|
1236
|
+
return [{ field: fieldSlug, operator: 'empty', value: null }];
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
if (fieldType === 'date') {
|
|
1240
|
+
const interval = (item.meta?.interval as [Date, Date] | null | undefined) ?? null;
|
|
1241
|
+
const fmt = (d: Date) => formatDateForFilter(d, isDateOnly);
|
|
1242
|
+
|
|
1243
|
+
if (item.id === 'BEFORE') {
|
|
1244
|
+
const end = interval?.[1];
|
|
1245
|
+
|
|
1246
|
+
return end ? [{ field: fieldSlug, operator: '<', value: fmt(end) }] : [];
|
|
1247
|
+
}
|
|
1248
|
+
if (item.id === 'UPCOMING') {
|
|
1249
|
+
const start = interval?.[0];
|
|
1250
|
+
|
|
1251
|
+
return start ? [{ field: fieldSlug, operator: '>', value: fmt(start) }] : [];
|
|
1252
|
+
}
|
|
1253
|
+
if (interval) {
|
|
1254
|
+
return [
|
|
1255
|
+
{
|
|
1256
|
+
field: fieldSlug,
|
|
1257
|
+
operator: 'between',
|
|
1258
|
+
value: [fmt(interval[0]), fmt(interval[1])]
|
|
1259
|
+
}
|
|
1260
|
+
];
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
return [];
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
if (fieldType === 'user-multi') {
|
|
1267
|
+
return [{ field: fieldSlug, operator: 'contains any', value: [item.id] }];
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
return [{ field: fieldSlug, operator: '=', value: item.id }];
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/*
|
|
1274
|
+
* Format a JS `Date` (whose components are interpreted in the user's local
|
|
1275
|
+
* timezone) for the filter payload, matching Vue `KvPivotFilter` semantics:
|
|
1276
|
+
*
|
|
1277
|
+
* - `field-date` (date-only): preserve the *wall-clock* numbers but stamp the
|
|
1278
|
+
* value as UTC (e.g. `2026-05-13T00:00:00+00:00`). This avoids the local
|
|
1279
|
+
* day being silently shifted by the TZ offset.
|
|
1280
|
+
* - `field-dateTime`: preserve the local offset (e.g.
|
|
1281
|
+
* `2026-05-13T00:00:00+03:00`).
|
|
1282
|
+
*/
|
|
1283
|
+
function formatDateForFilter(date: Date, isDateOnly: boolean): string {
|
|
1284
|
+
if (isDateOnly) {
|
|
1285
|
+
return formatISO(date).replace(/[+-]\d{2}:\d{2}$/, '+00:00');
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
return formatISO(date);
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
/*
|
|
1292
|
+
* -------------------------------------------------------------------------
|
|
1293
|
+
* <KivaPivotFilterGroup>
|
|
1294
|
+
* -------------------------------------------------------------------------
|
|
1295
|
+
*
|
|
1296
|
+
* Higher-level component that stacks multiple `<PivotFilter>` strips above
|
|
1297
|
+
* a consumer surface (data grid, calendar, map…) and wires bidirectional
|
|
1298
|
+
* cross-filtering between them: when the user picks an item in one strip,
|
|
1299
|
+
* the pill counts on every other strip automatically refetch with the new
|
|
1300
|
+
* selection applied as an `activeFilters` rule.
|
|
1301
|
+
*
|
|
1302
|
+
* Hooks can't be called in a loop with a dynamic count, so this component
|
|
1303
|
+
* delegates each field to a single-instance child (`<PivotFilterGroupRow>`)
|
|
1304
|
+
* that owns its own `useKivaPivotFilter`. The group component lifts each
|
|
1305
|
+
* row's `filterRule` into a shared map and feeds the OTHER rows' rules back
|
|
1306
|
+
* down as `activeFilters` — no glue code needed in consumer pages.
|
|
1307
|
+
*/
|
|
1308
|
+
|
|
1309
|
+
export interface KivaPivotFilterGroupField {
|
|
1310
|
+
/** Slug of the field to pivot on. */
|
|
1311
|
+
fieldSlug: string;
|
|
1312
|
+
/** Initial date bucket — only used for `field-date` / `field-dateTime`. */
|
|
1313
|
+
defaultDateBucket?: PivotFilterDateBucket;
|
|
1314
|
+
/** Initial calculation. `null` (default) is `count` of `id`. */
|
|
1315
|
+
calculation?: PivotFilterCalculation | null;
|
|
1316
|
+
/** Override the "All" pill label for this strip. */
|
|
1317
|
+
totalLabel?: string;
|
|
1318
|
+
/** Hide items whose stat is zero (except the currently selected one). */
|
|
1319
|
+
hideZeroValues?: boolean;
|
|
1320
|
+
/** Disable the settings popover for this strip. */
|
|
1321
|
+
disableSettings?: boolean;
|
|
1322
|
+
/** Initial selection. */
|
|
1323
|
+
defaultSelectedItemId?: string | null;
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
export interface KivaPivotFilterGroupProps {
|
|
1327
|
+
client: RestApiClient;
|
|
1328
|
+
appSlug: string;
|
|
1329
|
+
dataSourceSlug: string;
|
|
1330
|
+
/** One entry per stacked pivot. Order = stack order top-to-bottom. */
|
|
1331
|
+
fields: ReadonlyArray<KivaPivotFilterGroupField>;
|
|
1332
|
+
/** Base filter applied to every strip's items query (e.g. saved view). */
|
|
1333
|
+
defaultFilters?: unknown;
|
|
1334
|
+
/**
|
|
1335
|
+
* External filter applied to every strip's items query (e.g. the consumer
|
|
1336
|
+
* grid's current toolbar filter). Pill counts react to this filter.
|
|
1337
|
+
*/
|
|
1338
|
+
activeFilters?: unknown;
|
|
1339
|
+
/**
|
|
1340
|
+
* Fired with the AND-combined filter rule of every pivot's current
|
|
1341
|
+
* selection. `null` when no pivot has a selection. Feed it back to your
|
|
1342
|
+
* consumer surface's filter input.
|
|
1343
|
+
*/
|
|
1344
|
+
onFilterRuleChange?: (rule: Array<PivotFilterRule> | null) => void;
|
|
1345
|
+
/** Render strips vertically (column rail). */
|
|
1346
|
+
vertical?: boolean;
|
|
1347
|
+
/** Compact pill layout. */
|
|
1348
|
+
compact?: boolean;
|
|
1349
|
+
/** Wrapper class name. */
|
|
1350
|
+
className?: string;
|
|
1351
|
+
/** TanStack Query staleTime (ms). Forwarded to every strip. */
|
|
1352
|
+
staleTime?: number;
|
|
1353
|
+
/**
|
|
1354
|
+
* `expand` query param for the shared data-source schema fetch. Defaults to
|
|
1355
|
+
* `'enums'`. Pass `false` (or `''`) to omit `expand` for backends that don't
|
|
1356
|
+
* support it (e.g. core/tenant system data sources). Forwarded to every strip.
|
|
1357
|
+
*/
|
|
1358
|
+
dataSourceExpand?: string | false;
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
interface PivotFilterGroupRowProps {
|
|
1362
|
+
client: RestApiClient;
|
|
1363
|
+
appSlug: string;
|
|
1364
|
+
dataSourceSlug: string;
|
|
1365
|
+
field: KivaPivotFilterGroupField;
|
|
1366
|
+
defaultFilters: unknown;
|
|
1367
|
+
activeFilters: unknown;
|
|
1368
|
+
vertical: boolean;
|
|
1369
|
+
compact: boolean;
|
|
1370
|
+
staleTime: number | undefined;
|
|
1371
|
+
dataSourceExpand: string | false | undefined;
|
|
1372
|
+
onFilterRuleChange: (fieldSlug: string, rule: Array<PivotFilterRule> | null) => void;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
function PivotFilterGroupRow({
|
|
1376
|
+
client,
|
|
1377
|
+
appSlug,
|
|
1378
|
+
dataSourceSlug,
|
|
1379
|
+
field,
|
|
1380
|
+
defaultFilters,
|
|
1381
|
+
activeFilters,
|
|
1382
|
+
vertical,
|
|
1383
|
+
compact,
|
|
1384
|
+
staleTime,
|
|
1385
|
+
dataSourceExpand,
|
|
1386
|
+
onFilterRuleChange
|
|
1387
|
+
}: PivotFilterGroupRowProps) {
|
|
1388
|
+
const pivot = useKivaPivotFilter({
|
|
1389
|
+
client,
|
|
1390
|
+
appSlug,
|
|
1391
|
+
dataSourceSlug,
|
|
1392
|
+
fieldSlug: field.fieldSlug,
|
|
1393
|
+
defaultDateBucket: field.defaultDateBucket,
|
|
1394
|
+
calculation: field.calculation ?? null,
|
|
1395
|
+
defaultFilters,
|
|
1396
|
+
activeFilters,
|
|
1397
|
+
hideZeroValues: field.hideZeroValues,
|
|
1398
|
+
disableSettings: field.disableSettings,
|
|
1399
|
+
defaultSelectedItemId: field.defaultSelectedItemId,
|
|
1400
|
+
staleTime,
|
|
1401
|
+
dataSourceExpand
|
|
1402
|
+
});
|
|
1403
|
+
|
|
1404
|
+
/*
|
|
1405
|
+
* Bubble each row's filterRule up to the parent group. The parent merges
|
|
1406
|
+
* sibling rules into `activeFilters` for cross-filtering and emits the
|
|
1407
|
+
* combined rule to the consumer via `onFilterRuleChange`.
|
|
1408
|
+
*/
|
|
1409
|
+
useEffect(() => {
|
|
1410
|
+
onFilterRuleChange(field.fieldSlug, pivot.filterRule);
|
|
1411
|
+
}, [field.fieldSlug, pivot.filterRule, onFilterRuleChange]);
|
|
1412
|
+
|
|
1413
|
+
return (
|
|
1414
|
+
<PivotFilter
|
|
1415
|
+
{...pivot.pivotFilterProps}
|
|
1416
|
+
vertical={vertical}
|
|
1417
|
+
compact={compact}
|
|
1418
|
+
totalLabel={field.totalLabel} />
|
|
1419
|
+
);
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
export function KivaPivotFilterGroup({
|
|
1423
|
+
client,
|
|
1424
|
+
appSlug,
|
|
1425
|
+
dataSourceSlug,
|
|
1426
|
+
fields,
|
|
1427
|
+
defaultFilters,
|
|
1428
|
+
activeFilters,
|
|
1429
|
+
onFilterRuleChange,
|
|
1430
|
+
vertical = false,
|
|
1431
|
+
compact = false,
|
|
1432
|
+
className,
|
|
1433
|
+
staleTime,
|
|
1434
|
+
dataSourceExpand
|
|
1435
|
+
}: KivaPivotFilterGroupProps) {
|
|
1436
|
+
/*
|
|
1437
|
+
* `Map<fieldSlug, filterRule>` — each row reports its current rule here,
|
|
1438
|
+
* and we feed the *other* rows' rules back down as `activeFilters` for
|
|
1439
|
+
* cross-filtering. Using a Map (instead of a plain object) makes change
|
|
1440
|
+
* detection straightforward via reference equality.
|
|
1441
|
+
*/
|
|
1442
|
+
const [rulesByField, setRulesByField] = useState<Map<string, Array<PivotFilterRule> | null>>(
|
|
1443
|
+
() => new Map()
|
|
1444
|
+
);
|
|
1445
|
+
|
|
1446
|
+
const handleRowFilterRuleChange = useCallback(
|
|
1447
|
+
(fieldSlug: string, rule: Array<PivotFilterRule> | null) => {
|
|
1448
|
+
setRulesByField((prev) => {
|
|
1449
|
+
const previous = prev.get(fieldSlug) ?? null;
|
|
1450
|
+
|
|
1451
|
+
if (previous === rule) return prev;
|
|
1452
|
+
|
|
1453
|
+
const next = new Map(prev);
|
|
1454
|
+
|
|
1455
|
+
if (rule === null) {
|
|
1456
|
+
next.delete(fieldSlug);
|
|
1457
|
+
} else {
|
|
1458
|
+
next.set(fieldSlug, rule);
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
return next;
|
|
1462
|
+
});
|
|
1463
|
+
},
|
|
1464
|
+
[]
|
|
1465
|
+
);
|
|
1466
|
+
|
|
1467
|
+
const combinedRule = useMemo(() => {
|
|
1468
|
+
const rules: Array<PivotFilterRule> = [];
|
|
1469
|
+
|
|
1470
|
+
for (const rule of rulesByField.values()) {
|
|
1471
|
+
if (rule) rules.push(...rule);
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
return rules.length > 0 ? rules : null;
|
|
1475
|
+
}, [rulesByField]);
|
|
1476
|
+
|
|
1477
|
+
useEffect(() => {
|
|
1478
|
+
onFilterRuleChange?.(combinedRule);
|
|
1479
|
+
}, [combinedRule, onFilterRuleChange]);
|
|
1480
|
+
|
|
1481
|
+
return (
|
|
1482
|
+
<div
|
|
1483
|
+
data-pivot-filter-group
|
|
1484
|
+
className={cn(
|
|
1485
|
+
'flex',
|
|
1486
|
+
vertical ? 'flex-row gap-2' : 'flex-col gap-2',
|
|
1487
|
+
className
|
|
1488
|
+
)}>
|
|
1489
|
+
{fields.map((field) => {
|
|
1490
|
+
/*
|
|
1491
|
+
* `activeFilters` for this row = caller's `activeFilters` + every
|
|
1492
|
+
* sibling's filter rule (everyone except this row). Each row's
|
|
1493
|
+
* pill counts react to the user's selections in the other strips.
|
|
1494
|
+
*/
|
|
1495
|
+
const siblingRules: Array<PivotFilterRule> = [];
|
|
1496
|
+
|
|
1497
|
+
for (const [slug, rule] of rulesByField.entries()) {
|
|
1498
|
+
if (slug !== field.fieldSlug && rule) {
|
|
1499
|
+
siblingRules.push(...rule);
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
const rowActiveFilters = mergeFilters([activeFilters, siblingRules]);
|
|
1504
|
+
|
|
1505
|
+
return (
|
|
1506
|
+
<PivotFilterGroupRow
|
|
1507
|
+
key={field.fieldSlug}
|
|
1508
|
+
client={client}
|
|
1509
|
+
appSlug={appSlug}
|
|
1510
|
+
dataSourceSlug={dataSourceSlug}
|
|
1511
|
+
field={field}
|
|
1512
|
+
defaultFilters={defaultFilters}
|
|
1513
|
+
activeFilters={rowActiveFilters}
|
|
1514
|
+
vertical={vertical}
|
|
1515
|
+
compact={compact}
|
|
1516
|
+
staleTime={staleTime}
|
|
1517
|
+
dataSourceExpand={dataSourceExpand}
|
|
1518
|
+
onFilterRuleChange={handleRowFilterRuleChange} />
|
|
1519
|
+
);
|
|
1520
|
+
})}
|
|
1521
|
+
</div>
|
|
1522
|
+
);
|
|
1523
|
+
}
|