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/demo.py ADDED
@@ -0,0 +1,1066 @@
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ import secrets
5
+ from datetime import datetime, timedelta, timezone
6
+ from types import MappingProxyType
7
+ from typing import Any
8
+
9
+ import sqlalchemy as sa
10
+ from flask import Flask, redirect
11
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, sessionmaker
12
+
13
+ from flask_deck.audit import SQLAlchemyAuditStore, make_audit_entry
14
+ from flask_deck.auth import DeckUser, RBACAuthProvider, Role
15
+ from flask_deck.branding import BrandConfig
16
+ from flask_deck.dashboard import (
17
+ ActivityWidget,
18
+ CalloutWidget,
19
+ ChartWidget,
20
+ DashboardContext,
21
+ GaugeWidget,
22
+ HeatmapWidget,
23
+ KPIWidget,
24
+ StatBarWidget,
25
+ TableWidget,
26
+ TimelineWidget,
27
+ Widget,
28
+ )
29
+ from flask_deck.deck import Deck
30
+ from flask_deck.formatters import (
31
+ AvatarFormatter,
32
+ BadgeFormatter,
33
+ BooleanIconFormatter,
34
+ CodeFormatter,
35
+ CurrencyFormatter,
36
+ FileFormatter,
37
+ ImageFormatter,
38
+ ProgressBarFormatter,
39
+ RelativeTimeFormatter,
40
+ )
41
+ from flask_deck.jobs import JobContext
42
+ from flask_deck.model_view import ActionField, InlineModelView, ModelView, action
43
+ from flask_deck.query import QuickTab
44
+ from flask_deck.storage import FileFieldConfig, MemoryFileStorage, make_demo_png
45
+
46
+ DEMO_MEDIA_STORAGE = MemoryFileStorage()
47
+
48
+
49
+ class PlanTier(enum.Enum):
50
+ STARTER = "starter"
51
+ GROWTH = "growth"
52
+ ENTERPRISE = "enterprise"
53
+
54
+
55
+ class UserRole(enum.Enum):
56
+ OWNER = "owner"
57
+ ADMIN = "admin"
58
+ ENGINEER = "engineer"
59
+ MEMBER = "member"
60
+
61
+
62
+ class ProductCategory(enum.Enum):
63
+ COMPUTE = "compute"
64
+ STORAGE = "storage"
65
+ NETWORKING = "networking"
66
+ ADDON = "addon"
67
+
68
+
69
+ class OrderStatus(enum.Enum):
70
+ PENDING = "pending"
71
+ PAID = "paid"
72
+ SHIPPED = "shipped"
73
+ REFUNDED = "refunded"
74
+
75
+
76
+ class TicketPriority(enum.Enum):
77
+ LOW = "low"
78
+ MEDIUM = "medium"
79
+ HIGH = "high"
80
+ CRITICAL = "critical"
81
+
82
+
83
+ class TicketStatus(enum.Enum):
84
+ OPEN = "open"
85
+ IN_PROGRESS = "in_progress"
86
+ RESOLVED = "resolved"
87
+ CLOSED = "closed"
88
+
89
+
90
+ class DemoBase(DeclarativeBase):
91
+ pass
92
+
93
+
94
+ class Organization(DemoBase):
95
+ __tablename__ = "demo_organizations"
96
+
97
+ id: Mapped[int] = mapped_column(primary_key=True)
98
+ name: Mapped[str] = mapped_column(sa.String(120), nullable=False, index=True)
99
+ slug: Mapped[str] = mapped_column(sa.String(80), unique=True, index=True, nullable=False)
100
+ plan: Mapped[PlanTier] = mapped_column(sa.Enum(PlanTier), default=PlanTier.STARTER, index=True)
101
+ mrr_cents: Mapped[int] = mapped_column(sa.Integer, default=0, nullable=False)
102
+ seats_used: Mapped[int] = mapped_column(sa.Integer, default=1, nullable=False)
103
+ seats_limit: Mapped[int] = mapped_column(sa.Integer, default=10, nullable=False)
104
+ is_active: Mapped[bool] = mapped_column(sa.Boolean, default=True, nullable=False)
105
+ created_at: Mapped[datetime] = mapped_column(
106
+ sa.DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
107
+ )
108
+
109
+ users: Mapped[list[User]] = relationship(back_populates="organization")
110
+ orders: Mapped[list[Order]] = relationship(back_populates="organization")
111
+
112
+ def __str__(self) -> str:
113
+ return self.name
114
+
115
+
116
+ class User(DemoBase):
117
+ __tablename__ = "demo_users"
118
+
119
+ id: Mapped[int] = mapped_column(primary_key=True)
120
+ full_name: Mapped[str] = mapped_column(sa.String(120), nullable=False, index=True)
121
+ email: Mapped[str] = mapped_column(sa.String(160), unique=True, index=True, nullable=False)
122
+ role: Mapped[UserRole] = mapped_column(sa.Enum(UserRole), default=UserRole.MEMBER, index=True)
123
+ password_hash: Mapped[str] = mapped_column(sa.String(255), default="pbkdf2:sha256:redacted")
124
+ api_token: Mapped[str] = mapped_column(sa.String(128), default="sk_live_redacted_demo")
125
+ organization_id: Mapped[int] = mapped_column(sa.ForeignKey("demo_organizations.id"), index=True)
126
+ is_active: Mapped[bool] = mapped_column(sa.Boolean, default=True, nullable=False)
127
+ created_at: Mapped[datetime] = mapped_column(
128
+ sa.DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
129
+ )
130
+
131
+ organization: Mapped[Organization] = relationship(back_populates="users")
132
+
133
+ def __str__(self) -> str:
134
+ return f"{self.full_name} ({self.email})"
135
+
136
+
137
+ class Product(DemoBase):
138
+ __tablename__ = "demo_products"
139
+
140
+ id: Mapped[int] = mapped_column(primary_key=True)
141
+ sku: Mapped[str] = mapped_column(sa.String(40), unique=True, index=True, nullable=False)
142
+ name: Mapped[str] = mapped_column(sa.String(140), nullable=False, index=True)
143
+ category: Mapped[ProductCategory] = mapped_column(
144
+ sa.Enum(ProductCategory), default=ProductCategory.COMPUTE, index=True
145
+ )
146
+ price_cents: Mapped[int] = mapped_column(sa.Integer, nullable=False)
147
+ stock_pct: Mapped[int] = mapped_column(sa.Integer, default=100, nullable=False)
148
+ is_active: Mapped[bool] = mapped_column(sa.Boolean, default=True, nullable=False)
149
+ thumbnail_path: Mapped[str | None] = mapped_column(sa.String(255), nullable=True)
150
+ spec_sheet_path: Mapped[str | None] = mapped_column(sa.String(255), nullable=True)
151
+ metadata_json: Mapped[dict[str, Any] | None] = mapped_column(sa.JSON, nullable=True)
152
+ created_at: Mapped[datetime] = mapped_column(
153
+ sa.DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
154
+ )
155
+
156
+ def __str__(self) -> str:
157
+ return f"{self.sku} · {self.name}"
158
+
159
+
160
+ class Order(DemoBase):
161
+ __tablename__ = "demo_orders"
162
+
163
+ id: Mapped[int] = mapped_column(primary_key=True)
164
+ order_number: Mapped[str] = mapped_column(sa.String(32), unique=True, index=True, nullable=False)
165
+ organization_id: Mapped[int] = mapped_column(sa.ForeignKey("demo_organizations.id"), index=True)
166
+ customer_id: Mapped[int] = mapped_column(sa.ForeignKey("demo_users.id"), index=True)
167
+ status: Mapped[OrderStatus] = mapped_column(
168
+ sa.Enum(OrderStatus), default=OrderStatus.PENDING, index=True
169
+ )
170
+ total_cents: Mapped[int] = mapped_column(sa.Integer, default=0, nullable=False)
171
+ notes: Mapped[str | None] = mapped_column(sa.Text, nullable=True)
172
+ created_at: Mapped[datetime] = mapped_column(
173
+ sa.DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), index=True
174
+ )
175
+
176
+ organization: Mapped[Organization] = relationship(back_populates="orders")
177
+ customer: Mapped[User] = relationship()
178
+ items: Mapped[list[OrderItem]] = relationship(
179
+ back_populates="order", cascade="all, delete-orphan"
180
+ )
181
+
182
+ def __str__(self) -> str:
183
+ return self.order_number
184
+
185
+
186
+ class OrderItem(DemoBase):
187
+ __tablename__ = "demo_order_items"
188
+
189
+ id: Mapped[int] = mapped_column(primary_key=True)
190
+ order_id: Mapped[int] = mapped_column(sa.ForeignKey("demo_orders.id"), index=True)
191
+ product_id: Mapped[int] = mapped_column(sa.ForeignKey("demo_products.id"), index=True)
192
+ quantity: Mapped[int] = mapped_column(sa.Integer, default=1, nullable=False)
193
+ unit_price_cents: Mapped[int] = mapped_column(sa.Integer, default=0, nullable=False)
194
+
195
+ order: Mapped[Order] = relationship(back_populates="items")
196
+ product: Mapped[Product] = relationship()
197
+
198
+ def __str__(self) -> str:
199
+ return f"Item #{self.id} (x{self.quantity})"
200
+
201
+
202
+ class SupportTicket(DemoBase):
203
+ __tablename__ = "demo_tickets"
204
+
205
+ id: Mapped[int] = mapped_column(primary_key=True)
206
+ ticket_key: Mapped[str] = mapped_column(sa.String(24), unique=True, index=True, nullable=False)
207
+ subject: Mapped[str] = mapped_column(sa.String(180), nullable=False, index=True)
208
+ organization_id: Mapped[int] = mapped_column(sa.ForeignKey("demo_organizations.id"), index=True)
209
+ requester_id: Mapped[int] = mapped_column(sa.ForeignKey("demo_users.id"), index=True)
210
+ priority: Mapped[TicketPriority] = mapped_column(
211
+ sa.Enum(TicketPriority), default=TicketPriority.MEDIUM, index=True
212
+ )
213
+ status: Mapped[TicketStatus] = mapped_column(
214
+ sa.Enum(TicketStatus), default=TicketStatus.OPEN, index=True
215
+ )
216
+ sla_health: Mapped[int] = mapped_column(sa.Integer, default=95, nullable=False)
217
+ deleted_at: Mapped[datetime | None] = mapped_column(
218
+ sa.DateTime(timezone=True), nullable=True, index=True
219
+ )
220
+ created_at: Mapped[datetime] = mapped_column(
221
+ sa.DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), index=True
222
+ )
223
+
224
+ organization: Mapped[Organization] = relationship()
225
+ requester: Mapped[User] = relationship()
226
+
227
+ def __str__(self) -> str:
228
+ return f"{self.ticket_key} · {self.subject}"
229
+
230
+
231
+ # ---- Declarative ModelViews ----
232
+
233
+
234
+ class OrganizationView(ModelView):
235
+ model = Organization
236
+ icon = "building"
237
+ category = "Customers"
238
+ columns = ("name", "slug", "plan", "mrr_cents", "seats_used", "is_active", "created_at")
239
+ searchable_columns = ("name", "slug")
240
+ filterable_columns = ("plan", "is_active", "created_at")
241
+ inline_editable_columns = ("is_active", "plan")
242
+ column_labels = MappingProxyType({"mrr_cents": "MRR", "seats_used": "Seats"})
243
+ column_aggregates = MappingProxyType({"mrr_cents": "sum", "seats_used": "sum"})
244
+ form_layout = "tabs"
245
+ field_widgets = MappingProxyType({"plan": "segmented"})
246
+ saved_views = (
247
+ ("Enterprise Only", "?tab=enterprise"),
248
+ ("Paused Orgs", "?f_is_active=false"),
249
+ )
250
+ fieldsets = (
251
+ ("Organization Identity", ("name", "slug", "plan", "is_active")),
252
+ ("Billing & Quotas", ("mrr_cents", "seats_used", "seats_limit")),
253
+ )
254
+ quick_tabs = (
255
+ QuickTab("all", "All"),
256
+ QuickTab("enterprise", "Enterprise", filters={"plan": "enterprise"}, tone="ok"),
257
+ QuickTab("growth", "Growth", filters={"plan": "growth"}, tone="info"),
258
+ QuickTab("starter", "Starter", filters={"plan": "starter"}, tone="neutral"),
259
+ )
260
+ column_formatters = MappingProxyType(
261
+ {
262
+ "slug": CodeFormatter(copyable=True),
263
+ "plan": BadgeFormatter({"enterprise": "ok", "growth": "info", "starter": "neutral"}),
264
+ "mrr_cents": CurrencyFormatter(currency="USD", divisor=100, decimals=0),
265
+ "is_active": BooleanIconFormatter(true_label="Active", false_label="Paused"),
266
+ "created_at": RelativeTimeFormatter(),
267
+ }
268
+ )
269
+
270
+
271
+ class UserView(ModelView):
272
+ model = User
273
+ icon = "users"
274
+ category = "Customers"
275
+ columns = ("full_name", "email", "organization", "role", "is_active", "created_at")
276
+ searchable_columns = ("full_name", "email")
277
+ filterable_columns = ("role", "is_active", "organization_id", "created_at")
278
+ inline_editable_columns = ("is_active", "role")
279
+ form_layout = "tabs"
280
+ field_widgets = MappingProxyType({"role": "segmented"})
281
+ column_formatters = MappingProxyType(
282
+ {
283
+ "full_name": AvatarFormatter(),
284
+ "email": CodeFormatter(max_chars=32, copyable=True),
285
+ "role": BadgeFormatter({"owner": "warn", "admin": "info", "engineer": "ok", "member": "neutral"}),
286
+ "is_active": BooleanIconFormatter(),
287
+ "created_at": RelativeTimeFormatter(),
288
+ }
289
+ )
290
+ fieldsets = (
291
+ ("Identity", ("full_name", "email", "organization_id")),
292
+ ("Access Control", ("role", "is_active")),
293
+ )
294
+
295
+
296
+ class ProductView(ModelView):
297
+ model = Product
298
+ icon = "package"
299
+ category = "Commerce"
300
+ columns = ("thumbnail_path", "sku", "name", "category", "price_cents", "stock_pct", "spec_sheet_path", "is_active")
301
+ searchable_columns = ("sku", "name")
302
+ filterable_columns = ("category", "is_active", "price_cents", "metadata_json")
303
+ inline_editable_columns = ("is_active",)
304
+ import_key_columns = ("sku",)
305
+ column_labels = MappingProxyType(
306
+ {
307
+ "thumbnail_path": "Preview",
308
+ "spec_sheet_path": "Spec PDF",
309
+ "price_cents": "Unit Price",
310
+ "stock_pct": "Capacity",
311
+ }
312
+ )
313
+ column_aggregates = MappingProxyType({"price_cents": "avg", "stock_pct": "avg"})
314
+ form_layout = "wizard"
315
+ form_excluded_columns = ("created_at",)
316
+ file_fields = MappingProxyType(
317
+ {
318
+ "thumbnail_path": FileFieldConfig(
319
+ storage=DEMO_MEDIA_STORAGE, kind="image", prefix="products/thumbs"
320
+ ),
321
+ "spec_sheet_path": FileFieldConfig(
322
+ storage=DEMO_MEDIA_STORAGE, kind="file", prefix="products/specs"
323
+ ),
324
+ }
325
+ )
326
+ field_widgets = MappingProxyType(
327
+ {"category": "segmented", "stock_pct": "slider", "metadata_json": "json_kv"}
328
+ )
329
+ fieldsets = (
330
+ ("Catalog Identity", ("sku", "name", "category", "is_active")),
331
+ ("Pricing & Media", ("price_cents", "stock_pct", "thumbnail_path", "spec_sheet_path")),
332
+ ("Structured Metadata", ("metadata_json",)),
333
+ )
334
+ column_formatters = MappingProxyType(
335
+ {
336
+ "thumbnail_path": ImageFormatter(alt_prefix="Product"),
337
+ "spec_sheet_path": FileFormatter(),
338
+ "sku": CodeFormatter(copyable=True),
339
+ "category": BadgeFormatter({"compute": "info", "storage": "ok", "networking": "warn", "addon": "neutral"}),
340
+ "price_cents": CurrencyFormatter(currency="USD", divisor=100),
341
+ "stock_pct": ProgressBarFormatter(max_value=100, warn_below=45, danger_below=20),
342
+ "is_active": BooleanIconFormatter(true_label="Listed", false_label="Archived"),
343
+ }
344
+ )
345
+
346
+
347
+ class OrderItemInline(InlineModelView):
348
+ model = OrderItem
349
+ label = "Line Items"
350
+ columns = ("product_id", "quantity", "unit_price_cents")
351
+
352
+
353
+ class OrderView(ModelView):
354
+ model = Order
355
+ icon = "shopping-bag"
356
+ category = "Commerce"
357
+ columns = ("order_number", "organization", "customer", "status", "total_cents", "created_at")
358
+ searchable_columns = ("order_number", "organization.name", "customer.email")
359
+ filterable_columns = ("status", "organization_id", "total_cents", "created_at")
360
+ inline_editable_columns = ("status",)
361
+ inlines = (OrderItemInline,)
362
+ kanban_column = "status"
363
+ kanban_card_fields = ("order_number", "organization", "total_cents")
364
+ column_aggregates = MappingProxyType({"total_cents": "sum"})
365
+ form_layout = "tabs"
366
+ dependent_fields = MappingProxyType({"customer_id": ("organization_id", "organization_id")})
367
+ field_conditions = MappingProxyType({"notes": ("status", "neq", "shipped")})
368
+ field_widgets = MappingProxyType({"status": "segmented", "notes": "markdown"})
369
+ saved_views = (
370
+ ("High Value >$2K", "?f_total_cents__gte=200000"),
371
+ ("Settled (Paid+Shipped)", "?f_status=paid,shipped"),
372
+ )
373
+ column_labels = MappingProxyType({"order_number": "Order #", "total_cents": "Amount"})
374
+ quick_tabs = (
375
+ QuickTab("all", "All"),
376
+ QuickTab("paid", "Paid", filters={"status": "paid"}, tone="ok"),
377
+ QuickTab("shipped", "Shipped", filters={"status": "shipped"}, tone="info"),
378
+ QuickTab("pending", "Pending", filters={"status": "pending"}, tone="warn"),
379
+ QuickTab("refunded", "Refunded", filters={"status": "refunded"}, tone="danger"),
380
+ )
381
+ column_formatters = MappingProxyType(
382
+ {
383
+ "order_number": CodeFormatter(copyable=True),
384
+ "status": BadgeFormatter({"paid": "ok", "shipped": "info", "pending": "warn", "refunded": "danger"}),
385
+ "total_cents": CurrencyFormatter(currency="USD", divisor=100),
386
+ "created_at": RelativeTimeFormatter(),
387
+ }
388
+ )
389
+ fieldsets = (
390
+ ("Order Summary", ("order_number", "organization_id", "customer_id", "status")),
391
+ ("Billing & Markdown Notes", ("total_cents", "notes")),
392
+ )
393
+
394
+ @action("mark_shipped", label="Mark Shipped", icon="truck", confirm=True)
395
+ def mark_shipped(self, records: list[Order], form_data: Any, user: Any) -> str:
396
+ for order in records:
397
+ order.status = OrderStatus.SHIPPED
398
+ return f"Marked {len(records)} order(s) as shipped."
399
+
400
+ @action("issue_refund", label="Refund Selected", icon="rotate-ccw", confirm=True, variant="danger")
401
+ def issue_refund(self, records: list[Order], form_data: Any, user: Any) -> str:
402
+ for order in records:
403
+ order.status = OrderStatus.REFUNDED
404
+ return f"Refunded {len(records)} order(s)."
405
+
406
+ @action("sync_erp", label="Sync ERP (Async)", icon="cpu", async_job=True)
407
+ def sync_erp(self, records: list[Order], form_data: Any, user: Any, job_ctx: JobContext) -> str:
408
+ total = max(1, len(records))
409
+ for idx, order in enumerate(records, start=1):
410
+ if job_ctx.is_cancelled():
411
+ return "ERP sync cancelled."
412
+ job_ctx.log(f"Reconciling {order.order_number} (${order.total_cents / 100:,.2f})…")
413
+ job_ctx.set_progress(int((idx / total) * 100), f"Synced {idx}/{total} orders")
414
+ return f"Synced {len(records)} order(s) with ERP ledger."
415
+
416
+
417
+ class SupportTicketView(ModelView):
418
+ model = SupportTicket
419
+ slug = "tickets"
420
+ name = "Ticket"
421
+ plural_name = "Support Tickets"
422
+ icon = "life-buoy"
423
+ category = "Operations"
424
+ pagination_mode = "cursor"
425
+ page_size = 4
426
+ soft_delete_column = "deleted_at"
427
+ exclude_columns = ("deleted_at",)
428
+ form_excluded_columns = ("deleted_at",)
429
+ columns = ("ticket_key", "subject", "organization", "priority", "status", "sla_health", "created_at")
430
+ searchable_columns = ("ticket_key", "subject")
431
+ filterable_columns = ("priority", "status", "organization_id", "created_at")
432
+ inline_editable_columns = ("status", "priority")
433
+ kanban_column = "status"
434
+ kanban_card_fields = ("ticket_key", "organization", "priority", "sla_health")
435
+ column_aggregates = MappingProxyType({"sla_health": "avg"})
436
+ form_layout = "tabs"
437
+ field_widgets = MappingProxyType(
438
+ {"priority": "segmented", "status": "segmented", "sla_health": "slider"}
439
+ )
440
+ saved_views = (
441
+ ("Critical Queue", "?f_priority=critical"),
442
+ ("SLA At Risk (<50%)", "?f_sla_health__lte=50"),
443
+ )
444
+ fieldsets = (
445
+ ("Ticket Triage", ("ticket_key", "subject", "organization_id", "requester_id")),
446
+ ("Priority & SLA Budget", ("priority", "status", "sla_health")),
447
+ )
448
+ column_labels = MappingProxyType({"ticket_key": "Key", "sla_health": "SLA Budget"})
449
+ quick_tabs = (
450
+ QuickTab("all", "All"),
451
+ QuickTab("open", "Open", filters={"status": "open"}, tone="warn"),
452
+ QuickTab("in_progress", "In Progress", filters={"status": "in_progress"}, tone="info"),
453
+ QuickTab("resolved", "Resolved", filters={"status": "resolved"}, tone="ok"),
454
+ )
455
+ column_formatters = MappingProxyType(
456
+ {
457
+ "ticket_key": CodeFormatter(copyable=True),
458
+ "priority": BadgeFormatter({"critical": "danger", "high": "warn", "medium": "info", "low": "neutral"}),
459
+ "status": BadgeFormatter({"open": "warn", "in_progress": "info", "resolved": "ok", "closed": "neutral"}),
460
+ "sla_health": ProgressBarFormatter(max_value=100, warn_below=50, danger_below=25),
461
+ "created_at": RelativeTimeFormatter(),
462
+ }
463
+ )
464
+
465
+ @action(
466
+ "escalate",
467
+ label="Escalate Priority",
468
+ icon="alert-triangle",
469
+ fields=(
470
+ ActionField(
471
+ "priority",
472
+ "select",
473
+ label="Target Priority",
474
+ choices=(("high", "High"), ("critical", "Critical")),
475
+ default="critical",
476
+ required=True,
477
+ ),
478
+ ActionField(
479
+ "reason",
480
+ "text",
481
+ label="Escalation Reason",
482
+ placeholder="Enterprise SLA threshold breached…",
483
+ required=True,
484
+ ),
485
+ ),
486
+ )
487
+ def escalate(self, records: list[SupportTicket], form_data: Any, user: Any) -> str:
488
+ target = TicketPriority(form_data.get("priority", "critical"))
489
+ reason = str(form_data.get("reason", "")).strip()
490
+ for ticket in records:
491
+ ticket.priority = target
492
+ return f"Escalated {len(records)} ticket(s) to {target.value} ({reason})."
493
+
494
+
495
+ def _seed_demo_data(session_factory: sessionmaker[Any], audit_store: SQLAlchemyAuditStore) -> None:
496
+ now = datetime.now(timezone.utc)
497
+ with session_factory() as sess:
498
+ if sess.scalar(sa.select(sa.func.count()).select_from(Organization)) or 0:
499
+ return
500
+
501
+ orgs = [
502
+ Organization(name="Northstar Robotics", slug="northstar", plan=PlanTier.ENTERPRISE, mrr_cents=480000, seats_used=42, seats_limit=50, created_at=now - timedelta(days=42)),
503
+ Organization(name="Kestrel FinTech", slug="kestrel-fin", plan=PlanTier.ENTERPRISE, mrr_cents=620000, seats_used=64, seats_limit=80, created_at=now - timedelta(days=35)),
504
+ Organization(name="Helios Grid Labs", slug="helios-grid", plan=PlanTier.GROWTH, mrr_cents=195000, seats_used=18, seats_limit=25, created_at=now - timedelta(days=28)),
505
+ Organization(name="Vektor Mobility", slug="vektor-mob", plan=PlanTier.GROWTH, mrr_cents=149000, seats_used=14, seats_limit=20, created_at=now - timedelta(days=19)),
506
+ Organization(name="Meridian BioAI", slug="meridian-bio", plan=PlanTier.ENTERPRISE, mrr_cents=510000, seats_used=51, seats_limit=60, created_at=now - timedelta(days=12)),
507
+ Organization(name="Cinder Analytics", slug="cinder-data", plan=PlanTier.STARTER, mrr_cents=49000, seats_used=5, seats_limit=10, created_at=now - timedelta(days=7)),
508
+ Organization(name="Solstice Logistics", slug="solstice-log", plan=PlanTier.GROWTH, mrr_cents=180000, seats_used=21, seats_limit=25, created_at=now - timedelta(days=4)),
509
+ Organization(name="Boreal Systems", slug="boreal-sys", plan=PlanTier.STARTER, mrr_cents=39000, seats_used=4, seats_limit=10, is_active=False, created_at=now - timedelta(days=2)),
510
+ ]
511
+ sess.add_all(orgs)
512
+ sess.flush()
513
+
514
+ users = [
515
+ User(full_name="Ada Lindholm", email="ada@northstar.io", role=UserRole.OWNER, organization_id=orgs[0].id, created_at=now - timedelta(days=40)),
516
+ User(full_name="Kerem Kaya", email="kerem@kestrel.finance", role=UserRole.ADMIN, organization_id=orgs[1].id, created_at=now - timedelta(days=32)),
517
+ User(full_name="Elena Rostova", email="elena@heliosgrid.dev", role=UserRole.ENGINEER, organization_id=orgs[2].id, created_at=now - timedelta(days=25)),
518
+ User(full_name="Marcus Vance", email="marcus@vektor.io", role=UserRole.OWNER, organization_id=orgs[3].id, created_at=now - timedelta(days=18)),
519
+ User(full_name="Selin Demir", email="selin@meridian.bio", role=UserRole.ADMIN, organization_id=orgs[4].id, created_at=now - timedelta(days=11)),
520
+ User(full_name="Noah Sato", email="noah@cinder.sh", role=UserRole.ENGINEER, organization_id=orgs[5].id, created_at=now - timedelta(days=6)),
521
+ User(full_name="Clara Weber", email="clara@solstice.eu", role=UserRole.OWNER, organization_id=orgs[6].id, created_at=now - timedelta(days=3)),
522
+ User(full_name="Liam O'Connor", email="liam@boreal.dev", role=UserRole.MEMBER, organization_id=orgs[7].id, is_active=False, created_at=now - timedelta(days=1)),
523
+ ]
524
+ sess.add_all(users)
525
+ sess.flush()
526
+
527
+ sample_pdf = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n"
528
+ DEMO_MEDIA_STORAGE.save(sample_pdf, key="products/specs/acme-cloud-datasheet.pdf", content_type="application/pdf")
529
+ palette = [
530
+ (96, 165, 250),
531
+ (74, 222, 128),
532
+ (251, 191, 36),
533
+ (244, 244, 245),
534
+ (248, 113, 113),
535
+ (96, 165, 250),
536
+ (74, 222, 128),
537
+ ]
538
+ thumb_keys: list[str] = []
539
+ for idx, acc in enumerate(palette):
540
+ key = f"products/thumbs/sku-{idx + 1}.png"
541
+ DEMO_MEDIA_STORAGE.save(make_demo_png(64, 64, accent=acc), key=key, content_type="image/png")
542
+ thumb_keys.append(key)
543
+
544
+ products = [
545
+ Product(sku="GPU-H200-8X", name="Dedicated H200 8x Cluster Node", category=ProductCategory.COMPUTE, price_cents=245000, stock_pct=78, thumbnail_path=thumb_keys[0], spec_sheet_path="products/specs/acme-cloud-datasheet.pdf", metadata_json={"region": "eu-central-1", "vram_gb": 1128}),
546
+ Product(sku="CPU-ARM-64", name="Graviton4 64-vCPU Bare Metal", category=ProductCategory.COMPUTE, price_cents=42000, stock_pct=92, thumbnail_path=thumb_keys[1], spec_sheet_path="products/specs/acme-cloud-datasheet.pdf", metadata_json={"region": "us-east-1", "arch": "arm64", "ecc": True}),
547
+ Product(sku="NVME-10TB", name="Replicated NVMe Block Pool (10 TB)", category=ProductCategory.STORAGE, price_cents=31000, stock_pct=61, thumbnail_path=thumb_keys[2], spec_sheet_path="products/specs/acme-cloud-datasheet.pdf", metadata_json={"region": "eu-central-1", "iops": 120000}),
548
+ Product(sku="OBJ-S3-COLD", name="Immutable Audit Object Vault", category=ProductCategory.STORAGE, price_cents=12500, stock_pct=96, thumbnail_path=thumb_keys[3], metadata_json={"region": "eu-west-1", "worm": True}),
549
+ Product(sku="NET-ANYCAST", name="Global Anycast Edge Ingress", category=ProductCategory.NETWORKING, price_cents=18000, stock_pct=38, thumbnail_path=thumb_keys[4], metadata_json={"region": "global", "pops": 44}),
550
+ Product(sku="NET-PRIVLINK", name="Zero-Trust PrivateLink Tunnel", category=ProductCategory.NETWORKING, price_cents=15000, stock_pct=18, thumbnail_path=thumb_keys[5], metadata_json={"region": "eu-central-1", "mtls": True}),
551
+ Product(sku="ADD-SOC2-LOG", name="7-Year Compliance Audit Retention", category=ProductCategory.ADDON, price_cents=29000, stock_pct=100, thumbnail_path=thumb_keys[6], spec_sheet_path="products/specs/acme-cloud-datasheet.pdf", metadata_json={"region": "global", "packs": ["SOC2", "ISO27001"]}),
552
+ ]
553
+ sess.add_all(products)
554
+ sess.flush()
555
+
556
+ status_cycle = [
557
+ OrderStatus.PAID,
558
+ OrderStatus.PAID,
559
+ OrderStatus.SHIPPED,
560
+ OrderStatus.PAID,
561
+ OrderStatus.PENDING,
562
+ OrderStatus.SHIPPED,
563
+ OrderStatus.PAID,
564
+ OrderStatus.REFUNDED,
565
+ ]
566
+ orders: list[Order] = []
567
+ for idx in range(28):
568
+ org = orgs[idx % len(orgs)]
569
+ usr = users[idx % len(users)]
570
+ st = status_cycle[idx % len(status_cycle)]
571
+ p1 = products[idx % len(products)]
572
+ p2 = products[(idx + 2) % len(products)]
573
+ qty1 = 1 + (idx % 3)
574
+ total = p1.price_cents * qty1 + p2.price_cents
575
+ days_ago = idx % 14
576
+ ord_obj = Order(
577
+ order_number=f"ORD-2026-{1040 + idx}",
578
+ organization_id=org.id,
579
+ customer_id=usr.id,
580
+ status=st,
581
+ total_cents=total,
582
+ notes="Provisioned via automated enterprise billing cycle.",
583
+ created_at=now - timedelta(days=days_ago, hours=(idx * 3) % 20),
584
+ )
585
+ sess.add(ord_obj)
586
+ sess.flush()
587
+ sess.add_all(
588
+ [
589
+ OrderItem(order_id=ord_obj.id, product_id=p1.id, quantity=qty1, unit_price_cents=p1.price_cents),
590
+ OrderItem(order_id=ord_obj.id, product_id=p2.id, quantity=1, unit_price_cents=p2.price_cents),
591
+ ]
592
+ )
593
+ orders.append(ord_obj)
594
+
595
+ tickets = [
596
+ SupportTicket(ticket_key="OPS-412", subject="Dedicated PrivateLink BGP peering failover in eu-central-1", organization_id=orgs[1].id, requester_id=users[1].id, priority=TicketPriority.CRITICAL, status=TicketStatus.IN_PROGRESS, sla_health=22, created_at=now - timedelta(hours=3)),
597
+ SupportTicket(ticket_key="OPS-411", subject="Increase H200 cluster quota from 32 to 64 GPUs", organization_id=orgs[0].id, requester_id=users[0].id, priority=TicketPriority.HIGH, status=TicketStatus.OPEN, sla_health=44, created_at=now - timedelta(hours=7)),
598
+ SupportTicket(ticket_key="OPS-410", subject="Export SOC2 immutable audit trail for Q3 attestation", organization_id=orgs[4].id, requester_id=users[4].id, priority=TicketPriority.MEDIUM, status=TicketStatus.OPEN, sla_health=76, created_at=now - timedelta(days=1)),
599
+ SupportTicket(ticket_key="OPS-409", subject="Configure SAML SCIM group mapping for engineering role", organization_id=orgs[2].id, requester_id=users[2].id, priority=TicketPriority.MEDIUM, status=TicketStatus.IN_PROGRESS, sla_health=68, created_at=now - timedelta(days=2)),
600
+ SupportTicket(ticket_key="OPS-408", subject="Invoice VAT ID update for German subsidiary", organization_id=orgs[6].id, requester_id=users[6].id, priority=TicketPriority.LOW, status=TicketStatus.RESOLVED, sla_health=98, created_at=now - timedelta(days=3)),
601
+ SupportTicket(ticket_key="OPS-407", subject="Read replica lag spike during bulk CSV ingestion", organization_id=orgs[3].id, requester_id=users[3].id, priority=TicketPriority.HIGH, status=TicketStatus.RESOLVED, sla_health=91, created_at=now - timedelta(days=4)),
602
+ SupportTicket(ticket_key="OPS-406", subject="Duplicate staging webhook test alert (archived)", organization_id=orgs[5].id, requester_id=users[5].id, priority=TicketPriority.LOW, status=TicketStatus.CLOSED, sla_health=100, deleted_at=now - timedelta(days=1), created_at=now - timedelta(days=5)),
603
+ SupportTicket(ticket_key="OPS-405", subject="Legacy TLS 1.1 deprecation notice (archived)", organization_id=orgs[7].id, requester_id=users[7].id, priority=TicketPriority.LOW, status=TicketStatus.CLOSED, sla_health=100, deleted_at=now - timedelta(days=2), created_at=now - timedelta(days=6)),
604
+ ]
605
+ sess.add_all(tickets)
606
+ sess.commit()
607
+
608
+ # Pre-seed crisp realistic Audit Ledger entries
609
+ seed_audits = [
610
+ make_audit_entry(
611
+ actor_id="admin",
612
+ actor_name="Duhan Güler",
613
+ actor_ip="10.24.0.18",
614
+ action="update",
615
+ model_slug="orders",
616
+ model_label="Order",
617
+ record_pk=str(orders[0].id),
618
+ record_repr=orders[0].order_number,
619
+ changes={"status": {"old": "pending", "new": "paid"}},
620
+ timestamp=now - timedelta(minutes=14),
621
+ ),
622
+ make_audit_entry(
623
+ actor_id="support",
624
+ actor_name="Maya Chen",
625
+ actor_ip="10.24.0.42",
626
+ action="inline_edit",
627
+ model_slug="tickets",
628
+ model_label="Ticket",
629
+ record_pk=str(tickets[0].id),
630
+ record_repr=tickets[0].ticket_key,
631
+ changes={"status": {"old": "open", "new": "in_progress"}},
632
+ timestamp=now - timedelta(minutes=38),
633
+ ),
634
+ make_audit_entry(
635
+ actor_id="admin",
636
+ actor_name="Duhan Güler",
637
+ actor_ip="10.24.0.18",
638
+ action="update",
639
+ model_slug="organizations",
640
+ model_label="Organization",
641
+ record_pk=str(orgs[4].id),
642
+ record_repr=orgs[4].name,
643
+ changes={"plan": {"old": "growth", "new": "enterprise"}, "mrr_cents": {"old": 240000, "new": 510000}},
644
+ timestamp=now - timedelta(hours=2),
645
+ ),
646
+ make_audit_entry(
647
+ actor_id="admin",
648
+ actor_name="Duhan Güler",
649
+ actor_ip="10.24.0.18",
650
+ action="import",
651
+ model_slug="products",
652
+ model_label="Product",
653
+ record_pk="batch:7",
654
+ record_repr="Imported catalog_q4.csv (+4 / ~3)",
655
+ metadata={"filename": "catalog_q4.csv", "created": 4, "updated": 3},
656
+ timestamp=now - timedelta(hours=5),
657
+ ),
658
+ make_audit_entry(
659
+ actor_id="admin",
660
+ actor_name="Duhan Güler",
661
+ actor_ip="10.24.0.18",
662
+ action="update",
663
+ model_slug="users",
664
+ model_label="User",
665
+ record_pk=str(users[1].id),
666
+ record_repr=users[1].full_name,
667
+ changes={"role": {"old": "engineer", "new": "admin"}, "api_token": {"old": "[REDACTED]", "new": "[REDACTED]"}},
668
+ timestamp=now - timedelta(hours=9),
669
+ ),
670
+ ]
671
+ for entry in seed_audits:
672
+ audit_store.record(entry)
673
+
674
+
675
+ def create_demo_app(db_uri: str = "sqlite:///:memory:") -> Flask:
676
+ """Create the complete Acme Cloud Ops SaaS demo Flask application."""
677
+ app = Flask(__name__)
678
+ app.config["SECRET_KEY"] = secrets.token_hex(32)
679
+ app.config["SESSION_COOKIE_HTTPONLY"] = True
680
+ app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
681
+
682
+ connect_args = {"check_same_thread": False} if db_uri.startswith("sqlite") else {}
683
+ pool_kwargs: dict[str, Any] = {}
684
+ if db_uri == "sqlite:///:memory:":
685
+ from sqlalchemy.pool import StaticPool
686
+
687
+ pool_kwargs["poolclass"] = StaticPool
688
+
689
+ engine = sa.create_engine(db_uri, connect_args=connect_args, **pool_kwargs)
690
+ if db_uri.startswith("sqlite:///") and db_uri != "sqlite:///:memory:":
691
+ with engine.connect() as conn:
692
+ conn.exec_driver_sql("PRAGMA journal_mode=WAL")
693
+ conn.exec_driver_sql("PRAGMA busy_timeout=5000")
694
+ DemoBase.metadata.create_all(engine)
695
+ session_factory = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
696
+ audit_store = SQLAlchemyAuditStore(engine)
697
+ _seed_demo_data(session_factory, audit_store)
698
+
699
+ roles = [
700
+ Role(
701
+ name="superadmin",
702
+ label="Superadmin",
703
+ description="Unrestricted platform operations, dry-run imports, and audit revert.",
704
+ permissions=frozenset({"*"}),
705
+ ),
706
+ Role(
707
+ name="support",
708
+ label="Support Engineer",
709
+ description="Customer operations with PII email masking and read-only financials.",
710
+ permissions=frozenset(
711
+ {
712
+ "*:view",
713
+ "tickets:create",
714
+ "tickets:edit",
715
+ "orders:edit",
716
+ "orders:action:mark_shipped",
717
+ "orders:export",
718
+ "audit:view",
719
+ "rbac:view",
720
+ }
721
+ ),
722
+ masked_fields={"users": frozenset({"email"})},
723
+ readonly_fields={
724
+ "orders": frozenset({"total_cents", "organization_id"}),
725
+ "organizations": frozenset({"mrr_cents", "plan"}),
726
+ },
727
+ ),
728
+ Role(
729
+ name="auditor",
730
+ label="Compliance Auditor",
731
+ description="Strict read-only inspection across models, exports, and audit ledger.",
732
+ permissions=frozenset({"*:view", "*:export", "audit:view", "rbac:view"}),
733
+ masked_fields={"users": frozenset({"email"})},
734
+ ),
735
+ ]
736
+
737
+ demo_pwd = "deck-demo-2026"
738
+ auth = RBACAuthProvider(
739
+ roles=roles,
740
+ accounts=[
741
+ RBACAuthProvider.make_account(
742
+ user=DeckUser(
743
+ id="admin",
744
+ username="admin@acme.dev",
745
+ display_name="Duhan Güler",
746
+ email="admin@acme.dev",
747
+ roles=("superadmin",),
748
+ is_superuser=True,
749
+ ),
750
+ password=demo_pwd,
751
+ ),
752
+ RBACAuthProvider.make_account(
753
+ user=DeckUser(
754
+ id="support",
755
+ username="support@acme.dev",
756
+ display_name="Maya Chen",
757
+ email="support@acme.dev",
758
+ roles=("support",),
759
+ ),
760
+ password=demo_pwd,
761
+ ),
762
+ RBACAuthProvider.make_account(
763
+ user=DeckUser(
764
+ id="viewer",
765
+ username="viewer@acme.dev",
766
+ display_name="Alex Rivera",
767
+ email="viewer@acme.dev",
768
+ roles=("auditor",),
769
+ ),
770
+ password=demo_pwd,
771
+ ),
772
+ ],
773
+ )
774
+
775
+ deck = Deck(
776
+ app,
777
+ session_factory=session_factory,
778
+ engine=engine,
779
+ auth=auth,
780
+ audit_store=audit_store,
781
+ title="Acme Ops",
782
+ subtitle="Cloud Infrastructure & Billing Control Plane",
783
+ environment="staging",
784
+ enable_sql_console=True,
785
+ demo_role_switcher=True,
786
+ brand=BrandConfig(
787
+ accent="monochrome",
788
+ footer_note="Acme Cloud Ops",
789
+ login_notice="SOC2 Type II Audited · Select a Demo RBAC Profile Below",
790
+ ),
791
+ demo_credentials=[
792
+ ("admin@acme.dev", demo_pwd, "Superadmin · Full Access"),
793
+ ("support@acme.dev", demo_pwd, "Support · Masked PII + RO Billing"),
794
+ ("viewer@acme.dev", demo_pwd, "Auditor · Strict Read-Only"),
795
+ ],
796
+ sql_presets=[
797
+ (
798
+ "Top Orgs by MRR",
799
+ "SELECT name, plan, mrr_cents / 100 AS mrr_usd, seats_used, seats_limit FROM demo_organizations ORDER BY mrr_cents DESC LIMIT 10",
800
+ ),
801
+ (
802
+ "PII Auto-Redaction Demo",
803
+ "SELECT id, full_name, email, role, password_hash, api_token FROM demo_users ORDER BY id LIMIT 8",
804
+ ),
805
+ (
806
+ "Order Status Summary",
807
+ "SELECT status, COUNT(*) AS orders, SUM(total_cents) / 100 AS volume_usd FROM demo_orders GROUP BY status ORDER BY orders DESC",
808
+ ),
809
+ ],
810
+ )
811
+ deck.register(OrganizationView, UserView, ProductView, OrderView, SupportTicketView)
812
+
813
+ @deck.dashboard
814
+ def acme_dashboard(ctx: DashboardContext) -> list[Widget]:
815
+ sess = ctx.session
816
+ total_mrr = int(sess.scalar(sa.select(sa.func.coalesce(sa.func.sum(Organization.mrr_cents), 0)).where(Organization.is_active.is_(True))) or 0)
817
+ orgs_all = list(sess.scalars(sa.select(Organization).order_by(Organization.mrr_cents.desc())).all())
818
+ active_orgs = sum(1 for o in orgs_all if o.is_active)
819
+ order_total = int(sess.scalar(sa.select(sa.func.coalesce(sa.func.sum(Order.total_cents), 0)).where(Order.status.in_([OrderStatus.PAID, OrderStatus.SHIPPED]))) or 0)
820
+ tickets_all = list(
821
+ sess.scalars(
822
+ sa.select(SupportTicket)
823
+ .where(SupportTicket.deleted_at.is_(None))
824
+ .order_by(SupportTicket.sla_health.asc())
825
+ ).all()
826
+ )
827
+ open_tickets = sum(1 for t in tickets_all if t.status in {TicketStatus.OPEN, TicketStatus.IN_PROGRESS})
828
+ critical_t = next((t for t in tickets_all if t.priority == TicketPriority.CRITICAL and t.status != TicketStatus.RESOLVED), None)
829
+
830
+ span_days = ctx.range_days
831
+ labels = ctx.last_n_days(span_days)
832
+ today = datetime.now(timezone.utc).date()
833
+ start_day = today - timedelta(days=span_days - 1)
834
+ rev_buckets = [0.0] * span_days
835
+ all_orders = list(sess.scalars(sa.select(Order)).all())
836
+ status_counts: dict[str, int] = {"paid": 0, "shipped": 0, "pending": 0, "refunded": 0}
837
+ for o in all_orders:
838
+ status_counts[o.status.value] = status_counts.get(o.status.value, 0) + 1
839
+ if isinstance(o.created_at, datetime):
840
+ delta_d = (o.created_at.date() - start_day).days
841
+ if 0 <= delta_d < span_days and o.status in {OrderStatus.PAID, OrderStatus.SHIPPED}:
842
+ rev_buckets[delta_d] += o.total_cents / 100.0
843
+
844
+ # Deterministic 91-day activity heatmap series
845
+ heatmap_cells: list[tuple[str, int]] = []
846
+ for offset in range(90, -1, -1):
847
+ d = today - timedelta(days=offset)
848
+ val = ((d.toordinal() * 7 + d.weekday() * 3) % 11)
849
+ if d.weekday() >= 5:
850
+ val = val // 3
851
+ heatmap_cells.append((d.strftime("%Y-%m-%d"), val))
852
+
853
+ seat_bars = [
854
+ {
855
+ "label": o.name,
856
+ "value": o.seats_used,
857
+ "max": o.seats_limit,
858
+ "meta": f"{o.seats_used}/{o.seats_limit} ({int(o.seats_used / max(1, o.seats_limit) * 100)}%)",
859
+ "tone": "warn" if (o.seats_used / max(1, o.seats_limit)) >= 0.84 else "ok",
860
+ }
861
+ for o in orgs_all[:5]
862
+ ]
863
+
864
+ recent_orders = list(
865
+ sess.scalars(
866
+ sa.select(Order)
867
+ .options(sa.orm.joinedload(Order.organization))
868
+ .order_by(Order.created_at.desc())
869
+ .limit(5)
870
+ ).all()
871
+ )
872
+ status_fmt = BadgeFormatter({"paid": "ok", "shipped": "info", "pending": "warn", "refunded": "danger"})
873
+ money_fmt = CurrencyFormatter(currency="USD", divisor=100)
874
+ code_fmt = CodeFormatter(copyable=True)
875
+
876
+ widgets: list[Widget] = []
877
+ if critical_t is not None:
878
+ widgets.append(
879
+ CalloutWidget(
880
+ title=f"Critical SLA Alert · {critical_t.ticket_key}",
881
+ message=f"{critical_t.subject} ({critical_t.sla_health}% SLA budget remaining)",
882
+ tone="danger",
883
+ action_label="Open Kanban Board",
884
+ action_href=f"{ctx.url_for_model(SupportTicket)}?view=board",
885
+ col_span=12,
886
+ )
887
+ )
888
+
889
+ widgets.extend(
890
+ [
891
+ KPIWidget(
892
+ title="Active MRR",
893
+ value=f"${total_mrr / 100:,.0f}",
894
+ delta="+14.2% MoM",
895
+ trend="up",
896
+ icon="dollar-sign",
897
+ href=ctx.url_for_model(Organization),
898
+ sparkline=[178, 184, 192, 198, 206, 214, total_mrr / 10000.0],
899
+ col_span=3,
900
+ ),
901
+ KPIWidget(
902
+ title=f"Settled Volume ({span_days}d)",
903
+ value=f"${order_total / 100:,.0f}",
904
+ delta=f"{len(all_orders)} orders",
905
+ trend="up",
906
+ icon="shopping-bag",
907
+ href=ctx.url_for_model(Order),
908
+ sparkline=rev_buckets[-7:],
909
+ col_span=3,
910
+ ),
911
+ KPIWidget(
912
+ title="Active Organizations",
913
+ value=str(active_orgs),
914
+ delta="87% enterprise seats",
915
+ trend="up",
916
+ icon="building",
917
+ href=ctx.url_for_model(Organization),
918
+ sparkline=[4, 5, 5, 6, 6, 7, float(active_orgs)],
919
+ col_span=3,
920
+ ),
921
+ KPIWidget(
922
+ title="Open SLA Tickets",
923
+ value=str(open_tickets),
924
+ delta="1 critical (<4h SLA)",
925
+ trend="down" if open_tickets >= 4 else "flat",
926
+ icon="life-buoy",
927
+ href=f"{ctx.url_for_model(SupportTicket)}?view=board",
928
+ sparkline=[2, 3, 2, 4, 3, 5, float(open_tickets)],
929
+ col_span=3,
930
+ ),
931
+ ChartWidget(
932
+ title=f"Settled Revenue Trend ({span_days}d)",
933
+ subtitle="Daily paid + shipped order volume in USD (pure SSR SVG)",
934
+ chart_type="area",
935
+ labels=labels,
936
+ series=[{"name": "Revenue ($)", "data": rev_buckets, "tone": "primary"}],
937
+ col_span=8,
938
+ ),
939
+ ChartWidget(
940
+ title="Order Fulfillment Split",
941
+ subtitle="Live distribution across lifecycle states",
942
+ chart_type="donut",
943
+ labels=["Paid", "Shipped", "Pending", "Refunded"],
944
+ series=[
945
+ {
946
+ "data": [
947
+ status_counts["paid"],
948
+ status_counts["shipped"],
949
+ status_counts["pending"],
950
+ status_counts["refunded"],
951
+ ],
952
+ "tones": ["ok", "info", "warn", "danger"],
953
+ }
954
+ ],
955
+ center_label="Orders",
956
+ col_span=4,
957
+ ),
958
+ HeatmapWidget(
959
+ title="91-Day Operational Event Density",
960
+ subtitle="Daily billing, provisioning & mutation volume (zero JS chart library)",
961
+ cells=heatmap_cells,
962
+ unit="events",
963
+ col_span=8,
964
+ ),
965
+ StatBarWidget(
966
+ title="Enterprise Seat Utilization",
967
+ subtitle="Active seat allocation vs contracted quota",
968
+ items=seat_bars,
969
+ col_span=4,
970
+ ),
971
+ TableWidget(
972
+ title="Latest Orders",
973
+ subtitle="Most recent enterprise billing events",
974
+ headers=["Order #", "Organization", "Status", "Total"],
975
+ rows=[
976
+ [
977
+ code_fmt.format(o.order_number),
978
+ o.organization.name if o.organization else "—",
979
+ status_fmt.format(o.status),
980
+ money_fmt.format(o.total_cents),
981
+ ]
982
+ for o in recent_orders
983
+ ],
984
+ href=ctx.url_for_model(Order),
985
+ href_label="All Orders",
986
+ col_span=6,
987
+ ),
988
+ ActivityWidget(
989
+ title="Recent Audit Ledger",
990
+ subtitle="Immutable field-level diffs captured across operators",
991
+ limit=5,
992
+ col_span=6,
993
+ ),
994
+ ]
995
+ )
996
+ return widgets
997
+
998
+ @deck.page(
999
+ "sla-monitor",
1000
+ title="SLA & Capacity",
1001
+ icon="cpu",
1002
+ category="Operations",
1003
+ subtitle="Custom @deck.page operational view with pure SVG gauges, grouped bars & incident timeline",
1004
+ )
1005
+ def sla_monitor_page(ctx: DashboardContext) -> list[Widget]:
1006
+ sess = ctx.session
1007
+ products = list(sess.scalars(sa.select(Product).order_by(Product.stock_pct.asc())).all())
1008
+ avg_cap = sum(p.stock_pct for p in products) / max(1, len(products))
1009
+ return [
1010
+ GaugeWidget(
1011
+ title="Fleet Capacity Headroom",
1012
+ subtitle="Weighted across compute, storage & edge networking",
1013
+ value=round(avg_cap, 1),
1014
+ gauge_label="Available",
1015
+ tone="ok" if avg_cap >= 60 else "warn",
1016
+ details=[
1017
+ ("Compute Nodes", "85% avg"),
1018
+ ("Storage Pools", "78% avg"),
1019
+ ("Networking", "28% low"),
1020
+ ],
1021
+ col_span=4,
1022
+ ),
1023
+ ChartWidget(
1024
+ title="Capacity vs Demand by Tier",
1025
+ subtitle="Grouped SVG bar comparison across infrastructure categories",
1026
+ chart_type="grouped_bar",
1027
+ labels=["Compute", "Storage", "Networking", "Add-ons"],
1028
+ series=[
1029
+ {"name": "Provisioned %", "data": [85, 79, 28, 100], "tone": "primary"},
1030
+ {"name": "Reserved %", "data": [62, 54, 72, 41], "tone": "ok"},
1031
+ ],
1032
+ col_span=8,
1033
+ ),
1034
+ StatBarWidget(
1035
+ title="Per-SKU Capacity Utilization",
1036
+ subtitle="Live inventory headroom across infrastructure SKUs",
1037
+ items=[
1038
+ {
1039
+ "label": f"{p.sku} · {p.name}",
1040
+ "value": p.stock_pct,
1041
+ "max": 100,
1042
+ "meta": f"{p.stock_pct}%",
1043
+ "tone": "danger" if p.stock_pct <= 25 else ("warn" if p.stock_pct <= 45 else "ok"),
1044
+ }
1045
+ for p in products
1046
+ ],
1047
+ col_span=6,
1048
+ ),
1049
+ TimelineWidget(
1050
+ title="Infrastructure Incident & Provisioning Timeline",
1051
+ subtitle="Latest cluster operations and SLA events",
1052
+ events=[
1053
+ {"title": "OPS-412 · BGP peering failover opened", "detail": "Kestrel FinTech · eu-central-1 PrivateLink", "time": "3h ago", "tone": "danger", "href": f"{ctx.url_for_model(SupportTicket)}?view=board"},
1054
+ {"title": "OPS-411 · H200 cluster quota expansion requested", "detail": "Northstar Robotics · 32 → 64 GPUs", "time": "7h ago", "tone": "warn"},
1055
+ {"title": "Meridian BioAI upgraded Growth → Enterprise", "detail": "MRR updated $2,400 → $5,100 · audited", "time": "2h ago", "tone": "ok"},
1056
+ {"title": "Q4 catalog batch CSV committed", "detail": "4 created, 3 updated via SAVEPOINT dry-run", "time": "5h ago", "tone": "info"},
1057
+ ],
1058
+ col_span=6,
1059
+ ),
1060
+ ]
1061
+
1062
+ @app.route("/")
1063
+ def root_redirect() -> Any:
1064
+ return redirect("/admin/")
1065
+
1066
+ return app