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.
Files changed (57) hide show
  1. flask_deck/__init__.py +184 -0
  2. flask_deck/adapters/__init__.py +23 -0
  3. flask_deck/adapters/sqlalchemy.py +272 -0
  4. flask_deck/audit.py +363 -0
  5. flask_deck/auth.py +462 -0
  6. flask_deck/branding.py +217 -0
  7. flask_deck/charts.py +514 -0
  8. flask_deck/cli.py +135 -0
  9. flask_deck/config.py +81 -0
  10. flask_deck/dashboard.py +416 -0
  11. flask_deck/deck.py +4153 -0
  12. flask_deck/demo.py +1066 -0
  13. flask_deck/events.py +309 -0
  14. flask_deck/exceptions.py +34 -0
  15. flask_deck/exporter.py +240 -0
  16. flask_deck/formatters.py +386 -0
  17. flask_deck/i18n.py +399 -0
  18. flask_deck/icons.py +92 -0
  19. flask_deck/importer.py +612 -0
  20. flask_deck/introspection.py +376 -0
  21. flask_deck/jobs.py +382 -0
  22. flask_deck/mfa.py +670 -0
  23. flask_deck/model_view.py +1097 -0
  24. flask_deck/py.typed +0 -0
  25. flask_deck/query.py +1220 -0
  26. flask_deck/schema_graph.py +137 -0
  27. flask_deck/security.py +373 -0
  28. flask_deck/sql_console.py +391 -0
  29. flask_deck/sso.py +293 -0
  30. flask_deck/static/css/deck.css +1333 -0
  31. flask_deck/static/js/deck.js +1433 -0
  32. flask_deck/storage.py +669 -0
  33. flask_deck/templates/flask_deck/audit_list.html +117 -0
  34. flask_deck/templates/flask_deck/base.html +454 -0
  35. flask_deck/templates/flask_deck/custom_page.html +12 -0
  36. flask_deck/templates/flask_deck/dashboard.html +32 -0
  37. flask_deck/templates/flask_deck/diagnostics.html +80 -0
  38. flask_deck/templates/flask_deck/error.html +15 -0
  39. flask_deck/templates/flask_deck/import_wizard.html +143 -0
  40. flask_deck/templates/flask_deck/jobs_list.html +95 -0
  41. flask_deck/templates/flask_deck/login.html +93 -0
  42. flask_deck/templates/flask_deck/login_mfa.html +59 -0
  43. flask_deck/templates/flask_deck/mfa_setup.html +121 -0
  44. flask_deck/templates/flask_deck/model_detail.html +124 -0
  45. flask_deck/templates/flask_deck/model_form.html +389 -0
  46. flask_deck/templates/flask_deck/model_list.html +489 -0
  47. flask_deck/templates/flask_deck/partials/drawer_detail.html +93 -0
  48. flask_deck/templates/flask_deck/partials/widget_grid.html +207 -0
  49. flask_deck/templates/flask_deck/rbac_matrix.html +59 -0
  50. flask_deck/templates/flask_deck/record_history.html +102 -0
  51. flask_deck/templates/flask_deck/schema_inspector.html +83 -0
  52. flask_deck/templates/flask_deck/sql_console.html +87 -0
  53. flask_deck-0.3.0.dist-info/METADATA +382 -0
  54. flask_deck-0.3.0.dist-info/RECORD +57 -0
  55. flask_deck-0.3.0.dist-info/WHEEL +4 -0
  56. flask_deck-0.3.0.dist-info/entry_points.txt +5 -0
  57. flask_deck-0.3.0.dist-info/licenses/LICENSE +21 -0
