Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M7-006): report + dashboard + widget modules into core (report constants: intervals to plain Date math)

ralpha11c10301b2b
diff --git a/apps/start/src/components/overview/useOverviewOptions.ts b/apps/start/src/components/overview/useOverviewOptions.ts
index 0455ddaba..47640fe5e 100644
--- a/apps/start/src/components/overview/useOverviewOptions.ts
+++ b/apps/start/src/components/overview/useOverviewOptions.ts
@@ -7,6 +7,7 @@ import {
} from 'nuqs';
import { useCookieStore } from '@/hooks/use-cookie-store';
+import { mapKeys } from '@/utils/object-to-zod-enums';
import {
getDefaultIntervalByDates,
getDefaultIntervalByRange,
@@ -14,7 +15,6 @@ import {
timeWindows,
} from '@openpanel/constants';
import type { IChartRange } from '@openpanel/validation';
-import { mapKeys } from '@openpanel/validation';
const nuqsOptions = { history: 'push' } as const;
diff --git a/apps/start/src/components/overview/useOverviewWidget.tsx b/apps/start/src/components/overview/useOverviewWidget.tsx
index 52fb56b8c..db1a2399d 100644
--- a/apps/start/src/components/overview/useOverviewWidget.tsx
+++ b/apps/start/src/components/overview/useOverviewWidget.tsx
@@ -1,6 +1,6 @@
import { parseAsStringEnum, useQueryState } from 'nuqs';
-import { mapKeys } from '@openpanel/validation';
+import { mapKeys } from '@/utils/object-to-zod-enums';
import type { ReportChartProps } from '../report-chart/context';
diff --git a/apps/start/src/components/report/ReportChartType.tsx b/apps/start/src/components/report/ReportChartType.tsx
index 4d6129e68..dd88a379e 100644
--- a/apps/start/src/components/report/ReportChartType.tsx
+++ b/apps/start/src/components/report/ReportChartType.tsx
@@ -15,7 +15,7 @@ import {
} from 'lucide-react';
import { chartTypes } from '@openpanel/constants';
-import { type IChartType, objectToZodEnums } from '@openpanel/validation';
+import type { IChartType } from '@openpanel/validation';
import {
DropdownMenu,
@@ -28,6 +28,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/utils/cn';
+import { objectToZodEnums } from '@/utils/object-to-zod-enums';
import { Button } from '../ui/button';
import { changeChartType } from './reportSlice';
diff --git a/apps/start/src/components/report/ReportLineType.tsx b/apps/start/src/components/report/ReportLineType.tsx
index 5e1cf7b46..b528e5871 100644
--- a/apps/start/src/components/report/ReportLineType.tsx
+++ b/apps/start/src/components/report/ReportLineType.tsx
@@ -1,8 +1,8 @@
import { useDispatch, useSelector } from '@/redux';
+import { objectToZodEnums } from '@/utils/object-to-zod-enums';
import { Tv2Icon } from 'lucide-react';
import { lineTypes } from '@openpanel/constants';
-import { objectToZodEnums } from '@openpanel/validation';
import { Combobox } from '../ui/combobox';
import { changeLineType } from './reportSlice';
diff --git a/apps/start/src/components/report/ReportSegment.tsx b/apps/start/src/components/report/ReportSegment.tsx
index c320164e2..15a61ae6c 100644
--- a/apps/start/src/components/report/ReportSegment.tsx
+++ b/apps/start/src/components/report/ReportSegment.tsx
@@ -1,5 +1,5 @@
import { chartSegments } from '@openpanel/constants';
-import { type IChartEventSegment, mapKeys } from '@openpanel/validation';
+import type { IChartEventSegment } from '@openpanel/validation';
import {
ActivityIcon,
Building2Icon,
@@ -25,6 +25,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/utils/cn';
+import { mapKeys } from '@/utils/object-to-zod-enums';
interface ReportChartTypeProps {
className?: string;
diff --git a/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx b/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx
index 63b2e257c..c89ab1578 100644
--- a/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx
+++ b/apps/start/src/components/report/sidebar/filters/FilterTypeSelect.tsx
@@ -1,8 +1,8 @@
import { Button } from '@/components/ui/button';
import { DropdownMenuComposed } from '@/components/ui/dropdown-menu';
+import { mapKeys } from '@/utils/object-to-zod-enums';
import { filterValueTypes } from '@openpanel/constants';
import type { IChartFilterValueType } from '@openpanel/validation';
-import { mapKeys } from '@openpanel/validation';
interface FilterTypeSelectProps {
value: IChartFilterValueType | undefined;
diff --git a/apps/start/src/components/theme-provider.tsx b/apps/start/src/components/theme-provider.tsx
index 792b57f87..9e4b7b4e8 100644
--- a/apps/start/src/components/theme-provider.tsx
+++ b/apps/start/src/components/theme-provider.tsx
@@ -1,5 +1,5 @@
import { useCookieStore } from '@/hooks/use-cookie-store';
-import { mapKeys } from '@openpanel/validation';
+import { mapKeys } from '@/utils/object-to-zod-enums';
import { ScriptOnce, useRouteContext } from '@tanstack/react-router';
import { createIsomorphicFn } from '@tanstack/react-start';
import { type ReactNode, createContext, use, useEffect, useState } from 'react';
diff --git a/apps/start/src/utils/object-to-zod-enums.ts b/apps/start/src/utils/object-to-zod-enums.ts
new file mode 100644
index 000000000..36ee6f4e6
--- /dev/null
+++ b/apps/start/src/utils/object-to-zod-enums.ts
@@ -0,0 +1,11 @@
+// Helper, not vocabulary — ADR-008's ruling: `objectToZodEnums` has no
+// owning module, so it is copied here rather than value-imported from
+// @openpanel/core (same treatment ADR-007 gives the `common` math helpers).
+export function objectToZodEnums<K extends string>(
+ obj: Record<K, unknown>
+): [K, ...K[]] {
+ const [firstKey, ...otherKeys] = Object.keys(obj) as K[];
+ return [firstKey!, ...otherKeys];
+}
+
+export const mapKeys = objectToZodEnums;
diff --git a/packages/constants/index.ts b/packages/constants/index.ts
index d5d2263f9..be2dce2bf 100644
--- a/packages/constants/index.ts
+++ b/packages/constants/index.ts
@@ -1,620 +1,22 @@
-import { differenceInDays, isSameDay } from 'date-fns';
-
-export const DEFAULT_ASPECT_RATIO = 0.5625;
-export const NOT_SET_VALUE = '(not set)';
-
export const RESERVED_EVENT_NAMES = ['session_start', 'session_end'] as const;
-export const timeWindows = {
- '30min': {
- key: '30min',
- label: 'Last 30 min',
- shortcut: 'R',
- },
- lastHour: {
- key: 'lastHour',
- label: 'Last hour',
- shortcut: 'H',
- },
- last24h: {
- key: 'last24h',
- label: 'Last 24 hours',
- shortcut: '4',
- },
- today: {
- key: 'today',
- label: 'Today',
- shortcut: 'D',
- },
- yesterday: {
- key: 'yesterday',
- label: 'Yesterday',
- shortcut: 'E',
- },
- '7d': {
- key: '7d',
- label: 'Last 7 days',
- shortcut: 'W',
- },
- '30d': {
- key: '30d',
- label: 'Last 30 days',
- shortcut: 'T',
- },
- '3m': {
- key: '3m',
- label: 'Last 3 months',
- shortcut: '3',
- },
- '6m': {
- key: '6m',
- label: 'Last 6 months',
- shortcut: '6',
- },
- '12m': {
- key: '12m',
- label: 'Last 12 months',
- shortcut: '0',
- },
- monthToDate: {
- key: 'monthToDate',
- label: 'Month to Date',
- shortcut: 'M',
- },
- lastMonth: {
- key: 'lastMonth',
- label: 'Last Month',
- shortcut: 'P',
- },
- yearToDate: {
- key: 'yearToDate',
- label: 'Year to Date',
- shortcut: 'Y',
- },
- lastYear: {
- key: 'lastYear',
- label: 'Last year',
- shortcut: 'U',
- },
- custom: {
- key: 'custom',
- label: 'Custom range',
- shortcut: 'C',
- },
-} as const;
-
-// Moved into @openpanel/core's project module (M6-002, ADR-008's module
-// map: project owns "C"). Re-exported here for existing
-// @openpanel/constants importers — same shape as
-// packages/validation/src/import.validation.ts since M5-004.
-export { ProjectTypeNames } from '@openpanel/core/modules/project/project.constants';
-
-export const operators = {
- is: 'Is',
- isNot: 'Is not',
- contains: 'Contains',
- doesNotContain: 'Not contains',
- startsWith: 'Starts with',
- endsWith: 'Ends with',
- regex: 'Regex',
- isNull: 'Is null',
- isNotNull: 'Is not null',
- gt: 'Greater than',
- lt: 'Less than',
- gte: 'Greater than or equal to',
- lte: 'Less than or equal to',
- inCohort: 'In cohort',
- notInCohort: 'Not in cohort',
-} as const;
-
-// Compact labels for the operator trigger button. The comparison operators
-// have very long names ("Greater than or equal to"), so we show a symbol on
-// the trigger (reads naturally next to the value, e.g. "≥ 2019-01-01") and
-// surface the full `operators` text as a sub-line in the dropdown.
-export const operatorsShort: Record<keyof typeof operators, string> = {
- is: 'Is',
- isNot: 'Is not',
- contains: 'Contains',
- doesNotContain: 'Not contains',
- startsWith: 'Starts with',
- endsWith: 'Ends with',
- regex: 'Regex',
- isNull: 'Is null',
- isNotNull: 'Is not null',
- gt: '>',
- lt: '<',
- gte: '≥',
- lte: '≤',
- inCohort: 'In cohort',
- notInCohort: 'Not in cohort',
-};
-
-// Cast type a filter value/column should be coerced to before comparing.
-// `string` (the default) keeps raw text comparison; the others wrap both sides
-// of the comparison in the matching ClickHouse cast (see packages/db
-// filter-cast.ts) so e.g. a date property compares as a date instead of
-// crashing `toFloat64('2019-01-01')`.
-export const filterValueTypes = {
- string: 'Text',
- number: 'Number',
- date: 'Date',
- datetime: 'Date & time',
- boolean: 'Boolean',
-} as const;
-
-export type IFilterValueType = keyof typeof filterValueTypes;
-
-// Operators that make sense for each value type. The type constrains the
-// operator list in the UI (a Number can't `contains`, a Boolean only
-// `is`/`isNot`). Cohort operators are excluded everywhere — they're surfaced by
-// CohortFilterItem, not the standard operator select.
-const STRING_OPERATORS = [
- 'is',
- 'isNot',
- 'contains',
- 'doesNotContain',
- 'startsWith',
- 'endsWith',
- 'regex',
- 'isNull',
- 'isNotNull',
-] as const;
-
-const ORDERED_OPERATORS = [
- 'is',
- 'isNot',
- 'gt',
- 'gte',
- 'lt',
- 'lte',
- 'isNull',
- 'isNotNull',
-] as const;
-
-const BOOLEAN_OPERATORS = ['is', 'isNot', 'isNull', 'isNotNull'] as const;
-
-export function getOperatorsForType(
- type?: IFilterValueType
-): readonly (keyof typeof operators)[] {
- switch (type) {
- case 'number':
- case 'date':
- case 'datetime':
- return ORDERED_OPERATORS;
- case 'boolean':
- return BOOLEAN_OPERATORS;
- default:
- return STRING_OPERATORS;
- }
-}
-
-export const chartTypes = {
- linear: 'Linear',
- bar: 'Bar',
- histogram: 'Histogram',
- pie: 'Pie',
- metric: 'Metric',
- area: 'Area',
- map: 'Map',
- funnel: 'Funnel',
- retention: 'Retention',
- conversion: 'Conversion',
- sankey: 'Sankey',
-} as const;
-
-export const chartSegments = {
- event: 'All events',
- user: 'Unique users',
- session: 'Unique sessions',
- group: 'Unique groups',
- user_average: 'Average users',
- one_event_per_user: 'One event per user',
- property_sum: 'Sum of property',
- property_average: 'Average of property',
- property_max: 'Max of property',
- property_min: 'Min of property',
-};
-
-export const lineTypes = {
- monotone: 'Monotone',
- monotoneX: 'Monotone X',
- monotoneY: 'Monotone Y',
- linear: 'Linear',
- natural: 'Natural',
- basis: 'Basis',
- step: 'Step',
- stepBefore: 'Step before',
- stepAfter: 'Step after',
- basisClosed: 'Basis closed',
- basisOpen: 'Basis open',
- bumpX: 'Bump X',
- bumpY: 'Bump Y',
- bump: 'Bump',
- linearClosed: 'Linear closed',
-} as const;
-
-export const intervals = {
- minute: 'minute',
- day: 'day',
- hour: 'hour',
- week: 'week',
- month: 'month',
-} as const;
-
-export const alphabetIds = [
- 'A',
- 'B',
- 'C',
- 'D',
- 'E',
- 'F',
- 'G',
- 'H',
- 'I',
- 'J',
- 'K',
- 'L',
- 'M',
- 'N',
- 'O',
- 'P',
- 'Q',
- 'R',
- 'S',
- 'T',
- 'U',
- 'V',
- 'W',
- 'X',
- 'Y',
- 'Z',
-] as const;
-
-export const metrics = {
- count: 'count',
- sum: 'sum',
- average: 'average',
- min: 'min',
- max: 'max',
-} as const;
-
-export function isMinuteIntervalEnabledByRange(
- range: keyof typeof timeWindows
-) {
- return range === '30min' || range === 'lastHour';
-}
-
-export function isHourIntervalEnabledByRange(range: keyof typeof timeWindows) {
- return (
- isMinuteIntervalEnabledByRange(range) ||
- range === 'today' ||
- range === 'yesterday' ||
- range === 'last24h' ||
- range === '7d'
- );
-}
-
-export function getDefaultIntervalByRange(
- range: keyof typeof timeWindows
-): keyof typeof intervals {
- if (range === '30min' || range === 'lastHour') {
- return 'minute';
- }
- if (range === 'today' || range === 'yesterday' || range === 'last24h') {
- return 'hour';
- }
- if (
- range === '7d' ||
- range === '30d' ||
- range === '3m' ||
- range === 'lastMonth' ||
- range === 'monthToDate'
- ) {
- return 'day';
- }
- if (range === '6m') {
- return 'week';
- }
- return 'month';
-}
-
-export function getDefaultIntervalByDates(
- startDate: string | null,
- endDate: string | null
-): null | keyof typeof intervals {
- if (startDate && endDate) {
- if (isSameDay(startDate, endDate)) {
- return 'hour';
- }
- const days = differenceInDays(endDate, startDate);
- if (days <= 92) {
- return 'day';
- }
- if (days <= 186) {
- return 'week';
- }
- return 'month';
- }
-
- return null;
-}
-
-export const countries = {
- AF: 'Afghanistan',
- AL: 'Albania',
- DZ: 'Algeria',
- AS: 'American Samoa',
- AD: 'Andorra',
- AO: 'Angola',
- AI: 'Anguilla',
- AQ: 'Antarctica',
- AG: 'Antigua and Barbuda',
- AR: 'Argentina',
- AM: 'Armenia',
- AW: 'Aruba',
- AU: 'Australia',
- AT: 'Austria',
- AZ: 'Azerbaijan',
- BS: 'Bahamas',
- BH: 'Bahrain',
- BD: 'Bangladesh',
- BB: 'Barbados',
- BY: 'Belarus',
- BE: 'Belgium',
- BZ: 'Belize',
- BJ: 'Benin',
- BM: 'Bermuda',
- BT: 'Bhutan',
- BO: 'Bolivia',
- BQ: 'Bonaire, Sint Eustatius and Saba',
- BA: 'Bosnia and Herzegovina',
- BW: 'Botswana',
- BV: 'Bouvet Island',
- BR: 'Brazil',
- IO: 'British Indian Ocean Territory',
- BN: 'Brunei Darussalam',
- BG: 'Bulgaria',
- BF: 'Burkina Faso',
- BI: 'Burundi',
- CV: 'Cabo Verde',
- KH: 'Cambodia',
- CM: 'Cameroon',
- CA: 'Canada',
- KY: 'Cayman Islands',
- CF: 'Central African Republic',
- TD: 'Chad',
- CL: 'Chile',
- CN: 'China',
- CX: 'Christmas Island',
- CC: 'Cocos (Keeling) Islands',
- CO: 'Colombia',
- KM: 'Comoros',
- CD: 'Congo (Democratic Republic)',
- CG: 'Congo',
- CK: 'Cook Islands',
- CR: 'Costa Rica',
- HR: 'Croatia',
- CU: 'Cuba',
- CW: 'Curaçao',
- CY: 'Cyprus',
- CZ: 'Czechia',
- CI: "Côte d'Ivoire",
- DK: 'Denmark',
- DJ: 'Djibouti',
- DM: 'Dominica',
- DO: 'Dominican Republic',
- EC: 'Ecuador',
- EG: 'Egypt',
- SV: 'El Salvador',
- GQ: 'Equatorial Guinea',
- ER: 'Eritrea',
- EE: 'Estonia',
- SZ: 'Eswatina',
- ET: 'Ethiopia',
- FK: 'Falkland Islands',
- FO: 'Faroe Islands',
- FJ: 'Fiji',
- FI: 'Finland',
- FR: 'France',
- GF: 'French Guiana',
- PF: 'French Polynesia',
- TF: 'French Southern Territories',
- GA: 'Gabon',
- GM: 'Gambia',
- GE: 'Georgia',
- DE: 'Germany',
- GH: 'Ghana',
- GI: 'Gibraltar',
- GR: 'Greece',
- GL: 'Greenland',
- GD: 'Grenada',
- GP: 'Guadeloupe',
- GU: 'Guam',
- GT: 'Guatemala',
- GG: 'Guernsey',
- GN: 'Guinea',
- GW: 'Guinea-Bissau',
- GY: 'Guyana',
- HT: 'Haiti',
- HM: 'Heard Island and McDonald Islands',
- VA: 'Holy See',
- HN: 'Honduras',
- HK: 'Hong Kong',
- HU: 'Hungary',
- IS: 'Iceland',
- IN: 'India',
- ID: 'Indonesia',
- IR: 'Iran',
- IQ: 'Iraq',
- IE: 'Ireland',
- IM: 'Isle of Man',
- IL: 'Israel',
- IT: 'Italy',
- JM: 'Jamaica',
- JP: 'Japan',
- JE: 'Jersey',
- JO: 'Jordan',
- KZ: 'Kazakhstan',
- KE: 'Kenya',
- KI: 'Kiribati',
- KP: "Korea (Democratic People's Republic)",
- KR: 'Korea (Republic)',
- KW: 'Kuwait',
- KG: 'Kyrgyzstan',
- LA: "Lao People's Democratic Republic",
- LV: 'Latvia',
- LB: 'Lebanon',
- LS: 'Lesotho',
- LR: 'Liberia',
- LY: 'Libya',
- LI: 'Liechtenstein',
- LT: 'Lithuania',
- LU: 'Luxembourg',
- MO: 'Macao',
- MG: 'Madagascar',
- MW: 'Malawi',
- MY: 'Malaysia',
- MV: 'Maldives',
- ML: 'Mali',
- MT: 'Malta',
- MH: 'Marshall Islands',
- MQ: 'Martinique',
- MR: 'Mauritania',
- MU: 'Mauritius',
- YT: 'Mayotte',
- MX: 'Mexico',
- FM: 'Micronesia',
- MD: 'Moldova',
- MC: 'Monaco',
- MN: 'Mongolia',
- ME: 'Montenegro',
- MS: 'Montserrat',
- MA: 'Morocco',
- MZ: 'Mozambique',
- MM: 'Myanmar',
- NA: 'Namibia',
- NR: 'Nauru',
- NP: 'Nepal',
- NL: 'Netherlands',
- NC: 'New Caledonia',
- NZ: 'New Zealand',
- NI: 'Nicaragua',
- NE: 'Niger',
- NG: 'Nigeria',
- NU: 'Niue',
- NF: 'Norfolk Island',
- MP: 'Northern Mariana Islands',
- NO: 'Norway',
- OM: 'Oman',
- PK: 'Pakistan',
- PW: 'Palau',
- PS: 'Palestine, State of',
- PA: 'Panama',
- PG: 'Papua New Guinea',
- PY: 'Paraguay',
- PE: 'Peru',
- PH: 'Philippines',
- PN: 'Pitcairn',
- PL: 'Poland',
- PT: 'Portugal',
- PR: 'Puerto Rico',
- QA: 'Qatar',
- MK: 'Republic of North Macedonia',
- RO: 'Romania',
- RU: 'Russian Federation',
- RW: 'Rwanda',
- RE: 'Réunion',
- BL: 'Saint Barthélemy',
- SH: 'Saint Helena, Ascension and Tristan da Cunha',
- KN: 'Saint Kitts and Nevis',
- LC: 'Saint Lucia',
- MF: 'Saint Martin (French part)',
- PM: 'Saint Pierre and Miquelon',
- VC: 'Saint Vincent and the Grenadines',
- WS: 'Samoa',
- SM: 'San Marino',
- ST: 'Sao Tome and Principe',
- SA: 'Saudi Arabia',
- SN: 'Senegal',
- RS: 'Serbia',
- SC: 'Seychelles',
- SL: 'Sierra Leone',
- SG: 'Singapore',
- SX: 'Sint Maarten (Dutch part)',
- SK: 'Slovakia',
- SI: 'Slovenia',
- SB: 'Solomon Islands',
- SO: 'Somalia',
- ZA: 'South Africa',
- GS: 'South Georgia and the South Sandwich Islands',
- SS: 'South Sudan',
- ES: 'Spain',
- LK: 'Sri Lanka',
- SD: 'Sudan',
- SR: 'Suriname',
- SJ: 'Svalbard and Jan Mayen',
- SE: 'Sweden',
- CH: 'Switzerland',
- SY: 'Syrian Arab Republic',
- TW: 'Taiwan',
- TJ: 'Tajikistan',
- TZ: 'Tanzania, United Republic of',
- TH: 'Thailand',
- TL: 'Timor-Leste',
- TG: 'Togo',
- TK: 'Tokelau',
- TO: 'Tonga',
- TT: 'Trinidad and Tobago',
- TN: 'Tunisia',
- TR: 'Turkey',
- TM: 'Turkmenistan',
- TC: 'Turks and Caicos Islands',
- TV: 'Tuvalu',
- UG: 'Uganda',
- UA: 'Ukraine',
- AE: 'United Arab Emirates',
- GB: 'United Kingdom',
- US: 'United States',
- UM: 'United States Minor Outlying Islands',
- UY: 'Uruguay',
- UZ: 'Uzbekistan',
- VU: 'Vanuatu',
- VE: 'Venezuela',
- VN: 'Viet Nam',
- VG: 'Virgin Islands (British)',
- VI: 'Virgin Islands (U.S.)',
- WF: 'Wallis and Futuna',
- EH: 'Western Sahara',
- YE: 'Yemen',
- ZM: 'Zambia',
- ZW: 'Zimbabwe',
- AX: 'Åland Islands',
-} as const;
-
-export function getCountry(code?: string) {
- return countries[code as keyof typeof countries];
-}
-
+export type { EmailCategory } from '@openpanel/core/modules/email/email.constants';
// Moved into @openpanel/core's email module (M6-004, ADR-008's module map:
// email owns "C"). Re-exported here for existing @openpanel/constants
// importers (packages/trpc's email router, apps/start's unsubscribe +
// email-preferences pages) — same shape as `ProjectTypeNames`'s re-export
// since M6-002. Keys must match the template `category` in @openpanel/email.
export { emailCategories } from '@openpanel/core/modules/email/email.constants';
-export type { EmailCategory } from '@openpanel/core/modules/email/email.constants';
-
-export const chartColors = [
- { main: '#2563EB', translucent: 'rgba(37, 99, 235, 0.1)' },
- { main: '#ff7557', translucent: 'rgba(255, 117, 87, 0.1)' },
- { main: '#7fe1d8', translucent: 'rgba(127, 225, 216, 0.1)' },
- { main: '#f8bc3c', translucent: 'rgba(248, 188, 60, 0.1)' },
- { main: '#b3596e', translucent: 'rgba(179, 89, 110, 0.1)' },
- { main: '#72bef4', translucent: 'rgba(114, 190, 244, 0.1)' },
- { main: '#ffb27a', translucent: 'rgba(255, 178, 122, 0.1)' },
- { main: '#0f7ea0', translucent: 'rgba(15, 126, 160, 0.1)' },
- { main: '#3ba974', translucent: 'rgba(59, 169, 116, 0.1)' },
- { main: '#febbb2', translucent: 'rgba(254, 187, 178, 0.1)' },
- { main: '#cb80dc', translucent: 'rgba(203, 128, 220, 0.1)' },
- { main: '#5cb7af', translucent: 'rgba(92, 183, 175, 0.1)' },
- { main: '#7856ff', translucent: 'rgba(120, 86, 255, 0.1)' },
-];
+// Moved into @openpanel/core's project module (M6-002, ADR-008's module
+// map: project owns "C"). Re-exported here for existing
+// @openpanel/constants importers — same shape as
+// packages/validation/src/import.validation.ts since M5-004.
+export { ProjectTypeNames } from '@openpanel/core/modules/project/project.constants';
+// Moved into @openpanel/core's report module (M7-006, ADR-008's module map:
+// report owns "C" for the chart/report/widget vocabulary — timeWindows,
+// operators, chartTypes, chartColors, intervals + helpers, countries,
+// NOT_SET_VALUE, alphabetIds, metrics and friends). Re-exported here for
+// existing @openpanel/constants importers (apps/start's report builder, the
+// chart engine, apps/api's insights controller) — same shape as
+// `ProjectTypeNames`'s re-export since M6-002.
+export * from '@openpanel/core/modules/report/report.constants';
diff --git a/packages/core/package.json b/packages/core/package.json
index 49724655e..5ff893c30 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -52,6 +52,7 @@
"nanoid": "^5.1.6",
"pino": "catalog:",
"pino-pretty": "catalog:",
+ "prisma-error-enum": "^0.1.3",
"prom-client": "^15.1.3",
"qrcode": "^1.5.4",
"ramda": "^0.29.1",
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 194b9a3cb..1603f917d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -369,56 +369,6 @@ export {
getUserFlowCore,
zGetSankeyInput,
} from './modules/chart/sankey.service';
-// Dissolved from @openpanel/db's services/overview.service.ts +
-// pages.service.ts (M7-005) — packages/trpc's overview/event routers,
-// apps/api's insights controller, apps/worker's win-back job and the
-// mcp/assistant tools call these directly. packages/db/src/services/
-// overview.service.ts and pages.service.ts stay re-export shims.
-export type {
- IGetMapDataInput,
- IGetMetricsInput,
- IGetTopEntryExitInput,
- IGetTopEventsInput,
- IGetTopGenericInput,
- IGetTopGenericSeriesInput,
- IGetTopLinkOutInput,
- IGetTopPagesInput,
- IGetUserJourneyInput,
- ILiveData,
- ILiveMinuteCount,
- SegmentDailyPoint,
- TrafficColumn,
-} from './modules/overview/overview.service';
-export {
- getAnalyticsOverviewCore,
- getSegmentDailySeriesCore,
- getTrafficBreakdownCore,
- OverviewService,
- overviewService,
- zGetMapDataInput,
- zGetMetricsInput,
- zGetTopEntryExitInput,
- zGetTopEventsInput,
- zGetTopGenericInput,
- zGetTopGenericSeriesInput,
- zGetTopLinkOutInput,
- zGetTopPagesInput,
- zGetUserJourneyInput,
-} from './modules/overview/overview.service';
-export type {
- IGetPagesInput,
- IPageConversionRow,
- IPageTimeseriesRow,
- ITopPage,
-} from './modules/overview/pages.service';
-export {
- getEntryExitPagesCore,
- getPageConversionsCore,
- getPagePerformanceCore,
- getTopPagesCore,
- PagesService,
- pagesService,
-} from './modules/overview/pages.service';
// Dissolved from @openpanel/db's services/clients.service.ts (M6-002) —
// packages/trpc's client router, apps/api's manage controller and mcp/utils
// auth call these directly, the same way V1 reaches every other dissolved
@@ -477,6 +427,24 @@ export {
listConversations,
upsertConversationTitle,
} from './modules/conversation/conversation.service';
+// Dissolved from @openpanel/db's services/dashboard.service.ts, plus V1's
+// dashboard router mutation bodies (M7-006) — packages/trpc's dashboard
+// router, apps/api's insights controller and the mcp/assistant tools call
+// these. packages/db/src/services/dashboard.service.ts stays a re-export
+// shim.
+export type {
+ IServiceDashboard,
+ IServiceDashboards,
+} from './modules/dashboard/dashboard.service';
+export {
+ createDashboard,
+ deleteDashboard,
+ getDashboardById,
+ getDashboardByIdOrThrow,
+ getDashboardsByProjectId,
+ listDashboardsCore,
+ updateDashboard,
+} from './modules/dashboard/dashboard.service';
// R + C only (M6-004): the router's three bodies are three small
// `db.emailUnsubscribe` calls, small enough to live inline in
// `email.rpc.ts` rather than a dedicated `email.service.ts` — see that
@@ -727,6 +695,56 @@ export {
updateOrganization,
updateOrganizationMemberAccess,
} from './modules/organization/organization.service';
+// Dissolved from @openpanel/db's services/overview.service.ts +
+// pages.service.ts (M7-005) — packages/trpc's overview/event routers,
+// apps/api's insights controller, apps/worker's win-back job and the
+// mcp/assistant tools call these directly. packages/db/src/services/
+// overview.service.ts and pages.service.ts stay re-export shims.
+export type {
+ IGetMapDataInput,
+ IGetMetricsInput,
+ IGetTopEntryExitInput,
+ IGetTopEventsInput,
+ IGetTopGenericInput,
+ IGetTopGenericSeriesInput,
+ IGetTopLinkOutInput,
+ IGetTopPagesInput,
+ IGetUserJourneyInput,
+ ILiveData,
+ ILiveMinuteCount,
+ SegmentDailyPoint,
+ TrafficColumn,
+} from './modules/overview/overview.service';
+export {
+ getAnalyticsOverviewCore,
+ getSegmentDailySeriesCore,
+ getTrafficBreakdownCore,
+ OverviewService,
+ overviewService,
+ zGetMapDataInput,
+ zGetMetricsInput,
+ zGetTopEntryExitInput,
+ zGetTopEventsInput,
+ zGetTopGenericInput,
+ zGetTopGenericSeriesInput,
+ zGetTopLinkOutInput,
+ zGetTopPagesInput,
+ zGetUserJourneyInput,
+} from './modules/overview/overview.service';
+export type {
+ IGetPagesInput,
+ IPageConversionRow,
+ IPageTimeseriesRow,
+ ITopPage,
+} from './modules/overview/pages.service';
+export {
+ getEntryExitPagesCore,
+ getPageConversionsCore,
+ getPagePerformanceCore,
+ getTopPagesCore,
+ PagesService,
+ pagesService,
+} from './modules/overview/pages.service';
export type {
AdjustProfilePropertyResult,
FindProfilesInput,
@@ -826,6 +844,86 @@ export {
listReferences,
updateReference,
} from './modules/reference/reference.service';
+// Moved from packages/constants/index.ts and packages/validation/src/index.ts
+// (M7-006, ADR-008's module map: report owns "C" for the chart/report/widget
+// vocabulary) — apps/start's report builder and the assistant/mcp tools
+// reach the vocabulary directly through @openpanel/core here, same shape as
+// `emailCategories`/`ProjectTypeNames` below. Both origin packages stay
+// re-export shims.
+export type { IFilterValueType } from './modules/report/report.constants';
+export {
+ alphabetIds,
+ chartColors,
+ chartSegments,
+ chartTypes,
+ countries,
+ DEFAULT_ASPECT_RATIO,
+ filterValueTypes,
+ getCohortIds,
+ getCountry,
+ getDefaultIntervalByDates,
+ getDefaultIntervalByRange,
+ getOperatorsForType,
+ intervals,
+ isHourIntervalEnabledByRange,
+ isMinuteIntervalEnabledByRange,
+ lineTypes,
+ metrics,
+ NOT_SET_VALUE,
+ operators,
+ operatorsShort,
+ timeWindows,
+ zChartBreakdown,
+ zChartBreakdowns,
+ zChartEvent,
+ zChartEventFilter,
+ zChartEventItem,
+ zChartEventSegment,
+ zChartEventWithType,
+ zChartFormula,
+ zChartInput,
+ zChartSeries,
+ zChartType,
+ zCriteria,
+ zFunnelOptions,
+ zHistogramOptions,
+ zLineType,
+ zMetric,
+ zRange,
+ zReport,
+ zReportInput,
+ zReportOptions,
+ zRetentionOptions,
+ zSankeyOptions,
+ zTimeInterval,
+ zWidgetOptions,
+ zWidgetType,
+} from './modules/report/report.constants';
+// Dissolved from @openpanel/db's services/reports.service.ts, plus V1's
+// report router mutation bodies (M7-006) — packages/trpc's report router,
+// apps/api's insights controller and the mcp/assistant tools call these.
+// packages/db/src/services/reports.service.ts stays a re-export shim.
+export type { IServiceReport } from './modules/report/report.service';
+export {
+ createReport,
+ deleteReport,
+ duplicateReport,
+ getReportById,
+ getReportByIdOrThrow,
+ getReportDataCore,
+ getReportLayouts,
+ getReportsByDashboardId,
+ listReportsCore,
+ mergeGlobalFilters,
+ moveReport,
+ onlyReportEvents,
+ resetReportLayouts,
+ transformFilter,
+ transformReport,
+ transformReportEventItem,
+ updateReport,
+ updateReportLayout,
+} from './modules/report/report.service';
// Dissolved from @openpanel/db's services/session.service.ts and
// session-context.ts, plus apps/worker's session-end job, reaper and vacuum
// (M7-001, ADR-008's module map: session owns "R,S,J") — packages/trpc's
diff --git a/packages/core/src/modules/assistant/src/filter-command.ts b/packages/core/src/modules/assistant/src/filter-command.ts
index 8ab471372..8ba9fb740 100644
--- a/packages/core/src/modules/assistant/src/filter-command.ts
+++ b/packages/core/src/modules/assistant/src/filter-command.ts
@@ -20,7 +20,6 @@ import {
import {
type IChartEventFilter,
type IChartRange,
- objectToZodEnums,
zRange,
} from '@openpanel/validation';
import { z } from 'zod';
@@ -31,6 +30,15 @@ import {
type PageContext,
} from '../assistant.constants';
+// Helper, not vocabulary — ADR-008's ruling on objectToZodEnums: copy locally
+// rather than import from a module.
+function objectToZodEnums<K extends string>(
+ obj: Record<K, unknown>
+): [K, ...K[]] {
+ const [firstKey, ...otherKeys] = Object.keys(obj) as K[];
+ return [firstKey!, ...otherKeys];
+}
+
const operatorEnum = z.enum(objectToZodEnums(operators));
const rangeEnum = zRange;
const intervalEnum = z.enum(objectToZodEnums(intervals));
diff --git a/packages/core/src/modules/assistant/src/tools/base.ts b/packages/core/src/modules/assistant/src/tools/base.ts
index 8d2be174c..67bc2da4d 100644
--- a/packages/core/src/modules/assistant/src/tools/base.ts
+++ b/packages/core/src/modules/assistant/src/tools/base.ts
@@ -16,7 +16,7 @@ import {
queryEventsCore,
querySessionsCore,
} from '@openpanel/db';
-import { objectToZodEnums, zReportInput } from '@openpanel/validation';
+import { zReportInput } from '@openpanel/validation';
import { z } from 'zod';
import { runReport, runReportFromConfig } from '../report-runner';
import {
@@ -28,6 +28,15 @@ import {
truncateRows,
} from './helpers';
+// Helper, not vocabulary — ADR-008's ruling on objectToZodEnums: copy locally
+// rather than import from a module.
+function objectToZodEnums<K extends string>(
+ obj: Record<K, unknown>
+): [K, ...K[]] {
+ const [firstKey, ...otherKeys] = Object.keys(obj) as K[];
+ return [firstKey!, ...otherKeys];
+}
+
// ─────────────────────────────────────────────────────────────────
// DISCOVERY
// ─────────────────────────────────────────────────────────────────
diff --git a/packages/core/src/modules/cohort/cohort.constants.ts b/packages/core/src/modules/cohort/cohort.constants.ts
index 0a6d0e071..847705455 100644
--- a/packages/core/src/modules/cohort/cohort.constants.ts
+++ b/packages/core/src/modules/cohort/cohort.constants.ts
@@ -5,40 +5,16 @@
// apps/start and packages/db/src/types.ts keep resolving these symbols
// through @openpanel/validation's existing barrel unchanged.
//
-// Isomorphic by the AGENTS.md rule: zod and nothing else.
+// Isomorphic by the AGENTS.md rule: zod, another `*.constants.ts`, or
+// nothing. `zChartEventFilter` used to be a diverged local copy here
+// (TODO(P7) in M5-003) to dodge a TDZ from importing it through
+// @openpanel/validation's barrel before that barrel finished initializing;
+// now that it lives in report.constants.ts — an isomorphic, cycle-free
+// sibling — importing it directly is safe, and the duplicate is gone
+// (M7-006).
-import { operators } from '@openpanel/constants';
import { z } from 'zod';
-
-// TODO(P7): the canonical zChartEventFilter lives in
-// packages/validation/src/index.ts:31 and is due to move to
-// core/src/modules/report/report.constants.ts. That module does not exist
-// yet (creating it early is out of this task's scope), so this stays a
-// diverged local copy — defined here, rather than imported, to avoid a
-// runtime TDZ from this file being evaluated before validation's index.ts
-// finishes initializing zChartEventFilter. Once report.constants.ts exists,
-// delete this duplicate and import zChartEventFilter from there instead.
-function objectToZodEnums<K extends string>(
- obj: Record<K, unknown>
-): [K, ...K[]] {
- const [firstKey, ...otherKeys] = Object.keys(obj) as K[];
- return [firstKey!, ...otherKeys];
-}
-
-const zChartEventFilter = z.object({
- id: z.string().optional().describe('Unique identifier for the filter'),
- name: z.string().describe('The property name to filter on'),
- operator: z
- .enum(objectToZodEnums(operators))
- .describe('The operator to use for the filter'),
- value: z
- .array(z.string().or(z.number()).or(z.boolean()).or(z.null()))
- .describe('The values to filter on'),
- cohortId: z
- .string()
- .optional()
- .describe('Cohort ID when using inCohort/notInCohort operators'),
-});
+import { zChartEventFilter } from '../report/report.constants';
export const zRelativeTimeframe = z.object({
type: z.literal('relative'),
diff --git a/packages/core/src/modules/dashboard/dashboard.rpc.ts b/packages/core/src/modules/dashboard/dashboard.rpc.ts
new file mode 100644
index 000000000..776217526
--- /dev/null
+++ b/packages/core/src/modules/dashboard/dashboard.rpc.ts
@@ -0,0 +1,119 @@
+// Ported from packages/trpc/src/routers/dashboard.ts (M7-006).
+//
+// Same arrangement as project.rpc.ts: V1's `protectedProcedure` lands in
+// core with auth (rpc/base.ts), so each procedure does its own "is anyone
+// logged in" + `requireProjectAccess` check. The create/update/delete
+// mutation bodies moved to ./dashboard.service alongside the reads that
+// already lived there; packages/trpc's dashboard router delegates every
+// handler body onto ./dashboard.service while keeping V1's own procedure
+// stack (DELEGATE PATTERN).
+
+import { z } from 'zod';
+import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
+import {
+ createDashboard,
+ deleteDashboard,
+ getDashboardById,
+ getDashboardByIdOrThrow,
+ getDashboardsByProjectId,
+ updateDashboard,
+} from './dashboard.service';
+
+function loadAccessChecks() {
+ return import('./src/access');
+}
+
+function requireLogin(userId: string | null | undefined): string {
+ if (!userId) {
+ throw new TRPCAccessError('Not authenticated');
+ }
+ return userId;
+}
+
+async function requireAccess(
+ userId: string,
+ projectId: string,
+ level: 'read' | 'write'
+) {
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({ userId, projectId, level });
+}
+
+async function requireReadAccess(ctx: TrpcContext, projectId: string) {
+ await requireAccess(requireLogin(ctx.session.userId), projectId, 'read');
+}
+
+async function requireWriteAccess(ctx: TrpcContext, projectId: string) {
+ await requireAccess(requireLogin(ctx.session.userId), projectId, 'write');
+}
+
+export const dashboardRouter = createTRPCRouter({
+ list: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ })
+ )
+ .query(({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+ return getDashboardsByProjectId(input.projectId);
+ }),
+
+ byId: procedure
+ .input(
+ z.object({
+ id: z.string(),
+ projectId: z.string(),
+ })
+ )
+ .query(async ({ input, ctx }) => {
+ await requireReadAccess(ctx, input.projectId);
+
+ const dashboard = await getDashboardById(input.id, input.projectId);
+
+ if (!dashboard) {
+ throw new TRPCNotFoundError('Dashboard not found');
+ }
+
+ return dashboard;
+ }),
+
+ create: procedure
+ .input(
+ z.object({
+ name: z.string(),
+ projectId: z.string(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ await requireWriteAccess(ctx, input.projectId);
+ return createDashboard(input);
+ }),
+
+ update: procedure
+ .input(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ const dashboard = await getDashboardByIdOrThrow(input.id);
+ await requireWriteAccess(ctx, dashboard.projectId);
+ return updateDashboard(input);
+ }),
+
+ delete: procedure
+ .input(
+ z.object({
+ id: z.string(),
+ forceDelete: z.boolean().optional(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ const dashboard = await getDashboardByIdOrThrow(input.id);
+ await requireWriteAccess(ctx, dashboard.projectId);
+ return deleteDashboard(input);
+ }),
+});
diff --git a/packages/core/src/modules/dashboard/dashboard.service.ts b/packages/core/src/modules/dashboard/dashboard.service.ts
new file mode 100644
index 000000000..5143e5b82
--- /dev/null
+++ b/packages/core/src/modules/dashboard/dashboard.service.ts
@@ -0,0 +1,153 @@
+// Moved from packages/db/src/services/dashboard.service.ts, plus the
+// create/update/delete mutation bodies packages/trpc/src/routers/dashboard.ts
+// held inline (M7-006, ADR-008's module map: dashboard owns "R,S").
+// packages/db/src/services/dashboard.service.ts stays a re-export shim
+// (DELEGATE PATTERN), same shape as project.service.ts since M6-002.
+//
+// db access is LAZY, not a static top-level import — dashboard.rpc.ts lands
+// in the eager rpc.router.ts barrel chain nearly every core test file
+// reaches, and constructing @openpanel/db's clients at import time would
+// spawn a pino-pretty transport worker thread per test file (see
+// insight.service.ts's header / project.service.ts's header).
+
+import type { Dashboard, Prisma } from '@openpanel/db/src/prisma-client';
+import { PrismaError } from 'prisma-error-enum';
+import { TRPCNotFoundError } from '../../rpc/errors';
+import { getProjectById } from '../project/project.service';
+
+export type IServiceDashboard = Dashboard;
+export type IServiceDashboards = Prisma.DashboardGetPayload<{
+ include: {
+ project: true;
+ reports: true;
+ };
+}>[];
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+function loadIdService() {
+ return import('@openpanel/db/src/services/id.service').then((m) => m.getId);
+}
+
+export async function getDashboardById(id: string, projectId: string) {
+ const db = await loadDb();
+ const dashboard = await db.dashboard.findUnique({
+ where: {
+ id,
+ projectId,
+ },
+ include: {
+ project: true,
+ },
+ });
+
+ if (!dashboard) {
+ return null;
+ }
+
+ return dashboard;
+}
+
+/** Unscoped lookup for mutation handlers that only receive a dashboard id and
+ * need its `projectId` to run the access check — same shape as V1's inline
+ * `db.dashboard.findUniqueOrThrow`. */
+export async function getDashboardByIdOrThrow(id: string) {
+ const db = await loadDb();
+ return db.dashboard.findUniqueOrThrow({ where: { id } });
+}
+
+export function getDashboardsByProjectId(projectId: string) {
+ return loadDb().then((db) =>
+ db.dashboard.findMany({
+ where: {
+ projectId,
+ },
+ include: {
+ project: true,
+ reports: true,
+ },
+ })
+ );
+}
+
+export async function listDashboardsCore(input: {
+ projectId: string;
+ organizationId: string;
+}) {
+ const db = await loadDb();
+ return db.dashboard.findMany({
+ where: { projectId: input.projectId },
+ orderBy: { createdAt: 'desc' },
+ select: { id: true, name: true, projectId: true },
+ });
+}
+
+export async function createDashboard(input: {
+ name: string;
+ projectId: string;
+}) {
+ const db = await loadDb();
+ const project = await getProjectById(input.projectId);
+
+ if (!project) {
+ throw new TRPCNotFoundError('Project not found');
+ }
+
+ const getId = await loadIdService();
+
+ return db.dashboard.create({
+ data: {
+ id: await getId('dashboard', input.name),
+ projectId: input.projectId,
+ organizationId: project.organizationId,
+ name: input.name,
+ },
+ });
+}
+
+export async function updateDashboard(input: { id: string; name: string }) {
+ const db = await loadDb();
+ return db.dashboard.update({
+ where: {
+ id: input.id,
+ },
+ data: {
+ name: input.name,
+ },
+ });
+}
+
+export async function deleteDashboard(input: {
+ id: string;
+ forceDelete?: boolean;
+}) {
+ const db = await loadDb();
+ try {
+ if (input.forceDelete) {
+ await db.report.deleteMany({
+ where: {
+ dashboardId: input.id,
+ },
+ });
+ }
+ await db.dashboard.delete({
+ where: {
+ id: input.id,
+ },
+ });
+ } catch (e) {
+ // Below does not work...
+ // error instanceof Prisma.PrismaClientKnownRequestError
+ if (typeof e === 'object' && e && 'code' in e) {
+ const error = e as Prisma.PrismaClientKnownRequestError;
+ switch (error.code) {
+ case PrismaError.ForeignConstraintViolation:
+ throw new Error('Cannot delete dashboard with associated reports');
+ default:
+ throw new Error('Unknown error deleting dashboard');
+ }
+ }
+ }
+}
diff --git a/packages/core/src/modules/dashboard/src/access.ts b/packages/core/src/modules/dashboard/src/access.ts
new file mode 100644
index 000000000..315315e48
--- /dev/null
+++ b/packages/core/src/modules/dashboard/src/access.ts
@@ -0,0 +1,22 @@
+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
+// this module's own router — the same binding packages/trpc/src/access.ts
+// does for V1, self-contained here because the general core -> db binding
+// itself moves with auth (P6), not this wave. Same shape as
+// chart/src/access.ts and project/src/access.ts.
+
+import {
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectAccess,
+} from '@openpanel/db/src/services/access.service';
+import { getProjectById } from '@openpanel/db/src/services/project.service';
+import { createAccessChecks } from '../../../shared/access';
+
+const checks = createAccessChecks({
+ getProjectAccess,
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectById,
+});
+
+export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/report/report.constants.test.ts b/packages/core/src/modules/report/report.constants.test.ts
new file mode 100644
index 000000000..ddd9e5904
--- /dev/null
+++ b/packages/core/src/modules/report/report.constants.test.ts
@@ -0,0 +1,33 @@
+/**
+ * Locks down `getDefaultIntervalByDates`'s rewrite from date-fns
+ * (differenceInDays/isSameDay) to plain Date math (see file header) against
+ * the exact boundaries the original branches used.
+ */
+import { describe, expect, it } from 'bun:test';
+import { getDefaultIntervalByDates } from './report.constants';
+
+describe('getDefaultIntervalByDates', () => {
+ it('returns null when either date is missing', () => {
+ expect(getDefaultIntervalByDates(null, null)).toBeNull();
+ expect(getDefaultIntervalByDates('2024-01-01', null)).toBeNull();
+ expect(getDefaultIntervalByDates(null, '2024-01-01')).toBeNull();
+ });
+
+ it('returns hour for the same calendar day', () => {
+ expect(getDefaultIntervalByDates('2024-01-01', '2024-01-01')).toBe('hour');
+ });
+
+ it('returns day up to 92 days apart', () => {
+ expect(getDefaultIntervalByDates('2024-01-01', '2024-01-02')).toBe('day');
+ expect(getDefaultIntervalByDates('2024-01-01', '2024-04-02')).toBe('day');
+ });
+
+ it('returns week between 93 and 186 days apart', () => {
+ expect(getDefaultIntervalByDates('2024-01-01', '2024-04-03')).toBe('week');
+ expect(getDefaultIntervalByDates('2024-01-01', '2024-07-05')).toBe('week');
+ });
+
+ it('returns month beyond 186 days apart', () => {
+ expect(getDefaultIntervalByDates('2024-01-01', '2024-07-06')).toBe('month');
+ });
+});
diff --git a/packages/core/src/modules/report/report.constants.ts b/packages/core/src/modules/report/report.constants.ts
new file mode 100644
index 000000000..4e370ed36
--- /dev/null
+++ b/packages/core/src/modules/report/report.constants.ts
@@ -0,0 +1,955 @@
+// Moved from packages/constants/index.ts and packages/validation/src/index.ts
+// (M7-006, ADR-008's module map: report owns "C" for the chart/report/widget
+// vocabulary). Both origin files become re-export shims onto this one (same
+// shape as packages/validation/src/cohort.validation.ts since M5-003), so
+// existing @openpanel/constants / @openpanel/validation importers (the chart
+// engine, apps/start's report builder, packages/trpc's report/dashboard/
+// widget routers) keep resolving these symbols unchanged.
+//
+// `getDefaultIntervalByDates` is REWRITTEN from date-fns
+// (differenceInDays/isSameDay) to plain Date math per the module map. Every
+// process that constructs these Dates runs under TZ=UTC (ADR-012: "this ADR
+// makes that line load-bearing rather than incidental"), so Date's local
+// getters (getFullYear/getMonth/getDate) already read UTC — the helpers below
+// reproduce date-fns's local-calendar semantics exactly under that invariant,
+// and the only inputs this function ever receives are date-only strings
+// (midnight boundaries), where date-fns's exact-duration-vs-calendar-day
+// nuance cannot diverge from a plain ms division anyway.
+//
+// Isomorphic by the AGENTS.md rule: zod and nothing else.
+
+import { z } from 'zod';
+
+export const DEFAULT_ASPECT_RATIO = 0.5625;
+export const NOT_SET_VALUE = '(not set)';
+
+export const timeWindows = {
+ '30min': {
+ key: '30min',
+ label: 'Last 30 min',
+ shortcut: 'R',
+ },
+ lastHour: {
+ key: 'lastHour',
+ label: 'Last hour',
+ shortcut: 'H',
+ },
+ last24h: {
+ key: 'last24h',
+ label: 'Last 24 hours',
+ shortcut: '4',
+ },
+ today: {
+ key: 'today',
+ label: 'Today',
+ shortcut: 'D',
+ },
+ yesterday: {
+ key: 'yesterday',
+ label: 'Yesterday',
+ shortcut: 'E',
+ },
+ '7d': {
+ key: '7d',
+ label: 'Last 7 days',
+ shortcut: 'W',
+ },
+ '30d': {
+ key: '30d',
+ label: 'Last 30 days',
+ shortcut: 'T',
+ },
+ '3m': {
+ key: '3m',
+ label: 'Last 3 months',
+ shortcut: '3',
+ },
+ '6m': {
+ key: '6m',
+ label: 'Last 6 months',
+ shortcut: '6',
+ },
+ '12m': {
+ key: '12m',
+ label: 'Last 12 months',
+ shortcut: '0',
+ },
+ monthToDate: {
+ key: 'monthToDate',
+ label: 'Month to Date',
+ shortcut: 'M',
+ },
+ lastMonth: {
+ key: 'lastMonth',
+ label: 'Last Month',
+ shortcut: 'P',
+ },
+ yearToDate: {
+ key: 'yearToDate',
+ label: 'Year to Date',
+ shortcut: 'Y',
+ },
+ lastYear: {
+ key: 'lastYear',
+ label: 'Last year',
+ shortcut: 'U',
+ },
+ custom: {
+ key: 'custom',
+ label: 'Custom range',
+ shortcut: 'C',
+ },
+} as const;
+
+export const operators = {
+ is: 'Is',
+ isNot: 'Is not',
+ contains: 'Contains',
+ doesNotContain: 'Not contains',
+ startsWith: 'Starts with',
+ endsWith: 'Ends with',
+ regex: 'Regex',
+ isNull: 'Is null',
+ isNotNull: 'Is not null',
+ gt: 'Greater than',
+ lt: 'Less than',
+ gte: 'Greater than or equal to',
+ lte: 'Less than or equal to',
+ inCohort: 'In cohort',
+ notInCohort: 'Not in cohort',
+} as const;
+
+// Compact labels for the operator trigger button. The comparison operators
+// have very long names ("Greater than or equal to"), so we show a symbol on
+// the trigger (reads naturally next to the value, e.g. "≥ 2019-01-01") and
+// surface the full `operators` text as a sub-line in the dropdown.
+export const operatorsShort: Record<keyof typeof operators, string> = {
+ is: 'Is',
+ isNot: 'Is not',
+ contains: 'Contains',
+ doesNotContain: 'Not contains',
+ startsWith: 'Starts with',
+ endsWith: 'Ends with',
+ regex: 'Regex',
+ isNull: 'Is null',
+ isNotNull: 'Is not null',
+ gt: '>',
+ lt: '<',
+ gte: '≥',
+ lte: '≤',
+ inCohort: 'In cohort',
+ notInCohort: 'Not in cohort',
+};
+
+// Cast type a filter value/column should be coerced to before comparing.
+// `string` (the default) keeps raw text comparison; the others wrap both sides
+// of the comparison in the matching ClickHouse cast (see packages/db
+// filter-cast.ts) so e.g. a date property compares as a date instead of
+// crashing `toFloat64('2019-01-01')`.
+export const filterValueTypes = {
+ string: 'Text',
+ number: 'Number',
+ date: 'Date',
+ datetime: 'Date & time',
+ boolean: 'Boolean',
+} as const;
+
+export type IFilterValueType = keyof typeof filterValueTypes;
+
+// Operators that make sense for each value type. The type constrains the
+// operator list in the UI (a Number can't `contains`, a Boolean only
+// `is`/`isNot`). Cohort operators are excluded everywhere — they're surfaced by
+// CohortFilterItem, not the standard operator select.
+const STRING_OPERATORS = [
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ 'regex',
+ 'isNull',
+ 'isNotNull',
+] as const;
+
+const ORDERED_OPERATORS = [
+ 'is',
+ 'isNot',
+ 'gt',
+ 'gte',
+ 'lt',
+ 'lte',
+ 'isNull',
+ 'isNotNull',
+] as const;
+
+const BOOLEAN_OPERATORS = ['is', 'isNot', 'isNull', 'isNotNull'] as const;
+
+export function getOperatorsForType(
+ type?: IFilterValueType
+): readonly (keyof typeof operators)[] {
+ switch (type) {
+ case 'number':
+ case 'date':
+ case 'datetime':
+ return ORDERED_OPERATORS;
+ case 'boolean':
+ return BOOLEAN_OPERATORS;
+ default:
+ return STRING_OPERATORS;
+ }
+}
+
+export const chartTypes = {
+ linear: 'Linear',
+ bar: 'Bar',
+ histogram: 'Histogram',
+ pie: 'Pie',
+ metric: 'Metric',
+ area: 'Area',
+ map: 'Map',
+ funnel: 'Funnel',
+ retention: 'Retention',
+ conversion: 'Conversion',
+ sankey: 'Sankey',
+} as const;
+
+export const chartSegments = {
+ event: 'All events',
+ user: 'Unique users',
+ session: 'Unique sessions',
+ group: 'Unique groups',
+ user_average: 'Average users',
+ one_event_per_user: 'One event per user',
+ property_sum: 'Sum of property',
+ property_average: 'Average of property',
+ property_max: 'Max of property',
+ property_min: 'Min of property',
+};
+
+export const lineTypes = {
+ monotone: 'Monotone',
+ monotoneX: 'Monotone X',
+ monotoneY: 'Monotone Y',
+ linear: 'Linear',
+ natural: 'Natural',
+ basis: 'Basis',
+ step: 'Step',
+ stepBefore: 'Step before',
+ stepAfter: 'Step after',
+ basisClosed: 'Basis closed',
+ basisOpen: 'Basis open',
+ bumpX: 'Bump X',
+ bumpY: 'Bump Y',
+ bump: 'Bump',
+ linearClosed: 'Linear closed',
+} as const;
+
+export const intervals = {
+ minute: 'minute',
+ day: 'day',
+ hour: 'hour',
+ week: 'week',
+ month: 'month',
+} as const;
+
+export const alphabetIds = [
+ 'A',
+ 'B',
+ 'C',
+ 'D',
+ 'E',
+ 'F',
+ 'G',
+ 'H',
+ 'I',
+ 'J',
+ 'K',
+ 'L',
+ 'M',
+ 'N',
+ 'O',
+ 'P',
+ 'Q',
+ 'R',
+ 'S',
+ 'T',
+ 'U',
+ 'V',
+ 'W',
+ 'X',
+ 'Y',
+ 'Z',
+] as const;
+
+export const metrics = {
+ count: 'count',
+ sum: 'sum',
+ average: 'average',
+ min: 'min',
+ max: 'max',
+} as const;
+
+export function isMinuteIntervalEnabledByRange(
+ range: keyof typeof timeWindows
+) {
+ return range === '30min' || range === 'lastHour';
+}
+
+export function isHourIntervalEnabledByRange(range: keyof typeof timeWindows) {
+ return (
+ isMinuteIntervalEnabledByRange(range) ||
+ range === 'today' ||
+ range === 'yesterday' ||
+ range === 'last24h' ||
+ range === '7d'
+ );
+}
+
+export function getDefaultIntervalByRange(
+ range: keyof typeof timeWindows
+): keyof typeof intervals {
+ if (range === '30min' || range === 'lastHour') {
+ return 'minute';
+ }
+ if (range === 'today' || range === 'yesterday' || range === 'last24h') {
+ return 'hour';
+ }
+ if (
+ range === '7d' ||
+ range === '30d' ||
+ range === '3m' ||
+ range === 'lastMonth' ||
+ range === 'monthToDate'
+ ) {
+ return 'day';
+ }
+ if (range === '6m') {
+ return 'week';
+ }
+ return 'month';
+}
+
+const MS_PER_DAY = 86_400_000;
+
+function isSameCalendarDay(a: Date, b: Date): boolean {
+ return (
+ a.getFullYear() === b.getFullYear() &&
+ a.getMonth() === b.getMonth() &&
+ a.getDate() === b.getDate()
+ );
+}
+
+/** date-fns's differenceInDays without the dependency — see file header. */
+function differenceInDays(dateLeft: Date, dateRight: Date): number {
+ return Math.trunc((dateLeft.getTime() - dateRight.getTime()) / MS_PER_DAY);
+}
+
+export function getDefaultIntervalByDates(
+ startDate: string | null,
+ endDate: string | null
+): null | keyof typeof intervals {
+ if (startDate && endDate) {
+ const start = new Date(startDate);
+ const end = new Date(endDate);
+ if (isSameCalendarDay(start, end)) {
+ return 'hour';
+ }
+ const days = differenceInDays(end, start);
+ if (days <= 92) {
+ return 'day';
+ }
+ if (days <= 186) {
+ return 'week';
+ }
+ return 'month';
+ }
+
+ return null;
+}
+
+export const countries = {
+ AF: 'Afghanistan',
+ AL: 'Albania',
+ DZ: 'Algeria',
+ AS: 'American Samoa',
+ AD: 'Andorra',
+ AO: 'Angola',
+ AI: 'Anguilla',
+ AQ: 'Antarctica',
+ AG: 'Antigua and Barbuda',
+ AR: 'Argentina',
+ AM: 'Armenia',
+ AW: 'Aruba',
+ AU: 'Australia',
+ AT: 'Austria',
+ AZ: 'Azerbaijan',
+ BS: 'Bahamas',
+ BH: 'Bahrain',
+ BD: 'Bangladesh',
+ BB: 'Barbados',
+ BY: 'Belarus',
+ BE: 'Belgium',
+ BZ: 'Belize',
+ BJ: 'Benin',
+ BM: 'Bermuda',
+ BT: 'Bhutan',
+ BO: 'Bolivia',
+ BQ: 'Bonaire, Sint Eustatius and Saba',
+ BA: 'Bosnia and Herzegovina',
+ BW: 'Botswana',
+ BV: 'Bouvet Island',
+ BR: 'Brazil',
+ IO: 'British Indian Ocean Territory',
+ BN: 'Brunei Darussalam',
+ BG: 'Bulgaria',
+ BF: 'Burkina Faso',
+ BI: 'Burundi',
+ CV: 'Cabo Verde',
+ KH: 'Cambodia',
+ CM: 'Cameroon',
+ CA: 'Canada',
+ KY: 'Cayman Islands',
+ CF: 'Central African Republic',
+ TD: 'Chad',
+ CL: 'Chile',
+ CN: 'China',
+ CX: 'Christmas Island',
+ CC: 'Cocos (Keeling) Islands',
+ CO: 'Colombia',
+ KM: 'Comoros',
+ CD: 'Congo (Democratic Republic)',
+ CG: 'Congo',
+ CK: 'Cook Islands',
+ CR: 'Costa Rica',
+ HR: 'Croatia',
+ CU: 'Cuba',
+ CW: 'Curaçao',
+ CY: 'Cyprus',
+ CZ: 'Czechia',
+ CI: "Côte d'Ivoire",
+ DK: 'Denmark',
+ DJ: 'Djibouti',
+ DM: 'Dominica',
+ DO: 'Dominican Republic',
+ EC: 'Ecuador',
+ EG: 'Egypt',
+ SV: 'El Salvador',
+ GQ: 'Equatorial Guinea',
+ ER: 'Eritrea',
+ EE: 'Estonia',
+ SZ: 'Eswatina',
+ ET: 'Ethiopia',
+ FK: 'Falkland Islands',
+ FO: 'Faroe Islands',
+ FJ: 'Fiji',
+ FI: 'Finland',
+ FR: 'France',
+ GF: 'French Guiana',
+ PF: 'French Polynesia',
+ TF: 'French Southern Territories',
+ GA: 'Gabon',
+ GM: 'Gambia',
+ GE: 'Georgia',
+ DE: 'Germany',
+ GH: 'Ghana',
+ GI: 'Gibraltar',
+ GR: 'Greece',
+ GL: 'Greenland',
+ GD: 'Grenada',
+ GP: 'Guadeloupe',
+ GU: 'Guam',
+ GT: 'Guatemala',
+ GG: 'Guernsey',
+ GN: 'Guinea',
+ GW: 'Guinea-Bissau',
+ GY: 'Guyana',
+ HT: 'Haiti',
+ HM: 'Heard Island and McDonald Islands',
+ VA: 'Holy See',
+ HN: 'Honduras',
+ HK: 'Hong Kong',
+ HU: 'Hungary',
+ IS: 'Iceland',
+ IN: 'India',
+ ID: 'Indonesia',
+ IR: 'Iran',
+ IQ: 'Iraq',
+ IE: 'Ireland',
+ IM: 'Isle of Man',
+ IL: 'Israel',
+ IT: 'Italy',
+ JM: 'Jamaica',
+ JP: 'Japan',
+ JE: 'Jersey',
+ JO: 'Jordan',
+ KZ: 'Kazakhstan',
+ KE: 'Kenya',
+ KI: 'Kiribati',
+ KP: "Korea (Democratic People's Republic)",
+ KR: 'Korea (Republic)',
+ KW: 'Kuwait',
+ KG: 'Kyrgyzstan',
+ LA: "Lao People's Democratic Republic",
+ LV: 'Latvia',
+ LB: 'Lebanon',
+ LS: 'Lesotho',
+ LR: 'Liberia',
+ LY: 'Libya',
+ LI: 'Liechtenstein',
+ LT: 'Lithuania',
+ LU: 'Luxembourg',
+ MO: 'Macao',
+ MG: 'Madagascar',
+ MW: 'Malawi',
+ MY: 'Malaysia',
+ MV: 'Maldives',
+ ML: 'Mali',
+ MT: 'Malta',
+ MH: 'Marshall Islands',
+ MQ: 'Martinique',
+ MR: 'Mauritania',
+ MU: 'Mauritius',
+ YT: 'Mayotte',
+ MX: 'Mexico',
+ FM: 'Micronesia',
+ MD: 'Moldova',
+ MC: 'Monaco',
+ MN: 'Mongolia',
+ ME: 'Montenegro',
+ MS: 'Montserrat',
+ MA: 'Morocco',
+ MZ: 'Mozambique',
+ MM: 'Myanmar',
+ NA: 'Namibia',
+ NR: 'Nauru',
+ NP: 'Nepal',
+ NL: 'Netherlands',
+ NC: 'New Caledonia',
+ NZ: 'New Zealand',
+ NI: 'Nicaragua',
+ NE: 'Niger',
+ NG: 'Nigeria',
+ NU: 'Niue',
+ NF: 'Norfolk Island',
+ MP: 'Northern Mariana Islands',
+ NO: 'Norway',
+ OM: 'Oman',
+ PK: 'Pakistan',
+ PW: 'Palau',
+ PS: 'Palestine, State of',
+ PA: 'Panama',
+ PG: 'Papua New Guinea',
+ PY: 'Paraguay',
+ PE: 'Peru',
+ PH: 'Philippines',
+ PN: 'Pitcairn',
+ PL: 'Poland',
+ PT: 'Portugal',
+ PR: 'Puerto Rico',
+ QA: 'Qatar',
+ MK: 'Republic of North Macedonia',
+ RO: 'Romania',
+ RU: 'Russian Federation',
+ RW: 'Rwanda',
+ RE: 'Réunion',
+ BL: 'Saint Barthélemy',
+ SH: 'Saint Helena, Ascension and Tristan da Cunha',
+ KN: 'Saint Kitts and Nevis',
+ LC: 'Saint Lucia',
+ MF: 'Saint Martin (French part)',
+ PM: 'Saint Pierre and Miquelon',
+ VC: 'Saint Vincent and the Grenadines',
+ WS: 'Samoa',
+ SM: 'San Marino',
+ ST: 'Sao Tome and Principe',
+ SA: 'Saudi Arabia',
+ SN: 'Senegal',
+ RS: 'Serbia',
+ SC: 'Seychelles',
+ SL: 'Sierra Leone',
+ SG: 'Singapore',
+ SX: 'Sint Maarten (Dutch part)',
+ SK: 'Slovakia',
+ SI: 'Slovenia',
+ SB: 'Solomon Islands',
+ SO: 'Somalia',
+ ZA: 'South Africa',
+ GS: 'South Georgia and the South Sandwich Islands',
+ SS: 'South Sudan',
+ ES: 'Spain',
+ LK: 'Sri Lanka',
+ SD: 'Sudan',
+ SR: 'Suriname',
+ SJ: 'Svalbard and Jan Mayen',
+ SE: 'Sweden',
+ CH: 'Switzerland',
+ SY: 'Syrian Arab Republic',
+ TW: 'Taiwan',
+ TJ: 'Tajikistan',
+ TZ: 'Tanzania, United Republic of',
+ TH: 'Thailand',
+ TL: 'Timor-Leste',
+ TG: 'Togo',
+ TK: 'Tokelau',
+ TO: 'Tonga',
+ TT: 'Trinidad and Tobago',
+ TN: 'Tunisia',
+ TR: 'Turkey',
+ TM: 'Turkmenistan',
+ TC: 'Turks and Caicos Islands',
+ TV: 'Tuvalu',
+ UG: 'Uganda',
+ UA: 'Ukraine',
+ AE: 'United Arab Emirates',
+ GB: 'United Kingdom',
+ US: 'United States',
+ UM: 'United States Minor Outlying Islands',
+ UY: 'Uruguay',
+ UZ: 'Uzbekistan',
+ VU: 'Vanuatu',
+ VE: 'Venezuela',
+ VN: 'Viet Nam',
+ VG: 'Virgin Islands (British)',
+ VI: 'Virgin Islands (U.S.)',
+ WF: 'Wallis and Futuna',
+ EH: 'Western Sahara',
+ YE: 'Yemen',
+ ZM: 'Zambia',
+ ZW: 'Zimbabwe',
+ AX: 'Åland Islands',
+} as const;
+
+export function getCountry(code?: string) {
+ return countries[code as keyof typeof countries];
+}
+
+export const chartColors = [
+ { main: '#2563EB', translucent: 'rgba(37, 99, 235, 0.1)' },
+ { main: '#ff7557', translucent: 'rgba(255, 117, 87, 0.1)' },
+ { main: '#7fe1d8', translucent: 'rgba(127, 225, 216, 0.1)' },
+ { main: '#f8bc3c', translucent: 'rgba(248, 188, 60, 0.1)' },
+ { main: '#b3596e', translucent: 'rgba(179, 89, 110, 0.1)' },
+ { main: '#72bef4', translucent: 'rgba(114, 190, 244, 0.1)' },
+ { main: '#ffb27a', translucent: 'rgba(255, 178, 122, 0.1)' },
+ { main: '#0f7ea0', translucent: 'rgba(15, 126, 160, 0.1)' },
+ { main: '#3ba974', translucent: 'rgba(59, 169, 116, 0.1)' },
+ { main: '#febbb2', translucent: 'rgba(254, 187, 178, 0.1)' },
+ { main: '#cb80dc', translucent: 'rgba(203, 128, 220, 0.1)' },
+ { main: '#5cb7af', translucent: 'rgba(92, 183, 175, 0.1)' },
+ { main: '#7856ff', translucent: 'rgba(120, 86, 255, 0.1)' },
+];
+
+/**
+ * Chart formulas are plain arithmetic over series references (A, B, C, ...).
+ * The API validates the parsed expression tree as well; this charset guard
+ * rejects the obviously hostile shapes (assignment, indexing, object/array
+ * literals, statement separators) at the edge, in the browser and on the API.
+ */
+const CHART_FORMULA_PATTERN = /^[A-Za-z0-9_ .,+\-*/()%^]*$/;
+
+// Helper, not vocabulary — ADR-008 rules this the one genuine exception to
+// the module-export rule: every consumer copies these 4 lines locally
+// instead of importing them (apps/start/src/utils/object-to-zod-enums.ts is
+// the frontend's copy). Kept private here for report.constants.ts's own use
+// building the enums below.
+function objectToZodEnums<K extends string>(
+ obj: Record<K, unknown>
+): [K, ...K[]] {
+ const [firstKey, ...otherKeys] = Object.keys(obj) as K[];
+ return [firstKey!, ...otherKeys];
+}
+
+export const zChartEventFilter = z.object({
+ id: z.string().optional().describe('Unique identifier for the filter'),
+ name: z.string().describe('The property name to filter on'),
+ operator: z
+ .enum(objectToZodEnums(operators))
+ .describe('The operator to use for the filter'),
+ value: z
+ .array(z.string().or(z.number()).or(z.boolean()).or(z.null()))
+ .describe('The values to filter on'),
+ type: z
+ .enum(objectToZodEnums(filterValueTypes))
+ .optional()
+ .describe(
+ 'Cast type for the column/value in equality & comparison operators ' +
+ '(string/number/date/datetime/boolean). Absent = legacy behavior.'
+ ),
+ cohortId: z
+ .string()
+ .optional()
+ .describe(
+ 'DEPRECATED: legacy single-cohort id, kept for saved reports. ' +
+ 'New code reads cohortIds via getCohortIds(filter).'
+ ),
+ cohortIds: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Cohort IDs for inCohort/notInCohort. Multiple ids OR-match ' +
+ '(matches profiles in any of the listed cohorts).'
+ ),
+});
+
+/**
+ * Normalize the two cohort id fields on a filter into a single array.
+ *
+ * Both `cohortIds` (new, multi-value) and `cohortId` (legacy, single-value)
+ * coexist on `zChartEventFilter` for backward compatibility with saved
+ * reports. Always read cohort membership through this helper instead of
+ * accessing the raw fields, so legacy data keeps working.
+ */
+export function getCohortIds(filter: {
+ cohortIds?: string[];
+ cohortId?: string;
+}): string[] {
+ if (filter.cohortIds && filter.cohortIds.length > 0) {
+ return filter.cohortIds;
+ }
+ if (filter.cohortId) {
+ return [filter.cohortId];
+ }
+ return [];
+}
+
+export const zChartEventSegment = z
+ .enum(objectToZodEnums(chartSegments))
+ .default('event')
+ .describe('Defines how the event data should be segmented or aggregated');
+
+export const zChartEvent = z.object({
+ id: z
+ .string()
+ .optional()
+ .describe('Unique identifier for the chart event configuration'),
+ name: z.string().describe('The name of the event as tracked in the system'),
+ displayName: z
+ .string()
+ .optional()
+ .describe('A user-friendly name for display purposes'),
+ property: z
+ .string()
+ .optional()
+ .describe(
+ 'Optional property of the event used for specific segment calculations (e.g., value for property_sum/average)'
+ ),
+ segment: zChartEventSegment,
+ filters: z
+ .array(zChartEventFilter)
+ .default([])
+ .describe('Filters applied specifically to this event'),
+});
+
+export const zChartFormula = z.object({
+ id: z
+ .string()
+ .optional()
+ .describe('Unique identifier for the formula configuration'),
+ type: z.literal('formula'),
+ formula: z
+ .string()
+ .max(1000)
+ .regex(
+ CHART_FORMULA_PATTERN,
+ 'Formula may only contain series references, numbers and arithmetic operators'
+ )
+ .describe('The formula expression (e.g., A+B, A/B)'),
+ displayName: z
+ .string()
+ .optional()
+ .describe('A user-friendly name for display purposes'),
+ hideSeries: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Alpha IDs (e.g. ["A", "B"]) of series referenced by this formula that should be hidden from the chart while still being used in the formula computation'
+ ),
+});
+
+// Event with type field for discriminated union
+export const zChartEventWithType = zChartEvent.extend({
+ type: z.literal('event'),
+});
+
+export const zChartEventItem = z.discriminatedUnion('type', [
+ zChartEventWithType,
+ zChartFormula,
+]);
+
+export const zChartBreakdown = z.object({
+ id: z.string().optional(),
+ name: z.string(),
+});
+
+export const zChartSeries = z
+ .array(zChartEventItem)
+ .describe(
+ 'Array of series (events or formulas) to be tracked and displayed in the chart'
+ );
+
+export const zChartBreakdowns = z.array(zChartBreakdown);
+
+export const zChartType = z.enum(objectToZodEnums(chartTypes));
+
+export const zLineType = z.enum(objectToZodEnums(lineTypes));
+
+export const zTimeInterval = z.enum(objectToZodEnums(intervals));
+
+export const zMetric = z.enum(objectToZodEnums(metrics));
+
+export const zRange = z.enum(objectToZodEnums(timeWindows));
+
+export const zCriteria = z.enum(['on_or_after', 'on']);
+
+// Report Options - Discriminated union based on chart type
+export const zFunnelOptions = z.object({
+ type: z.literal('funnel'),
+ funnelGroup: z.string().optional(),
+ funnelWindow: z.number().optional(),
+});
+
+export const zRetentionOptions = z.object({
+ type: z.literal('retention'),
+ criteria: zCriteria.optional(),
+});
+
+export const zSankeyOptions = z.object({
+ type: z.literal('sankey'),
+ mode: z.enum(['between', 'after', 'before']),
+ steps: z.number().min(2).max(10).default(5),
+ exclude: z.array(z.string()).default([]),
+ include: z.array(z.string()).optional(),
+});
+
+export const zHistogramOptions = z.object({
+ type: z.literal('histogram'),
+ stacked: z.boolean().default(false),
+});
+
+export const zReportOptions = z.discriminatedUnion('type', [
+ zFunnelOptions,
+ zRetentionOptions,
+ zSankeyOptions,
+ zHistogramOptions,
+]);
+
+export type IReportOptions = z.infer<typeof zReportOptions>;
+export type ISankeyOptions = z.infer<typeof zSankeyOptions>;
+export type IHistogramOptions = z.infer<typeof zHistogramOptions>;
+
+export const zWidgetType = z.enum(['realtime', 'counter']);
+export type IWidgetType = z.infer<typeof zWidgetType>;
+
+export const zRealtimeWidgetOptions = z.object({
+ type: z.literal('realtime'),
+ referrers: z.boolean().default(true),
+ countries: z.boolean().default(true),
+ paths: z.boolean().default(false),
+});
+
+export const zCounterWidgetOptions = z.object({
+ type: z.literal('counter'),
+});
+
+export const zWidgetOptions = z.discriminatedUnion('type', [
+ zRealtimeWidgetOptions,
+ zCounterWidgetOptions,
+]);
+
+export type IWidgetOptions = z.infer<typeof zWidgetOptions>;
+export type ICounterWidgetOptions = z.infer<typeof zCounterWidgetOptions>;
+export type IRealtimeWidgetOptions = z.infer<typeof zRealtimeWidgetOptions>;
+
+// Base input schema - for API calls, engine, chart queries
+export const zReportInput = z.object({
+ projectId: z.string().describe('The ID of the project this chart belongs to'),
+ chartType: zChartType
+ .default('linear')
+ .describe('What type of chart should be displayed'),
+ interval: zTimeInterval
+ .default('day')
+ .describe(
+ 'The time interval for data aggregation (e.g., day, week, month)'
+ ),
+ series: zChartSeries.describe(
+ 'Array of series (events or formulas) to be tracked and displayed in the chart'
+ ),
+ breakdowns: zChartBreakdowns
+ .default([])
+ .describe('Array of dimensions to break down the data by'),
+ globalFilters: z
+ .array(zChartEventFilter)
+ .optional()
+ .describe(
+ 'Filters applied to ALL event series in this report (combined with each series own filters using AND)'
+ ),
+ range: zRange
+ .default('30d')
+ .describe('The time range for which data should be displayed'),
+ startDate: z
+ .string()
+ .nullish()
+ .describe(
+ 'Custom start date for the data range (overrides range if provided)'
+ ),
+ endDate: z
+ .string()
+ .nullish()
+ .describe(
+ 'Custom end date for the data range (overrides range if provided)'
+ ),
+ previous: z
+ .boolean()
+ .default(false)
+ .describe('Whether to show data from the previous period for comparison'),
+ formula: z
+ .string()
+ .optional()
+ .describe('Custom formula for calculating derived metrics'),
+ metric: zMetric
+ .default('sum')
+ .describe(
+ 'The aggregation method for the metric (e.g., sum, count, average)'
+ ),
+ limit: z
+ .number()
+ .optional()
+ .describe('Limit how many series should be returned'),
+ offset: z
+ .number()
+ .optional()
+ .describe('Skip how many series should be returned'),
+ visibleSeries: z
+ .array(z.string())
+ .nullish()
+ .describe('IDs of series that should be visible on the chart'),
+ options: zReportOptions
+ .optional()
+ .describe('Chart-specific options (funnel, retention, sankey)'),
+ // Optional display fields
+ name: z.string().optional().describe('The user-defined name for the report'),
+ lineType: zLineType
+ .optional()
+ .describe('The visual style of the line in the chart'),
+ unit: z
+ .string()
+ .optional()
+ .describe(
+ "Optional unit of measurement for the chart's Y-axis (e.g., $, %, users)"
+ ),
+});
+
+// Complete report schema - for saved reports
+export const zReport = zReportInput.extend({
+ name: z
+ .string()
+ .default('Untitled')
+ .describe('The user-defined name for the report'),
+ lineType: zLineType
+ .default('monotone')
+ .describe('The visual style of the line in the chart'),
+});
+
+// Alias for backward compatibility
+export const zChartInput = zReportInput;
diff --git a/packages/core/src/modules/report/report.rpc.ts b/packages/core/src/modules/report/report.rpc.ts
new file mode 100644
index 000000000..52fa073da
--- /dev/null
+++ b/packages/core/src/modules/report/report.rpc.ts
@@ -0,0 +1,224 @@
+// Ported from packages/trpc/src/routers/report.ts (M7-006).
+//
+// Same arrangement as chart.rpc.ts/project.rpc.ts: V1's `protectedProcedure`
+// lands in core with auth (rpc/base.ts), so each procedure does its own "is
+// anyone logged in" + `requireProjectAccess` check. The mutation bodies
+// (create/update/move/delete/duplicate/layout) moved to ./report.service
+// alongside the reads that already lived there; packages/trpc's report
+// router delegates every handler body onto ./report.service while keeping
+// V1's own procedure stack (DELEGATE PATTERN).
+
+import { z } from 'zod';
+import { createTRPCRouter, procedure, type TrpcContext } from '../../rpc/base';
+import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
+import {
+ getDashboardById,
+ getDashboardByIdOrThrow,
+} from '../dashboard/dashboard.service';
+import { zReport } from './report.constants';
+import {
+ createReport,
+ deleteReport,
+ duplicateReport,
+ getReportById,
+ getReportByIdOrThrow,
+ getReportLayouts,
+ getReportsByDashboardId,
+ moveReport,
+ resetReportLayouts,
+ updateReport,
+ updateReportLayout,
+} from './report.service';
+
+const zReportLayout = z.object({
+ x: z.number(),
+ y: z.number(),
+ w: z.number(),
+ h: z.number(),
+ minW: z.number().optional(),
+ minH: z.number().optional(),
+ maxW: z.number().optional(),
+ maxH: z.number().optional(),
+});
+
+function loadAccessChecks() {
+ return import('./src/access');
+}
+
+function requireLogin(userId: string | null | undefined): string {
+ if (!userId) {
+ throw new TRPCAccessError('Not authenticated');
+ }
+ return userId;
+}
+
+async function requireAccess(
+ userId: string,
+ projectId: string,
+ level: 'read' | 'write'
+) {
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({ userId, projectId, level });
+}
+
+async function requireReadAccess(ctx: TrpcContext, projectId: string) {
+ await requireAccess(requireLogin(ctx.session.userId), projectId, 'read');
+}
+
+async function requireWriteAccess(ctx: TrpcContext, projectId: string) {
+ await requireAccess(requireLogin(ctx.session.userId), projectId, 'write');
+}
+
+export const reportRouter = createTRPCRouter({
+ list: procedure
+ .input(
+ z.object({
+ dashboardId: z.string(),
+ projectId: z.string(),
+ })
+ )
+ .query(async ({ input: { dashboardId, projectId }, ctx }) => {
+ requireLogin(ctx.session.userId);
+ const dashboard = await getDashboardById(dashboardId, projectId);
+ if (!dashboard) {
+ throw new TRPCNotFoundError('Dashboard not found');
+ }
+ return getReportsByDashboardId(dashboardId);
+ }),
+
+ create: procedure
+ .input(
+ z.object({
+ report: zReport.omit({ projectId: true }),
+ dashboardId: z.string(),
+ })
+ )
+ .mutation(async ({ input: { report, dashboardId }, ctx }) => {
+ const dbDashboard = await getDashboardByIdOrThrow(dashboardId);
+ await requireWriteAccess(ctx, dbDashboard.projectId);
+ return createReport({
+ dashboardId,
+ projectId: dbDashboard.projectId,
+ report,
+ });
+ }),
+
+ update: procedure
+ .input(
+ z.object({
+ reportId: z.string(),
+ report: zReport.omit({ projectId: true }),
+ })
+ )
+ .mutation(async ({ input: { report, reportId }, ctx }) => {
+ const dbReport = await getReportByIdOrThrow(reportId);
+ await requireWriteAccess(ctx, dbReport.projectId);
+ return updateReport({ reportId, report });
+ }),
+
+ move: procedure
+ .input(
+ z.object({
+ reportId: z.string(),
+ dashboardId: z.string(),
+ })
+ )
+ .mutation(async ({ input: { reportId, dashboardId }, ctx }) => {
+ const dbReport = await getReportByIdOrThrow(reportId);
+ await requireWriteAccess(ctx, dbReport.projectId);
+ return moveReport({ report: dbReport, dashboardId });
+ }),
+
+ delete: procedure
+ .input(
+ z.object({
+ reportId: z.string(),
+ })
+ )
+ .mutation(async ({ input: { reportId }, ctx }) => {
+ const dbReport = await getReportByIdOrThrow(reportId);
+ await requireWriteAccess(ctx, dbReport.projectId);
+ return deleteReport(reportId);
+ }),
+
+ duplicate: procedure
+ .input(
+ z.object({
+ reportId: z.string(),
+ })
+ )
+ .mutation(async ({ input: { reportId }, ctx }) => {
+ const dbReport = await getReportByIdOrThrow(reportId);
+ await requireWriteAccess(ctx, dbReport.projectId);
+ return duplicateReport(dbReport);
+ }),
+
+ get: procedure
+ .input(
+ z.object({
+ reportId: z.string(),
+ })
+ )
+ .query(async ({ input: { reportId }, ctx }) => {
+ const report = await getReportById(reportId);
+ if (!report) {
+ throw new TRPCNotFoundError('Report not found');
+ }
+ await requireReadAccess(ctx, report.projectId);
+ return report;
+ }),
+
+ updateLayout: procedure
+ .input(
+ z.object({
+ reportId: z.string(),
+ layout: zReportLayout,
+ })
+ )
+ .mutation(async ({ input: { reportId, layout }, ctx }) => {
+ const dbReport = await getReportByIdOrThrow(reportId);
+ await requireWriteAccess(ctx, dbReport.projectId);
+ return updateReportLayout({ reportId, layout });
+ }),
+
+ getLayouts: procedure
+ .input(
+ z.object({
+ dashboardId: z.string(),
+ projectId: z.string(),
+ })
+ )
+ .query(async ({ input: { dashboardId, projectId }, ctx }) => {
+ await requireReadAccess(ctx, projectId);
+
+ // The access check above only proves the caller owns `projectId`. Bind
+ // the caller-supplied `dashboardId` to that project as well, otherwise a
+ // dashboard from another organization can be read through this handler.
+ const dashboard = await getDashboardById(dashboardId, projectId);
+ if (!dashboard) {
+ throw new TRPCNotFoundError('Dashboard not found');
+ }
+
+ return getReportLayouts({ dashboardId, projectId });
+ }),
+
+ resetLayout: procedure
+ .input(
+ z.object({
+ dashboardId: z.string(),
+ projectId: z.string(),
+ })
+ )
+ .mutation(async ({ input: { dashboardId, projectId }, ctx }) => {
+ await requireWriteAccess(ctx, projectId);
+
+ // Same as `getLayouts`: bind the dashboard to the access-checked project
+ // before deleting anything, so a foreign dashboard cannot be wiped.
+ const dashboard = await getDashboardById(dashboardId, projectId);
+ if (!dashboard) {
+ throw new TRPCNotFoundError('Dashboard not found');
+ }
+
+ return resetReportLayouts({ dashboardId, projectId });
+ }),
+});
diff --git a/packages/db/src/services/reports.service.test.ts b/packages/core/src/modules/report/report.service.test.ts
similarity index 86%
rename from packages/db/src/services/reports.service.test.ts
rename to packages/core/src/modules/report/report.service.test.ts
index ccc2fada9..412e10a85 100644
--- a/packages/db/src/services/reports.service.test.ts
+++ b/packages/core/src/modules/report/report.service.test.ts
@@ -1,11 +1,12 @@
/**
* Unit tests for mergeGlobalFilters — the helper that combines report-level
* global filters with each event series' own filters (AND semantics). Pure
- * function, no ClickHouse/Postgres needed.
+ * function, no ClickHouse/Postgres needed. Ported from
+ * packages/db/src/services/reports.service.test.ts (M7-006), vitest -> bun:test.
*/
+import { describe, expect, it } from 'bun:test';
import type { IChartEventFilter, IChartEventItem } from '@openpanel/validation';
-import { describe, expect, it } from 'vitest';
-import { mergeGlobalFilters } from './reports.service';
+import { mergeGlobalFilters } from './report.service';
const globalFilter: IChartEventFilter = {
id: 'g1',
@@ -48,7 +49,7 @@ describe('mergeGlobalFilters', () => {
it('leaves formula series untouched', () => {
const [, formula] = mergeGlobalFilters(
[eventSeries, formulaSeries],
- [globalFilter],
+ [globalFilter]
);
expect(formula).toBe(formulaSeries);
});
diff --git a/packages/core/src/modules/report/report.service.ts b/packages/core/src/modules/report/report.service.ts
new file mode 100644
index 000000000..5f2a53386
--- /dev/null
+++ b/packages/core/src/modules/report/report.service.ts
@@ -0,0 +1,460 @@
+// Moved from packages/db/src/services/reports.service.ts, plus the
+// create/update/move/delete/duplicate/layout mutation bodies
+// packages/trpc/src/routers/report.ts held inline (M7-006, ADR-008's module
+// map: report owns "R,S,C"). packages/db/src/services/reports.service.ts
+// stays a re-export shim (DELEGATE PATTERN), same shape as
+// project.service.ts since M6-002.
+
+import type {
+ Report as DbReport,
+ ReportLayout,
+} from '@openpanel/db/src/prisma-client';
+import { getChartStartEndDate } from '@openpanel/db/src/services/date.service';
+import type {
+ IChartBreakdown,
+ IChartEventFilter,
+ IChartEventItem,
+ IChartLineType,
+ IChartRange,
+ IReport,
+ IReportOptions,
+} from '@openpanel/validation';
+import { TRPCBadRequestError } from '../../rpc/errors';
+import { getFunnel } from '../chart/funnel.service';
+import { AggregateChartEngine, ChartEngine } from '../chart/src/engine/execute';
+import { getDashboardById } from '../dashboard/dashboard.service';
+import { getSettingsForProject } from '../organization/organization.service';
+import { alphabetIds, lineTypes } from './report.constants';
+
+export type IServiceReport = Awaited<ReturnType<typeof getReportById>>;
+
+// Only the Postgres client stays lazy: report.rpc.ts lands in the eager
+// rpc.router.ts barrel chain nearly every core test file reaches, and
+// constructing @openpanel/db's prisma-client at import time would spawn a
+// pino-pretty transport worker thread per test file (see
+// insight.service.ts's header / project.service.ts's header). date.service
+// and the chart engine carry no db construction of their own, and the chart
+// engine is already eager via chart.rpc.ts, so both stay static imports.
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+export const onlyReportEvents = (
+ series: NonNullable<IServiceReport>['series']
+) => {
+ return series.filter((item) => item.type === 'event');
+};
+
+/**
+ * Prepend report-level global filters to every event series' own filters.
+ * Combining is AND (filters already combine with AND in getEventFiltersWhereClause).
+ * Formulas reference other series, so they inherit the global filters transitively
+ * and are left untouched here.
+ */
+export function mergeGlobalFilters(
+ series: IChartEventItem[],
+ globalFilters: IChartEventFilter[] = []
+): IChartEventItem[] {
+ if (!globalFilters.length) {
+ return series;
+ }
+ return series.map((item) =>
+ item.type === 'event'
+ ? { ...item, filters: [...globalFilters, ...item.filters] }
+ : item
+ );
+}
+
+export function transformFilter(
+ filter: Partial<IChartEventFilter>,
+ index: number
+): IChartEventFilter {
+ return {
+ id: filter.id ?? alphabetIds[index] ?? 'A',
+ name: filter.name ?? 'Unknown Filter',
+ operator: filter.operator ?? 'is',
+ value:
+ typeof filter.value === 'string' ? [filter.value] : (filter.value ?? []),
+ };
+}
+
+export function transformReportEventItem(
+ item: IChartEventItem,
+ index: number
+): IChartEventItem {
+ if (item.type === 'formula') {
+ // Transform formula
+ return {
+ type: 'formula',
+ id: item.id ?? alphabetIds[index]!,
+ formula: item.formula || '',
+ displayName: item.displayName,
+ hideSeries: item.hideSeries,
+ };
+ }
+
+ // Transform event with type field
+ return {
+ type: 'event',
+ segment: item.segment ?? 'event',
+ filters: (item.filters ?? []).map(transformFilter),
+ id: item.id ?? alphabetIds[index]!,
+ name: item.name || 'unknown_event',
+ displayName: item.displayName,
+ property: item.property,
+ };
+}
+
+export function transformReport(
+ report: DbReport & { layout?: ReportLayout | null }
+): IReport & {
+ id: string;
+ layout?: ReportLayout | null;
+} {
+ const options = report.options as IReportOptions | null | undefined;
+
+ return {
+ id: report.id,
+ projectId: report.projectId,
+ name: report.name || 'Untitled',
+ chartType: report.chartType,
+ lineType: (report.lineType as IChartLineType) ?? lineTypes.monotone,
+ interval: report.interval,
+ series:
+ (report.events as IChartEventItem[]).map(transformReportEventItem) ?? [],
+ breakdowns: report.breakdowns as IChartBreakdown[],
+ globalFilters:
+ (report.globalFilters as IChartEventFilter[] | null)?.map(
+ transformFilter
+ ) ?? [],
+ range: report.range as IChartRange,
+ previous: report.previous ?? false,
+ formula: report.formula ?? undefined,
+ metric: report.metric ?? 'sum',
+ unit: report.unit ?? undefined,
+ layout: report.layout ?? undefined,
+ options: options ?? undefined,
+ visibleSeries: report.visibleSeries ?? undefined,
+ startDate: report.startDate ?? undefined,
+ endDate: report.endDate ?? undefined,
+ };
+}
+
+export async function getReportsByDashboardId(dashboardId: string) {
+ const db = await loadDb();
+ const reports = await db.report.findMany({
+ where: {
+ dashboardId,
+ },
+ include: {
+ layout: true,
+ },
+ });
+ return reports.map(transformReport);
+}
+
+export async function getReportById(id: string) {
+ const db = await loadDb();
+ const report = await db.report.findUnique({
+ where: {
+ id,
+ },
+ include: {
+ layout: true,
+ },
+ });
+
+ if (!report) {
+ return null;
+ }
+
+ return transformReport(report);
+}
+
+/** Unscoped lookup for mutation handlers that only receive a report id and
+ * need its `projectId`/`dashboardId` to run the access check — same shape as
+ * V1's inline `db.report.findUniqueOrThrow`. */
+export async function getReportByIdOrThrow(id: string) {
+ const db = await loadDb();
+ return db.report.findUniqueOrThrow({ where: { id } });
+}
+
+export async function listReportsCore(input: {
+ projectId: string;
+ dashboardId: string;
+ organizationId: string;
+}) {
+ const dashboard = await getDashboardById(input.dashboardId, input.projectId);
+ if (!dashboard) {
+ return [];
+ }
+ const reports = await getReportsByDashboardId(input.dashboardId);
+ return reports.map((r) => ({
+ id: r.id,
+ name: r.name,
+ chartType: r.chartType,
+ range: r.range,
+ interval: r.interval,
+ metric: r.metric,
+ series: r.series.map((s) =>
+ s.type === 'formula'
+ ? { type: 'formula', id: s.id, formula: s.formula }
+ : {
+ type: 'event',
+ id: s.id,
+ name: s.name,
+ displayName: s.displayName,
+ segment: s.segment,
+ }
+ ),
+ breakdowns: r.breakdowns,
+ }));
+}
+
+export async function getReportDataCore(input: {
+ projectId: string;
+ reportId: string;
+ organizationId: string;
+}) {
+ const db = await loadDb();
+ const rawReport = await db.report.findUnique({
+ where: { id: input.reportId, projectId: input.projectId },
+ include: { layout: true },
+ });
+
+ if (!rawReport) {
+ throw new Error(`Report not found: ${input.reportId}`);
+ }
+
+ const report = transformReport(rawReport);
+ const { timezone } = await getSettingsForProject(input.projectId);
+ const { startDate, endDate } = getChartStartEndDate(report, timezone);
+ const chartInput = { ...report, startDate, endDate, timezone };
+
+ const meta = {
+ id: report.id,
+ name: report.name,
+ chartType: report.chartType,
+ range: report.range,
+ interval: report.interval,
+ startDate,
+ endDate,
+ };
+
+ if (report.chartType === 'funnel') {
+ const result = await getFunnel(chartInput);
+ return { ...meta, data: result };
+ }
+
+ if (report.chartType === 'metric') {
+ const result = await AggregateChartEngine.execute(chartInput);
+ return { ...meta, data: result };
+ }
+
+ const result = await ChartEngine.execute(chartInput);
+ return { ...meta, data: result };
+}
+
+// -----------------------------------------------------------------------
+// Mutations — moved from packages/trpc/src/routers/report.ts's handler
+// bodies. Each takes the resource already fetched by report.rpc.ts for the
+// access check, so the ported router does exactly one extra Prisma round
+// trip fewer than re-fetching, matching V1's query count.
+
+type IReportInputForWrite = Omit<IReport, 'projectId'>;
+
+function reportWriteData(report: IReportInputForWrite) {
+ return {
+ name: report.name,
+ events: report.series,
+ globalFilters: report.globalFilters ?? [],
+ interval: report.interval,
+ breakdowns: report.breakdowns,
+ chartType: report.chartType,
+ lineType: report.lineType,
+ range: report.range,
+ formula: report.formula,
+ previous: report.previous ?? false,
+ unit: report.unit,
+ metric: report.metric,
+ options: report.options,
+ visibleSeries: report.visibleSeries ?? [],
+ startDate: report.range === 'custom' ? report.startDate : null,
+ endDate: report.range === 'custom' ? report.endDate : null,
+ };
+}
+
+export async function createReport(input: {
+ dashboardId: string;
+ projectId: string;
+ report: IReportInputForWrite;
+}) {
+ const db = await loadDb();
+ return db.report.create({
+ data: {
+ projectId: input.projectId,
+ dashboardId: input.dashboardId,
+ ...reportWriteData(input.report),
+ },
+ });
+}
+
+export async function updateReport(input: {
+ reportId: string;
+ report: IReportInputForWrite;
+}) {
+ const db = await loadDb();
+ return db.report.update({
+ where: {
+ id: input.reportId,
+ },
+ data: reportWriteData(input.report),
+ });
+}
+
+export async function moveReport(input: {
+ report: DbReport;
+ dashboardId: string;
+}) {
+ const db = await loadDb();
+ const { report, dashboardId } = input;
+
+ if (report.dashboardId === dashboardId) {
+ throw new TRPCBadRequestError('Report is already on this dashboard');
+ }
+
+ const dashboard = await db.dashboard.findUniqueOrThrow({
+ where: {
+ id: dashboardId,
+ },
+ });
+
+ // A report keeps its own projectId and that is what powers the chart
+ // queries, public shares included. Moving it to a dashboard in another
+ // project would expose the source project through the target project.
+ if (dashboard.projectId !== report.projectId) {
+ throw new TRPCBadRequestError(
+ 'You can only move a report to a dashboard in the same project'
+ );
+ }
+
+ const [, moved] = await db.$transaction([
+ // The layout belongs to the report, not the dashboard. Keeping it would
+ // drop the report on top of whatever already sits at those coordinates
+ // in the target dashboard.
+ db.reportLayout.deleteMany({
+ where: {
+ reportId: report.id,
+ },
+ }),
+ db.report.update({
+ where: {
+ id: report.id,
+ },
+ data: {
+ dashboardId,
+ },
+ }),
+ ]);
+
+ return moved;
+}
+
+export async function deleteReport(reportId: string) {
+ const db = await loadDb();
+ return db.report.delete({
+ where: {
+ id: reportId,
+ },
+ });
+}
+
+export async function duplicateReport(report: DbReport) {
+ const db = await loadDb();
+ return db.report.create({
+ data: {
+ projectId: report.projectId,
+ dashboardId: report.dashboardId,
+ name: `Copy of ${report.name}`,
+ events: report.events!,
+ globalFilters: report.globalFilters ?? [],
+ interval: report.interval,
+ breakdowns: report.breakdowns!,
+ chartType: report.chartType,
+ lineType: report.lineType,
+ range: report.range,
+ formula: report.formula,
+ previous: report.previous,
+ unit: report.unit,
+ metric: report.metric,
+ options: report.options,
+ visibleSeries: report.visibleSeries,
+ startDate: report.startDate,
+ endDate: report.endDate,
+ },
+ });
+}
+
+interface ReportLayoutInput {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ minW?: number;
+ minH?: number;
+ maxW?: number;
+ maxH?: number;
+}
+
+export async function updateReportLayout(input: {
+ reportId: string;
+ layout: ReportLayoutInput;
+}) {
+ const db = await loadDb();
+ const { reportId, layout } = input;
+
+ // Upsert the layout (create if doesn't exist, update if it does)
+ return db.reportLayout.upsert({
+ where: {
+ reportId,
+ },
+ create: {
+ reportId,
+ ...layout,
+ },
+ update: layout,
+ });
+}
+
+export async function getReportLayouts(input: {
+ dashboardId: string;
+ projectId: string;
+}) {
+ const db = await loadDb();
+ return db.reportLayout.findMany({
+ where: {
+ report: {
+ dashboardId: input.dashboardId,
+ projectId: input.projectId,
+ },
+ },
+ include: {
+ report: true,
+ },
+ });
+}
+
+export async function resetReportLayouts(input: {
+ dashboardId: string;
+ projectId: string;
+}) {
+ const db = await loadDb();
+ return db.reportLayout.deleteMany({
+ where: {
+ report: {
+ dashboardId: input.dashboardId,
+ projectId: input.projectId,
+ },
+ },
+ });
+}
diff --git a/packages/core/src/modules/report/src/access.ts b/packages/core/src/modules/report/src/access.ts
new file mode 100644
index 000000000..315315e48
--- /dev/null
+++ b/packages/core/src/modules/report/src/access.ts
@@ -0,0 +1,22 @@
+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
+// this module's own router — the same binding packages/trpc/src/access.ts
+// does for V1, self-contained here because the general core -> db binding
+// itself moves with auth (P6), not this wave. Same shape as
+// chart/src/access.ts and project/src/access.ts.
+
+import {
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectAccess,
+} from '@openpanel/db/src/services/access.service';
+import { getProjectById } from '@openpanel/db/src/services/project.service';
+import { createAccessChecks } from '../../../shared/access';
+
+const checks = createAccessChecks({
+ getProjectAccess,
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectById,
+});
+
+export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/widget/widget.rpc.ts b/packages/core/src/modules/widget/widget.rpc.ts
new file mode 100644
index 000000000..418f9ffc7
--- /dev/null
+++ b/packages/core/src/modules/widget/widget.rpc.ts
@@ -0,0 +1,386 @@
+// Ported from packages/trpc/src/routers/widget.ts (M7-006, ADR-008's module
+// map: widget is R only — its zod schemas (zWidgetType/zWidgetOptions) are
+// chart/report vocabulary owned by ./report/report.constants.ts, so this
+// module carries no `widget.constants.ts` of its own).
+//
+// V1's `protectedProcedure`/`publicProcedure` split lands in core with auth
+// (rpc/base.ts), so `get`/`toggle`/`updateOptions` do their own "is anyone
+// logged in" check and `counter`/`badge`/`realtimeData` stay open, matching
+// V1's split exactly. There is no `widget.service.ts` (same shape as
+// email.rpc.ts's "R + C only" module): V1's own router keeps its own
+// ClickHouse/Postgres calls rather than delegating to a shared service —
+// the one genuinely shared piece is the report module's widget zod schemas.
+//
+// db/ch/redis access is LAZY (`load*` below): this router lands in the eager
+// rpc.router.ts barrel chain nearly every core test file reaches, and
+// constructing @openpanel/db's clients (or reaching @openpanel/redis's
+// `getCache`) at import time would spawn a pino-pretty transport worker
+// thread per test file / break a test that partially mocks that package —
+// see subscription.service.ts's header for the `getCache` half specifically.
+
+import { clix } from '@openpanel/db/src/clickhouse/query-builder';
+import ShortUniqueId from 'short-unique-id';
+import { z } from 'zod';
+import { createTRPCRouter, procedure } from '../../rpc/base';
+import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
+import { getSettingsForProject } from '../organization/organization.service';
+import { zWidgetOptions, zWidgetType } from '../report/report.constants';
+
+const uid = new ShortUniqueId({ length: 6 });
+const BADGE_CACHE_TTL_SECONDS = 5 * 60; // queries 30 days of data
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+function loadChClient() {
+ return import('@openpanel/db/src/clickhouse/client');
+}
+
+function loadEventBuffer() {
+ return import('@openpanel/db/src/buffers').then((m) => m.eventBuffer);
+}
+
+function loadCache() {
+ return import('@openpanel/redis').then((m) => m.getCache);
+}
+
+function requireLogin(userId: string | null | undefined): string {
+ if (!userId) {
+ throw new TRPCAccessError('Not authenticated');
+ }
+ return userId;
+}
+
+// Helper to find widget by projectId and type
+async function findWidgetByType(projectId: string, type: string) {
+ const db = await loadDb();
+ const widgets = await db.shareWidget.findMany({
+ where: { projectId },
+ });
+ return widgets.find(
+ (w) => (w.options as z.infer<typeof zWidgetOptions>)?.type === type
+ );
+}
+
+export const widgetRouter = createTRPCRouter({
+ // Get widget by projectId and type (returns null if not found or not public)
+ get: procedure
+ .input(z.object({ projectId: z.string(), type: zWidgetType }))
+ .query(async ({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+ const widget = await findWidgetByType(input.projectId, input.type);
+
+ if (!widget) {
+ return null;
+ }
+
+ return widget;
+ }),
+
+ // Toggle widget public status (creates if doesn't exist)
+ toggle: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ organizationId: z.string(),
+ type: zWidgetType,
+ enabled: z.boolean(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+ const db = await loadDb();
+ const existing = await findWidgetByType(input.projectId, input.type);
+
+ if (existing) {
+ return db.shareWidget.update({
+ where: { id: existing.id },
+ data: { public: input.enabled },
+ });
+ }
+
+ // Create new widget with default options
+ const defaultOptions =
+ input.type === 'realtime'
+ ? {
+ type: 'realtime' as const,
+ referrers: true,
+ countries: true,
+ paths: false,
+ }
+ : { type: 'counter' as const };
+
+ return db.shareWidget.create({
+ data: {
+ id: uid.rnd(),
+ projectId: input.projectId,
+ organizationId: input.organizationId,
+ public: input.enabled,
+ options: defaultOptions,
+ },
+ });
+ }),
+
+ // Update widget options (for realtime widget)
+ updateOptions: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ organizationId: z.string(),
+ options: zWidgetOptions,
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+ const db = await loadDb();
+ const existing = await findWidgetByType(
+ input.projectId,
+ input.options.type
+ );
+
+ if (existing) {
+ return db.shareWidget.update({
+ where: { id: existing.id },
+ data: { options: input.options },
+ });
+ }
+
+ // Create new widget if it doesn't exist
+ return db.shareWidget.create({
+ data: {
+ id: uid.rnd(),
+ projectId: input.projectId,
+ organizationId: input.organizationId,
+ public: false,
+ options: input.options,
+ },
+ });
+ }),
+
+ counter: procedure
+ .input(z.object({ shareId: z.string() }))
+ .query(async ({ input }) => {
+ const db = await loadDb();
+ const widget = await db.shareWidget.findUnique({
+ where: {
+ id: input.shareId,
+ },
+ });
+
+ if (!widget?.public) {
+ throw new TRPCNotFoundError('Widget not found');
+ }
+
+ if (widget.options.type !== 'counter') {
+ throw new TRPCNotFoundError('Invalid widget type');
+ }
+
+ const eventBuffer = await loadEventBuffer();
+
+ return {
+ projectId: widget.projectId,
+ counter: await eventBuffer.getActiveVisitorCount(widget.projectId),
+ };
+ }),
+
+ badge: procedure
+ .input(z.object({ shareId: z.string() }))
+ .query(async ({ input }) => {
+ const db = await loadDb();
+ const widget = await db.shareWidget.findUnique({
+ where: {
+ id: input.shareId,
+ },
+ });
+
+ if (!widget?.public) {
+ throw new TRPCNotFoundError('Widget not found');
+ }
+
+ if (widget.options.type !== 'counter') {
+ throw new TRPCNotFoundError('Invalid widget type');
+ }
+
+ const { projectId } = widget;
+ const { timezone } = await getSettingsForProject(projectId);
+ const { ch, TABLE_NAMES } = await loadChClient();
+ const getCache = await loadCache();
+
+ // Cache for 5 minutes since this queries 30 days of data
+ const cacheKey = `widget:badge:${projectId}`;
+ const visitors = await getCache(
+ cacheKey,
+ BADGE_CACHE_TTL_SECONDS,
+ async () => {
+ const uniqueVisitorsQuery = clix(ch, timezone)
+ .select<{ count: number }>(['uniq(profile_id) as count'])
+ .from(TABLE_NAMES.events)
+ .where('project_id', '=', projectId)
+ .where('created_at', '>=', clix.exp('now() - INTERVAL 30 DAY'));
+
+ const result = await uniqueVisitorsQuery.execute();
+ return result[0]?.count || 0;
+ }
+ );
+
+ return {
+ projectId,
+ visitors,
+ };
+ }),
+
+ realtimeData: procedure
+ .input(z.object({ shareId: z.string() }))
+ .query(async ({ input }) => {
+ const db = await loadDb();
+ // Validate ShareWidget exists and is public
+ const widget = await db.shareWidget.findUnique({
+ where: {
+ id: input.shareId,
+ },
+ include: {
+ project: {
+ select: {
+ domain: true,
+ name: true,
+ },
+ },
+ },
+ });
+
+ if (!widget?.public) {
+ throw new TRPCNotFoundError('Widget not found');
+ }
+
+ const { projectId, options } = widget;
+
+ if (options.type !== 'realtime') {
+ throw new TRPCNotFoundError('Invalid widget type');
+ }
+
+ const { timezone } = await getSettingsForProject(projectId);
+ const { ch, TABLE_NAMES } = await loadChClient();
+
+ // Always fetch live count and histogram
+ const totalSessionsQuery = clix(ch, timezone)
+ .select<{ total_sessions: number }>([
+ 'uniq(session_id) as total_sessions',
+ ])
+ .from(TABLE_NAMES.events)
+ .where('project_id', '=', projectId)
+ .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'));
+
+ const minuteCountsQuery = clix(ch, timezone)
+ .select<{
+ minute: string;
+ session_count: number;
+ visitor_count: number;
+ }>([
+ `${clix.toStartOf('created_at', 'minute')} as minute`,
+ 'uniq(session_id) as session_count',
+ 'uniq(profile_id) as visitor_count',
+ ])
+ .from(TABLE_NAMES.events)
+ .where('project_id', '=', projectId)
+ .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))
+ .groupBy(['minute'])
+ .orderBy('minute', 'ASC')
+ .fill(
+ clix.exp('toStartOfMinute(now() - INTERVAL 30 MINUTE)'),
+ clix.exp('toStartOfMinute(now())'),
+ clix.exp('INTERVAL 1 MINUTE')
+ );
+
+ // Conditionally fetch countries
+ const countriesQueryPromise = options.countries
+ ? clix(ch, timezone)
+ .select<{
+ country: string;
+ count: number;
+ }>(['country', 'uniq(session_id) as count'])
+ .from(TABLE_NAMES.events)
+ .where('project_id', '=', projectId)
+ .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))
+ .where('country', '!=', '')
+ .where('country', 'IS NOT NULL')
+ .groupBy(['country'])
+ .orderBy('count', 'DESC')
+ .limit(10)
+ .execute()
+ : Promise.resolve<Array<{ country: string; count: number }>>([]);
+
+ // Conditionally fetch referrers
+ const referrersQueryPromise = options.referrers
+ ? clix(ch, timezone)
+ .select<{ referrer: string; count: number }>([
+ 'referrer_name as referrer',
+ 'uniq(session_id) as count',
+ ])
+ .from(TABLE_NAMES.events)
+ .where('project_id', '=', projectId)
+ .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))
+ .where('referrer_name', '!=', '')
+ .where('referrer_name', 'IS NOT NULL')
+ .groupBy(['referrer_name'])
+ .orderBy('count', 'DESC')
+ .limit(10)
+ .execute()
+ : Promise.resolve<Array<{ referrer: string; count: number }>>([]);
+
+ // Conditionally fetch paths
+ const pathsQueryPromise = options.paths
+ ? clix(ch, timezone)
+ .select<{ path: string; count: number }>([
+ 'path',
+ 'uniq(session_id) as count',
+ ])
+ .from(TABLE_NAMES.events)
+ .where('project_id', '=', projectId)
+ .where('created_at', '>=', clix.exp('now() - INTERVAL 30 MINUTE'))
+ .where('path', '!=', '')
+ .where('path', 'IS NOT NULL')
+ .groupBy(['path'])
+ .orderBy('count', 'DESC')
+ .limit(10)
+ .execute()
+ : Promise.resolve<Array<{ path: string; count: number }>>([]);
+
+ const [totalSessions, minuteCounts, countries, referrers, paths] =
+ await Promise.all([
+ totalSessionsQuery.execute(),
+ minuteCountsQuery.execute(),
+ countriesQueryPromise,
+ referrersQueryPromise,
+ pathsQueryPromise,
+ ]);
+
+ return {
+ projectId,
+ liveCount: totalSessions[0]?.total_sessions || 0,
+ project: widget.project,
+ histogram: minuteCounts.map((item) => ({
+ minute: item.minute,
+ sessionCount: item.session_count,
+ visitorCount: item.visitor_count,
+ timestamp: new Date(item.minute).getTime(),
+ time: new Date(item.minute).toLocaleTimeString([], {
+ hour: '2-digit',
+ minute: '2-digit',
+ }),
+ })),
+ countries: countries.map((item) => ({
+ country: item.country,
+ count: item.count,
+ })),
+ referrers: referrers.map((item) => ({
+ referrer: item.referrer,
+ count: item.count,
+ })),
+ paths: paths.map((item) => ({
+ path: item.path,
+ count: item.count,
+ })),
+ };
+ }),
+});
diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.ts
index c27a93d73..a67169032 100644
--- a/packages/core/src/rpc.router.ts
+++ b/packages/core/src/rpc.router.ts
@@ -10,6 +10,7 @@ import { chartRouter } from './modules/chart/chart.rpc';
import { clientRouter } from './modules/client/client.rpc';
import { cohortRouter } from './modules/cohort/cohort.rpc';
import { conversationRouter } from './modules/conversation/conversation.rpc';
+import { dashboardRouter } from './modules/dashboard/dashboard.rpc';
import { emailRouter } from './modules/email/email.rpc';
import { eventRouter } from './modules/event/event.rpc';
import { groupRouter } from './modules/group/group.rpc';
@@ -26,10 +27,12 @@ import { profileRouter } from './modules/profile/profile.rpc';
import { projectRouter } from './modules/project/project.rpc';
import { realtimeRouter } from './modules/realtime/realtime.rpc';
import { referenceRouter } from './modules/reference/reference.rpc';
+import { reportRouter } from './modules/report/report.rpc';
import { sessionRouter } from './modules/session/session.rpc';
import { shareRouter } from './modules/share/share.rpc';
import { subscriptionRouter } from './modules/subscription/subscription.rpc';
import { userRouter } from './modules/user/user.rpc';
+import { widgetRouter } from './modules/widget/widget.rpc';
import { createTRPCRouter } from './rpc/base';
export const appRouter = createTRPCRouter({
@@ -59,6 +62,9 @@ export const appRouter = createTRPCRouter({
group: groupRouter,
chart: chartRouter,
overview: overviewRouter,
+ report: reportRouter,
+ dashboard: dashboardRouter,
+ widget: widgetRouter,
});
export type AppRouter = typeof appRouter;
diff --git a/packages/db/src/services/dashboard.service.ts b/packages/db/src/services/dashboard.service.ts
index d4d392afe..75f7cf788 100644
--- a/packages/db/src/services/dashboard.service.ts
+++ b/packages/db/src/services/dashboard.service.ts
@@ -1,51 +1,18 @@
-import type { Dashboard, Prisma } from '../prisma-client';
-import { db } from '../prisma-client';
-
-export type IServiceDashboard = Dashboard;
-export type IServiceDashboards = Prisma.DashboardGetPayload<{
- include: {
- project: true;
- reports: true;
- };
-}>[];
-
-export async function getDashboardById(id: string, projectId: string) {
- const dashboard = await db.dashboard.findUnique({
- where: {
- id,
- projectId,
- },
- include: {
- project: true,
- },
- });
-
- if (!dashboard) {
- return null;
- }
-
- return dashboard;
-}
-
-export function getDashboardsByProjectId(projectId: string) {
- return db.dashboard.findMany({
- where: {
- projectId,
- },
- include: {
- project: true,
- reports: true,
- },
- });
-}
-
-export async function listDashboardsCore(input: {
- projectId: string;
- organizationId: string;
-}) {
- return db.dashboard.findMany({
- where: { projectId: input.projectId },
- orderBy: { createdAt: 'desc' },
- select: { id: true, name: true, projectId: true },
- });
-}
+// The dashboard service lives in @openpanel/core now (M7-006). Re-exported
+// here for existing `@openpanel/db` importers (packages/trpc's dashboard/
+// report routers, apps/api's insights controller, the mcp/assistant tools,
+// packages/core's report.service and share.service) — same shape as
+// packages/db/src/services/chart.service.ts since M7-003.
+export type {
+ IServiceDashboard,
+ IServiceDashboards,
+} from '@openpanel/core';
+export {
+ createDashboard,
+ deleteDashboard,
+ getDashboardById,
+ getDashboardByIdOrThrow,
+ getDashboardsByProjectId,
+ listDashboardsCore,
+ updateDashboard,
+} from '@openpanel/core';
diff --git a/packages/db/src/services/reports.service.ts b/packages/db/src/services/reports.service.ts
index de28ecfad..3fc635892 100644
--- a/packages/db/src/services/reports.service.ts
+++ b/packages/db/src/services/reports.service.ts
@@ -1,221 +1,27 @@
-import { alphabetIds, lineTypes } from '@openpanel/constants';
-import type {
- IChartBreakdown,
- IChartEventFilter,
- IChartEventItem,
- IChartLineType,
- IChartRange,
- IReport,
- IReportOptions,
-} from '@openpanel/validation';
-
-import type { Report as DbReport, ReportLayout } from '../prisma-client';
-import { db } from '../prisma-client';
-
-export type IServiceReport = Awaited<ReturnType<typeof getReportById>>;
-
-export const onlyReportEvents = (
- series: NonNullable<IServiceReport>['series'],
-) => {
- return series.filter((item) => item.type === 'event');
-};
-
-/**
- * Prepend report-level global filters to every event series' own filters.
- * Combining is AND (filters already combine with AND in getEventFiltersWhereClause).
- * Formulas reference other series, so they inherit the global filters transitively
- * and are left untouched here.
- */
-export function mergeGlobalFilters(
- series: IChartEventItem[],
- globalFilters: IChartEventFilter[] = [],
-): IChartEventItem[] {
- if (!globalFilters.length) {
- return series;
- }
- return series.map((item) =>
- item.type === 'event'
- ? { ...item, filters: [...globalFilters, ...item.filters] }
- : item,
- );
-}
-
-export function transformFilter(
- filter: Partial<IChartEventFilter>,
- index: number,
-): IChartEventFilter {
- return {
- id: filter.id ?? alphabetIds[index] ?? 'A',
- name: filter.name ?? 'Unknown Filter',
- operator: filter.operator ?? 'is',
- value:
- typeof filter.value === 'string' ? [filter.value] : (filter.value ?? []),
- };
-}
-
-export function transformReportEventItem(
- item: IChartEventItem,
- index: number,
-): IChartEventItem {
- if (item.type === 'formula') {
- // Transform formula
- return {
- type: 'formula',
- id: item.id ?? alphabetIds[index]!,
- formula: item.formula || '',
- displayName: item.displayName,
- hideSeries: item.hideSeries,
- };
- }
-
- // Transform event with type field
- return {
- type: 'event',
- segment: item.segment ?? 'event',
- filters: (item.filters ?? []).map(transformFilter),
- id: item.id ?? alphabetIds[index]!,
- name: item.name || 'unknown_event',
- displayName: item.displayName,
- property: item.property,
- };
-}
-
-export function transformReport(
- report: DbReport & { layout?: ReportLayout | null },
-): IReport & {
- id: string;
- layout?: ReportLayout | null;
-} {
- const options = report.options as IReportOptions | null | undefined;
-
- return {
- id: report.id,
- projectId: report.projectId,
- name: report.name || 'Untitled',
- chartType: report.chartType,
- lineType: (report.lineType as IChartLineType) ?? lineTypes.monotone,
- interval: report.interval,
- series:
- (report.events as IChartEventItem[]).map(transformReportEventItem) ?? [],
- breakdowns: report.breakdowns as IChartBreakdown[],
- globalFilters:
- (report.globalFilters as IChartEventFilter[] | null)?.map(
- transformFilter,
- ) ?? [],
- range: report.range as IChartRange,
- previous: report.previous ?? false,
- formula: report.formula ?? undefined,
- metric: report.metric ?? 'sum',
- unit: report.unit ?? undefined,
- layout: report.layout ?? undefined,
- options: options ?? undefined,
- visibleSeries: report.visibleSeries ?? undefined,
- startDate: report.startDate ?? undefined,
- endDate: report.endDate ?? undefined,
- };
-}
-
-export function getReportsByDashboardId(dashboardId: string) {
- return db.report
- .findMany({
- where: {
- dashboardId,
- },
- include: {
- layout: true,
- },
- })
- .then((reports) => reports.map(transformReport));
-}
-
-export async function getReportById(id: string) {
- const report = await db.report.findUnique({
- where: {
- id,
- },
- include: {
- layout: true,
- },
- });
-
- if (!report) {
- return null;
- }
-
- return transformReport(report);
-}
-
-import { AggregateChartEngine, ChartEngine } from '../engine';
-import { getDashboardById } from './dashboard.service';
-import { getChartStartEndDate } from './date.service';
-import { getFunnel } from './funnel.service';
-import { getSettingsForProject } from './organization.service';
-
-export async function listReportsCore(input: {
- projectId: string;
- dashboardId: string;
- organizationId: string;
-}) {
- const dashboard = await getDashboardById(input.dashboardId, input.projectId);
- if (!dashboard) {
- return [];
- }
- const reports = await getReportsByDashboardId(input.dashboardId);
- return reports.map((r) => ({
- id: r.id,
- name: r.name,
- chartType: r.chartType,
- range: r.range,
- interval: r.interval,
- metric: r.metric,
- series: r.series.map((s) =>
- s.type === 'formula'
- ? { type: 'formula', id: s.id, formula: s.formula }
- : { type: 'event', id: s.id, name: s.name, displayName: s.displayName, segment: s.segment },
- ),
- breakdowns: r.breakdowns,
- }));
-}
-
-export async function getReportDataCore(input: {
- projectId: string;
- reportId: string;
- organizationId: string;
-}) {
- const rawReport = await db.report.findUnique({
- where: { id: input.reportId, projectId: input.projectId },
- include: { layout: true },
- });
-
- if (!rawReport) {
- throw new Error(`Report not found: ${input.reportId}`);
- }
-
- const report = transformReport(rawReport);
- const { timezone } = await getSettingsForProject(input.projectId);
- const { startDate, endDate } = getChartStartEndDate(report, timezone);
- const chartInput = { ...report, startDate, endDate, timezone };
-
- const meta = {
- id: report.id,
- name: report.name,
- chartType: report.chartType,
- range: report.range,
- interval: report.interval,
- startDate,
- endDate,
- };
-
- if (report.chartType === 'funnel') {
- const result = await getFunnel(chartInput);
- return { ...meta, data: result };
- }
-
- if (report.chartType === 'metric') {
- const result = await AggregateChartEngine.execute(chartInput);
- return { ...meta, data: result };
- }
-
- const result = await ChartEngine.execute(chartInput);
- return { ...meta, data: result };
-}
+// The report service — transforms, mutations, listReportsCore and
+// getReportDataCore — lives in @openpanel/core now (M7-006). Re-exported here
+// for existing `@openpanel/db` importers (packages/trpc's report/chart
+// routers, apps/api's insights controller, the chart engine's funnel/
+// conversion services, the mcp/assistant tools) — same shape as
+// packages/db/src/services/chart.service.ts since M7-003.
+export type { IServiceReport } from '@openpanel/core';
+export {
+ createReport,
+ deleteReport,
+ duplicateReport,
+ getReportById,
+ getReportByIdOrThrow,
+ getReportDataCore,
+ getReportLayouts,
+ getReportsByDashboardId,
+ listReportsCore,
+ mergeGlobalFilters,
+ moveReport,
+ onlyReportEvents,
+ resetReportLayouts,
+ transformFilter,
+ transformReport,
+ transformReportEventItem,
+ updateReport,
+ updateReportLayout,
+} from '@openpanel/core';
diff --git a/packages/trpc/src/routers/dashboard.ts b/packages/trpc/src/routers/dashboard.ts
index b8393c43e..e3e4516d9 100644
--- a/packages/trpc/src/routers/dashboard.ts
+++ b/packages/trpc/src/routers/dashboard.ts
@@ -1,15 +1,19 @@
-import { PrismaError } from 'prisma-error-enum';
-import { z } from 'zod';
+// Dissolved into @openpanel/core's dashboard module (M7-006): the reads plus
+// the create/update/delete mutation bodies moved to
+// packages/core/src/modules/dashboard/dashboard.service.ts. This router
+// stays (DELEGATE PATTERN) — it keeps V1's `protectedProcedure` stack and
+// delegates every handler body to core's dashboard functions, same as
+// overview.ts/chart.ts.
import {
- db,
+ createDashboard,
+ deleteDashboard,
getDashboardById,
+ getDashboardByIdOrThrow,
getDashboardsByProjectId,
- getId,
- getProjectById,
-} from '@openpanel/db';
-import type { Prisma } from '@openpanel/db';
-
+ updateDashboard,
+} from '@openpanel/core';
+import { z } from 'zod';
import { getProjectAccess, requireProjectAccess } from '../access';
import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -19,7 +23,7 @@ export const dashboardRouter = createTRPCRouter({
.input(
z.object({
projectId: z.string(),
- }),
+ })
)
.query(({ input }) => {
return getDashboardsByProjectId(input.projectId);
@@ -29,7 +33,7 @@ export const dashboardRouter = createTRPCRouter({
z.object({
id: z.string(),
projectId: z.string(),
- }),
+ })
)
.query(async ({ input, ctx }) => {
const access = await getProjectAccess({
@@ -54,7 +58,7 @@ export const dashboardRouter = createTRPCRouter({
z.object({
name: z.string(),
projectId: z.string(),
- }),
+ })
)
.mutation(async ({ input, ctx }) => {
await requireProjectAccess({
@@ -63,34 +67,17 @@ export const dashboardRouter = createTRPCRouter({
level: 'write',
});
- const project = await getProjectById(input.projectId);
-
- if (!project) {
- throw new TRPCNotFoundError('Project not found');
- }
-
- return db.dashboard.create({
- data: {
- id: await getId('dashboard', input.name),
- projectId: input.projectId,
- organizationId: project.organizationId,
- name: input.name,
- },
- });
+ return createDashboard(input);
}),
update: protectedProcedure
.input(
z.object({
id: z.string(),
name: z.string(),
- }),
+ })
)
.mutation(async ({ input, ctx }) => {
- const dashboard = await db.dashboard.findUniqueOrThrow({
- where: {
- id: input.id,
- },
- });
+ const dashboard = await getDashboardByIdOrThrow(input.id);
await requireProjectAccess({
userId: ctx.session.userId,
@@ -98,28 +85,17 @@ export const dashboardRouter = createTRPCRouter({
level: 'write',
});
- return db.dashboard.update({
- where: {
- id: input.id,
- },
- data: {
- name: input.name,
- },
- });
+ return updateDashboard(input);
}),
delete: protectedProcedure
.input(
z.object({
id: z.string(),
forceDelete: z.boolean().optional(),
- }),
+ })
)
.mutation(async ({ input, ctx }) => {
- const dashboard = await db.dashboard.findUniqueOrThrow({
- where: {
- id: input.id,
- },
- });
+ const dashboard = await getDashboardByIdOrThrow(input.id);
await requireProjectAccess({
userId: ctx.session.userId,
@@ -127,33 +103,6 @@ export const dashboardRouter = createTRPCRouter({
level: 'write',
});
- try {
- if (input.forceDelete) {
- await db.report.deleteMany({
- where: {
- dashboardId: input.id,
- },
- });
- }
- await db.dashboard.delete({
- where: {
- id: input.id,
- },
- });
- } catch (e) {
- // Below does not work...
- // error instanceof Prisma.PrismaClientKnownRequestError
- if (typeof e === 'object' && e && 'code' in e) {
- const error = e as Prisma.PrismaClientKnownRequestError;
- switch (error.code) {
- case PrismaError.ForeignConstraintViolation:
- throw new Error(
- 'Cannot delete dashboard with associated reports',
- );
- default:
- throw new Error('Unknown error deleting dashboard');
- }
- }
- }
+ return deleteDashboard(input);
}),
});
diff --git a/packages/trpc/src/routers/report.ts b/packages/trpc/src/routers/report.ts
index 3b89874a5..930ffa53e 100644
--- a/packages/trpc/src/routers/report.ts
+++ b/packages/trpc/src/routers/report.ts
@@ -1,19 +1,32 @@
-import { z } from 'zod';
+// Dissolved into @openpanel/core's report module (M7-006): the transforms,
+// listReportsCore/getReportDataCore and the create/update/move/delete/
+// duplicate/layout mutation bodies moved to
+// packages/core/src/modules/report/report.service.ts, and the chart/report/
+// widget zod schemas (zReport included) moved to
+// packages/core/src/modules/report/report.constants.ts. This router stays
+// (DELEGATE PATTERN) — it keeps V1's `protectedProcedure` stack and
+// delegates every handler body to core's report functions, same as
+// overview.ts/chart.ts.
import {
- db,
+ createReport,
+ deleteReport,
+ duplicateReport,
getDashboardById,
+ getDashboardByIdOrThrow,
getReportById,
+ getReportByIdOrThrow,
+ getReportLayouts,
getReportsByDashboardId,
-} from '@openpanel/db';
-import { zReport } from '@openpanel/validation';
-
+ moveReport,
+ resetReportLayouts,
+ updateReport,
+ updateReportLayout,
+ zReport,
+} from '@openpanel/core';
+import { z } from 'zod';
import { getProjectAccess, requireProjectAccess } from '../access';
-import {
- TRPCBadRequestError,
- TRPCForbiddenError,
- TRPCNotFoundError,
-} from '../errors';
+import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
export const reportRouter = createTRPCRouter({
@@ -22,7 +35,7 @@ export const reportRouter = createTRPCRouter({
z.object({
dashboardId: z.string(),
projectId: z.string(),
- }),
+ })
)
.query(async ({ input: { dashboardId, projectId } }) => {
const dashboard = await getDashboardById(dashboardId, projectId);
@@ -36,14 +49,10 @@ export const reportRouter = createTRPCRouter({
z.object({
report: zReport.omit({ projectId: true }),
dashboardId: z.string(),
- }),
+ })
)
.mutation(async ({ input: { report, dashboardId }, ctx }) => {
- const dashboard = await db.dashboard.findUniqueOrThrow({
- where: {
- id: dashboardId,
- },
- });
+ const dashboard = await getDashboardByIdOrThrow(dashboardId);
await requireProjectAccess({
userId: ctx.session.userId,
@@ -51,27 +60,10 @@ export const reportRouter = createTRPCRouter({
level: 'write',
});
- return db.report.create({
- data: {
- projectId: dashboard.projectId,
- dashboardId,
- name: report.name,
- events: report.series,
- globalFilters: report.globalFilters ?? [],
- interval: report.interval,
- breakdowns: report.breakdowns,
- chartType: report.chartType,
- lineType: report.lineType,
- range: report.range,
- formula: report.formula,
- previous: report.previous ?? false,
- unit: report.unit,
- metric: report.metric,
- options: report.options,
- visibleSeries: report.visibleSeries ?? [],
- startDate: report.range === 'custom' ? report.startDate : null,
- endDate: report.range === 'custom' ? report.endDate : null,
- },
+ return createReport({
+ dashboardId,
+ projectId: dashboard.projectId,
+ report,
});
}),
update: protectedProcedure
@@ -79,14 +71,10 @@ export const reportRouter = createTRPCRouter({
z.object({
reportId: z.string(),
report: zReport.omit({ projectId: true }),
- }),
+ })
)
.mutation(async ({ input: { report, reportId }, ctx }) => {
- const dbReport = await db.report.findUniqueOrThrow({
- where: {
- id: reportId,
- },
- });
+ const dbReport = await getReportByIdOrThrow(reportId);
await requireProjectAccess({
userId: ctx.session.userId,
@@ -94,162 +82,65 @@ export const reportRouter = createTRPCRouter({
level: 'write',
});
- return db.report.update({
- where: {
- id: reportId,
- },
- data: {
- name: report.name,
- events: report.series,
- globalFilters: report.globalFilters ?? [],
- interval: report.interval,
- breakdowns: report.breakdowns,
- chartType: report.chartType,
- lineType: report.lineType,
- range: report.range,
- formula: report.formula,
- previous: report.previous ?? false,
- unit: report.unit,
- metric: report.metric,
- options: report.options,
- visibleSeries: report.visibleSeries ?? [],
- startDate: report.range === 'custom' ? report.startDate : null,
- endDate: report.range === 'custom' ? report.endDate : null,
- },
- });
+ return updateReport({ reportId, report });
}),
move: protectedProcedure
.input(
z.object({
reportId: z.string(),
dashboardId: z.string(),
- }),
+ })
)
.mutation(async ({ input: { reportId, dashboardId }, ctx }) => {
- const report = await db.report.findUniqueOrThrow({
- where: {
- id: reportId,
- },
- });
+ const dbReport = await getReportByIdOrThrow(reportId);
await requireProjectAccess({
userId: ctx.session.userId,
- projectId: report.projectId,
+ projectId: dbReport.projectId,
level: 'write',
});
- if (report.dashboardId === dashboardId) {
- throw new TRPCBadRequestError('Report is already on this dashboard');
- }
-
- const dashboard = await db.dashboard.findUniqueOrThrow({
- where: {
- id: dashboardId,
- },
- });
-
- // A report keeps its own projectId and that is what powers the chart
- // queries, public shares included. Moving it to a dashboard in another
- // project would expose the source project through the target project.
- if (dashboard.projectId !== report.projectId) {
- throw new TRPCBadRequestError(
- 'You can only move a report to a dashboard in the same project',
- );
- }
-
- const [, moved] = await db.$transaction([
- // The layout belongs to the report, not the dashboard. Keeping it would
- // drop the report on top of whatever already sits at those coordinates
- // in the target dashboard.
- db.reportLayout.deleteMany({
- where: {
- reportId,
- },
- }),
- db.report.update({
- where: {
- id: reportId,
- },
- data: {
- dashboardId,
- },
- }),
- ]);
-
- return moved;
+ return moveReport({ report: dbReport, dashboardId });
}),
delete: protectedProcedure
.input(
z.object({
reportId: z.string(),
- }),
+ })
)
.mutation(async ({ input: { reportId }, ctx }) => {
- const report = await db.report.findUniqueOrThrow({
- where: {
- id: reportId,
- },
- });
+ const dbReport = await getReportByIdOrThrow(reportId);
await requireProjectAccess({
userId: ctx.session.userId,
- projectId: report.projectId,
+ projectId: dbReport.projectId,
level: 'write',
});
- return db.report.delete({
- where: {
- id: reportId,
- },
- });
+ return deleteReport(reportId);
}),
duplicate: protectedProcedure
.input(
z.object({
reportId: z.string(),
- }),
+ })
)
.mutation(async ({ input: { reportId }, ctx }) => {
- const report = await db.report.findUniqueOrThrow({
- where: {
- id: reportId,
- },
- });
+ const dbReport = await getReportByIdOrThrow(reportId);
await requireProjectAccess({
userId: ctx.session.userId,
- projectId: report.projectId,
+ projectId: dbReport.projectId,
level: 'write',
});
- return db.report.create({
- data: {
- projectId: report.projectId,
- dashboardId: report.dashboardId,
- name: `Copy of ${report.name}`,
- events: report.events!,
- globalFilters: report.globalFilters ?? [],
- interval: report.interval,
- breakdowns: report.breakdowns!,
- chartType: report.chartType,
- lineType: report.lineType,
- range: report.range,
- formula: report.formula,
- previous: report.previous,
- unit: report.unit,
- metric: report.metric,
- options: report.options,
- visibleSeries: report.visibleSeries,
- startDate: report.startDate,
- endDate: report.endDate,
- },
- });
+ return duplicateReport(dbReport);
}),
get: protectedProcedure
.input(
z.object({
reportId: z.string(),
- }),
+ })
)
.query(async ({ input: { reportId }, ctx }) => {
const report = await getReportById(reportId);
@@ -279,60 +170,30 @@ export const reportRouter = createTRPCRouter({
maxW: z.number().optional(),
maxH: z.number().optional(),
}),
- }),
+ })
)
.mutation(async ({ input: { reportId, layout }, ctx }) => {
- const report = await db.report.findUniqueOrThrow({
- where: {
- id: reportId,
- },
- });
+ const dbReport = await getReportByIdOrThrow(reportId);
await requireProjectAccess({
userId: ctx.session.userId,
- projectId: report.projectId,
+ projectId: dbReport.projectId,
level: 'write',
});
- // Upsert the layout (create if doesn't exist, update if it does)
- return db.reportLayout.upsert({
- where: {
- reportId,
- },
- create: {
- reportId,
- x: layout.x,
- y: layout.y,
- w: layout.w,
- h: layout.h,
- minW: layout.minW,
- minH: layout.minH,
- maxW: layout.maxW,
- maxH: layout.maxH,
- },
- update: {
- x: layout.x,
- y: layout.y,
- w: layout.w,
- h: layout.h,
- minW: layout.minW,
- minH: layout.minH,
- maxW: layout.maxW,
- maxH: layout.maxH,
- },
- });
+ return updateReportLayout({ reportId, layout });
}),
getLayouts: protectedProcedure
.input(
z.object({
dashboardId: z.string(),
projectId: z.string(),
- }),
+ })
)
.query(async ({ input: { dashboardId, projectId }, ctx }) => {
const access = await getProjectAccess({
userId: ctx.session.userId,
- projectId: projectId,
+ projectId,
});
if (!access) {
@@ -347,29 +208,19 @@ export const reportRouter = createTRPCRouter({
throw new TRPCNotFoundError('Dashboard not found');
}
- return db.reportLayout.findMany({
- where: {
- report: {
- dashboardId: dashboardId,
- projectId,
- },
- },
- include: {
- report: true,
- },
- });
+ return getReportLayouts({ dashboardId, projectId });
}),
resetLayout: protectedProcedure
.input(
z.object({
dashboardId: z.string(),
projectId: z.string(),
- }),
+ })
)
.mutation(async ({ input: { dashboardId, projectId }, ctx }) => {
await requireProjectAccess({
userId: ctx.session.userId,
- projectId: projectId,
+ projectId,
level: 'write',
});
@@ -380,14 +231,6 @@ export const reportRouter = createTRPCRouter({
throw new TRPCNotFoundError('Dashboard not found');
}
- // Delete all layout data for reports in this dashboard
- return db.reportLayout.deleteMany({
- where: {
- report: {
- dashboardId: dashboardId,
- projectId,
- },
- },
- });
+ return resetReportLayouts({ dashboardId, projectId });
}),
});
diff --git a/packages/trpc/src/routers/widget.ts b/packages/trpc/src/routers/widget.ts
index 56ba74bb7..529db12a2 100644
--- a/packages/trpc/src/routers/widget.ts
+++ b/packages/trpc/src/routers/widget.ts
@@ -1,3 +1,12 @@
+// Ported into @openpanel/core's widget module (M7-006): `zWidgetOptions`/
+// `zWidgetType` moved to the report module's report.constants.ts (ADR-008's
+// module map: widget's own schemas are chart/report vocabulary, so widget
+// carries no `widget.constants.ts` of its own). This router is R + C-only
+// downstream, same as email.ts — there is no `widget.service.ts` to
+// delegate to, so V1 keeps its own ClickHouse/Postgres calls here, reading
+// the schemas core now owns instead of @openpanel/validation's copy.
+
+import { zWidgetOptions, zWidgetType } from '@openpanel/core';
import {
ch,
clix,
@@ -7,7 +16,6 @@ import {
TABLE_NAMES,
} from '@openpanel/db';
import { getCache } from '@openpanel/redis';
-import { zWidgetOptions, zWidgetType } from '@openpanel/validation';
import ShortUniqueId from 'short-unique-id';
import { z } from 'zod';
import { TRPCNotFoundError } from '../errors';
@@ -124,7 +132,7 @@ export const widgetRouter = createTRPCRouter({
},
});
- if (!(widget && widget.public)) {
+ if (!widget?.public) {
throw new TRPCNotFoundError('Widget not found');
}
@@ -147,7 +155,7 @@ export const widgetRouter = createTRPCRouter({
},
});
- if (!(widget && widget.public)) {
+ if (!widget?.public) {
throw new TRPCNotFoundError('Widget not found');
}
@@ -199,7 +207,7 @@ export const widgetRouter = createTRPCRouter({
},
});
- if (!(widget && widget.public)) {
+ if (!widget?.public) {
throw new TRPCNotFoundError('Widget not found');
}
diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.ts
index 32edaed71..a5a440f96 100644
--- a/packages/validation/src/index.ts
+++ b/packages/validation/src/index.ts
@@ -1,325 +1,14 @@
-import {
- chartSegments,
- chartTypes,
- filterValueTypes,
- intervals,
- lineTypes,
- metrics,
- operators,
- timeWindows,
-} from '@openpanel/constants';
+import { zChartEvent } from '@openpanel/core/modules/report/report.constants';
import { z } from 'zod';
-/**
- * Chart formulas are plain arithmetic over series references (A, B, C, ...).
- * The API validates the parsed expression tree as well; this charset guard
- * rejects the obviously hostile shapes (assignment, indexing, object/array
- * literals, statement separators) at the edge, in the browser and on the API.
- */
-const CHART_FORMULA_PATTERN = /^[A-Za-z0-9_ .,+\-*/()%^]*$/;
-
-export function objectToZodEnums<K extends string>(
- obj: Record<K, any>
-): [K, ...K[]] {
- const [firstKey, ...otherKeys] = Object.keys(obj) as K[];
- return [firstKey!, ...otherKeys];
-}
-
-export const mapKeys = objectToZodEnums;
-
-export const zChartEventFilter = z.object({
- id: z.string().optional().describe('Unique identifier for the filter'),
- name: z.string().describe('The property name to filter on'),
- operator: z
- .enum(objectToZodEnums(operators))
- .describe('The operator to use for the filter'),
- value: z
- .array(z.string().or(z.number()).or(z.boolean()).or(z.null()))
- .describe('The values to filter on'),
- type: z
- .enum(objectToZodEnums(filterValueTypes))
- .optional()
- .describe(
- 'Cast type for the column/value in equality & comparison operators ' +
- '(string/number/date/datetime/boolean). Absent = legacy behavior.'
- ),
- cohortId: z
- .string()
- .optional()
- .describe(
- 'DEPRECATED: legacy single-cohort id, kept for saved reports. ' +
- 'New code reads cohortIds via getCohortIds(filter).'
- ),
- cohortIds: z
- .array(z.string())
- .optional()
- .describe(
- 'Cohort IDs for inCohort/notInCohort. Multiple ids OR-match ' +
- '(matches profiles in any of the listed cohorts).'
- ),
-});
-
-/**
- * Normalize the two cohort id fields on a filter into a single array.
- *
- * Both `cohortIds` (new, multi-value) and `cohortId` (legacy, single-value)
- * coexist on `zChartEventFilter` for backward compatibility with saved
- * reports. Always read cohort membership through this helper instead of
- * accessing the raw fields, so legacy data keeps working.
- */
-export function getCohortIds(filter: {
- cohortIds?: string[];
- cohortId?: string;
-}): string[] {
- if (filter.cohortIds && filter.cohortIds.length > 0) {
- return filter.cohortIds;
- }
- if (filter.cohortId) {
- return [filter.cohortId];
- }
- return [];
-}
-
-export const zChartEventSegment = z
- .enum(objectToZodEnums(chartSegments))
- .default('event')
- .describe('Defines how the event data should be segmented or aggregated');
-
-export const zChartEvent = z.object({
- id: z
- .string()
- .optional()
- .describe('Unique identifier for the chart event configuration'),
- name: z.string().describe('The name of the event as tracked in the system'),
- displayName: z
- .string()
- .optional()
- .describe('A user-friendly name for display purposes'),
- property: z
- .string()
- .optional()
- .describe(
- 'Optional property of the event used for specific segment calculations (e.g., value for property_sum/average)'
- ),
- segment: zChartEventSegment,
- filters: z
- .array(zChartEventFilter)
- .default([])
- .describe('Filters applied specifically to this event'),
-});
-
-export const zChartFormula = z.object({
- id: z
- .string()
- .optional()
- .describe('Unique identifier for the formula configuration'),
- type: z.literal('formula'),
- formula: z
- .string()
- .max(1000)
- .regex(
- CHART_FORMULA_PATTERN,
- 'Formula may only contain series references, numbers and arithmetic operators'
- )
- .describe('The formula expression (e.g., A+B, A/B)'),
- displayName: z
- .string()
- .optional()
- .describe('A user-friendly name for display purposes'),
- hideSeries: z
- .array(z.string())
- .optional()
- .describe(
- 'Alpha IDs (e.g. ["A", "B"]) of series referenced by this formula that should be hidden from the chart while still being used in the formula computation'
- ),
-});
-
-// Event with type field for discriminated union
-export const zChartEventWithType = zChartEvent.extend({
- type: z.literal('event'),
-});
-
-export const zChartEventItem = z.discriminatedUnion('type', [
- zChartEventWithType,
- zChartFormula,
-]);
-
-export const zChartBreakdown = z.object({
- id: z.string().optional(),
- name: z.string(),
-});
-
-export const zChartSeries = z
- .array(zChartEventItem)
- .describe(
- 'Array of series (events or formulas) to be tracked and displayed in the chart'
- );
-
-export const zChartBreakdowns = z.array(zChartBreakdown);
-
-export const zChartType = z.enum(objectToZodEnums(chartTypes));
-
-export const zLineType = z.enum(objectToZodEnums(lineTypes));
-
-export const zTimeInterval = z.enum(objectToZodEnums(intervals));
-
-export const zMetric = z.enum(objectToZodEnums(metrics));
-
-export const zRange = z.enum(objectToZodEnums(timeWindows));
-
-export const zCriteria = z.enum(['on_or_after', 'on']);
-
-// Report Options - Discriminated union based on chart type
-export const zFunnelOptions = z.object({
- type: z.literal('funnel'),
- funnelGroup: z.string().optional(),
- funnelWindow: z.number().optional(),
-});
-
-export const zRetentionOptions = z.object({
- type: z.literal('retention'),
- criteria: zCriteria.optional(),
-});
-
-export const zSankeyOptions = z.object({
- type: z.literal('sankey'),
- mode: z.enum(['between', 'after', 'before']),
- steps: z.number().min(2).max(10).default(5),
- exclude: z.array(z.string()).default([]),
- include: z.array(z.string()).optional(),
-});
-
-export const zHistogramOptions = z.object({
- type: z.literal('histogram'),
- stacked: z.boolean().default(false),
-});
-
-export const zReportOptions = z.discriminatedUnion('type', [
- zFunnelOptions,
- zRetentionOptions,
- zSankeyOptions,
- zHistogramOptions,
-]);
-
-export type IReportOptions = z.infer<typeof zReportOptions>;
-export type ISankeyOptions = z.infer<typeof zSankeyOptions>;
-export type IHistogramOptions = z.infer<typeof zHistogramOptions>;
-
-export const zWidgetType = z.enum(['realtime', 'counter']);
-export type IWidgetType = z.infer<typeof zWidgetType>;
-
-export const zRealtimeWidgetOptions = z.object({
- type: z.literal('realtime'),
- referrers: z.boolean().default(true),
- countries: z.boolean().default(true),
- paths: z.boolean().default(false),
-});
-
-export const zCounterWidgetOptions = z.object({
- type: z.literal('counter'),
-});
-
-export const zWidgetOptions = z.discriminatedUnion('type', [
- zRealtimeWidgetOptions,
- zCounterWidgetOptions,
-]);
-
-export type IWidgetOptions = z.infer<typeof zWidgetOptions>;
-export type ICounterWidgetOptions = z.infer<typeof zCounterWidgetOptions>;
-export type IRealtimeWidgetOptions = z.infer<typeof zRealtimeWidgetOptions>;
-
-// Base input schema - for API calls, engine, chart queries
-export const zReportInput = z.object({
- projectId: z.string().describe('The ID of the project this chart belongs to'),
- chartType: zChartType
- .default('linear')
- .describe('What type of chart should be displayed'),
- interval: zTimeInterval
- .default('day')
- .describe(
- 'The time interval for data aggregation (e.g., day, week, month)'
- ),
- series: zChartSeries.describe(
- 'Array of series (events or formulas) to be tracked and displayed in the chart'
- ),
- breakdowns: zChartBreakdowns
- .default([])
- .describe('Array of dimensions to break down the data by'),
- globalFilters: z
- .array(zChartEventFilter)
- .optional()
- .describe(
- 'Filters applied to ALL event series in this report (combined with each series own filters using AND)'
- ),
- range: zRange
- .default('30d')
- .describe('The time range for which data should be displayed'),
- startDate: z
- .string()
- .nullish()
- .describe(
- 'Custom start date for the data range (overrides range if provided)'
- ),
- endDate: z
- .string()
- .nullish()
- .describe(
- 'Custom end date for the data range (overrides range if provided)'
- ),
- previous: z
- .boolean()
- .default(false)
- .describe('Whether to show data from the previous period for comparison'),
- formula: z
- .string()
- .optional()
- .describe('Custom formula for calculating derived metrics'),
- metric: zMetric
- .default('sum')
- .describe(
- 'The aggregation method for the metric (e.g., sum, count, average)'
- ),
- limit: z
- .number()
- .optional()
- .describe('Limit how many series should be returned'),
- offset: z
- .number()
- .optional()
- .describe('Skip how many series should be returned'),
- visibleSeries: z
- .array(z.string())
- .nullish()
- .describe('IDs of series that should be visible on the chart'),
- options: zReportOptions
- .optional()
- .describe('Chart-specific options (funnel, retention, sankey)'),
- // Optional display fields
- name: z.string().optional().describe('The user-defined name for the report'),
- lineType: zLineType
- .optional()
- .describe('The visual style of the line in the chart'),
- unit: z
- .string()
- .optional()
- .describe(
- "Optional unit of measurement for the chart's Y-axis (e.g., $, %, users)"
- ),
-});
-
-// Complete report schema - for saved reports
-export const zReport = zReportInput.extend({
- name: z
- .string()
- .default('Untitled')
- .describe('The user-defined name for the report'),
- lineType: zLineType
- .default('monotone')
- .describe('The visual style of the line in the chart'),
-});
-
-// Alias for backward compatibility
-export const zChartInput = zReportInput;
+// Moved into @openpanel/core's report module (M7-006, ADR-008's module map:
+// report owns "C" for the chart/report/widget vocabulary). Re-exported here
+// for existing @openpanel/validation importers (packages/trpc's chart/
+// report/dashboard/widget routers, apps/start's report builder) — same
+// shape as ./cohort.validation.ts's re-export since M5-003. `zChartEvent` is
+// imported by name too (not just re-exported): `zProjectFilterEvent` below
+// extends it as a bound identifier, which `export *` alone does not provide.
+export * from '@openpanel/core/modules/report/report.constants';
/**
* A per-project grant. `read` means exactly that: the member can look at the
@@ -374,9 +63,10 @@ export * from '@openpanel/core/modules/integration/integration.constants';
// @openpanel/validation importers (packages/trpc's notification router,
// apps/start's notification rule form) — same shape as
// ./onboarding.constants.ts re-export since M6-003. `zChartEvent` (used
-// above, and by notification.constants.ts itself) is defined earlier in this
-// file, so the resulting module cycle resolves at the value level: see
-// notification.constants.ts's header.
+// above, and by notification.constants.ts itself) is imported earlier in
+// this file from core's report.constants.ts (M7-006), so the resulting
+// module cycle resolves at the value level: see notification.constants.ts's
+// header.
export * from '@openpanel/core/modules/notification/notification.constants';
// Moved into @openpanel/core's onboarding module (M6-003, ADR-008's module
// map: onboarding owns "C"). Re-exported here for existing
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index db7e295eb..3bc85e5b2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1184,6 +1184,9 @@ importers:
pino-pretty:
specifier: 'catalog:'
version: 13.1.3
+ prisma-error-enum:
+ specifier: ^0.1.3
+ version: 0.1.3
prom-client:
specifier: ^15.1.3
version: 15.1.3