flask-deck 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flask_deck/__init__.py +184 -0
- flask_deck/adapters/__init__.py +23 -0
- flask_deck/adapters/sqlalchemy.py +272 -0
- flask_deck/audit.py +363 -0
- flask_deck/auth.py +462 -0
- flask_deck/branding.py +217 -0
- flask_deck/charts.py +514 -0
- flask_deck/cli.py +135 -0
- flask_deck/config.py +81 -0
- flask_deck/dashboard.py +416 -0
- flask_deck/deck.py +4153 -0
- flask_deck/demo.py +1066 -0
- flask_deck/events.py +309 -0
- flask_deck/exceptions.py +34 -0
- flask_deck/exporter.py +240 -0
- flask_deck/formatters.py +386 -0
- flask_deck/i18n.py +399 -0
- flask_deck/icons.py +92 -0
- flask_deck/importer.py +612 -0
- flask_deck/introspection.py +376 -0
- flask_deck/jobs.py +382 -0
- flask_deck/mfa.py +670 -0
- flask_deck/model_view.py +1097 -0
- flask_deck/py.typed +0 -0
- flask_deck/query.py +1220 -0
- flask_deck/schema_graph.py +137 -0
- flask_deck/security.py +373 -0
- flask_deck/sql_console.py +391 -0
- flask_deck/sso.py +293 -0
- flask_deck/static/css/deck.css +1333 -0
- flask_deck/static/js/deck.js +1433 -0
- flask_deck/storage.py +669 -0
- flask_deck/templates/flask_deck/audit_list.html +117 -0
- flask_deck/templates/flask_deck/base.html +454 -0
- flask_deck/templates/flask_deck/custom_page.html +12 -0
- flask_deck/templates/flask_deck/dashboard.html +32 -0
- flask_deck/templates/flask_deck/diagnostics.html +80 -0
- flask_deck/templates/flask_deck/error.html +15 -0
- flask_deck/templates/flask_deck/import_wizard.html +143 -0
- flask_deck/templates/flask_deck/jobs_list.html +95 -0
- flask_deck/templates/flask_deck/login.html +93 -0
- flask_deck/templates/flask_deck/login_mfa.html +59 -0
- flask_deck/templates/flask_deck/mfa_setup.html +121 -0
- flask_deck/templates/flask_deck/model_detail.html +124 -0
- flask_deck/templates/flask_deck/model_form.html +389 -0
- flask_deck/templates/flask_deck/model_list.html +489 -0
- flask_deck/templates/flask_deck/partials/drawer_detail.html +93 -0
- flask_deck/templates/flask_deck/partials/widget_grid.html +207 -0
- flask_deck/templates/flask_deck/rbac_matrix.html +59 -0
- flask_deck/templates/flask_deck/record_history.html +102 -0
- flask_deck/templates/flask_deck/schema_inspector.html +83 -0
- flask_deck/templates/flask_deck/sql_console.html +87 -0
- flask_deck-0.3.0.dist-info/METADATA +382 -0
- flask_deck-0.3.0.dist-info/RECORD +57 -0
- flask_deck-0.3.0.dist-info/WHEEL +4 -0
- flask_deck-0.3.0.dist-info/entry_points.txt +5 -0
- flask_deck-0.3.0.dist-info/licenses/LICENSE +21 -0
flask_deck/config.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from flask_deck.branding import BrandConfig
|
|
9
|
+
from flask_deck.security import is_valid_csp_img_source
|
|
10
|
+
|
|
11
|
+
EnvironmentName = Literal["development", "staging", "production"]
|
|
12
|
+
ThemeName = Literal["dark", "light", "system"]
|
|
13
|
+
PaginationMode = Literal["offset", "cursor"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class DeckConfig:
|
|
18
|
+
"""Immutable runtime configuration for a Deck instance."""
|
|
19
|
+
|
|
20
|
+
title: str = "Flask-Deck"
|
|
21
|
+
subtitle: str = "Operations Workbench"
|
|
22
|
+
url_prefix: str = "/admin"
|
|
23
|
+
name: str = "deck"
|
|
24
|
+
environment: EnvironmentName = "development"
|
|
25
|
+
default_theme: ThemeName = "dark"
|
|
26
|
+
read_only: bool = False
|
|
27
|
+
allow_insecure_open: bool = False
|
|
28
|
+
page_size: int = 25
|
|
29
|
+
max_page_size: int = 200
|
|
30
|
+
default_pagination_mode: PaginationMode = "offset"
|
|
31
|
+
max_upload_bytes: int = 5 * 1024 * 1024 # 5 MiB
|
|
32
|
+
max_import_rows: int = 5000
|
|
33
|
+
max_import_columns: int = 100
|
|
34
|
+
max_json_depth: int = 12
|
|
35
|
+
import_preview_ttl_seconds: int = 900 # 15 minutes
|
|
36
|
+
import_preview_max_entries: int = 64
|
|
37
|
+
sanitize_csv: bool = True
|
|
38
|
+
auto_audit: bool = True
|
|
39
|
+
enable_audit_revert: bool = True
|
|
40
|
+
enable_sql_telemetry: bool = True
|
|
41
|
+
session_idle_timeout_seconds: int = 1800 # 30 minutes
|
|
42
|
+
session_absolute_timeout_seconds: int = 43200 # 12 hours
|
|
43
|
+
login_rate_limit_attempts: int = 5
|
|
44
|
+
login_rate_limit_window_seconds: int = 300
|
|
45
|
+
login_rate_limit_lockout_seconds: int = 300
|
|
46
|
+
require_confirm_text_in_prod: bool = True
|
|
47
|
+
search_min_chars: int = 2
|
|
48
|
+
search_limit_per_model: int = 5
|
|
49
|
+
enable_sql_console: bool = False
|
|
50
|
+
sql_console_max_rows: int = 200
|
|
51
|
+
demo_role_switcher: bool = False
|
|
52
|
+
# v0.3.0 Enterprise capabilities
|
|
53
|
+
brand: BrandConfig = field(default_factory=BrandConfig)
|
|
54
|
+
default_locale: str = "en"
|
|
55
|
+
available_locales: tuple[str, ...] = ("en", "tr", "de", "ar")
|
|
56
|
+
default_timezone: str = "UTC"
|
|
57
|
+
enable_user_preferences: bool = True
|
|
58
|
+
locale_selector: Callable[[], str] | None = None
|
|
59
|
+
timezone_selector: Callable[[], str] | None = None
|
|
60
|
+
require_mfa_for_superusers: bool = False
|
|
61
|
+
enable_impersonation: bool = True
|
|
62
|
+
impersonate_read_only: bool = True
|
|
63
|
+
enable_jobs: bool = True
|
|
64
|
+
csp_img_sources: tuple[str, ...] = ()
|
|
65
|
+
csp_nonce_getter: Callable[[], str] | None = None
|
|
66
|
+
extra_sensitive_patterns: tuple[re.Pattern[str], ...] = field(default_factory=tuple)
|
|
67
|
+
|
|
68
|
+
def __post_init__(self) -> None:
|
|
69
|
+
if self.page_size < 1 or self.page_size > self.max_page_size:
|
|
70
|
+
raise ValueError("page_size must be between 1 and max_page_size")
|
|
71
|
+
if self.max_page_size < 1 or self.max_page_size > 1000:
|
|
72
|
+
raise ValueError("max_page_size must be between 1 and 1000")
|
|
73
|
+
if self.max_upload_bytes < 1024:
|
|
74
|
+
raise ValueError("max_upload_bytes must be at least 1024 bytes")
|
|
75
|
+
if self.max_import_rows < 1:
|
|
76
|
+
raise ValueError("max_import_rows must be positive")
|
|
77
|
+
if not self.url_prefix.startswith("/"):
|
|
78
|
+
raise ValueError("url_prefix must start with '/'")
|
|
79
|
+
for src in self.csp_img_sources:
|
|
80
|
+
if not is_valid_csp_img_source(src):
|
|
81
|
+
raise ValueError(f"Unsafe csp_img_sources token: {src!r}")
|
flask_deck/dashboard.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Sequence
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from datetime import datetime, timedelta, timezone
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
7
|
+
|
|
8
|
+
import sqlalchemy as sa
|
|
9
|
+
from markupsafe import Markup
|
|
10
|
+
from sqlalchemy.orm import Session
|
|
11
|
+
|
|
12
|
+
from flask_deck.audit import AuditEntry
|
|
13
|
+
from flask_deck.auth import DeckUser
|
|
14
|
+
from flask_deck.charts import (
|
|
15
|
+
render_area_chart,
|
|
16
|
+
render_bar_chart,
|
|
17
|
+
render_donut_chart,
|
|
18
|
+
render_gauge_chart,
|
|
19
|
+
render_grouped_bar_chart,
|
|
20
|
+
render_heatmap_chart,
|
|
21
|
+
render_sparkline,
|
|
22
|
+
render_stat_bars,
|
|
23
|
+
)
|
|
24
|
+
from flask_deck.formatters import normalize_tone
|
|
25
|
+
from flask_deck.query import soft_delete_predicate
|
|
26
|
+
from flask_deck.security import is_safe_display_url
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from flask_deck.deck import Deck
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class Widget:
|
|
34
|
+
"""Base dashboard widget."""
|
|
35
|
+
|
|
36
|
+
title: str
|
|
37
|
+
col_span: int = 12
|
|
38
|
+
subtitle: str = ""
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def span_class(self) -> str:
|
|
42
|
+
allowed = {3, 4, 6, 8, 9, 12}
|
|
43
|
+
span = self.col_span if self.col_span in allowed else 12
|
|
44
|
+
return f"dk-span-{span}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class KPIWidget(Widget):
|
|
49
|
+
"""Single operational metric tile with tabular numerals and optional sparkline."""
|
|
50
|
+
|
|
51
|
+
value: str = "0"
|
|
52
|
+
delta: str = ""
|
|
53
|
+
trend: Literal["up", "down", "flat"] = "flat"
|
|
54
|
+
icon: str = "activity"
|
|
55
|
+
href: str | None = None
|
|
56
|
+
sparkline: Sequence[float] = field(default_factory=tuple)
|
|
57
|
+
col_span: int = 3
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def kind(self) -> str:
|
|
61
|
+
return "kpi"
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def safe_href(self) -> str | None:
|
|
65
|
+
return self.href if is_safe_display_url(self.href) else None
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def sparkline_svg(self) -> Markup:
|
|
69
|
+
tone = "ok" if self.trend == "up" else ("danger" if self.trend == "down" else "primary")
|
|
70
|
+
return render_sparkline(self.sparkline, tone=tone)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True, slots=True)
|
|
74
|
+
class ChartWidget(Widget):
|
|
75
|
+
"""Pure SVG chart widget (area, bar, grouped_bar, or donut)."""
|
|
76
|
+
|
|
77
|
+
chart_type: Literal["area", "bar", "grouped_bar", "donut"] = "area"
|
|
78
|
+
labels: Sequence[str] = field(default_factory=tuple)
|
|
79
|
+
series: Sequence[dict[str, Any]] = field(default_factory=tuple)
|
|
80
|
+
center_label: str = "Total"
|
|
81
|
+
col_span: int = 8
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def kind(self) -> str:
|
|
85
|
+
return "chart"
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def chart_svg(self) -> Markup:
|
|
89
|
+
if self.chart_type == "bar":
|
|
90
|
+
return render_bar_chart(self.labels, self.series)
|
|
91
|
+
if self.chart_type == "grouped_bar":
|
|
92
|
+
return render_grouped_bar_chart(self.labels, self.series)
|
|
93
|
+
if self.chart_type == "donut":
|
|
94
|
+
return render_donut_chart(self.labels, self.series, center_label=self.center_label)
|
|
95
|
+
return render_area_chart(self.labels, self.series)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True, slots=True)
|
|
99
|
+
class HeatmapWidget(Widget):
|
|
100
|
+
"""91-day GitHub-style pure SVG activity heatmap."""
|
|
101
|
+
|
|
102
|
+
cells: Sequence[tuple[str, int]] = field(default_factory=tuple)
|
|
103
|
+
unit: str = "events"
|
|
104
|
+
col_span: int = 8
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def kind(self) -> str:
|
|
108
|
+
return "heatmap"
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def heatmap_svg(self) -> Markup:
|
|
112
|
+
return render_heatmap_chart(self.cells, unit=self.unit)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True, slots=True)
|
|
116
|
+
class StatBarWidget(Widget):
|
|
117
|
+
"""Horizontal utilization / quota progress bars widget."""
|
|
118
|
+
|
|
119
|
+
items: Sequence[dict[str, Any]] = field(default_factory=tuple)
|
|
120
|
+
col_span: int = 4
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def kind(self) -> str:
|
|
124
|
+
return "statbars"
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def bars_svg(self) -> Markup:
|
|
128
|
+
return render_stat_bars(self.items)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass(frozen=True, slots=True)
|
|
132
|
+
class GaugeWidget(Widget):
|
|
133
|
+
"""Precision semi-circular SVG gauge dial with key metrics."""
|
|
134
|
+
|
|
135
|
+
value: float = 0.0
|
|
136
|
+
max_value: float = 100.0
|
|
137
|
+
gauge_label: str = "Score"
|
|
138
|
+
suffix: str = "%"
|
|
139
|
+
tone: str = "ok"
|
|
140
|
+
details: Sequence[tuple[str, str]] = field(default_factory=tuple)
|
|
141
|
+
col_span: int = 4
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def kind(self) -> str:
|
|
145
|
+
return "gauge"
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def gauge_svg(self) -> Markup:
|
|
149
|
+
return render_gauge_chart(
|
|
150
|
+
self.value,
|
|
151
|
+
max_value=self.max_value,
|
|
152
|
+
label=self.gauge_label,
|
|
153
|
+
suffix=self.suffix,
|
|
154
|
+
tone=self.tone,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@dataclass(frozen=True, slots=True)
|
|
159
|
+
class TimelineWidget(Widget):
|
|
160
|
+
"""Structured operational event timeline with semantic status rail."""
|
|
161
|
+
|
|
162
|
+
events: Sequence[dict[str, Any]] = field(default_factory=tuple)
|
|
163
|
+
col_span: int = 6
|
|
164
|
+
|
|
165
|
+
@property
|
|
166
|
+
def kind(self) -> str:
|
|
167
|
+
return "timeline"
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def safe_events(self) -> tuple[dict[str, Any], ...]:
|
|
171
|
+
out: list[dict[str, Any]] = []
|
|
172
|
+
for ev in self.events:
|
|
173
|
+
href = ev.get("href")
|
|
174
|
+
safe_href = href if (isinstance(href, str) and is_safe_display_url(href)) else None
|
|
175
|
+
if safe_href != href:
|
|
176
|
+
cleaned = dict(ev)
|
|
177
|
+
cleaned["href"] = safe_href
|
|
178
|
+
out.append(cleaned)
|
|
179
|
+
else:
|
|
180
|
+
out.append(ev)
|
|
181
|
+
return tuple(out)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@dataclass(frozen=True, slots=True)
|
|
185
|
+
class CalloutWidget(Widget):
|
|
186
|
+
"""High-signal operational alert banner with optional direct CTA."""
|
|
187
|
+
|
|
188
|
+
message: str = ""
|
|
189
|
+
tone: str = "warn"
|
|
190
|
+
action_label: str = ""
|
|
191
|
+
action_href: str | None = None
|
|
192
|
+
col_span: int = 12
|
|
193
|
+
|
|
194
|
+
@property
|
|
195
|
+
def kind(self) -> str:
|
|
196
|
+
return "callout"
|
|
197
|
+
|
|
198
|
+
@property
|
|
199
|
+
def safe_action_href(self) -> str | None:
|
|
200
|
+
return self.action_href if is_safe_display_url(self.action_href) else None
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def normalized_tone(self) -> str:
|
|
204
|
+
return normalize_tone(self.tone)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@dataclass(frozen=True, slots=True)
|
|
208
|
+
class TableWidget(Widget):
|
|
209
|
+
"""Compact summary table widget for recent/critical records."""
|
|
210
|
+
|
|
211
|
+
headers: Sequence[str] = field(default_factory=tuple)
|
|
212
|
+
rows: Sequence[Sequence[Any]] = field(default_factory=tuple)
|
|
213
|
+
href: str | None = None
|
|
214
|
+
href_label: str = "View all"
|
|
215
|
+
col_span: int = 6
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def kind(self) -> str:
|
|
219
|
+
return "table"
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def safe_href(self) -> str | None:
|
|
223
|
+
return self.href if is_safe_display_url(self.href) else None
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
@dataclass(frozen=True, slots=True)
|
|
227
|
+
class ActivityWidget(Widget):
|
|
228
|
+
"""Recent Audit Log activity feed widget."""
|
|
229
|
+
|
|
230
|
+
limit: int = 8
|
|
231
|
+
entries: Sequence[AuditEntry] = field(default_factory=tuple)
|
|
232
|
+
col_span: int = 6
|
|
233
|
+
|
|
234
|
+
@property
|
|
235
|
+
def kind(self) -> str:
|
|
236
|
+
return "activity"
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@dataclass(frozen=True, slots=True)
|
|
240
|
+
class MarkdownWidget(Widget):
|
|
241
|
+
"""Plain operational notes / runbook checklist block."""
|
|
242
|
+
|
|
243
|
+
lines: Sequence[str] = field(default_factory=tuple)
|
|
244
|
+
col_span: int = 6
|
|
245
|
+
|
|
246
|
+
@property
|
|
247
|
+
def kind(self) -> str:
|
|
248
|
+
return "notes"
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class DashboardContext:
|
|
252
|
+
"""Context passed to custom ``@deck.dashboard`` callbacks."""
|
|
253
|
+
|
|
254
|
+
__slots__ = ("_deck", "range_days", "session", "user")
|
|
255
|
+
|
|
256
|
+
def __init__(
|
|
257
|
+
self,
|
|
258
|
+
deck: Deck,
|
|
259
|
+
session: Session,
|
|
260
|
+
user: DeckUser | None,
|
|
261
|
+
*,
|
|
262
|
+
range_days: int = 14,
|
|
263
|
+
) -> None:
|
|
264
|
+
self._deck = deck
|
|
265
|
+
self.session = session
|
|
266
|
+
self.user = user
|
|
267
|
+
self.range_days = range_days if range_days in {7, 14, 30, 90} else 14
|
|
268
|
+
|
|
269
|
+
def url_for_model(self, model_or_slug: type[Any] | str) -> str | None:
|
|
270
|
+
return self._deck.url_for_model(model_or_slug)
|
|
271
|
+
|
|
272
|
+
def recent_audit_entries(self, limit: int = 8) -> list[AuditEntry]:
|
|
273
|
+
if self._deck.audit_store is None:
|
|
274
|
+
return []
|
|
275
|
+
if not self._deck.auth.has_permission(self.user, "audit:view"):
|
|
276
|
+
return []
|
|
277
|
+
entries, _ = self._deck.audit_store.list_entries(limit=limit)
|
|
278
|
+
return entries
|
|
279
|
+
|
|
280
|
+
def last_n_days(self, n: int = 14) -> list[str]:
|
|
281
|
+
today = datetime.now(timezone.utc).date()
|
|
282
|
+
return [(today - timedelta(days=n - 1 - i)).strftime("%b %d") for i in range(n)]
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
DashboardBuilder = Callable[[DashboardContext], Sequence[Widget]]
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def build_default_dashboard(deck: Deck, ctx: DashboardContext) -> list[Widget]:
|
|
289
|
+
"""Generate an automatic operational dashboard from registered models and audit store."""
|
|
290
|
+
widgets: list[Widget] = []
|
|
291
|
+
views = [
|
|
292
|
+
v
|
|
293
|
+
for v in deck.views.values()
|
|
294
|
+
if v.can_view
|
|
295
|
+
and deck.auth.has_permission(ctx.user, f"{v.meta.slug}:view", model_slug=v.meta.slug)
|
|
296
|
+
]
|
|
297
|
+
|
|
298
|
+
model_counts: list[tuple[str, int]] = []
|
|
299
|
+
trend_labels = ctx.last_n_days(14)
|
|
300
|
+
trend_series: list[dict[str, Any]] = []
|
|
301
|
+
today = datetime.now(timezone.utc).date()
|
|
302
|
+
window_start = datetime(
|
|
303
|
+
(today - timedelta(days=13)).year,
|
|
304
|
+
(today - timedelta(days=13)).month,
|
|
305
|
+
(today - timedelta(days=13)).day,
|
|
306
|
+
tzinfo=timezone.utc,
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
for view in views[:4]:
|
|
310
|
+
view_sess = deck.get_session(view.bind_key)
|
|
311
|
+
base = view.scope_query(sa.select(view.model), ctx.user)
|
|
312
|
+
sd_pred = soft_delete_predicate(view.meta, view.soft_delete_column, trashed=False)
|
|
313
|
+
if sd_pred is not None:
|
|
314
|
+
base = base.where(sd_pred)
|
|
315
|
+
count_stmt = sa.select(sa.func.count()).select_from(base.subquery())
|
|
316
|
+
total = int(view_sess.execute(count_stmt).scalar_one() or 0)
|
|
317
|
+
model_counts.append((view.plural_label, total))
|
|
318
|
+
|
|
319
|
+
# Check if model has a creation timestamp to build real 7d/14d series.
|
|
320
|
+
ts_field = next(
|
|
321
|
+
(
|
|
322
|
+
f
|
|
323
|
+
for f in view.meta.fields
|
|
324
|
+
if f.field_type == "datetime"
|
|
325
|
+
and f.name in {"created_at", "created", "inserted_at", "timestamp", "updated_at"}
|
|
326
|
+
),
|
|
327
|
+
None,
|
|
328
|
+
)
|
|
329
|
+
spark: list[float] = []
|
|
330
|
+
delta = ""
|
|
331
|
+
trend: Literal["up", "down", "flat"] = "flat"
|
|
332
|
+
if ts_field is not None:
|
|
333
|
+
ts_col = getattr(view.model, ts_field.name)
|
|
334
|
+
ts_stmt = (
|
|
335
|
+
sa.select(ts_col)
|
|
336
|
+
.where(ts_col >= window_start)
|
|
337
|
+
.where(*base._where_criteria)
|
|
338
|
+
)
|
|
339
|
+
dates = list(view_sess.scalars(ts_stmt).all())
|
|
340
|
+
buckets = [0] * 14
|
|
341
|
+
for dt in dates:
|
|
342
|
+
if isinstance(dt, datetime):
|
|
343
|
+
dt_utc = dt.astimezone(timezone.utc) if dt.tzinfo is not None else dt
|
|
344
|
+
d = dt_utc.date()
|
|
345
|
+
diff_days = (d - (today - timedelta(days=13))).days
|
|
346
|
+
if 0 <= diff_days < 14:
|
|
347
|
+
buckets[diff_days] += 1
|
|
348
|
+
spark = [float(b) for b in buckets[-7:]]
|
|
349
|
+
prev_7 = sum(buckets[:7])
|
|
350
|
+
curr_7 = sum(buckets[7:])
|
|
351
|
+
if prev_7 > 0:
|
|
352
|
+
pct = ((curr_7 - prev_7) / prev_7) * 100.0
|
|
353
|
+
delta = f"{pct:+.1f}% 7d"
|
|
354
|
+
trend = "up" if pct > 0 else ("down" if pct < 0 else "flat")
|
|
355
|
+
elif curr_7 > 0:
|
|
356
|
+
delta = f"+{curr_7} new (7d)"
|
|
357
|
+
trend = "up"
|
|
358
|
+
if len(trend_series) < 2:
|
|
359
|
+
trend_series.append(
|
|
360
|
+
{
|
|
361
|
+
"name": view.plural_label,
|
|
362
|
+
"data": [float(b) for b in buckets],
|
|
363
|
+
"tone": "primary" if not trend_series else "ok",
|
|
364
|
+
}
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
widgets.append(
|
|
368
|
+
KPIWidget(
|
|
369
|
+
title=view.plural_label,
|
|
370
|
+
value=f"{total:,}",
|
|
371
|
+
delta=delta or "total rows",
|
|
372
|
+
trend=trend,
|
|
373
|
+
icon=view.icon,
|
|
374
|
+
href=ctx.url_for_model(view.meta.slug),
|
|
375
|
+
sparkline=spark,
|
|
376
|
+
col_span=3,
|
|
377
|
+
)
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
if trend_series:
|
|
381
|
+
widgets.append(
|
|
382
|
+
ChartWidget(
|
|
383
|
+
title="14-Day Record Activity",
|
|
384
|
+
subtitle="New records indexed per day across primary tables",
|
|
385
|
+
chart_type="area",
|
|
386
|
+
labels=trend_labels,
|
|
387
|
+
series=trend_series,
|
|
388
|
+
col_span=8,
|
|
389
|
+
)
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
if model_counts:
|
|
393
|
+
widgets.append(
|
|
394
|
+
ChartWidget(
|
|
395
|
+
title="Schema Distribution",
|
|
396
|
+
subtitle="Row share across registered models",
|
|
397
|
+
chart_type="donut",
|
|
398
|
+
labels=[name for name, _ in model_counts],
|
|
399
|
+
series=[{"data": [count for _, count in model_counts]}],
|
|
400
|
+
center_label="Rows",
|
|
401
|
+
col_span=4 if trend_series else 6,
|
|
402
|
+
)
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
if deck.auth.has_permission(ctx.user, "audit:view"):
|
|
406
|
+
entries = ctx.recent_audit_entries(limit=8)
|
|
407
|
+
widgets.append(
|
|
408
|
+
ActivityWidget(
|
|
409
|
+
title="Recent Audit Trail",
|
|
410
|
+
subtitle="Latest mutations captured by Flask-Deck",
|
|
411
|
+
entries=entries,
|
|
412
|
+
limit=8,
|
|
413
|
+
col_span=12 if trend_series else 6,
|
|
414
|
+
)
|
|
415
|
+
)
|
|
416
|
+
return widgets
|