flask_deck/charts.py ADDED
@@ -0,0 +1,514 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections.abc import Sequence
5
+ from typing import Any
6
+
7
+ from markupsafe import Markup, escape
8
+
9
+ _SERIES_CLASSES: tuple[str, ...] = ("primary", "ok", "info", "warn", "danger")
10
+
11
+
12
+ def _safe_float(val: Any, default: float = 0.0) -> float:
13
+ try:
14
+ num = float(val)
15
+ except (TypeError, ValueError):
16
+ return default
17
+ return num if math.isfinite(num) else default
18
+
19
+
20
+ def _fmt_num(val: float) -> str:
21
+ if not math.isfinite(val):
22
+ return "0"
23
+ if abs(val) >= 1_000_000:
24
+ return f"{val / 1_000_000:.1f}M"
25
+ if abs(val) >= 1_000:
26
+ return f"{val / 1_000:.1f}k"
27
+ return f"{int(val)}" if float(val).is_integer() else f"{val:.1f}"
28
+
29
+
30
+ def render_sparkline(values: Sequence[float], *, tone: str = "primary") -> Markup:
31
+ """Render a minimal flat sparkline SVG for KPI cards (strict CSP-compliant)."""
32
+ if len(values) < 2:
33
+ return Markup("")
34
+ nums = [_safe_float(v) for v in values]
35
+ lo = min(nums)
36
+ hi = max(nums)
37
+ span = (hi - lo) or 1.0
38
+ w, h = 88.0, 26.0
39
+ pad_y = 3.0
40
+ step = w / (len(nums) - 1)
41
+ pts: list[tuple[float, float]] = []
42
+ for i, val in enumerate(nums):
43
+ x = i * step
44
+ y = h - pad_y - ((val - lo) / span) * (h - 2 * pad_y)
45
+ pts.append((x, y))
46
+
47
+ line_d = " ".join(
48
+ f"{'M' if i == 0 else 'L'}{x:.1f},{y:.1f}" for i, (x, y) in enumerate(pts)
49
+ )
50
+ area_d = f"{line_d} L{w:.1f},{h:.1f} L0,{h:.1f} Z"
51
+ cls = tone if tone in _SERIES_CLASSES else "primary"
52
+ return Markup(
53
+ f'<svg class="dk-sparkline dk-spark-{cls}" viewBox="0 0 {int(w)} {int(h)}" '
54
+ f'width="{int(w)}" height="{int(h)}" aria-hidden="true">'
55
+ f'<path class="dk-spark-area" d="{area_d}"/>'
56
+ f'<path class="dk-spark-line" d="{line_d}"/>'
57
+ "</svg>"
58
+ )
59
+
60
+
61
+ def render_area_chart(
62
+ labels: Sequence[str],
63
+ series: Sequence[dict[str, Any]],
64
+ *,
65
+ height: int = 210,
66
+ ) -> Markup:
67
+ """Render a crisp anti-slop SVG area/line chart with hairline grid and hover hooks."""
68
+ if not labels or not series:
69
+ return Markup('<div class="dk-chart-empty">No chart data available</div>')
70
+
71
+ w = 640.0
72
+ h = float(height)
73
+ pad_l, pad_r, pad_t, pad_b = 44.0, 14.0, 14.0, 28.0
74
+ plot_w = w - pad_l - pad_r
75
+ plot_h = h - pad_t - pad_b
76
+
77
+ all_vals: list[float] = []
78
+ clean_series: list[tuple[str, list[float], str]] = []
79
+ for idx, item in enumerate(series):
80
+ name = str(item.get("name", f"Series {idx + 1}"))
81
+ raw_data = [_safe_float(v) for v in item.get("data", [])][: len(labels)]
82
+ if not raw_data:
83
+ continue
84
+ all_vals.extend(raw_data)
85
+ tone = str(item.get("tone", _SERIES_CLASSES[idx % len(_SERIES_CLASSES)]))
86
+ if tone not in _SERIES_CLASSES:
87
+ tone = _SERIES_CLASSES[idx % len(_SERIES_CLASSES)]
88
+ clean_series.append((name, raw_data, tone))
89
+
90
+ if not all_vals:
91
+ return Markup('<div class="dk-chart-empty">No chart data available</div>')
92
+
93
+ max_v = max(all_vals)
94
+ min_v = min(0.0, min(all_vals))
95
+ span = (max_v - min_v) or 1.0
96
+ # Slight headroom so the highest point sits cleanly below the top rule.
97
+ top_v = min_v + span * 1.12
98
+ eff_span = top_v - min_v
99
+
100
+ parts: list[str] = [
101
+ '<div class="dk-chart-wrap" data-deck-chart="area">',
102
+ f'<svg class="dk-chart-svg" viewBox="0 0 {int(w)} {int(h)}" role="img" aria-label="Area chart">',
103
+ ]
104
+
105
+ # 4 crisp horizontal hairline gridlines + monospace Y axis labels.
106
+ ticks = 4
107
+ for t in range(ticks + 1):
108
+ frac = t / ticks
109
+ y = pad_t + plot_h * (1.0 - frac)
110
+ val = min_v + eff_span * frac
111
+ parts.append(
112
+ f'<line class="dk-chart-grid" x1="{pad_l:.1f}" y1="{y:.1f}" x2="{w - pad_r:.1f}" y2="{y:.1f}"/>'
113
+ )
114
+ parts.append(
115
+ f'<text class="dk-chart-axis" x="{pad_l - 8:.1f}" y="{y + 3:.1f}" text-anchor="end">'
116
+ f"{escape(_fmt_num(val))}</text>"
117
+ )
118
+
119
+ n = len(labels)
120
+ step_x = plot_w / max(1, n - 1)
121
+
122
+ # X axis labels (evenly spaced without crowding the final tick)
123
+ label_stride = max(1, math.ceil(n / 7))
124
+ for i, lbl in enumerate(labels):
125
+ is_last = i == n - 1
126
+ if not is_last and (i % label_stride != 0 or (n - 1 - i) < label_stride):
127
+ continue
128
+ x = pad_l + i * step_x
129
+ parts.append(
130
+ f'<text class="dk-chart-axis" x="{x:.1f}" y="{h - 6:.1f}" text-anchor="middle">'
131
+ f"{escape(str(lbl))}</text>"
132
+ )
133
+
134
+ # Crosshair placeholder controlled by deck.js
135
+ parts.append(
136
+ f'<line class="dk-chart-crosshair" x1="{pad_l:.1f}" y1="{pad_t:.1f}" '
137
+ f'x2="{pad_l:.1f}" y2="{pad_t + plot_h:.1f}" hidden="hidden"/>'
138
+ )
139
+
140
+ # Paths and interactive data points
141
+ for name, data, tone in clean_series:
142
+ pts: list[tuple[float, float]] = []
143
+ for i, val in enumerate(data):
144
+ x = pad_l + i * step_x
145
+ y = pad_t + plot_h * (1.0 - (val - min_v) / eff_span)
146
+ pts.append((x, y))
147
+
148
+ line_d = " ".join(
149
+ f"{'M' if i == 0 else 'L'}{x:.1f},{y:.1f}" for i, (x, y) in enumerate(pts)
150
+ )
151
+ base_y = pad_t + plot_h
152
+ area_d = f"{line_d} L{pts[-1][0]:.1f},{base_y:.1f} L{pts[0][0]:.1f},{base_y:.1f} Z"
153
+ parts.append(f'<path class="dk-area-fill dk-tone-{tone}" d="{area_d}"/>')
154
+ parts.append(f'<path class="dk-area-line dk-tone-{tone}" d="{line_d}"/>')
155
+
156
+ for i, (x, y) in enumerate(pts):
157
+ parts.append(
158
+ f'<circle class="dk-chart-pt dk-tone-{tone}" cx="{x:.1f}" cy="{y:.1f}" r="3.5" '
159
+ f'data-label="{escape(str(labels[i]))}" '
160
+ f'data-series="{escape(name)}" '
161
+ f'data-value="{escape(_fmt_num(data[i]))}" '
162
+ f'data-raw="{data[i]:.2f}" '
163
+ f'data-x="{x:.1f}"/>'
164
+ )
165
+
166
+ parts.append("</svg>")
167
+ parts.append('<div class="dk-chart-tooltip" hidden="hidden"></div>')
168
+ if len(clean_series) > 1:
169
+ legend_items = "".join(
170
+ f'<span class="dk-legend-item"><span class="dk-legend-swatch dk-tone-{tone}"></span>'
171
+ f"{escape(name)}</span>"
172
+ for name, _, tone in clean_series
173
+ )
174
+ parts.append(f'<div class="dk-chart-legend">{legend_items}</div>')
175
+ parts.append("</div>")
176
+ return Markup("".join(parts))
177
+
178
+
179
+ def render_bar_chart(
180
+ labels: Sequence[str],
181
+ series: Sequence[dict[str, Any]],
182
+ *,
183
+ height: int = 210,
184
+ ) -> Markup:
185
+ """Render a crisp geometric bar chart in pure SVG."""
186
+ if not labels or not series:
187
+ return Markup('<div class="dk-chart-empty">No chart data available</div>')
188
+
189
+ w = 640.0
190
+ h = float(height)
191
+ pad_l, pad_r, pad_t, pad_b = 44.0, 14.0, 14.0, 28.0
192
+ plot_w = w - pad_l - pad_r
193
+ plot_h = h - pad_t - pad_b
194
+
195
+ first = series[0]
196
+ name = str(first.get("name", "Count"))
197
+ data = [_safe_float(v) for v in first.get("data", [])][: len(labels)]
198
+ tone = str(first.get("tone", "primary"))
199
+ if tone not in _SERIES_CLASSES:
200
+ tone = "primary"
201
+ if not data:
202
+ return Markup('<div class="dk-chart-empty">No chart data available</div>')
203
+
204
+ max_v = max(0.0, max(data)) or 1.0
205
+ top_v = max_v * 1.12
206
+
207
+ parts: list[str] = [
208
+ '<div class="dk-chart-wrap" data-deck-chart="bar">',
209
+ f'<svg class="dk-chart-svg" viewBox="0 0 {int(w)} {int(h)}" role="img" aria-label="Bar chart">',
210
+ ]
211
+
212
+ for t in range(5):
213
+ frac = t / 4
214
+ y = pad_t + plot_h * (1.0 - frac)
215
+ parts.append(
216
+ f'<line class="dk-chart-grid" x1="{pad_l:.1f}" y1="{y:.1f}" x2="{w - pad_r:.1f}" y2="{y:.1f}"/>'
217
+ )
218
+ parts.append(
219
+ f'<text class="dk-chart-axis" x="{pad_l - 8:.1f}" y="{y + 3:.1f}" text-anchor="end">'
220
+ f"{escape(_fmt_num(top_v * frac))}</text>"
221
+ )
222
+
223
+ n = len(data)
224
+ slot_w = plot_w / max(1, n)
225
+ bar_w = max(8.0, min(34.0, slot_w * 0.58))
226
+
227
+ for i, val in enumerate(data):
228
+ bar_h = max(1.0, (max(0.0, val) / top_v) * plot_h)
229
+ cx = pad_l + i * slot_w + slot_w / 2.0
230
+ bx = cx - bar_w / 2.0
231
+ by = pad_t + plot_h - bar_h
232
+ parts.append(
233
+ f'<rect class="dk-bar-rect dk-tone-{tone}" x="{bx:.1f}" y="{by:.1f}" '
234
+ f'width="{bar_w:.1f}" height="{bar_h:.1f}" rx="2" '
235
+ f'data-label="{escape(str(labels[i]))}" '
236
+ f'data-series="{escape(name)}" '
237
+ f'data-value="{escape(_fmt_num(val))}" '
238
+ f'data-x="{cx:.1f}"/>'
239
+ )
240
+ parts.append(
241
+ f'<text class="dk-chart-axis" x="{cx:.1f}" y="{h - 6:.1f}" text-anchor="middle">'
242
+ f"{escape(str(labels[i])[:10])}</text>"
243
+ )
244
+
245
+ parts.append("</svg>")
246
+ parts.append('<div class="dk-chart-tooltip" hidden="hidden"></div>')
247
+ parts.append("</div>")
248
+ return Markup("".join(parts))
249
+
250
+
251
+ def render_donut_chart(
252
+ labels: Sequence[str],
253
+ series: Sequence[dict[str, Any]],
254
+ *,
255
+ center_label: str = "Total",
256
+ ) -> Markup:
257
+ """Render a minimal high-contrast donut ring chart with aligned tabular breakdown."""
258
+ if not labels or not series:
259
+ return Markup('<div class="dk-chart-empty">No chart data available</div>')
260
+
261
+ data = [max(0.0, _safe_float(v)) for v in series[0].get("data", [])][: len(labels)]
262
+ total = sum(data)
263
+ if total <= 0:
264
+ return Markup('<div class="dk-chart-empty">No chart data available</div>')
265
+
266
+ tones = series[0].get("tones") or []
267
+ cx, cy, r = 80.0, 80.0, 58.0
268
+ circ = 2.0 * math.pi * r
269
+ offset = 0.0
270
+
271
+ segments: list[str] = []
272
+ legend_rows: list[str] = []
273
+ for i, val in enumerate(data):
274
+ frac = val / total
275
+ seg_len = frac * circ
276
+ tone = str(tones[i]) if i < len(tones) else _SERIES_CLASSES[i % len(_SERIES_CLASSES)]
277
+ if tone not in _SERIES_CLASSES:
278
+ tone = _SERIES_CLASSES[i % len(_SERIES_CLASSES)]
279
+ segments.append(
280
+ f'<circle class="dk-donut-seg dk-tone-{tone}" cx="{cx:.1f}" cy="{cy:.1f}" r="{r:.1f}" '
281
+ f'stroke-dasharray="{max(0.0, seg_len - 1.5):.2f} {circ:.2f}" '
282
+ f'stroke-dashoffset="{-offset:.2f}" '
283
+ f'data-label="{escape(str(labels[i]))}" '
284
+ f'data-value="{escape(_fmt_num(val))} ({frac * 100:.0f}%)"/>'
285
+ )
286
+ offset += seg_len
287
+ legend_rows.append(
288
+ '<div class="dk-donut-row">'
289
+ f'<span class="dk-donut-key"><span class="dk-legend-swatch dk-tone-{tone}"></span>'
290
+ f"{escape(str(labels[i]))}</span>"
291
+ f'<span class="dk-mono dk-tabular dk-muted">{escape(_fmt_num(val))} · {frac * 100:.0f}%</span>'
292
+ "</div>"
293
+ )
294
+
295
+ svg = (
296
+ '<div class="dk-donut-layout" data-deck-chart="donut">'
297
+ '<div class="dk-donut-ring-wrap">'
298
+ '<svg class="dk-donut-svg" viewBox="0 0 160 160" width="152" height="152" role="img" aria-label="Donut chart">'
299
+ f'<circle class="dk-donut-track" cx="{cx:.1f}" cy="{cy:.1f}" r="{r:.1f}"/>'
300
+ f'{"".join(segments)}'
301
+ f'<text class="dk-donut-total" x="{cx:.1f}" y="{cy + 2:.1f}" text-anchor="middle">{escape(_fmt_num(total))}</text>'
302
+ f'<text class="dk-donut-sub" x="{cx:.1f}" y="{cy + 18:.1f}" text-anchor="middle">{escape(center_label)}</text>'
303
+ "</svg>"
304
+ '<div class="dk-chart-tooltip" hidden="hidden"></div>'
305
+ "</div>"
306
+ f'<div class="dk-donut-legend">{"".join(legend_rows)}</div>'
307
+ "</div>"
308
+ )
309
+ return Markup(svg)
310
+
311
+
312
+ def render_grouped_bar_chart(
313
+ labels: Sequence[str],
314
+ series: Sequence[dict[str, Any]],
315
+ *,
316
+ height: int = 210,
317
+ ) -> Markup:
318
+ """Render a multi-series grouped bar chart in pure SVG with hairline grid and tooltips."""
319
+ if not labels or not series:
320
+ return Markup('<div class="dk-chart-empty">No chart data available</div>')
321
+
322
+ w = 640.0
323
+ h = float(height)
324
+ pad_l, pad_r, pad_t, pad_b = 44.0, 14.0, 14.0, 28.0
325
+ plot_w = w - pad_l - pad_r
326
+ plot_h = h - pad_t - pad_b
327
+
328
+ clean: list[tuple[str, list[float], str]] = []
329
+ all_vals: list[float] = []
330
+ for idx, item in enumerate(series[:3]):
331
+ name = str(item.get("name", f"Series {idx + 1}"))
332
+ vals = [max(0.0, _safe_float(v)) for v in item.get("data", [])][: len(labels)]
333
+ if not vals:
334
+ continue
335
+ tone = str(item.get("tone", _SERIES_CLASSES[idx % len(_SERIES_CLASSES)]))
336
+ if tone not in _SERIES_CLASSES:
337
+ tone = _SERIES_CLASSES[idx % len(_SERIES_CLASSES)]
338
+ all_vals.extend(vals)
339
+ clean.append((name, vals, tone))
340
+
341
+ if not all_vals:
342
+ return Markup('<div class="dk-chart-empty">No chart data available</div>')
343
+
344
+ top_v = (max(all_vals) or 1.0) * 1.15
345
+ parts: list[str] = [
346
+ '<div class="dk-chart-wrap" data-deck-chart="grouped_bar">',
347
+ f'<svg class="dk-chart-svg" viewBox="0 0 {int(w)} {int(h)}" role="img" aria-label="Grouped bar chart">',
348
+ ]
349
+ for t in range(5):
350
+ frac = t / 4
351
+ y = pad_t + plot_h * (1.0 - frac)
352
+ parts.append(
353
+ f'<line class="dk-chart-grid" x1="{pad_l:.1f}" y1="{y:.1f}" x2="{w - pad_r:.1f}" y2="{y:.1f}"/>'
354
+ )
355
+ parts.append(
356
+ f'<text class="dk-chart-axis" x="{pad_l - 8:.1f}" y="{y + 3:.1f}" text-anchor="end">'
357
+ f"{escape(_fmt_num(top_v * frac))}</text>"
358
+ )
359
+
360
+ n = len(labels)
361
+ k = len(clean)
362
+ slot_w = plot_w / max(1, n)
363
+ group_w = min(46.0, slot_w * 0.72)
364
+ bar_w = max(5.0, (group_w - (k - 1) * 3.0) / k)
365
+
366
+ for i, lbl in enumerate(labels):
367
+ gx = pad_l + i * slot_w + (slot_w - group_w) / 2.0
368
+ for s_idx, (name, vals, tone) in enumerate(clean):
369
+ val = vals[i] if i < len(vals) else 0.0
370
+ bh = max(1.0, (val / top_v) * plot_h)
371
+ bx = gx + s_idx * (bar_w + 3.0)
372
+ by = pad_t + plot_h - bh
373
+ parts.append(
374
+ f'<rect class="dk-bar-rect dk-tone-{tone}" x="{bx:.1f}" y="{by:.1f}" '
375
+ f'width="{bar_w:.1f}" height="{bh:.1f}" rx="2" '
376
+ f'data-label="{escape(str(lbl))}" '
377
+ f'data-series="{escape(name)}" '
378
+ f'data-value="{escape(_fmt_num(val))}" '
379
+ f'data-x="{bx + bar_w / 2.0:.1f}"/>'
380
+ )
381
+ cx = pad_l + i * slot_w + slot_w / 2.0
382
+ parts.append(
383
+ f'<text class="dk-chart-axis" x="{cx:.1f}" y="{h - 6:.1f}" text-anchor="middle">'
384
+ f"{escape(str(lbl)[:10])}</text>"
385
+ )
386
+
387
+ parts.append("</svg>")
388
+ parts.append('<div class="dk-chart-tooltip" hidden="hidden"></div>')
389
+ legend_items = "".join(
390
+ f'<span class="dk-legend-item"><span class="dk-legend-swatch dk-tone-{tone}"></span>'
391
+ f"{escape(name)}</span>"
392
+ for name, _, tone in clean
393
+ )
394
+ parts.append(f'<div class="dk-chart-legend">{legend_items}</div></div>')
395
+ return Markup("".join(parts))
396
+
397
+
398
+ def render_heatmap_chart(cells: Sequence[tuple[str, int]], *, unit: str = "events") -> Markup:
399
+ """Render a crisp 7x13 (91-day) GitHub-style activity heatmap in pure SVG."""
400
+ if not cells:
401
+ return Markup('<div class="dk-chart-empty">No activity data available</div>')
402
+
403
+ data = list(cells)[-91:]
404
+ max_val = max((c for _, c in data), default=1) or 1
405
+ cell_sz = 13.0
406
+ gap = 4.0
407
+ step = cell_sz + gap
408
+ pad_l, pad_t = 28.0, 10.0
409
+ weeks = max(1, math.ceil(len(data) / 7))
410
+ w = pad_l + weeks * step + 6.0
411
+ h = pad_t + 7 * step + 8.0
412
+
413
+ day_labels = ("Mon", "", "Wed", "", "Fri", "", "Sun")
414
+ parts: list[str] = [
415
+ '<div class="dk-chart-wrap" data-deck-chart="heatmap">',
416
+ f'<svg class="dk-chart-svg dk-heatmap-svg" viewBox="0 0 {int(w)} {int(h)}" role="img" aria-label="Activity heatmap">',
417
+ ]
418
+ for d_idx, dlbl in enumerate(day_labels):
419
+ if dlbl:
420
+ parts.append(
421
+ f'<text class="dk-chart-axis" x="0" y="{pad_t + d_idx * step + 10:.1f}">{dlbl}</text>'
422
+ )
423
+
424
+ for idx, (date_str, count) in enumerate(data):
425
+ wk = idx // 7
426
+ dow = idx % 7
427
+ x = pad_l + wk * step
428
+ y = pad_t + dow * step
429
+ safe_count = int(_safe_float(count))
430
+ if safe_count <= 0:
431
+ lvl = 0
432
+ else:
433
+ ratio = safe_count / max_val
434
+ lvl = 1 if ratio <= 0.25 else (2 if ratio <= 0.5 else (3 if ratio <= 0.75 else 4))
435
+ parts.append(
436
+ f'<rect class="dk-hm-cell dk-hm-{lvl}" x="{x:.1f}" y="{y:.1f}" '
437
+ f'width="{cell_sz:.1f}" height="{cell_sz:.1f}" rx="2" '
438
+ f'data-label="{escape(date_str)}" data-value="{safe_count} {escape(unit)}"/>'
439
+ )
440
+
441
+ parts.append("</svg>")
442
+ parts.append('<div class="dk-chart-tooltip" hidden="hidden"></div>')
443
+ parts.append(
444
+ '<div class="dk-hm-legend dk-mono dk-subtle">'
445
+ "<span>Less</span>"
446
+ '<span class="dk-hm-swatch dk-hm-0"></span>'
447
+ '<span class="dk-hm-swatch dk-hm-1"></span>'
448
+ '<span class="dk-hm-swatch dk-hm-2"></span>'
449
+ '<span class="dk-hm-swatch dk-hm-3"></span>'
450
+ '<span class="dk-hm-swatch dk-hm-4"></span>'
451
+ "<span>More</span>"
452
+ "</div></div>"
453
+ )
454
+ return Markup("".join(parts))
455
+
456
+
457
+ def render_stat_bars(items: Sequence[dict[str, Any]]) -> Markup:
458
+ """Render horizontal precision utilization bars using pure SVG tracks (zero inline styles)."""
459
+ if not items:
460
+ return Markup('<div class="dk-chart-empty">No breakdown data</div>')
461
+
462
+ rows: list[str] = ['<div class="dk-statbars">']
463
+ for item in items:
464
+ label = str(item.get("label", ""))
465
+ val = _safe_float(item.get("value", 0))
466
+ max_v = max(0.0001, _safe_float(item.get("max", 100), 100.0))
467
+ pct = max(0.0, min(100.0, (val / max_v) * 100.0))
468
+ meta = str(item.get("meta", f"{pct:.0f}%"))
469
+ tone = str(item.get("tone", "primary"))
470
+ if tone not in _SERIES_CLASSES:
471
+ tone = "primary"
472
+ rows.append(
473
+ '<div class="dk-statbar-row">'
474
+ '<div class="dk-statbar-top">'
475
+ f'<span class="dk-statbar-lbl">{escape(label)}</span>'
476
+ f'<span class="dk-mono dk-tabular dk-muted">{escape(meta)}</span>'
477
+ "</div>"
478
+ '<svg class="dk-statbar-svg" viewBox="0 0 100 5" preserveAspectRatio="none" aria-hidden="true">'
479
+ '<rect class="dk-prog-track" x="0" y="0" width="100" height="5" rx="1.5"/>'
480
+ f'<rect class="dk-bar-rect dk-tone-{tone}" x="0" y="0" width="{pct:.1f}" height="5" rx="1.5"/>'
481
+ "</svg>"
482
+ "</div>"
483
+ )
484
+ rows.append("</div>")
485
+ return Markup("".join(rows))
486
+
487
+
488
+ def render_gauge_chart(
489
+ value: float,
490
+ *,
491
+ max_value: float = 100.0,
492
+ label: str = "Health",
493
+ suffix: str = "%",
494
+ tone: str = "ok",
495
+ ) -> Markup:
496
+ """Render a minimal precision semi-circular SVG gauge dial."""
497
+ safe_val = _safe_float(value)
498
+ safe_max = max(0.0001, _safe_float(max_value, 100.0))
499
+ pct = max(0.0, min(1.0, safe_val / safe_max))
500
+ r = 56.0
501
+ semi_circ = math.pi * r
502
+ dash = pct * semi_circ
503
+ cls = tone if tone in _SERIES_CLASSES else "ok"
504
+ display = f"{int(safe_val) if safe_val.is_integer() else f'{safe_val:.1f}'}{suffix}"
505
+ return Markup(
506
+ '<div class="dk-gauge-wrap">'
507
+ '<svg class="dk-gauge-svg" viewBox="0 0 160 98" width="160" height="98" role="img" aria-label="Gauge">'
508
+ '<path class="dk-gauge-track" d="M 24 80 A 56 56 0 0 1 136 80"/>'
509
+ f'<path class="dk-gauge-fill dk-tone-{cls}" d="M 24 80 A 56 56 0 0 1 136 80" '
510
+ f'stroke-dasharray="{dash:.2f} {semi_circ:.2f}"/>'
511
+ f'<text class="dk-donut-total" x="80" y="72" text-anchor="middle">{escape(display)}</text>'
512
+ f'<text class="dk-donut-sub" x="80" y="90" text-anchor="middle">{escape(label)}</text>'
513
+ "</svg></div>"
514
+ )
flask_deck/cli.py ADDED
@@ -0,0 +1,135 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from collections.abc import Sequence
6
+
7
+ import click
8
+ from flask import current_app
9
+ from flask.cli import AppGroup, with_appcontext
10
+
11
+ from flask_deck.deck import Deck, run_security_audit
12
+
13
+ deck_cli = AppGroup("deck", help="Flask-Deck admin workbench commands.")
14
+
15
+
16
+ def _get_registered_decks() -> dict[str, Deck]:
17
+ decks: dict[str, Deck] = current_app.extensions.get("flask_deck", {})
18
+ return decks
19
+
20
+
21
+ @deck_cli.command("info")
22
+ @with_appcontext
23
+ def cli_info() -> None:
24
+ """List registered Flask-Deck instances, models, columns, and security settings."""
25
+ decks = _get_registered_decks()
26
+ if not decks:
27
+ click.echo("No Flask-Deck instances registered on this Flask app.")
28
+ return
29
+ for name, deck in decks.items():
30
+ click.echo(
31
+ f"Deck '{name}' | prefix={deck.config.url_prefix} | env={deck.config.environment} "
32
+ f"| auth={deck.auth.__class__.__name__} | read_only={deck.config.read_only}"
33
+ )
34
+ for slug, view in deck.views.items():
35
+ click.echo(
36
+ f" - /{slug}/ ({view.meta.name}) "
37
+ f"cols={len(view.list_columns)} search={list(view.resolved_searchable)} "
38
+ f"tabs={len(view.quick_tabs)} actions={list(view.actions.keys())}"
39
+ )
40
+
41
+
42
+ @deck_cli.command("audit")
43
+ @with_appcontext
44
+ def cli_audit() -> None:
45
+ """Audit Flask-Deck security headers, session flags, RBAC, and searchable DB indexes."""
46
+ decks = _get_registered_decks()
47
+ if not decks:
48
+ click.echo("No Flask-Deck instances registered on this Flask app.")
49
+ return
50
+
51
+ exit_code = 0
52
+ for name, deck in decks.items():
53
+ click.echo(f"Auditing Flask-Deck '{name}' ({deck.config.environment})...")
54
+ findings = run_security_audit(current_app._get_current_object(), deck) # type: ignore[attr-defined]
55
+ if not findings:
56
+ click.echo(" [OK] Zero security or index findings.")
57
+ continue
58
+ for item in findings:
59
+ sev = item["severity"]
60
+ if sev in {"CRITICAL", "HIGH"}:
61
+ exit_code = 1
62
+ click.echo(f" [{sev}] ({item['category']}) {item['message']}")
63
+ if exit_code:
64
+ sys.exit(exit_code)
65
+
66
+
67
+ def _run_demo(host: str = "127.0.0.1", port: int = 5055, open_browser: bool = False) -> None:
68
+ import atexit
69
+ import shutil
70
+ import tempfile
71
+ from pathlib import Path
72
+
73
+ from flask_deck.demo import create_demo_app
74
+
75
+ tmp_dir = Path(tempfile.mkdtemp(prefix="flask_deck_demo_"))
76
+ db_file = tmp_dir / "demo.sqlite3"
77
+ app = create_demo_app(db_uri=f"sqlite:///{db_file.as_posix()}")
78
+
79
+ def _cleanup_demo() -> None:
80
+ decks = app.extensions.get("flask_deck", {})
81
+ for d in decks.values():
82
+ if hasattr(d, "close"):
83
+ d.close()
84
+ shutil.rmtree(tmp_dir, ignore_errors=True)
85
+
86
+ atexit.register(_cleanup_demo)
87
+ url = f"http://{host}:{port}/admin/"
88
+ click.echo(f"Flask-Deck Demo Workbench running at {url}")
89
+ click.echo("Demo accounts (password: 'deck-demo-2026'):")
90
+ click.echo(" - admin@acme.dev (Superadmin — full access + revert)")
91
+ click.echo(" - support@acme.dev (Support — masked PII, read-only billing, no delete)")
92
+ click.echo(" - viewer@acme.dev (Auditor — strict read-only inspection)")
93
+ if open_browser:
94
+ import webbrowser
95
+
96
+ webbrowser.open(url)
97
+ app.run(host=host, port=port, debug=False, use_reloader=False)
98
+
99
+
100
+ @deck_cli.command("demo")
101
+ @click.option("--host", default="127.0.0.1", show_default=True)
102
+ @click.option("--port", default=5055, type=int, show_default=True)
103
+ @click.option("--open-browser", is_flag=True, default=False)
104
+ def cli_demo(host: str, port: int, open_browser: bool) -> None:
105
+ """Launch the built-in Acme Cloud Ops SaaS demo workbench."""
106
+ _run_demo(host=host, port=port, open_browser=open_browser)
107
+
108
+
109
+ def main(argv: Sequence[str] | None = None) -> int:
110
+ """Standalone CLI entry point (`flask-deck demo`, `flask-deck version`)."""
111
+ parser = argparse.ArgumentParser(
112
+ prog="flask-deck",
113
+ description="Flask-Deck — Precision Carbon Dark & Swiss Light Admin Panel for Flask.",
114
+ )
115
+ sub = parser.add_subparsers(dest="command")
116
+
117
+ demo_p = sub.add_parser("demo", help="Launch the interactive SaaS demo workbench")
118
+ demo_p.add_argument("--host", default="127.0.0.1")
119
+ demo_p.add_argument("--port", type=int, default=5055)
120
+ demo_p.add_argument("--open", dest="open_browser", action="store_true")
121
+
122
+ sub.add_parser("version", help="Print installed flask-deck version")
123
+
124
+ args = parser.parse_args(argv)
125
+ if args.command == "demo":
126
+ _run_demo(host=args.host, port=args.port, open_browser=args.open_browser)
127
+ return 0
128
+ if args.command == "version":
129
+ from flask_deck import __version__
130
+
131
+ print(f"flask-deck {__version__}")
132
+ return 0
133
+
134
+ parser.print_help()
135
+ return 0