Spaces:
Paused

File size: 7,021 Bytes
5b7f283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
5b7f283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
5b7f283
 
 
 
 
 
 
 
 
 
091ca1d
5b7f283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
 
5b7f283
 
 
 
 
 
 
 
 
 
 
091ca1d
5b7f283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""
Analytics Tool - Domain Models
==================================

Domain-agnostic analytics, metrics, and KPI tracking engine.
Supports real-time dashboards, cohort analysis, funnel tracking,
trend detection, and predictive analytics.

Entities:
    AnalyticsDefinition - Reusable metric/KPI blueprint
    MetricSnapshot      - Point-in-time metric capture
    Dashboard           - Configurable widget layout
    AnalyticsEvent      - Hash-chained audit trail

Enums:
    MetricType, AggregationMethod, TimeGranularity,
    WidgetType, AnalyticsEventType
"""

from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Dict, List, Optional
from uuid import UUID, uuid4

from pydantic import BaseModel, Field


# ============================================================================
# ENUMS
# ============================================================================

class MetricType(str, Enum):
    COUNTER = "counter"
    GAUGE = "gauge"
    HISTOGRAM = "histogram"
    RATE = "rate"
    RATIO = "ratio"
    PERCENTILE = "percentile"
    TREND = "trend"
    COMPOSITE = "composite"


class AggregationMethod(str, Enum):
    SUM = "sum"
    AVG = "avg"
    MIN = "min"
    MAX = "max"
    COUNT = "count"
    MEDIAN = "median"
    P95 = "p95"
    P99 = "p99"
    LAST = "last"
    RATE_PER_MINUTE = "rate_per_minute"


class TimeGranularity(str, Enum):
    MINUTE = "minute"
    HOUR = "hour"
    DAY = "day"
    WEEK = "week"
    MONTH = "month"
    QUARTER = "quarter"
    YEAR = "year"


class WidgetType(str, Enum):
    LINE_CHART = "line_chart"
    BAR_CHART = "bar_chart"
    PIE_CHART = "pie_chart"
    GAUGE = "gauge"
    STAT_CARD = "stat_card"
    TABLE = "table"
    HEATMAP = "heatmap"
    FUNNEL = "funnel"
    SCATTER = "scatter"
    SPARKLINE = "sparkline"


class DashboardStatus(str, Enum):
    DRAFT = "draft"
    ACTIVE = "active"
    ARCHIVED = "archived"


class AnalyticsEventType(str, Enum):
    DEFINITION_CREATED = "analytics.definition_created"
    METRIC_RECORDED = "analytics.metric_recorded"
    DASHBOARD_CREATED = "analytics.dashboard_created"
    DASHBOARD_UPDATED = "analytics.dashboard_updated"
    THRESHOLD_BREACHED = "analytics.threshold_breached"
    TREND_DETECTED = "analytics.trend_detected"
    COHORT_COMPUTED = "analytics.cohort_computed"
    EXPORT_GENERATED = "analytics.export_generated"


# ============================================================================
# DOMAIN ENTITIES
# ============================================================================

@dataclass
class AnalyticsDefinition:
    """Reusable metric/KPI definition blueprint."""
    id: UUID = field(default_factory=uuid4)
    tenant_id: UUID = field(default_factory=uuid4)
    key: str = ""
    title: str = ""
    description: str = ""
    version: str = "1.0.0"
    domain: str = ""
    metric_type: MetricType = MetricType.GAUGE
    aggregation: AggregationMethod = AggregationMethod.AVG
    unit: str = ""
    data_source: str = ""
    query_template: str = ""
    thresholds: Dict[str, Any] = field(default_factory=dict)
    granularity: TimeGranularity = TimeGranularity.DAY
    retention_days: int = 365
    is_active: bool = True
    is_system: bool = False
    metadata: Dict[str, Any] = field(default_factory=dict)
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))


@dataclass
class MetricSnapshot:
    """Point-in-time metric value capture."""
    id: UUID = field(default_factory=uuid4)
    tenant_id: UUID = field(default_factory=uuid4)
    definition_id: UUID = field(default_factory=uuid4)
    value: float = 0.0
    dimensions: Dict[str, str] = field(default_factory=dict)
    timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    granularity: TimeGranularity = TimeGranularity.DAY
    metadata: Dict[str, Any] = field(default_factory=dict)


@dataclass
class DashboardWidget:
    """Single widget within a dashboard."""
    widget_id: str = ""
    title: str = ""
    widget_type: WidgetType = WidgetType.LINE_CHART
    definition_keys: List[str] = field(default_factory=list)
    position: Dict[str, int] = field(default_factory=lambda: {"x": 0, "y": 0, "w": 6, "h": 4})
    config: Dict[str, Any] = field(default_factory=dict)


@dataclass
class Dashboard:
    """Configurable analytics dashboard with widget grid layout."""
    id: UUID = field(default_factory=uuid4)
    tenant_id: UUID = field(default_factory=uuid4)
    key: str = ""
    title: str = ""
    description: str = ""
    domain: str = ""
    widgets: List[DashboardWidget] = field(default_factory=list)
    refresh_interval_seconds: int = 60
    status: DashboardStatus = DashboardStatus.ACTIVE
    is_system: bool = False
    created_by: UUID = field(default_factory=uuid4)
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))


@dataclass
class AnalyticsEvent:
    """Hash-chained analytics event for audit trail."""
    id: UUID = field(default_factory=uuid4)
    tenant_id: UUID = field(default_factory=uuid4)
    event_type: AnalyticsEventType = AnalyticsEventType.METRIC_RECORDED
    data: Dict[str, Any] = field(default_factory=dict)
    prev_hash: str = ""
    hash: str = ""
    timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))


# ============================================================================
# PYDANTIC SCHEMAS
# ============================================================================

class MetricRecordRequest(BaseModel):
    definition_key: str = Field(..., min_length=1)
    value: float
    dimensions: Dict[str, str] = Field(default_factory=dict)
    timestamp: Optional[datetime] = None
    tenant_id: Optional[UUID] = None
    user_id: Optional[UUID] = None


class DashboardCreateRequest(BaseModel):
    key: str = Field(..., min_length=1)
    title: str = Field(..., min_length=1)
    description: str = ""
    domain: str = ""
    widgets: List[Dict[str, Any]] = Field(default_factory=list)
    refresh_interval_seconds: int = 60
    tenant_id: Optional[UUID] = None
    user_id: Optional[UUID] = None


class AnalyticsDefinitionResponse(BaseModel):
    id: UUID
    key: str
    title: str
    description: str
    version: str
    domain: str
    metric_type: str
    aggregation: str
    unit: str
    data_source: str
    thresholds: Dict[str, Any]
    granularity: str
    is_active: bool
    is_system: bool


class MetricSnapshotResponse(BaseModel):
    id: UUID
    definition_id: UUID
    value: float
    dimensions: Dict[str, str]
    timestamp: datetime
    granularity: str


class DashboardResponse(BaseModel):
    id: UUID
    key: str
    title: str
    description: str
    domain: str
    widgets: List[Dict[str, Any]]
    refresh_interval_seconds: int
    status: str
    is_system: bool
    created_at: datetime