Compare commits
113
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db22abdb7d | ||
|
|
eff9e72681 | ||
|
|
565aca4d56 | ||
|
|
3636556ae7 | ||
|
|
fb35ace0c7 | ||
|
|
da83f2a1cd | ||
|
|
9deff308b6 | ||
|
|
2e3d7ba062 | ||
|
|
5ab87fa9f0 | ||
|
|
62be80c9d8 | ||
|
|
2a6f9697b8 | ||
|
|
fba5110cc0 | ||
|
|
cdf5fc79a0 | ||
|
|
e4ea43a079 | ||
|
|
8837eb1e70 | ||
|
|
d1799bd3b1 | ||
|
|
ca53d2e871 | ||
|
|
65ff2372ca | ||
|
|
c2767ca7e0 | ||
|
|
bbd356d846 | ||
|
|
18705aaefb | ||
|
|
f1a7c5a7ca | ||
|
|
82cf95a9af | ||
|
|
963516ece0 | ||
|
|
46c5c0a846 | ||
|
|
18e57c6e5f | ||
|
|
98dd16b597 | ||
|
|
36f9540a89 | ||
|
|
c1df3b5aa3 | ||
|
|
3f3d2cc63c | ||
|
|
e663b0a609 | ||
|
|
61e9bfab7c | ||
|
|
43102c617d | ||
|
|
ecfe00307a | ||
|
|
6ea7e9d2c5 | ||
|
|
f5db83f26c | ||
|
|
3acd89a2c6 | ||
|
|
81365eed89 | ||
|
|
1253ec155e | ||
|
|
8a668ca60f | ||
|
|
85bd2f7e51 | ||
|
|
79a87e48f1 | ||
|
|
017911bece | ||
|
|
c36e4c41f8 | ||
|
|
8b229e7fb3 | ||
|
|
9d9b46056a | ||
|
|
adec979182 | ||
|
|
99baec9fcf | ||
|
|
c56344a6dc | ||
|
|
0c0dd9d0e9 | ||
|
|
529e866fff | ||
|
|
c8ac0b78c5 | ||
|
|
80c0e955f0 | ||
|
|
ae5da6046f | ||
|
|
aad5f4b98c | ||
|
|
751cac72ce | ||
|
|
cef5e1f0f5 | ||
|
|
f036000769 | ||
|
|
d87925516a | ||
|
|
f54500a9d9 | ||
|
|
4737ab4306 | ||
|
|
6686faad6b | ||
|
|
b07bdafd85 | ||
|
|
dff1a35560 | ||
|
|
acd1896788 | ||
|
|
0d79a9f72c | ||
|
|
6e0a291228 | ||
|
|
8ec13947cb | ||
|
|
0bec4c4648 | ||
|
|
cc138e3d82 | ||
|
|
7c533b9245 | ||
|
|
e5d556fee1 | ||
|
|
38750ba951 | ||
|
|
7f6145ca35 | ||
|
|
2f7c5e859d | ||
|
|
883c0556dd | ||
|
|
1ce0137ba9 | ||
|
|
eaf92f1581 | ||
|
|
cc28ed880b | ||
|
|
44609352b2 | ||
|
|
70e0f9f734 | ||
|
|
a9b3b4e9b0 | ||
|
|
65ce446e44 | ||
|
|
bff90965bf | ||
|
|
3394716f8f | ||
|
|
abf3c3825b | ||
|
|
1ed5012a95 | ||
|
|
72f7e00990 | ||
|
|
9df80dd4e1 | ||
|
|
1022b7e5f1 | ||
|
|
024ba88470 | ||
|
|
9a213e93f8 | ||
|
|
d8b0b9ce28 | ||
|
|
063106a29c | ||
|
|
6a958a8d7d | ||
|
|
4f35bef6e3 | ||
|
|
2ef199e4c5 | ||
|
|
a605143c5d | ||
|
|
da4608c937 | ||
|
|
83361fad77 | ||
|
|
c7d5206d0c | ||
|
|
914027e580 | ||
|
|
b70753d805 | ||
|
|
a7b73b0564 | ||
|
|
4c2400b596 | ||
|
|
0a8a42d69b | ||
|
|
eb773c5531 | ||
|
|
ea8b2c96d6 | ||
|
|
435aa88e29 | ||
|
|
7a5321c097 | ||
|
|
2b05ff8b02 | ||
|
|
5d8ef96d4c | ||
|
|
fee686a9f3 |
@@ -17,6 +17,10 @@ MOSQUITTO_PASSWORD_FILE=/etc/mosquitto/passwd
|
||||
MQTT_CLIENT_ID=bellsystems-admin-panel
|
||||
# HMAC secret used to derive per-device MQTT passwords (must match firmware)
|
||||
MQTT_SECRET=change-me-in-production
|
||||
# Accept the legacy shared "vesper" MQTT password for device usernames
|
||||
# (old firmware). Each use is logged once/hour per board; set to false
|
||||
# once no boards show up in those logs.
|
||||
MQTT_ALLOW_LEGACY_PASSWORD=true
|
||||
|
||||
# App
|
||||
BACKEND_CORS_ORIGINS=["http://localhost:5173"]
|
||||
|
||||
@@ -41,3 +41,5 @@ Thumbs.db
|
||||
|
||||
# claude
|
||||
.claude/
|
||||
# Per-machine compose overrides (e.g. Windows Postgres volume)
|
||||
docker-compose.override.yml
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# Design System: BellSystems Console Design
|
||||
**Project ID:** 18406618574074411899
|
||||
|
||||
---
|
||||
|
||||
## 1. Visual Theme & Atmosphere
|
||||
|
||||
**"The Digital Observatory"** — A high-fidelity, immersive enterprise command center aesthetic that rejects the typical boxed-in SaaS feel. The mood is best described as **Atmospheric Depth**: dark, spacious, and precision-focused. Inspired by high-end editorial design and command center interfaces, data is treated as a premium asset surfaced through tonal layering rather than structural lines.
|
||||
|
||||
The base is built on **Midnight Navy** — a deep blue-black that evokes an infinite canvas — with UI elements that appear to float and glow rather than sit flat. Hierarchy is established exclusively through surface tone shifts; hard borders are forbidden. The result feels like peering through a high-resolution window into enterprise data, where clarity comes from contrast in depth rather than weight.
|
||||
|
||||
Overall density is **medium-high** — information-rich layouts with generous vertical whitespace between elements, but no wasted screen real estate.
|
||||
|
||||
---
|
||||
|
||||
## 2. Color Palette & Roles
|
||||
|
||||
### Core Surfaces (darkest to lightest)
|
||||
| Name | Hex | Role |
|
||||
|---|---|---|
|
||||
| **Abyss** | `#0a0e14` | Deepest well; nested content backgrounds |
|
||||
| **Midnight** | `#10141a` | Main application viewport / page background |
|
||||
| **Void Navy** | `#181c22` | Sidebar, header, and secondary navigation surfaces |
|
||||
| **Deep Slate** | `#1c2026` | Default card and information module background |
|
||||
| **Elevated Slate** | `#262a31` | High cards, hovered table rows |
|
||||
| **Island** | `#31353c` | Active states, selected rows, top-layer containers |
|
||||
| **Frosted Glass** | `#353940` | Floating modals and dropdowns (at 80% opacity with blur) |
|
||||
|
||||
### Accent & Brand Colors
|
||||
| Name | Hex | Role |
|
||||
|---|---|---|
|
||||
| **Indigo Glow** | `#c0c1ff` | Primary accent; CTA text, key metrics, active nav indicator |
|
||||
| **Lavender Soft** | `#8083ff` | Primary container fills |
|
||||
| **Violet Pulse** | `#d2bbff` | Secondary accent; gradient pair to Indigo Glow |
|
||||
| **Deep Indigo** | `#6001d1` | Secondary container fills |
|
||||
| **Royal Indigo** | `#494bd6` | Inverse primary; used on light-over-dark contexts |
|
||||
| **Aqua Sky** | `#7bd0ff` | Tertiary accent; data visualization, device status indicators |
|
||||
| **Ocean** | `#009bd1` | Tertiary container |
|
||||
|
||||
### Semantic / State Colors
|
||||
| Name | Hex | Role |
|
||||
|---|---|---|
|
||||
| **Coral Error** | `#ffb4ab` | Error text and destructive action labels |
|
||||
| **Crimson** | `#93000a` | Error container backgrounds |
|
||||
| **Emerald** (Tailwind) | `emerald-*` | Online / active device status badges |
|
||||
| **Amber** (Tailwind) | `amber-*` | Warning / pending device status badges |
|
||||
|
||||
### Text Colors
|
||||
| Name | Hex | Role |
|
||||
|---|---|---|
|
||||
| **Cloud** | `#dfe2eb` | Primary text; body copy, data values, headings |
|
||||
| **Mist** | `#c7c4d7` | Secondary / muted text; labels, metadata |
|
||||
| **Ghost** | `#908fa0` | Placeholder text, disabled states, divider fill |
|
||||
| **Boundary** | `#464554` | Ghost border fallback for inputs (used at low opacity) |
|
||||
|
||||
---
|
||||
|
||||
## 3. Typography Rules
|
||||
|
||||
**Single font family throughout: Inter** (geometric sans-serif). Used for headlines, body, and labels alike — unity is achieved through weight and tracking variation rather than font switching.
|
||||
|
||||
| Level | Size | Weight | Tracking | Usage |
|
||||
|---|---|---|---|---|
|
||||
| **Display** | 56px / 3.5rem | Bold (700) | Tight (negative) | Hero KPI metrics, total counts |
|
||||
| **Headline** | 24px / 1.5rem | SemiBold (600) | Normal | Page titles, major section headings |
|
||||
| **Title** | 16px / 1.0rem | Medium (500) | Normal | Card titles, module headers, tab labels |
|
||||
| **Body** | 14px / 0.875rem | Regular (400) | Normal | Default text, table rows, descriptions |
|
||||
| **Label** | 11px / 0.6875rem | SemiBold (600) | Wide (+0.1em) | Sidebar category headers, metadata chips — All Caps |
|
||||
|
||||
**The Editorial Rule:** Sidebar category headers use the Label style in all-caps with wide letter-spacing (+0.1em). This creates a "system-level" authority that contrasts with fluid body text and signals structural navigation. Body text must never be all-caps.
|
||||
|
||||
---
|
||||
|
||||
## 4. Component Stylings
|
||||
|
||||
### Buttons
|
||||
- **Primary CTA:** Gradient fill from Indigo Glow (`#c0c1ff`) to Violet Pulse (`#d2bbff`). White text. Softly rounded corners (matching `lg` radius — just barely rounded, not pill). On hover, a high-glow indigo shadow emanates beneath the button.
|
||||
- **Secondary / Outline:** Island background (`#31353c`) with an extremely faint ghost border — outline-variant (`#464554`) at 20–30% opacity. Mist text (`#c7c4d7`).
|
||||
- **Tertiary / Ghost:** Fully transparent background. Mist text. On hover: Cloud text with elevated background tint.
|
||||
- **Destructive:** Coral Error text (`#ffb4ab`) on a Crimson container (`#93000a` at low opacity). Used for delete and irreversible actions. Never bright red.
|
||||
|
||||
### Cards & Containers
|
||||
- **Default Card:** Deep Slate background (`#1c2026`). No visible border — separation is purely tonal. Features a **subtle top-edge inner glow**: `inset 0px 1px 0px rgba(192, 193, 255, 0.05)` — mimics a ceiling light reflecting off the card's glass surface.
|
||||
- **Corner Rounding:** Minimal — just enough to soften, not enough to feel playful. Approximately 4px (the `lg` token = 0.25rem). Cards feel rectangular and purposeful, not bubbly.
|
||||
- **Elevation principle:** No drop shadows on standard cards. Hierarchy comes from the surface color step (Void Navy → Deep Slate → Elevated Slate).
|
||||
- **Floating Modals / Dropdowns:** Frosted Glass background (`rgba(53, 57, 64, 0.8)`) with `backdrop-filter: blur(12px)`. This "Glassmorphism" effect keeps the user contextually anchored to the underlying page while the modal floats above. Shadow: `0px 8px 24px rgba(13, 17, 23, 0.6)` — navy-tinted, never pure black.
|
||||
|
||||
### Inputs & Forms
|
||||
- **Default state:** Deep Slate background. Ghost border at very low opacity (near invisible). Text in Cloud color.
|
||||
- **Focus state:** Indigo Glow (`#c0c1ff`) border at 40% alpha creates a soft halo glow — not a hard ring. The inner glow on the input also subtly strengthens.
|
||||
- **Placeholder text:** Ghost color (`#908fa0`).
|
||||
- **Select / Dropdown:** Same surface as inputs; opens as a Frosted Glass panel with blur.
|
||||
- **No hard outlines at rest** — inputs feel embedded in the surface until interacted with.
|
||||
|
||||
### Status Badges
|
||||
- **Shape:** Fully pill-shaped (maximum border-radius / `full` = 0.75rem).
|
||||
- **Style:** Functional color (Emerald, Amber, Coral) at approximately 15% background opacity, with the same color at full 100% opacity for the label text. Creates a "glowing ink" effect — the badge appears illuminated from within.
|
||||
- **Examples:** Online → soft emerald glow; Warning → soft amber glow; Error/Offline → soft coral glow.
|
||||
|
||||
### Navigation Sidebar (224px wide)
|
||||
- **Background:** Void Navy (`#181c22`) — one step lighter than the main viewport.
|
||||
- **Active item indicator:** A `3px` vertical bar on the far-left edge using Indigo Glow (`#c0c1ff`). The text weight also increases slightly. No background highlight on active items — the light bar IS the indicator.
|
||||
- **Inactive items:** Mist text (`#c7c4d7`) at normal weight.
|
||||
- **Category headers:** Label-style — all-caps, 11px, SemiBold, wide tracking. Ghost color (`#908fa0`).
|
||||
- **Item padding:** Comfortable vertical padding (~9.6px / 0.6rem) for breathing room between items.
|
||||
- **No dividers** between nav sections — spacing does the work.
|
||||
|
||||
### Data Tables
|
||||
- **Row separation:** No horizontal dividers. Alternating subtle tonal rows (Island `#31353c` on hover) and consistent vertical gap rhythm.
|
||||
- **Header row:** Mist text (`#c7c4d7`), Label-style capitalization, slightly smaller than body.
|
||||
- **Hovered row:** Elevated Slate (`#262a31`) or Island (`#31353c`) background.
|
||||
- **Selected row:** Island background with Indigo Glow left border accent.
|
||||
|
||||
### Scrollbars
|
||||
- Slim — 4px wide track.
|
||||
- Thumb: Boundary color (`#464554`), with 2px border-radius.
|
||||
- Track: Transparent.
|
||||
- Overall feel: Nearly invisible unless sought out.
|
||||
|
||||
---
|
||||
|
||||
## 5. Layout Principles
|
||||
|
||||
**Whitespace is structure.** The design never uses lines or dividers to separate sections — space does that job. When content feels disconnected, the solution is always to add vertical breathing room, never to draw a border.
|
||||
|
||||
- **Page content area:** Fills the viewport to the right of the 224px sidebar. Padding inside the content area is generous — approximately 24–32px on all sides.
|
||||
- **Section spacing:** Major sections within a page are separated by approximately 24px of vertical space. Sub-sections by 16px.
|
||||
- **Card grid:** Cards sit in fluid grids with 16px gaps. Cards never touch each other.
|
||||
- **Alignment:** Strong left-edge alignment for all content. Data tables, card headers, and page titles all share the same left origin point.
|
||||
- **No horizontal rules / `<hr>` elements:** Surface color transitions and whitespace define the visual structure entirely.
|
||||
- **Modals:** Centered in the viewport, overlaid on a dark scrim. The page content behind is still readable through the frosted glass effect, maintaining spatial context.
|
||||
- **The "No Raw Border" rule:** Any element requiring a visible boundary for accessibility (e.g., an active input) must use the ghost border approach — Boundary color (`#464554`) at 20% opacity maximum. Full-opacity borders are strictly prohibited.
|
||||
- **Mobile / responsive:** The sidebar collapses to a drawer on narrow viewports. Cards reflow to single-column. The design's depth relies on background layers, so it translates naturally to smaller screens.
|
||||
@@ -0,0 +1,429 @@
|
||||
# CLAUDE.md — BellSystems Control Panel v2
|
||||
# Instructions for Claude Code
|
||||
|
||||
> Read this file at the start of every session.
|
||||
> This is the v2 project — a clean rebuild. The old v1 code lives in `frontend/src/_archive/` for reference only.
|
||||
> Also read `DESIGN.md` before writing any UI code.
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
C:\development\bellsystems-cp-v2\
|
||||
│ CLAUDE.md ← you are here
|
||||
│ DESIGN.md ← design rules, component contracts, page layout spec
|
||||
│ docker-compose.yml
|
||||
│
|
||||
├── backend/ ← FastAPI backend — DO NOT MODIFY
|
||||
│
|
||||
└── frontend/
|
||||
├── src/
|
||||
│ ├── _archive/ ← v1 reference code — READ ONLY, never import from here except auth
|
||||
│ ├── assets/
|
||||
│ │ ├── global-icons/ ← action SVGs (edit, delete, download, etc.)
|
||||
│ │ ├── side-menu-icons/ ← sidebar navigation SVGs
|
||||
│ │ ├── comms/ ← communication type SVGs
|
||||
│ │ ├── other-icons/ ← misc SVGs
|
||||
│ │ └── customer-status/ ← CRM status SVGs
|
||||
│ ├── components/
|
||||
│ │ ├── ui/ ← design system components (the ONLY place to source UI)
|
||||
│ │ ├── layout/ ← Sidebar, Header, MainLayout
|
||||
│ │ └── shared/
|
||||
│ ├── hooks/
|
||||
│ ├── lib/
|
||||
│ ├── modals/ ← all modal components live here, grouped by domain
|
||||
│ ├── pages/ ← one file per page, grouped by domain
|
||||
│ ├── providers/
|
||||
│ ├── router/
|
||||
│ │ └── index.jsx ← all routes defined here
|
||||
│ ├── styles/
|
||||
│ │ ├── tokens.css ← ALL design tokens (colors, fonts, spacing, shadows)
|
||||
│ │ ├── components.css ← ALL component-level styles
|
||||
│ │ └── global.css ← base resets, typography, scrollbar, .page-wrapper
|
||||
│ └── main.jsx ← app entry point
|
||||
└── vite.config.js
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Project Overview
|
||||
|
||||
Bespoke SaaS Admin Console for BellSystems. Manages Devices, Customers (CRM),
|
||||
Manufacturing, Firmware, MQTT, Melodies, Staff, and more.
|
||||
|
||||
- **Backend:** FastAPI at `backend/` — never modify
|
||||
- **Archive:** `frontend/src/_archive/` — v1 reference, read-only
|
||||
- **Active code:** `frontend/src/` (everything except `_archive/`)
|
||||
- **Design rules:** `DESIGN.md` at project root — read before writing any UI
|
||||
- **Style Guide:** live at `/dev/styleguide` — shows every component with every variant
|
||||
- **API client:** `frontend/src/lib/api.js` wraps `_archive/api/client.js`
|
||||
|
||||
---
|
||||
|
||||
## Import Alias
|
||||
|
||||
`@/` maps to `frontend/src/`:
|
||||
|
||||
```js
|
||||
import Button from '@/components/ui/Button' ✅
|
||||
import Select from '@/components/ui/Select' ✅
|
||||
import { useAuth } from '@/hooks/useAuth' ✅
|
||||
import MainLayout from '@/components/layout/MainLayout' ✅
|
||||
```
|
||||
|
||||
Never use relative `../` paths except inside `providers/` and `hooks/` when referencing `_archive/`.
|
||||
|
||||
---
|
||||
|
||||
## The Golden Rules
|
||||
|
||||
- **Never modify `_archive/`** — it is read-only reference material
|
||||
- **All new code goes in `frontend/src/`** — no exceptions
|
||||
- **No `/v2/` prefix anywhere** — routes start from `/`, imports start from `@/`
|
||||
- **Read `DESIGN.md` before writing any UI code**
|
||||
- **Source every UI element from `@/components/ui/`** — no raw HTML elements for styled things
|
||||
- **Use only CSS tokens** — never raw hex, rgb, or pixel values in component or page files
|
||||
- **Use `.masonry-grid` for all content pages with multiple variable-height sections** — never `display: grid` with fixed columns for card layouts. See DESIGN.md §11.
|
||||
- **Every change, major or minor, must be documented and committed** — see "Documentation & Commit Policy" below.
|
||||
|
||||
---
|
||||
|
||||
## Available UI Components
|
||||
|
||||
Every component lives in `frontend/src/components/ui/`. These are the ONLY components to use.
|
||||
Check the live Style Guide at `/dev/styleguide` to see all variants and states.
|
||||
|
||||
| Component | Import path | Purpose |
|
||||
|-----------------|--------------------------------------|----------------------------------------------|
|
||||
| `Button` | `@/components/ui/Button` | All interactive actions |
|
||||
| `StatusBadge` | `@/components/ui/StatusBadge` | Coloured status pills |
|
||||
| `FormField` | `@/components/ui/FormField` | Every text/email/password/textarea input |
|
||||
| `Select` | `@/components/ui/Select` | Custom dropdown (used inside FormField type="select") |
|
||||
| `MultiSelect` | `@/components/ui/MultiSelect` | Checkbox dropdown for selecting multiple values (filters, tags) |
|
||||
| `Modal` | `@/components/ui/Modal` | All overlay dialogs |
|
||||
| `ConfirmDialog` | `@/components/ui/ConfirmDialog` | Destructive / confirmation prompts |
|
||||
| `DataTable` | `@/components/ui/DataTable` | All tabular data with sorting/selection |
|
||||
| `Pagination` | `@/components/ui/Pagination` | Page controls beneath DataTable |
|
||||
| `Spinner` | `@/components/ui/Spinner` | Loading indicators |
|
||||
| `PageHeader` | `@/components/ui/PageHeader` | Page title block — every page starts with this |
|
||||
| `Card` | `@/components/ui/Card` | Contained content sections |
|
||||
| `Tabs` | `@/components/ui/Tabs` | Tabbed navigation within a page |
|
||||
| `Toast` | `@/components/ui/Toast` | Transient notifications (via `useToast`) |
|
||||
| `SearchBar` | `@/components/ui/SearchBar` | Search inputs with debounce |
|
||||
| `Breadcrumbs` | `@/components/ui/Breadcrumbs` | Navigation trail on detail pages |
|
||||
| `Icon` | `@/components/ui/Icon` | Inline SVG icons by name |
|
||||
|
||||
---
|
||||
|
||||
## Folder Structure — Pages & Modals
|
||||
|
||||
Folders mirror the sidebar section hierarchy exactly.
|
||||
|
||||
```
|
||||
frontend/src/pages/
|
||||
├── auth/ ← unauthenticated routes (login)
|
||||
├── dashboard/ ← General section
|
||||
├── bellcloud/ ← Bell Cloud section
|
||||
│ ├── devices/
|
||||
│ │ └── notes/
|
||||
│ ├── users/
|
||||
│ ├── melodies/
|
||||
│ │ └── archetypes/
|
||||
│ └── mqtt/
|
||||
├── crm/ ← Headquarters section
|
||||
│ ├── comms/
|
||||
│ │ └── mail/
|
||||
│ ├── customers/
|
||||
│ │ └── tabs/
|
||||
│ ├── orders/
|
||||
│ ├── quotations/
|
||||
│ └── products/
|
||||
├── engineering/ ← Engineering section
|
||||
│ ├── manufacturing/
|
||||
│ ├── firmware/
|
||||
│ └── developer/
|
||||
├── public/ ← Public / unauthenticated pages
|
||||
│ ├── cloudflash/
|
||||
│ └── serial/
|
||||
├── settings/ ← Console Settings section
|
||||
│ └── staff/
|
||||
└── dev/ ← Internal dev tools (StyleGuide)
|
||||
```
|
||||
|
||||
```
|
||||
frontend/src/modals/
|
||||
├── bellcloud/
|
||||
│ ├── devices/
|
||||
│ ├── melodies/
|
||||
│ └── users/
|
||||
├── crm/
|
||||
│ └── products/
|
||||
├── engineering/
|
||||
│ └── manufacturing/
|
||||
└── shared/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Page Layout — How Every Page Is Structured
|
||||
|
||||
Every authenticated page is rendered inside `MainLayout`, which provides:
|
||||
- **Sidebar** — fixed left, `224px` wide (`--sidebar-width`)
|
||||
- **Header** — fixed top, `56px` tall (`--header-height`)
|
||||
- **Content area** — the remaining viewport space
|
||||
|
||||
Inside the content area, every page uses the `.page-wrapper` class (defined in `global.css`):
|
||||
|
||||
```css
|
||||
.page-wrapper {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: var(--space-12); /* 48px on all sides — desktop */
|
||||
gap: var(--space-6); /* 24px between top-level sections */
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.page-wrapper {
|
||||
padding: var(--space-8); /* 32px on mobile */
|
||||
gap: var(--space-4);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**This is the consistency guarantee**: because every page uses `.page-wrapper`, the `<PageHeader>` title on every page starts at exactly the same position — 48px from the top and 48px from the left edge of the content area. Never override these paddings. Never add extra wrappers around `page-wrapper` that introduce additional offset.
|
||||
|
||||
### Content width modes
|
||||
|
||||
Pages fall into two modes — choose based on how much content the page has:
|
||||
|
||||
**Full-width** (default — lists, tables, dashboards):
|
||||
```jsx
|
||||
<div className="page-wrapper">
|
||||
```
|
||||
|
||||
**Centered** (forms, settings, pages with very few items):
|
||||
```jsx
|
||||
<div className="page-wrapper page-wrapper--centered">
|
||||
```
|
||||
Centered mode caps each direct child at `--content-max-width-sm` (640px) by default and centers it horizontally. Override when needed:
|
||||
```jsx
|
||||
<div className="page-wrapper page-wrapper--centered"
|
||||
style={{ '--page-content-max-width': 'var(--content-max-width-md)' }}>
|
||||
```
|
||||
Available tokens: `--content-max-width-xs` (480px), `--content-max-width-sm` (640px), `--content-max-width-md` (800px), `--content-max-width-lg` (1024px).
|
||||
|
||||
---
|
||||
|
||||
## Rules for Every Page
|
||||
|
||||
### Before writing any code
|
||||
1. Read `DESIGN.md` — confirm tokens and components to use
|
||||
2. Check `frontend/src/components/ui/` — use existing components only
|
||||
3. Check the Style Guide at `/dev/styleguide` for the correct variant/props
|
||||
4. Check `frontend/src/_archive/` for the equivalent v1 page — copy API calls and data shape only, never styling
|
||||
|
||||
### Page template
|
||||
|
||||
```jsx
|
||||
// frontend/src/pages/[domain]/PageName.jsx
|
||||
|
||||
import PageHeader from '@/components/ui/PageHeader'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
// Import ONLY from @/components/ui/ — never raw HTML elements for styled things
|
||||
|
||||
export default function PageName() {
|
||||
// 1. Auth
|
||||
const { user } = useAuth()
|
||||
|
||||
// 2. State & data fetching
|
||||
|
||||
// 3. Event handlers
|
||||
|
||||
// 4. Render — always handle: loading, error, empty, data states
|
||||
return (
|
||||
<div className="page-wrapper">
|
||||
<PageHeader title="Page Title" subtitle="Optional description">
|
||||
{/* Action buttons — use <Button variant="primary"> etc. */}
|
||||
</PageHeader>
|
||||
|
||||
{/* Page content — use Card, DataTable, Tabs, etc. */}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Styling rules
|
||||
- **Tailwind** for layout only: `flex`, `grid`, `items-center`, `min-w-0`, etc.
|
||||
- **CSS token variables** for ALL colors, spacing, typography — `var(--token-name)`
|
||||
- **No** `.module.css` or per-page scoped CSS files
|
||||
- **No** `style={{ }}` inline styles except for genuinely dynamic values (e.g. calculated widths)
|
||||
- **No** raw hex, rgb, or pixel values anywhere
|
||||
|
||||
### Toolbar buttons — matching SearchBar height
|
||||
|
||||
`.btn` has `line-height: 1` while `.searchbar-input` has `line-height: var(--line-height-base)` (1.5). This makes buttons shorter than the search bar by default. Whenever a `<Button>`, `<SegmentedControl>`, or `<IconButtonGroup>` sits in the same toolbar row as a `<SearchBar>`, all buttons must use `padding-top/bottom: var(--space-3)` and `line-height: var(--line-height-base)`.
|
||||
|
||||
**Already handled automatically (no extra props needed):**
|
||||
- `SegmentedControl` — `.seg-ctrl__btn` in `components.css` enforces `--space-3` padding and `var(--line-height-base)` globally.
|
||||
- `IconButtonGroup` — `.icon-btn-group__btn` in `components.css` enforces `--space-3` padding globally.
|
||||
|
||||
**Must be overridden manually — standalone `<Button>` in the same row as a `<SearchBar>`:**
|
||||
|
||||
```jsx
|
||||
// Option A — inline style prop on the button:
|
||||
<Button
|
||||
size="md"
|
||||
style={{ paddingTop: 'var(--space-3)', paddingBottom: 'var(--space-3)', lineHeight: 'var(--line-height-base)' }}
|
||||
>
|
||||
Label
|
||||
</Button>
|
||||
|
||||
// Option B (preferred when multiple buttons share a toolbar) — scoped CSS block:
|
||||
<>
|
||||
<style>{`
|
||||
.my-toolbar .btn {
|
||||
padding-top: var(--space-3) !important;
|
||||
padding-bottom: var(--space-3) !important;
|
||||
line-height: var(--line-height-base) !important;
|
||||
}
|
||||
`}</style>
|
||||
<div className="my-toolbar" style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
|
||||
<IconButtonGroup … />
|
||||
<Button variant="primary" size="md">Compose</Button>
|
||||
</div>
|
||||
</>
|
||||
```
|
||||
|
||||
### Date & time formatting
|
||||
- **Greek/European date style everywhere** — DD/MM/YYYY, never US-style MM/DD/YYYY
|
||||
- **All date/time formatting must use `@/lib/formatters`** — never use raw `toLocaleDateString()`, `Intl.DateTimeFormat`, `toLocaleString()`, or `toISOString().slice()` in pages or modals
|
||||
- **For `datetime-local` input values** — use `toDatetimeLocal(iso)` and `nowLocal()` from formatters. Never use `new Date(x).toISOString().slice(0, 16)` — it converts to UTC and shifts the time (timezone bug)
|
||||
- **Currency** — use `fmtEuro(n)` from formatters (Greek locale: `1.250,00 €`)
|
||||
|
||||
Available formatters (`import { ... } from '@/lib/formatters'`):
|
||||
|
||||
| Function | Output example | Use for |
|
||||
|---------------------|------------------------------------|--------------------------------------|
|
||||
| `fmtDate` | `05/03/2026` | Short numeric dates (tables, lists) |
|
||||
| `fmtDateMedium` | `5 Mar 2026` | Medium dates (cards, details) |
|
||||
| `fmtDateLong` | `5 March 2026` | Long dates (headings, summaries) |
|
||||
| `fmtDateFull` | `Wednesday, 5 March 2026` | Dashboard, full context |
|
||||
| `fmtDateTime` | `5 March 2026, 2:30 pm` | Date + 12h time |
|
||||
| `fmtDateTimeMedium` | `5 Mar 2026, 14:30` | Date + 24h time (compact) |
|
||||
| `fmtDateTimeFull` | `Wed, 5 Mar 2026, 2:30 pm` | Emails, comms |
|
||||
| `fmtTime24` | `14:30:05` | Time with seconds |
|
||||
| `fmtRelative` | `5 minutes ago` | Relative timestamps |
|
||||
| `toDatetimeLocal` | `2026-03-05T14:30` | `datetime-local` input values |
|
||||
| `nowLocal` | `2026-03-05T14:30` | Current time for form defaults |
|
||||
| `toDateInput` | `2026-03-05` | `date` input values |
|
||||
| `fmtEuro` | `1.250,00 €` | Euro currency |
|
||||
|
||||
### Data fetching
|
||||
- Use `frontend/src/lib/api.js` (wraps `_archive/api/client.js`)
|
||||
- Every data-fetching component must handle **loading**, **error**, and **empty** states
|
||||
|
||||
### Modals
|
||||
- Never defined inside page files
|
||||
- Live in `frontend/src/modals/[sidebar-section]/[domain]/ModalName.jsx` — mirror the pages folder structure
|
||||
- Pass data via props, actions via callbacks
|
||||
|
||||
---
|
||||
|
||||
## Missing Components — Stop and Ask
|
||||
|
||||
If building a page requires a UI component that does not exist in
|
||||
frontend/src/components/ui/, Claude Code must STOP and say:
|
||||
|
||||
"I need a [ComponentName] component which doesn't exist yet.
|
||||
Please build it and add it to the StyleGuide before I continue."
|
||||
|
||||
Do NOT:
|
||||
- Invent an inline one-off component inside a page file
|
||||
- Use raw HTML elements styled with inline CSS as a substitute
|
||||
- Proceed and leave a placeholder
|
||||
|
||||
The StyleGuide at frontend/src/pages/dev/StyleGuide.jsx is the source
|
||||
of truth for what components exist and how they look. Every component
|
||||
used in a page must have a visible example there first.
|
||||
|
||||
## Building a New Page — Checklist
|
||||
|
||||
- [ ] File in correct `frontend/src/pages/[domain]/` folder
|
||||
- [ ] Root element is `<div className="page-wrapper">` — nothing else, nothing wrapping it
|
||||
- [ ] First child inside `page-wrapper` is `<PageHeader title="...">`
|
||||
- [ ] Only components from `frontend/src/components/ui/` used
|
||||
- [ ] No raw hex colors or pixel spacing values anywhere
|
||||
- [ ] Loading state implemented
|
||||
- [ ] Error state implemented
|
||||
- [ ] Empty state implemented
|
||||
- [ ] Mobile responsive (375px minimum)
|
||||
- [ ] Modals in `frontend/src/modals/`
|
||||
- [ ] Route added to `frontend/src/router/index.jsx`
|
||||
|
||||
---
|
||||
|
||||
## MQTT Auth (devices + phone-app users)
|
||||
|
||||
Read `docs/mqtt-app-user-auth.md` before touching `backend/mqtt/auth.py`,
|
||||
`backend/mqtt/app_users.py`, or any code that changes a device's `user_list` or a
|
||||
user's `status`. Any code that edits `user_list` must also update the user's
|
||||
`device_serials` in the same batch and invalidate the MQTT ACL cache, or app users
|
||||
lose (or keep) access to the wrong devices.
|
||||
|
||||
---
|
||||
|
||||
## Firestore Schema v1 (devices)
|
||||
|
||||
The tablet and phone apps (FlutterFlow) and this console share Firestore. The contract
|
||||
is the `bellsystems-schema` repo (`C:\development\bellsystems-schema`, `v1/firestore.schema.json`).
|
||||
One wrongly typed field makes the apps **silently drop the whole device** from the user's list.
|
||||
|
||||
- Every device write goes through `backend/devices/firestore_v1.py` (`to_firestore`), every
|
||||
read through `to_api`. Never write a device dict to Firestore any other way.
|
||||
- Timestamps: ISO 8601 strings in the API, Firestore Timestamps in the DB. Unset = `null`, never `""`.
|
||||
- IP addresses: dotted strings (`"10.0.0.5"`), never octet arrays. The firmware's
|
||||
`network.set_config` MQTT command has its own names (`useStaticIP`, `ip`) — that's the
|
||||
MQTT protocol, not Firestore.
|
||||
- Key spelling is the apps': `bellguardSafetyOn`, `usesStaticIP`, `maintainancePeriod`.
|
||||
- `device_id` and `serial_number` are always equal (decision D1); `serial_number` is canonical.
|
||||
- Hardware identity is `hw_family` / `hw_revision` — the firmware's NVS names (decision D2).
|
||||
`hw_family` is a code (`vesper_plus`), never a label (`"Bell Plus"`). The firmware *catalog*
|
||||
(`/api/firmware/{hw_type}/…`, flash assets) keeps `hw_type` as its variable name — same values.
|
||||
- Check live data with `node tools/audit.js <service-account.json>` in the schema repo.
|
||||
|
||||
---
|
||||
|
||||
## API Client
|
||||
|
||||
```js
|
||||
// frontend/src/lib/api.js
|
||||
export { default } from '../_archive/api/client'
|
||||
```
|
||||
|
||||
All pages import from `@/lib/api`, never directly from `_archive`.
|
||||
|
||||
---
|
||||
|
||||
## Auth
|
||||
|
||||
`frontend/src/hooks/useAuth.js` re-exports from the archive AuthContext.
|
||||
`frontend/src/providers/AuthProvider.jsx` re-exports the AuthProvider.
|
||||
|
||||
These are the ONLY two files permitted to import from `_archive/auth/`.
|
||||
All other files use `@/hooks/useAuth`.
|
||||
|
||||
---
|
||||
|
||||
## Documentation & Commit Policy
|
||||
|
||||
**Every change to this project — major or minor — must be documented and committed.** This is how we keep a record of what happened over time. Uncommitted or undocumented work is effectively invisible to future sessions.
|
||||
|
||||
- **Commit every change**, no matter how small (a copy tweak, a token rename, a bug fix, a new page). Do not batch unrelated work silently into "cleanup later" — if it changed, commit it.
|
||||
- **Write descriptive commit messages** that explain *why*, not just *what* — future sessions rely on `git log` to reconstruct project history since this isn't otherwise tracked elsewhere.
|
||||
- **Never leave work uncommitted** at the end of a session/task unless the user explicitly says to hold off.
|
||||
- Follow the repo's existing commit message conventions (see recent `git log` for style/format).
|
||||
- If a change is large enough to warrant explanation beyond the commit message (a new module, a non-obvious fix, a schema/API change), note the reasoning in the commit body — don't rely on memory or chat history to preserve it.
|
||||
- This applies to backend, frontend, and config changes alike — even though `backend/` and `_archive/` are off-limits to modify directly in most cases, any change made anywhere in the repo still follows this same commit discipline.
|
||||
@@ -0,0 +1,627 @@
|
||||
# DESIGN SYSTEM — BellSystems Control Panel v2
|
||||
|
||||
> Single source of truth for all UI/UX decisions.
|
||||
> Read before writing any page, component, or modal.
|
||||
> Never override these rules inline. Change the rule here first, then propagate.
|
||||
>
|
||||
> Live reference: `/dev/styleguide` — every component, every variant, every state.
|
||||
|
||||
---
|
||||
|
||||
## 1. Core Philosophy
|
||||
|
||||
- **Consistency over creativity.** Every page must feel like it belongs to the same product.
|
||||
- **Tokens over hardcoded values.** Never write a raw color, spacing value, or font size. Always `var(--token)`.
|
||||
- **Components over repetition.** If you write the same pattern twice, it becomes a shared component.
|
||||
- **Page layout is global.** All pages share the same padding and spacing anchors. Content always starts at the same position.
|
||||
- **Accessible by default.** ARIA labels, keyboard navigation, visible focus states on all interactive elements.
|
||||
|
||||
---
|
||||
|
||||
## 2. Page Layout Anatomy
|
||||
|
||||
Every authenticated page lives inside `MainLayout`, which provides:
|
||||
|
||||
```
|
||||
┌─────────────┬────────────────────────────────────────────┐
|
||||
│ │ HEADER (height: 56px / --header-height) │
|
||||
│ │────────────────────────────────────────────┤
|
||||
│ │ │
|
||||
│ SIDEBAR │ CONTENT AREA │
|
||||
│ (224px / │ ┌──────────────────────────────────────┐ │
|
||||
│ --sidebar- │ │ .page-wrapper │ │
|
||||
│ width) │ │ padding: 48px (--space-12) │ │
|
||||
│ │ │ gap: 24px between sections │ │
|
||||
│ │ │ │ │
|
||||
│ │ │ <PageHeader> ← always first │ │
|
||||
│ │ │ <content...> │ │
|
||||
│ │ └──────────────────────────────────────┘ │
|
||||
└─────────────┴────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### The consistency guarantee
|
||||
|
||||
`.page-wrapper` is defined once in `global.css`. It is the only wrapper used on every page:
|
||||
|
||||
```css
|
||||
.page-wrapper {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: var(--space-12); /* 48px — desktop */
|
||||
gap: var(--space-6); /* 24px between direct children */
|
||||
min-width: 0;
|
||||
}
|
||||
/* Mobile: padding drops to --space-8 (32px), gap to --space-4 (16px) */
|
||||
```
|
||||
|
||||
**Rules:**
|
||||
- Every page's root element is `<div className="page-wrapper">` — no exceptions
|
||||
- Never add extra padding, margin, or wrapper divs that shift content relative to `.page-wrapper`
|
||||
- Never override `.page-wrapper` padding per-page
|
||||
- The `<PageHeader>` is always the first child inside `.page-wrapper`
|
||||
- This ensures that on every page, the title starts at exactly 48px from the top-left corner of the content area
|
||||
|
||||
### Content width modes
|
||||
|
||||
Every page falls into one of two modes:
|
||||
|
||||
#### 1. Full-width (default)
|
||||
Content expands to fill the entire available area. Use this for all data-heavy pages: lists, tables, dashboards, detail views.
|
||||
|
||||
```jsx
|
||||
<div className="page-wrapper">
|
||||
{/* content fills the full content area */}
|
||||
</div>
|
||||
```
|
||||
|
||||
#### 2. Centered (narrow content)
|
||||
For pages with a small number of elements that would look lost spanning the full viewport — e.g. settings forms, auth pages, single-entity configuration screens.
|
||||
|
||||
```jsx
|
||||
<div className="page-wrapper page-wrapper--centered">
|
||||
{/* every direct child is capped at --content-max-width-sm (640px) and centered */}
|
||||
</div>
|
||||
```
|
||||
|
||||
Default max-width is `--content-max-width-sm` (640px). Override per-page only when necessary:
|
||||
|
||||
```jsx
|
||||
<div
|
||||
className="page-wrapper page-wrapper--centered"
|
||||
style={{ '--page-content-max-width': 'var(--content-max-width-md)' }}
|
||||
>
|
||||
```
|
||||
|
||||
Available width tokens:
|
||||
|
||||
| Token | Value | Use |
|
||||
|-----------------------------|--------|-----------------------------------------|
|
||||
| `--content-max-width-xs` | 480px | Tiny forms, login, auth |
|
||||
| `--content-max-width-sm` | 640px | Small forms, simple settings (default) |
|
||||
| `--content-max-width-md` | 800px | Medium forms, detail-light pages |
|
||||
| `--content-max-width-lg` | 1024px | Moderate-width constrained pages |
|
||||
|
||||
**Rules:**
|
||||
- Never use `page-wrapper--centered` on a list page, data table page, or any page where content should grow with the viewport
|
||||
- Never hardcode a pixel `max-width` in a page file — always use a token
|
||||
|
||||
---
|
||||
|
||||
## 3. Color Tokens
|
||||
|
||||
All colors are CSS custom properties defined in `frontend/src/styles/tokens.css`.
|
||||
The system is **dark-first**: `:root` = dark theme. `[data-theme="light"]` overrides exist as a placeholder.
|
||||
|
||||
### Rule: never write a raw color value in any component or page file. Always `var(--token)`.
|
||||
|
||||
### Background Surfaces (7-step tonal ladder)
|
||||
|
||||
| Token | Value | Use |
|
||||
|------------------------|--------------|--------------------------------------------------------|
|
||||
| `--color-bg-abyss` | `#0a0e14` | Deepest well: code blocks, input backgrounds |
|
||||
| `--color-bg-base` | `#10141a` | Page background (viewport fill) |
|
||||
| `--color-bg-void` | `#181c22` | Sidebar, header |
|
||||
| `--color-bg-surface` | `#1c2026` | Default card / panel background |
|
||||
| `--color-bg-elevated` | `#262a31` | Raised cards, hovered rows, dropdowns |
|
||||
| `--color-bg-island` | `#31353c` | Active states, selected rows, pressed buttons |
|
||||
| `--color-bg-float` | `rgba(53,57,64,0.80)` | Glassmorphism: modals, floating panels |
|
||||
|
||||
### Brand / Primary (Indigo Glow)
|
||||
|
||||
| Token | Value | Use |
|
||||
|----------------------------|------------------------------|--------------------------------------|
|
||||
| `--color-primary` | `#c0c1ff` | CTAs, active nav, key accent |
|
||||
| `--color-primary-hover` | `#d2bbff` | Hover, gradient endpoint |
|
||||
| `--color-primary-container`| `#8083ff` | Container fills |
|
||||
| `--color-primary-subtle` | `rgba(128,131,255,0.12)` | Hover backgrounds, tinted areas |
|
||||
| `--gradient-primary` | `linear-gradient(135deg, #c0c1ff, #d2bbff)` | Primary button fill |
|
||||
|
||||
### Semantic / State Colors
|
||||
|
||||
| Token | Value | Use |
|
||||
|------------------------|---------------------------|------------------------------------------------|
|
||||
| `--color-success` | `#4ade80` | Online, active, confirmed |
|
||||
| `--color-success-bg` | `rgba(74,222,128,0.12)` | Success badge / button resting background |
|
||||
| `--color-warning` | `#fbbf24` | Pending, needs attention |
|
||||
| `--color-warning-bg` | `rgba(251,191,36,0.12)` | Warning badge / button resting background |
|
||||
| `--color-danger` | `#ff5c5c` | Error text, destructive actions |
|
||||
| `--color-danger-bg` | `rgba(255,92,92,0.12)` | Danger badge / button resting background |
|
||||
| `--color-info` | `#7bd0ff` | Informational, aqua-sky accent |
|
||||
| `--color-info-bg` | `rgba(123,208,255,0.12)` | Info badge background |
|
||||
|
||||
### Text Colors (4-step hierarchy)
|
||||
|
||||
| Token | Value | Use |
|
||||
|---------------------------|-------------|---------------------------------------------------|
|
||||
| `--color-text-primary` | `#dfe2eb` | Body copy, data values, headings |
|
||||
| `--color-text-secondary` | `#c7c4d7` | Labels, metadata, inactive nav |
|
||||
| `--color-text-muted` | `#908fa0` | Placeholders, disabled, category headers |
|
||||
| `--color-text-inverse` | `#10141a` | Text on primary/accent backgrounds (dark on light)|
|
||||
| `--color-text-accent` | `#c0c1ff` | Active nav items, links |
|
||||
|
||||
### Borders
|
||||
|
||||
| Token | Value | Use |
|
||||
|-------------------------|----------------------------|--------------------------------------------|
|
||||
| `--color-border` | `rgba(70,69,84,0.20)` | Resting inputs, card outlines |
|
||||
| `--color-border-strong` | `rgba(70,69,84,0.45)` | Secondary buttons, stronger dividers |
|
||||
| `--color-border-focus` | `rgba(192,193,255,0.40)` | Focus ring halo on inputs |
|
||||
|
||||
---
|
||||
|
||||
## 4. Typography
|
||||
|
||||
Two-font system. Three families total.
|
||||
|
||||
### Font Families
|
||||
|
||||
| Token | Font | Role |
|
||||
|--------------------------|---------------------|---------------------------------------------------|
|
||||
| `--font-family-display` | `Barlow Condensed` | H1, H2, page titles, modal titles |
|
||||
| `--font-family-base` | `Onest` | All UI text, body, labels, buttons, table rows |
|
||||
| `--font-family-mono` | `JetBrains Mono` | Serial numbers, IDs, code, API keys, terminal |
|
||||
|
||||
**Why this pairing:**
|
||||
- `Barlow Condensed` has an industrial/engineering quality — feels like instrument panel labelling. Makes page titles immediately distinctive.
|
||||
- `Onest` is a Ukrainian geometric grotesque with slightly unusual proportions and excellent numerics. Clean at 14px. Not the overused Inter/Space Grotesk.
|
||||
- `JetBrains Mono` is the standard for developer-facing data.
|
||||
|
||||
### Font Sizes
|
||||
|
||||
| Token | Value | Use |
|
||||
|--------------------|------------|----------------------------------------------|
|
||||
| `--font-size-xs` | `0.6875rem` (11px) | Labels, sidebar category headers, chips |
|
||||
| `--font-size-sm` | `0.75rem` (12px) | Captions, helper text, table headers |
|
||||
| `--font-size-base` | `0.875rem` (14px) | Body text, table rows (default) |
|
||||
| `--font-size-md` | `1rem` (16px) | Card titles, module headers |
|
||||
| `--font-size-lg` | `1.125rem` (18px) | Section subheadings |
|
||||
| `--font-size-xl` | `1.5rem` (24px) | Page headings (h1/h2) |
|
||||
| `--font-size-2xl` | `3.5rem` (56px) | Hero KPI numbers, dashboard metrics |
|
||||
|
||||
### Font Weights
|
||||
|
||||
| Token | Value | Use |
|
||||
|---------------------------|-------|----------------------------------------|
|
||||
| `--font-weight-normal` | 400 | Body copy |
|
||||
| `--font-weight-medium` | 500 | Emphasized body, table values |
|
||||
| `--font-weight-semibold` | 600 | Headings, button labels, field labels |
|
||||
| `--font-weight-bold` | 700 | Strong emphasis, hero metrics |
|
||||
|
||||
### Typography Usage Rules
|
||||
|
||||
- **Page titles (`<PageHeader>`):** `Barlow Condensed`, `1.75rem`, weight 600 (handled by `.v2-page-header-title`)
|
||||
- **Modal titles:** `Barlow Condensed`, `1.125rem`, weight 600 (handled by `.v2-modal-title`)
|
||||
- **H1, H2 globally:** `Barlow Condensed`, `var(--font-size-xl)`, weight 600 — set in `global.css`
|
||||
- **H3–H6:** `Onest` (body font), normal heading weights
|
||||
- **Card titles:** `Onest`, `--font-size-base`, weight 600
|
||||
- **Table headers:** `Onest`, `--font-size-sm`, weight 600, uppercase, `--tracking-wide`
|
||||
- **Body / cell text:** `Onest`, `--font-size-base`, weight 400
|
||||
- **Muted / helper text:** `Onest`, `--font-size-sm`, `--color-text-muted`
|
||||
- **Serials, IDs, codes:** `JetBrains Mono`, `--font-size-sm`
|
||||
|
||||
### Letter Spacing
|
||||
|
||||
| Token | Value | Use |
|
||||
|---------------------|-----------|--------------------------------------------|
|
||||
| `--tracking-normal` | `0em` | Default |
|
||||
| `--tracking-tight` | `-0.01em` | Barlow Condensed headings |
|
||||
| `--tracking-wide` | `0.08em` | Uppercase labels, sidebar category headers |
|
||||
| `--tracking-display`| `-0.02em` | Hero KPI numbers at 56px |
|
||||
|
||||
---
|
||||
|
||||
## 4b. Date, Time & Currency Formatting
|
||||
|
||||
All dates use **Greek/European style** (day-first). Never use US-style MM/DD/YYYY anywhere in the app.
|
||||
|
||||
All formatting is centralized in `frontend/src/lib/formatters.js`. Never use raw `toLocaleDateString()`, `Intl.DateTimeFormat`, `toLocaleString()`, or `toISOString().slice()` in pages or modals — always import from `@/lib/formatters`.
|
||||
|
||||
### Available formatters
|
||||
|
||||
| Function | Output example | Use for |
|
||||
|---------------------|------------------------------------|--------------------------------------|
|
||||
| `fmtDate` | `05/03/2026` | Short numeric dates (tables, lists) |
|
||||
| `fmtDateMedium` | `5 Mar 2026` | Medium dates (cards, details) |
|
||||
| `fmtDateLong` | `5 March 2026` | Long dates (headings, summaries) |
|
||||
| `fmtDateFull` | `Wednesday, 5 March 2026` | Dashboard, full context |
|
||||
| `fmtDateTime` | `5 March 2026, 2:30 pm` | Date + 12h time |
|
||||
| `fmtDateTimeMedium` | `5 Mar 2026, 14:30` | Date + 24h time (compact) |
|
||||
| `fmtDateTimeFull` | `Wed, 5 Mar 2026, 2:30 pm` | Emails, comms |
|
||||
| `fmtRelative` | `5 minutes ago` | Relative timestamps |
|
||||
| `fmtEuro` | `1.250,00 €` | Euro currency (Greek locale) |
|
||||
|
||||
### Form input helpers
|
||||
|
||||
| Function | Output example | Use for |
|
||||
|---------------------|-------------------------|--------------------------------------------------|
|
||||
| `toDatetimeLocal` | `2026-03-05T14:30` | Populating `datetime-local` inputs (local time) |
|
||||
| `nowLocal` | `2026-03-05T14:30` | Current time for form defaults |
|
||||
| `toDateInput` | `2026-03-05` | Populating `date` inputs |
|
||||
|
||||
### Critical rule: no `toISOString().slice()` for form inputs
|
||||
|
||||
`toISOString()` converts to **UTC**, which shifts the time by the user's timezone offset (e.g. 3 hours for Greece). Always use `toDatetimeLocal()` or `nowLocal()` instead.
|
||||
|
||||
---
|
||||
|
||||
## 5. Spacing System
|
||||
|
||||
4px base unit. All spacing must use tokens — no arbitrary pixel values.
|
||||
|
||||
| Token | Value | Common use |
|
||||
|--------------|--------|--------------------------------------------------|
|
||||
| `--space-1` | 4px | Tight gaps, icon padding |
|
||||
| `--space-2` | 8px | Between label and input, inline gaps |
|
||||
| `--space-3` | 12px | Table cell padding, compact button padding |
|
||||
| `--space-4` | 16px | Between form fields, mobile page padding |
|
||||
| `--space-5` | 20px | Tab item spacing |
|
||||
| `--space-6` | 24px | **Page padding**, card padding, section gap |
|
||||
| `--space-8` | 32px | Between major sections |
|
||||
| `--space-10` | 40px | Large section gap |
|
||||
| `--space-12` | 48px | Extra large spacing |
|
||||
| `--space-16` | 64px | Maximum spacing, hero sections |
|
||||
|
||||
---
|
||||
|
||||
## 6. Border Radius & Shadows
|
||||
|
||||
### Border Radius
|
||||
|
||||
| Token | Value | Use |
|
||||
|----------------|----------|-------------------------------------------|
|
||||
| `--radius-sm` | 4px | Tags, small chips, select option rows |
|
||||
| `--radius-md` | 6px | Buttons, inputs, table badges |
|
||||
| `--radius-lg` | 8px | Cards, panels, dropdown menus |
|
||||
| `--radius-xl` | 12px | Modals, large containers |
|
||||
| `--radius-full`| 9999px | Status badge pills, avatars |
|
||||
|
||||
### Shadows
|
||||
|
||||
| Token | Value | Use |
|
||||
|-------------------------|------------------------------------------|------------------------------------|
|
||||
| `--shadow-card` | `inset 0 1px 0 rgba(192,193,255,0.05)` | Card top-edge glass reflection |
|
||||
| `--shadow-sm` | `0 2px 8px rgba(10,14,20,0.40)` | Subtle lift |
|
||||
| `--shadow-md` | `0 4px 16px rgba(10,14,20,0.50)` | Elevated cards |
|
||||
| `--shadow-lg` | `0 8px 24px rgba(13,17,23,0.60)` | Modals, dropdowns |
|
||||
| `--shadow-focus` | `0 0 0 3px rgba(192,193,255,0.20)` | Focus ring glow |
|
||||
| `--shadow-primary-glow` | `0 4px 16px rgba(192,193,255,0.28)` | Primary button hover halo |
|
||||
| `--shadow-danger-glow` | `0 4px 16px rgba(255,92,92,0.40)` | Danger button hover halo |
|
||||
| `--shadow-success-glow` | `0 4px 16px rgba(74,222,128,0.35)` | Success button hover halo |
|
||||
|
||||
---
|
||||
|
||||
## 7. Component Rules
|
||||
|
||||
### Button
|
||||
|
||||
Import: `@/components/ui/Button`
|
||||
|
||||
**Variants:**
|
||||
|
||||
| Variant | Resting state | Hover state |
|
||||
|------------------|---------------------------------------|----------------------------------------------------------|
|
||||
| `primary` | Indigo→violet gradient, dark text | `+brightness(1.06)` + `--shadow-primary-glow` halo |
|
||||
| `secondary` | Island bg, ghost border | Elevated bg + focus border + subtle indigo glow |
|
||||
| `ghost` | Transparent | Elevated bg + whisper indigo glow |
|
||||
| `danger` | Coral tint bg, coral text | **Solid coral fill**, dark text + `--shadow-danger-glow` |
|
||||
| `success` | Emerald tint bg, emerald text | **Solid emerald fill**, dark text + `--shadow-success-glow` |
|
||||
| `table-actions` | Fully transparent, muted text | Island bg + strong border (identical to `secondary`) — also activates on `tr:hover` |
|
||||
|
||||
**Sizes:** `sm`, `md` (default), `lg`
|
||||
|
||||
**Rules:**
|
||||
- Never use a raw `<button>` element for a styled action
|
||||
- Always pass `loading` prop for async actions (shows spinner, disables interaction)
|
||||
- Icon-only buttons must have `aria-label`
|
||||
- Active/press state: `filter: brightness(0.94)`, glow removed
|
||||
|
||||
---
|
||||
|
||||
### FormField
|
||||
|
||||
Import: `@/components/ui/FormField`
|
||||
|
||||
Wraps every form control: label + input/textarea/select + hint + error message.
|
||||
Never place a raw `<input>` on a page.
|
||||
|
||||
**Types:** `text`, `email`, `password`, `number`, `tel`, `url`, `textarea`, `select`
|
||||
|
||||
**For `type="select"`**: pass `<option>` elements as children. FormField uses the custom `Select` component internally — the native `<select>` is never rendered.
|
||||
|
||||
```jsx
|
||||
<FormField label="Status" name="status" type="select" value={val} onChange={handleChange}>
|
||||
<option value="">Choose…</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="inactive">Inactive</option>
|
||||
</FormField>
|
||||
```
|
||||
|
||||
**Input appearance:** "cutout" inset-shadow treatment — the field appears recessed into the surface. Background: `--color-bg-abyss`. Focus: `--color-border-focus` ring.
|
||||
|
||||
---
|
||||
|
||||
### Select (standalone)
|
||||
|
||||
Import: `@/components/ui/Select`
|
||||
|
||||
Fully custom dropdown replacing native `<select>`. Floating menu via portal, keyboard navigation, checkmark on selected item. Usually consumed via `FormField type="select"`. Use directly when you need a select outside a form label context.
|
||||
|
||||
---
|
||||
|
||||
### DataTable
|
||||
|
||||
Import: `@/components/ui/DataTable`
|
||||
|
||||
**Always include:** column headers, loading skeleton, empty state, pagination.
|
||||
**Rows:** alternate tint via `--color-tint-row` (`rgba(192,193,255,0.015)`). Hover: `--color-bg-island`.
|
||||
**Status columns:** always `<StatusBadge>` — never raw text.
|
||||
**Row actions:** last column, right-aligned, use portal-based action menu.
|
||||
|
||||
---
|
||||
|
||||
### Modal
|
||||
|
||||
Import: `@/components/ui/Modal`
|
||||
|
||||
Sizes: `sm` (480px), `md` (640px — default), `lg` (800px), `xl` (60vw/60vh), `xxl` (85vw/85vh), `full` (calc(100vw/100vh − 64px)).
|
||||
|
||||
**Rules:**
|
||||
- Always has: title, close (×) button, footer action buttons
|
||||
- Closes on Escape + backdrop click unless `persistent={true}`
|
||||
- Destructive prompts use `<ConfirmDialog>` instead
|
||||
- Modal JSX never lives inside a page file — always in `frontend/src/modals/[domain]/`
|
||||
|
||||
---
|
||||
|
||||
### ConfirmDialog
|
||||
|
||||
Import: `@/components/ui/ConfirmDialog`
|
||||
|
||||
Wraps `<Modal size="sm">` with a centred icon + message. Use for any action that is destructive or hard to reverse.
|
||||
|
||||
Variants: `danger` (coral circle + triangle icon), `primary` (indigo circle + info icon).
|
||||
|
||||
---
|
||||
|
||||
### PageHeader
|
||||
|
||||
Import: `@/components/ui/PageHeader`
|
||||
|
||||
**Always the first element inside `.page-wrapper`.** Creates the page title block.
|
||||
|
||||
Props: `title` (required), `subtitle`, `breadcrumbs`, `children` (action buttons slot).
|
||||
|
||||
The title renders as `<h1>` with class `.v2-page-header-title` — uses `Barlow Condensed` at `1.75rem` / weight 600.
|
||||
|
||||
```jsx
|
||||
<PageHeader title="Device Inventory" subtitle="All registered Bell units">
|
||||
<Button variant="primary">Add Device</Button>
|
||||
</PageHeader>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Card
|
||||
|
||||
Import: `@/components/ui/Card`
|
||||
|
||||
Variants: `flat` (default), `elevated`, `outlined`.
|
||||
|
||||
Props: `title`, `subtitle`, `footer`, `padding` (bool, default true), `children`.
|
||||
|
||||
Card header has a faint indigo gradient ceiling (`linear-gradient` from top).
|
||||
|
||||
---
|
||||
|
||||
### Tabs
|
||||
|
||||
Import: `@/components/ui/Tabs`
|
||||
|
||||
Variants: `line` (default — underline indicator), `pill` (filled background).
|
||||
|
||||
Props: `tabs` (array of `{key, label, icon?, count?}`), `active`, `onChange`, `variant`.
|
||||
|
||||
Line variant uses a sliding indicator measured with `useLayoutEffect`. Pill variant uses filled backgrounds.
|
||||
|
||||
Spacing: line tabs have `gap: --space-5` between items, pill tabs `gap: --space-4`.
|
||||
|
||||
---
|
||||
|
||||
### Toast
|
||||
|
||||
Import: `@/components/ui/Toast` → `{ ToastProvider, useToast }`
|
||||
|
||||
Setup: wrap the app (or router) with `<ToastProvider>`. Then in any component:
|
||||
|
||||
```jsx
|
||||
const toast = useToast()
|
||||
toast.success('Saved', 'Device updated successfully.')
|
||||
toast.danger('Error', 'Failed to connect.')
|
||||
toast.warning('Warning', 'Firmware is outdated.')
|
||||
toast.info('Info', 'Sync in progress.')
|
||||
```
|
||||
|
||||
Toasts auto-dismiss after 4000ms. Hover pauses the timer. Stack appears in the bottom-right corner.
|
||||
|
||||
---
|
||||
|
||||
### SearchBar
|
||||
|
||||
Import: `@/components/ui/SearchBar`
|
||||
|
||||
Supports controlled (`value` + `onChange`) or uncontrolled mode.
|
||||
Debounced by default (300ms). Clear button appears when text is present.
|
||||
Appearance matches the `FormField` cutout treatment.
|
||||
|
||||
---
|
||||
|
||||
### Breadcrumbs
|
||||
|
||||
Import: `@/components/ui/Breadcrumbs`
|
||||
|
||||
Use on detail pages only (not list pages). Items: array of `{ label, href? }`. Last item has no href — it is the current page.
|
||||
|
||||
---
|
||||
|
||||
### Spinner
|
||||
|
||||
Import: `@/components/ui/Spinner`
|
||||
|
||||
Props: `size` (`sm`, `md`, `lg`), `color` (defaults to `--color-primary`).
|
||||
|
||||
Use inside loading states. Buttons show their own spinner via `loading` prop — do not add a separate `<Spinner>` inside buttons.
|
||||
|
||||
---
|
||||
|
||||
### StatusBadge
|
||||
|
||||
Import: `@/components/ui/StatusBadge`
|
||||
|
||||
Never use a raw `<span>` with a background color for status. Always `<StatusBadge>`.
|
||||
|
||||
Variants: `success`, `warning`, `danger`, `info`, `neutral`.
|
||||
|
||||
---
|
||||
|
||||
### Icon
|
||||
|
||||
Import: `@/components/ui/Icon`
|
||||
|
||||
Renders an inline SVG by name. 35 named icons available (see Style Guide `/dev/styleguide` → Icon section for the full list).
|
||||
|
||||
```jsx
|
||||
<Icon name="edit" size={16} />
|
||||
<Icon name="delete" size={20} color="var(--color-danger)" />
|
||||
```
|
||||
|
||||
**Asset SVGs** (from `/assets/` folders) are displayed via `<img>` tags in the Style Guide, not via `<Icon>`. These are pre-rendered SVG files used for sidebar icons, comms icons, customer status icons, etc. Use them as image sources, not as Icon component names.
|
||||
|
||||
---
|
||||
|
||||
## 8. Icons
|
||||
|
||||
Three sources:
|
||||
|
||||
| Source | Use case | How to render |
|
||||
|-------------------------------------|---------------------------------------|-----------------------------|
|
||||
| `<Icon name="..." />` | Action icons, UI chrome | `@/components/ui/Icon` |
|
||||
| `assets/side-menu-icons/*.svg` | Sidebar navigation | `<img src={...} />` |
|
||||
| `assets/comms/*.svg` | Communication type indicators | `<img src={...} />` |
|
||||
| `assets/customer-status/*.svg` | CRM status icons | `<img src={...} />` |
|
||||
| `assets/global-icons/*.svg` | Legacy action icons (prefer `<Icon>`) | `<img src={...} />` |
|
||||
| `assets/other-icons/*.svg` | Misc UI icons | `<img src={...} />` |
|
||||
|
||||
Never add a new icon library (e.g. heroicons, lucide). Use the existing sources.
|
||||
|
||||
---
|
||||
|
||||
## 9. Theming Rules
|
||||
|
||||
- Theme is controlled by `data-theme` attribute on `<html>`
|
||||
- Default is dark (`:root` = dark theme)
|
||||
- **Never** use Tailwind's `dark:` prefix — theming is handled entirely via CSS tokens
|
||||
- `[data-theme="light"]` overrides exist in `tokens.css` as a future placeholder
|
||||
|
||||
---
|
||||
|
||||
## 10. Responsive Breakpoints
|
||||
|
||||
| Token | Value | Behaviour |
|
||||
|--------------------|--------|--------------------------------------------------------|
|
||||
| `--breakpoint-sm` | 640px | |
|
||||
| `--breakpoint-md` | 768px | Sidebar collapses; page padding drops to `--space-4` |
|
||||
| `--breakpoint-lg` | 1024px | Full sidebar shown |
|
||||
| `--breakpoint-xl` | 1280px | |
|
||||
|
||||
Mobile (`< 768px`): single column, sidebar hidden (drawer), tables may become card lists.
|
||||
|
||||
---
|
||||
|
||||
## 11. Section Layout — Masonry Grid
|
||||
|
||||
**Default layout for ALL content pages with multiple variable-height sections.**
|
||||
|
||||
Sections on a content page must flow like physical objects stacked in columns — the next section always drops into the shortest column. This is CSS column masonry.
|
||||
|
||||
### How it works
|
||||
|
||||
```
|
||||
Column 1 | Column 2 | Column 3
|
||||
────────────┼─────────────┼────────────
|
||||
Section A | Section B | Section C
|
||||
(300px) | (250px) | (350px)
|
||||
│ │
|
||||
Section E | Section D |
|
||||
(200px) | (200px) |
|
||||
```
|
||||
|
||||
Sections fill left-to-right across the top, then each new section drops into whichever column is currently shortest. This is automatic — the browser handles placement via CSS `columns`.
|
||||
|
||||
### Usage
|
||||
|
||||
```jsx
|
||||
{/* 2 columns */}
|
||||
<div className="masonry-grid masonry-grid--2">
|
||||
<Card title="Account Info">…</Card>
|
||||
<Card title="Profile">…</Card>
|
||||
<Card title="Security">…</Card> {/* auto-drops into shortest column */}
|
||||
</div>
|
||||
|
||||
{/* 3 columns */}
|
||||
<div className="masonry-grid masonry-grid--3">
|
||||
{sections.map(s => <Card key={s.id}>…</Card>)}
|
||||
</div>
|
||||
```
|
||||
|
||||
Available variants: `masonry-grid--2`, `masonry-grid--3`, `masonry-grid--4`
|
||||
|
||||
Responsive behaviour:
|
||||
- `--4` collapses to 3 cols at 1024px, 1 col at 768px
|
||||
- `--3` collapses to 2 cols at 1024px, 1 col at 768px
|
||||
- `--2` collapses to 1 col at 768px
|
||||
|
||||
### Rules
|
||||
|
||||
- **Use `.masonry-grid` by default** on all content pages with 2+ variable-height sections
|
||||
- **Do NOT** use `display: grid` with `gridTemplateColumns` for variable-height card layouts — this creates uneven whitespace when cards differ in height
|
||||
- **Do NOT** use `.masonry-grid` for DataTable pages — tables span full width on their own
|
||||
- **Do NOT** use `.masonry-grid` when sections must align horizontally (e.g. two fields that are semantically paired side-by-side within a card) — that's an internal card layout, not page-level masonry
|
||||
- The `Card` component already has `break-inside: avoid` so it will never be split across columns
|
||||
|
||||
---
|
||||
|
||||
## 12. What Claude Code Must NEVER Do
|
||||
|
||||
- ❌ Write a hex color, `rgb()`, or `hsl()` value directly in any component or page file
|
||||
- ❌ Write a pixel spacing or size value that isn't a `--space-*` token
|
||||
- ❌ Use a raw `<button>`, `<input>`, or `<select>` for anything styled — always use the wrapper component
|
||||
- ❌ Create a `.module.css` or any per-page CSS file
|
||||
- ❌ Use Tailwind's `dark:` prefix — theming is via CSS tokens only
|
||||
- ❌ Place modal JSX inside a page file — modals live in `frontend/src/modals/`
|
||||
- ❌ Wrap `.page-wrapper` in additional divs that shift content alignment
|
||||
- ❌ Override `.page-wrapper`'s padding to make a single page "different"
|
||||
- ❌ Skip loading, error, and empty states on any data-fetching component
|
||||
- ❌ Import from `_archive/` anywhere except `@/lib/api.js`, `@/hooks/useAuth.js`, and `@/providers/AuthProvider.jsx`
|
||||
- ❌ Install a new icon library or introduce new SVG icons outside of `assets/`
|
||||
- ❌ Invent new color values not in `tokens.css`
|
||||
@@ -39,6 +39,20 @@ bellsystems-admin/
|
||||
└── .env
|
||||
```
|
||||
|
||||
## Shared data contract (Firestore schema v1)
|
||||
|
||||
Firestore is shared with the BellSystems tablet and phone apps (FlutterFlow). Device
|
||||
documents must follow the schema in the **bellsystems-schema** repo
|
||||
(`v1/firestore.schema.json`) — one wrongly typed field makes the apps silently hide the
|
||||
device from its users.
|
||||
|
||||
- All device writes go through `backend/devices/firestore_v1.py`.
|
||||
- Adding or changing a shared field: update the schema repo first, then every app and this
|
||||
console in the same release.
|
||||
- Check production data: `node tools/audit.js <service-account.json>` in the schema repo.
|
||||
|
||||
Details: the "Firestore Schema v1" section of `CLAUDE.md`.
|
||||
|
||||
## Documentation
|
||||
|
||||
See `BellSystems_AdminPanel_Strategy.md` for the full architecture and build plan.
|
||||
@@ -0,0 +1,113 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = alembic
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python>=3.9 or backports.zoneinfo library.
|
||||
# Any required deps can installed by adding `tzdata` to the `[alembic]` section
|
||||
# of pyproject.toml.
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to alembic/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
|
||||
|
||||
# version path separator; As mentioned above, this is the character used to split
|
||||
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||
# Valid values for version_path_separator are:
|
||||
#
|
||||
# version_path_separator = :
|
||||
# version_path_separator = ;
|
||||
# version_path_separator = space
|
||||
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in "version_locations" directory
|
||||
# New in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# NOTE: The database URL is set programmatically in env.py from settings.
|
||||
# Do not set sqlalchemy.url here.
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = %(here)s/.venv/bin/ruff
|
||||
# ruff.options = --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,44 @@
|
||||
import asyncio
|
||||
from logging.config import fileConfig
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from alembic import context
|
||||
from config import settings
|
||||
|
||||
# Import all models so Alembic can see them
|
||||
from database.models import Base # noqa: F401 — triggers all ORM imports
|
||||
|
||||
config = context.config
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
url = settings.database_url
|
||||
context.configure(url=url, target_metadata=target_metadata, literal_binds=True)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection):
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
engine = create_async_engine(settings.database_url)
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(do_run_migrations)
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
asyncio.run(run_async_migrations())
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,83 @@
|
||||
"""rename_entries_to_crm_entries
|
||||
|
||||
Revision ID: 244a0b0f35be
|
||||
Revises: 485d40e86e4b
|
||||
Create Date: 2026-04-15 20:05:20.835281
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '244a0b0f35be'
|
||||
down_revision: Union[str, None] = '485d40e86e4b'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# 1. Drop FK from support_tickets -> entries before touching the entries table
|
||||
op.drop_constraint('support_tickets_linked_entry_id_fkey', 'support_tickets', type_='foreignkey')
|
||||
# 2. Drop dependent table first, then parent
|
||||
op.drop_table('entry_links')
|
||||
op.drop_table('entries')
|
||||
# 3. Create new tables with crm_ prefix
|
||||
op.create_table('crm_entries',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('type', sa.String(length=10), nullable=False),
|
||||
sa.Column('title', sa.String(length=500), nullable=False),
|
||||
sa.Column('body', sa.Text(), nullable=True),
|
||||
sa.Column('status', sa.String(length=20), nullable=True),
|
||||
sa.Column('severity', sa.String(length=10), nullable=True),
|
||||
sa.Column('author_id', sa.String(length=128), nullable=False),
|
||||
sa.Column('author_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('crm_entry_links',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('entry_id', sa.UUID(), nullable=False),
|
||||
sa.Column('entity_type', sa.String(length=20), nullable=False),
|
||||
sa.Column('entity_id', sa.String(length=128), nullable=False),
|
||||
sa.ForeignKeyConstraint(['entry_id'], ['crm_entries.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('entry_id', 'entity_type', 'entity_id')
|
||||
)
|
||||
# 4. Recreate FK on support_tickets pointing at new table
|
||||
op.create_foreign_key(None, 'support_tickets', 'crm_entries', ['linked_entry_id'], ['id'], ondelete='SET NULL')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint(None, 'support_tickets', type_='foreignkey')
|
||||
op.create_foreign_key('support_tickets_linked_entry_id_fkey', 'support_tickets', 'entries', ['linked_entry_id'], ['id'], ondelete='SET NULL')
|
||||
op.create_table('entries',
|
||||
sa.Column('id', sa.UUID(), autoincrement=False, nullable=False),
|
||||
sa.Column('type', sa.VARCHAR(length=10), autoincrement=False, nullable=False),
|
||||
sa.Column('title', sa.VARCHAR(length=500), autoincrement=False, nullable=False),
|
||||
sa.Column('body', sa.TEXT(), autoincrement=False, nullable=True),
|
||||
sa.Column('status', sa.VARCHAR(length=20), autoincrement=False, nullable=True),
|
||||
sa.Column('severity', sa.VARCHAR(length=10), autoincrement=False, nullable=True),
|
||||
sa.Column('author_id', sa.VARCHAR(length=128), autoincrement=False, nullable=False),
|
||||
sa.Column('author_name', sa.VARCHAR(length=255), autoincrement=False, nullable=True),
|
||||
sa.Column('created_at', postgresql.TIMESTAMP(timezone=True), autoincrement=False, nullable=False),
|
||||
sa.Column('updated_at', postgresql.TIMESTAMP(timezone=True), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name='entries_pkey'),
|
||||
postgresql_ignore_search_path=False
|
||||
)
|
||||
op.create_table('entry_links',
|
||||
sa.Column('id', sa.UUID(), autoincrement=False, nullable=False),
|
||||
sa.Column('entry_id', sa.UUID(), autoincrement=False, nullable=False),
|
||||
sa.Column('entity_type', sa.VARCHAR(length=20), autoincrement=False, nullable=False),
|
||||
sa.Column('entity_id', sa.VARCHAR(length=128), autoincrement=False, nullable=False),
|
||||
sa.ForeignKeyConstraint(['entry_id'], ['entries.id'], name='entry_links_entry_id_fkey', ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id', name='entry_links_pkey'),
|
||||
sa.UniqueConstraint('entry_id', 'entity_type', 'entity_id', name='entry_links_entry_id_entity_type_entity_id_key')
|
||||
)
|
||||
op.drop_table('crm_entry_links')
|
||||
op.drop_table('crm_entries')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,82 @@
|
||||
"""initial_notes_and_tickets
|
||||
|
||||
Revision ID: 485d40e86e4b
|
||||
Revises:
|
||||
Create Date: 2026-04-15 20:01:04.225959
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '485d40e86e4b'
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('entries',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('type', sa.String(length=10), nullable=False),
|
||||
sa.Column('title', sa.String(length=500), nullable=False),
|
||||
sa.Column('body', sa.Text(), nullable=True),
|
||||
sa.Column('status', sa.String(length=20), nullable=True),
|
||||
sa.Column('severity', sa.String(length=10), nullable=True),
|
||||
sa.Column('author_id', sa.String(length=128), nullable=False),
|
||||
sa.Column('author_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('entry_links',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('entry_id', sa.UUID(), nullable=False),
|
||||
sa.Column('entity_type', sa.String(length=20), nullable=False),
|
||||
sa.Column('entity_id', sa.String(length=128), nullable=False),
|
||||
sa.ForeignKeyConstraint(['entry_id'], ['entries.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('entry_id', 'entity_type', 'entity_id')
|
||||
)
|
||||
op.create_table('support_tickets',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('customer_id', sa.String(length=128), nullable=False),
|
||||
sa.Column('customer_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('device_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('device_serial', sa.String(length=64), nullable=True),
|
||||
sa.Column('subject', sa.String(length=500), nullable=False),
|
||||
sa.Column('status', sa.String(length=30), nullable=False),
|
||||
sa.Column('priority', sa.String(length=10), nullable=True),
|
||||
sa.Column('opened_via', sa.String(length=20), nullable=True),
|
||||
sa.Column('linked_entry_id', sa.UUID(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['linked_entry_id'], ['entries.id'], ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('ticket_messages',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('ticket_id', sa.UUID(), nullable=False),
|
||||
sa.Column('sender_type', sa.String(length=10), nullable=False),
|
||||
sa.Column('sender_id', sa.String(length=128), nullable=False),
|
||||
sa.Column('sender_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('body', sa.Text(), nullable=False),
|
||||
sa.Column('is_internal', sa.Boolean(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['ticket_id'], ['support_tickets.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('ticket_messages')
|
||||
op.drop_table('support_tickets')
|
||||
op.drop_table('entry_links')
|
||||
op.drop_table('entries')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,23 @@
|
||||
"""add_category_to_crm_entries
|
||||
|
||||
Revision ID: a1b2c3d4e5f6
|
||||
Revises: 244a0b0f35be
|
||||
Create Date: 2026-04-16 09:00:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision: str = 'a1b2c3d4e5f6'
|
||||
down_revision: Union[str, None] = '244a0b0f35be'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column('crm_entries', sa.Column('category', sa.String(length=30), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column('crm_entries', 'category')
|
||||
@@ -0,0 +1,73 @@
|
||||
"""device diagnostics reports
|
||||
|
||||
Adds device_diagnostics_reports — structured storage for the firmware's
|
||||
diagnostics_report MQTT event (vesper/{uid}/status/info, type="diagnostics_report"),
|
||||
published every 5 minutes. Cleanly separate from device_boot_events (one row per
|
||||
boot, event-driven) and heartbeats (one row every 30s, transport/liveness facts):
|
||||
this table is periodic health telemetry — CPU temperature (min/max/avg over the
|
||||
5-minute window), WiFi reconnect count + last disconnect reason, OTA/firmware
|
||||
check state, and per-task stack high-water marks (bytes free).
|
||||
|
||||
stack_high_water is stored as a JSON-encoded TEXT column rather than flattened
|
||||
columns — unlike the other three groups (fixed field sets), the set of
|
||||
monitored tasks is open-ended on the firmware side (see project-vesper's
|
||||
Telemetry::registerTaskForStackMonitoring), so a fixed column per task would
|
||||
need a migration every time a task is added. TEXT (not JSONB) matches this
|
||||
codebase's existing convention for JSON blobs stored via raw SQL — see
|
||||
commands.command_payload / response_payload.
|
||||
|
||||
Revision ID: a7b8c9d0e1f2
|
||||
Revises: f6a7b8c9d0e1
|
||||
Create Date: 2026-07-17 00:00:00.000000
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "a7b8c9d0e1f2"
|
||||
down_revision: Union[str, None] = "f6a7b8c9d0e1"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"device_diagnostics_reports",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("device_serial", sa.String(128), nullable=False),
|
||||
|
||||
# cpu_temp — omitted by firmware (all null here) if no samples were
|
||||
# taken yet this window (e.g. very first report shortly after boot).
|
||||
sa.Column("cpu_temp_avg", sa.Float(), nullable=True),
|
||||
sa.Column("cpu_temp_min", sa.Float(), nullable=True),
|
||||
sa.Column("cpu_temp_max", sa.Float(), nullable=True),
|
||||
sa.Column("cpu_temp_samples", sa.Integer(), nullable=True),
|
||||
|
||||
# wifi_reconnects — this-boot-only lifetime count, not device lifetime.
|
||||
sa.Column("wifi_reconnect_count", sa.Integer(), nullable=True),
|
||||
sa.Column("wifi_last_disconnect_reason", sa.String(64), nullable=True),
|
||||
sa.Column("wifi_last_disconnect_uptime_ms", sa.BigInteger(), nullable=True),
|
||||
|
||||
# ota
|
||||
sa.Column("ota_current_version", sa.String(32), nullable=True),
|
||||
sa.Column("ota_update_available", sa.Boolean(), nullable=True),
|
||||
sa.Column("ota_available_version", sa.String(32), nullable=True),
|
||||
sa.Column("ota_last_check_uptime_ms", sa.BigInteger(), nullable=True),
|
||||
sa.Column("ota_last_error", sa.String(32), nullable=True),
|
||||
|
||||
# stack_high_water — open-ended task set, see module docstring.
|
||||
sa.Column("stack_high_water", sa.Text(), nullable=True),
|
||||
|
||||
sa.Column("received_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index(
|
||||
"idx_device_diagnostics_reports_serial_received",
|
||||
"device_diagnostics_reports",
|
||||
["device_serial", sa.text("received_at DESC")],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("idx_device_diagnostics_reports_serial_received", table_name="device_diagnostics_reports")
|
||||
op.drop_table("device_diagnostics_reports")
|
||||
@@ -0,0 +1,507 @@
|
||||
"""phase_0_schema_foundation
|
||||
|
||||
Adds all Phase 0 tables:
|
||||
- _migration_runs (migration tracking)
|
||||
- audit_log (staff action audit trail)
|
||||
- crm_products
|
||||
- crm_customers
|
||||
- crm_orders
|
||||
- crm_comms_log
|
||||
- crm_media
|
||||
- crm_sync_state
|
||||
- crm_quotations
|
||||
- crm_quotation_items
|
||||
- staff
|
||||
- console_settings
|
||||
- public_features
|
||||
- melody_drafts
|
||||
- built_melodies
|
||||
- mfg_audit_log
|
||||
- device_alerts
|
||||
- commands (raw SQL — no ORM model)
|
||||
- heartbeats (raw SQL — no ORM model)
|
||||
- device_logs (partitioned by month — raw SQL)
|
||||
- device_logs_2025_01 … device_logs_2026_06 (initial partitions)
|
||||
|
||||
Revision ID: b1c2d3e4f5a6
|
||||
Revises: a1b2c3d4e5f6
|
||||
Create Date: 2026-04-17 00:00:00.000000
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
|
||||
|
||||
# revision identifiers
|
||||
revision: str = "b1c2d3e4f5a6"
|
||||
down_revision: Union[str, None] = "a1b2c3d4e5f6"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ------------------------------------------------------------------ #
|
||||
# _migration_runs
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"_migration_runs",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("script_name", sa.String(256), nullable=False),
|
||||
sa.Column("ran_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
sa.Column("source_rows", sa.BigInteger(), nullable=False, server_default="0"),
|
||||
sa.Column("dest_rows", sa.BigInteger(), nullable=False, server_default="0"),
|
||||
sa.Column("success", sa.String(8), nullable=False, server_default="ok"),
|
||||
sa.Column("notes", sa.Text(), nullable=True),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# audit_log
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"audit_log",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
sa.Column("actor_id", sa.String(128), nullable=False),
|
||||
sa.Column("actor_name", sa.String(255), nullable=False),
|
||||
sa.Column("action", sa.String(64), nullable=False),
|
||||
sa.Column("entity_type", sa.String(64), nullable=False),
|
||||
sa.Column("entity_id", sa.String(128), nullable=False),
|
||||
sa.Column("entity_label", sa.String(500), nullable=True),
|
||||
sa.Column("changes", JSONB, nullable=True),
|
||||
sa.Column("meta", JSONB, nullable=True),
|
||||
)
|
||||
op.create_index("idx_audit_actor", "audit_log", ["actor_id", "occurred_at"])
|
||||
op.create_index("idx_audit_entity", "audit_log", ["entity_type","entity_id", "occurred_at"])
|
||||
op.create_index("idx_audit_action", "audit_log", ["action", "occurred_at"])
|
||||
op.create_index("idx_audit_occurred", "audit_log", ["occurred_at"])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# staff
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"staff",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("firestore_id", sa.String(128), nullable=True, unique=True),
|
||||
sa.Column("email", sa.String(256), nullable=False, unique=True),
|
||||
sa.Column("name", sa.String(255), nullable=False),
|
||||
sa.Column("role", sa.String(64), nullable=False, server_default="staff"),
|
||||
sa.Column("permissions", JSONB, nullable=False, server_default="{}"),
|
||||
sa.Column("hashed_password", sa.String(256), nullable=False),
|
||||
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# console_settings & public_features
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"console_settings",
|
||||
sa.Column("key", sa.String(128), primary_key=True),
|
||||
sa.Column("value", JSONB, nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
op.create_table(
|
||||
"public_features",
|
||||
sa.Column("key", sa.String(128), primary_key=True),
|
||||
sa.Column("value", JSONB, nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# crm_products
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"crm_products",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("firestore_id", sa.String(128), nullable=True, unique=True),
|
||||
sa.Column("name", sa.String(500), nullable=False),
|
||||
sa.Column("sku", sa.String(128), nullable=True),
|
||||
sa.Column("category", sa.String(128), nullable=True),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("unit_cost", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("currency", sa.String(10), nullable=False, server_default="EUR"),
|
||||
sa.Column("unit_type", sa.String(32), nullable=False, server_default="pcs"),
|
||||
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# crm_customers
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"crm_customers",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("firestore_id", sa.String(128), nullable=True, unique=True),
|
||||
sa.Column("title", sa.String(32), nullable=True),
|
||||
sa.Column("name", sa.String(255), nullable=False),
|
||||
sa.Column("surname", sa.String(255), nullable=True),
|
||||
sa.Column("organization", sa.String(500), nullable=True),
|
||||
sa.Column("religion", sa.String(64), nullable=True),
|
||||
sa.Column("language", sa.String(10), nullable=False, server_default="el"),
|
||||
sa.Column("folder_id", sa.String(128), nullable=False, unique=True),
|
||||
sa.Column("relationship_status", sa.String(64), nullable=False, server_default="lead"),
|
||||
sa.Column("nextcloud_folder", sa.String(500), nullable=True),
|
||||
sa.Column("contacts", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("notes", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("location", JSONB, nullable=True),
|
||||
sa.Column("tags", ARRAY(sa.String()), nullable=False, server_default="{}"),
|
||||
sa.Column("owned_items", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("linked_user_ids", ARRAY(sa.String()), nullable=False, server_default="{}"),
|
||||
sa.Column("technical_issues", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("install_support", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("transaction_history", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("crm_summary", JSONB, nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
)
|
||||
op.create_index("idx_crm_customers_rel_status", "crm_customers", ["relationship_status"])
|
||||
op.create_index("idx_crm_customers_name", "crm_customers", ["name", "surname"])
|
||||
op.create_index("idx_crm_customers_tags", "crm_customers", ["tags"],
|
||||
postgresql_using="gin")
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# crm_orders
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"crm_orders",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("customer_id", sa.String(128),
|
||||
sa.ForeignKey("crm_customers.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("order_number", sa.String(64), nullable=False, unique=True),
|
||||
sa.Column("title", sa.String(500), nullable=True),
|
||||
sa.Column("created_by", sa.String(128), nullable=True),
|
||||
sa.Column("status", sa.String(64), nullable=False,
|
||||
server_default="negotiating"),
|
||||
sa.Column("status_updated_date", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("status_updated_by", sa.String(128), nullable=True),
|
||||
sa.Column("items", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("subtotal", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("discount", JSONB, nullable=True),
|
||||
sa.Column("total_price", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("currency", sa.String(10), nullable=False, server_default="EUR"),
|
||||
sa.Column("shipping", JSONB, nullable=True),
|
||||
sa.Column("payment_status", JSONB, nullable=False, server_default="{}"),
|
||||
sa.Column("invoice_path", sa.String(500), nullable=True),
|
||||
sa.Column("notes", sa.Text(), nullable=True),
|
||||
sa.Column("timeline", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
)
|
||||
op.create_index("idx_crm_orders_customer", "crm_orders", ["customer_id"])
|
||||
op.create_index("idx_crm_orders_status", "crm_orders", ["status"])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# crm_comms_log
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"crm_comms_log",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("customer_id", sa.String(128),
|
||||
sa.ForeignKey("crm_customers.id", ondelete="SET NULL"), nullable=True),
|
||||
sa.Column("type", sa.String(32), nullable=False),
|
||||
sa.Column("mail_account", sa.String(256), nullable=True),
|
||||
sa.Column("direction", sa.String(16), nullable=False),
|
||||
sa.Column("subject", sa.String(500), nullable=True),
|
||||
sa.Column("body", sa.Text(), nullable=True),
|
||||
sa.Column("body_html", sa.Text(), nullable=True),
|
||||
sa.Column("attachments", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("ext_message_id", sa.String(500), nullable=True),
|
||||
sa.Column("from_addr", sa.String(500), nullable=True),
|
||||
sa.Column("to_addrs", sa.Text(), nullable=True),
|
||||
sa.Column("logged_by", sa.String(128), nullable=True),
|
||||
sa.Column("is_important", sa.Boolean(), nullable=False, server_default="false"),
|
||||
sa.Column("is_read", sa.Boolean(), nullable=False, server_default="true"),
|
||||
sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index("idx_crm_comms_customer", "crm_comms_log", ["customer_id", "occurred_at"])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# crm_media
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"crm_media",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("customer_id", sa.String(128),
|
||||
sa.ForeignKey("crm_customers.id", ondelete="SET NULL"), nullable=True),
|
||||
sa.Column("order_id", sa.String(128), nullable=True),
|
||||
sa.Column("filename", sa.String(500), nullable=False),
|
||||
sa.Column("nextcloud_path", sa.String(1000), nullable=False),
|
||||
sa.Column("thumbnail_path", sa.String(1000), nullable=True),
|
||||
sa.Column("mime_type", sa.String(128), nullable=True),
|
||||
sa.Column("direction", sa.String(16), nullable=True),
|
||||
sa.Column("tags", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("uploaded_by", sa.String(128), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index("idx_crm_media_customer", "crm_media", ["customer_id"])
|
||||
op.create_index("idx_crm_media_order", "crm_media", ["order_id"])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# crm_sync_state
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"crm_sync_state",
|
||||
sa.Column("key", sa.String(128), primary_key=True),
|
||||
sa.Column("value", sa.Text(), nullable=True),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# crm_quotations
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"crm_quotations",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("quotation_number", sa.String(64), nullable=False, unique=True),
|
||||
sa.Column("title", sa.String(500), nullable=True),
|
||||
sa.Column("subtitle", sa.String(500), nullable=True),
|
||||
sa.Column("customer_id", sa.String(128),
|
||||
sa.ForeignKey("crm_customers.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("language", sa.String(10), nullable=False, server_default="en"),
|
||||
sa.Column("status", sa.String(32), nullable=False, server_default="draft"),
|
||||
sa.Column("order_type", sa.String(64), nullable=True),
|
||||
sa.Column("shipping_method", sa.String(64), nullable=True),
|
||||
sa.Column("estimated_shipping_date", sa.String(32), nullable=True),
|
||||
sa.Column("global_discount_label", sa.String(128), nullable=True),
|
||||
sa.Column("global_discount_percent", sa.Numeric(8, 4), nullable=False, server_default="0"),
|
||||
sa.Column("vat_percent", sa.Numeric(8, 4), nullable=False, server_default="24"),
|
||||
sa.Column("global_vat_percent", sa.Numeric(8, 4), nullable=False, server_default="24"),
|
||||
sa.Column("shipping_cost", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("shipping_cost_discount", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("install_cost", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("install_cost_discount", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("extras_label", sa.String(256), nullable=True),
|
||||
sa.Column("extras_cost", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("comments", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("quick_notes", JSONB, nullable=False, server_default="{}"),
|
||||
sa.Column("subtotal_before_discount", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("global_discount_amount", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("new_subtotal", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("vat_amount", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("final_total", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("nextcloud_pdf_path", sa.String(1000), nullable=True),
|
||||
sa.Column("nextcloud_pdf_url", sa.String(1000), nullable=True),
|
||||
sa.Column("client_org", sa.String(500), nullable=True),
|
||||
sa.Column("client_name", sa.String(500), nullable=True),
|
||||
sa.Column("client_location", sa.String(500), nullable=True),
|
||||
sa.Column("client_phone", sa.String(64), nullable=True),
|
||||
sa.Column("client_email", sa.String(256), nullable=True),
|
||||
sa.Column("is_legacy", sa.Boolean(), nullable=False, server_default="false"),
|
||||
sa.Column("legacy_date", sa.String(32), nullable=True),
|
||||
sa.Column("legacy_pdf_path", sa.String(1000), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
)
|
||||
op.create_index("idx_crm_quotations_customer", "crm_quotations", ["customer_id"])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# crm_quotation_items
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"crm_quotation_items",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("quotation_id", sa.String(128),
|
||||
sa.ForeignKey("crm_quotations.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("product_id", sa.String(128), nullable=True),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("description_en", sa.Text(), nullable=True),
|
||||
sa.Column("description_gr", sa.Text(), nullable=True),
|
||||
sa.Column("unit_type", sa.String(32), nullable=False, server_default="pcs"),
|
||||
sa.Column("unit_cost", sa.Numeric(12, 4), nullable=False, server_default="0"),
|
||||
sa.Column("discount_percent", sa.Numeric(8, 4), nullable=False, server_default="0"),
|
||||
sa.Column("vat_percent", sa.Numeric(8, 4), nullable=False, server_default="24"),
|
||||
sa.Column("quantity", sa.Numeric(12, 4), nullable=False, server_default="1"),
|
||||
sa.Column("line_total", sa.Numeric(12, 2), nullable=False, server_default="0"),
|
||||
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
|
||||
)
|
||||
op.create_index("idx_crm_quotation_items_quotation", "crm_quotation_items",
|
||||
["quotation_id", "sort_order"])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# melody_drafts
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"melody_drafts",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("status", sa.String(32), nullable=False, server_default="draft"),
|
||||
sa.Column("data", JSONB, nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index("idx_melody_drafts_status", "melody_drafts", ["status"])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# built_melodies
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"built_melodies",
|
||||
sa.Column("id", sa.String(128), primary_key=True),
|
||||
sa.Column("name", sa.String(500), nullable=False),
|
||||
sa.Column("pid", sa.String(128), nullable=False),
|
||||
sa.Column("steps", JSONB, nullable=False),
|
||||
sa.Column("binary_path", sa.String(1000), nullable=True),
|
||||
sa.Column("progmem_code", sa.Text(), nullable=True),
|
||||
sa.Column("assigned_melody_ids", JSONB, nullable=False, server_default="[]"),
|
||||
sa.Column("is_builtin", sa.Boolean(), nullable=False, server_default="false"),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# mfg_audit_log
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"mfg_audit_log",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("timestamp", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
sa.Column("admin_user", sa.String(256), nullable=False),
|
||||
sa.Column("action", sa.String(128), nullable=False),
|
||||
sa.Column("serial_number", sa.String(128), nullable=True),
|
||||
sa.Column("detail", sa.Text(), nullable=True),
|
||||
)
|
||||
op.create_index("idx_mfg_audit_time", "mfg_audit_log", ["timestamp"])
|
||||
op.create_index("idx_mfg_audit_action", "mfg_audit_log", ["action"])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# device_alerts
|
||||
# ------------------------------------------------------------------ #
|
||||
op.create_table(
|
||||
"device_alerts",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("device_serial", sa.String(128), nullable=False),
|
||||
sa.Column("subsystem", sa.String(128), nullable=False),
|
||||
sa.Column("state", sa.String(64), nullable=False),
|
||||
sa.Column("message", sa.Text(), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
sa.UniqueConstraint("device_serial", "subsystem", name="uq_device_alerts_serial_subsystem"),
|
||||
)
|
||||
op.create_index("idx_device_alerts_serial", "device_alerts", ["device_serial"])
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# commands (raw SQL — mirrors SQLite schema, no ORM model)
|
||||
# ------------------------------------------------------------------ #
|
||||
op.execute("""
|
||||
CREATE TABLE commands (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
device_serial TEXT NOT NULL,
|
||||
command_name TEXT NOT NULL,
|
||||
command_payload TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
response_payload TEXT,
|
||||
sent_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
responded_at TIMESTAMPTZ
|
||||
)
|
||||
""")
|
||||
op.execute("CREATE INDEX idx_commands_serial_time ON commands(device_serial, sent_at DESC)")
|
||||
op.execute("CREATE INDEX idx_commands_status ON commands(status)")
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# heartbeats (raw SQL — mirrors SQLite schema, no ORM model)
|
||||
# ------------------------------------------------------------------ #
|
||||
op.execute("""
|
||||
CREATE TABLE heartbeats (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
device_serial TEXT NOT NULL,
|
||||
device_id TEXT,
|
||||
firmware_version TEXT,
|
||||
ip_address TEXT,
|
||||
gateway TEXT,
|
||||
uptime_ms BIGINT,
|
||||
uptime_display TEXT,
|
||||
received_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
""")
|
||||
op.execute("CREATE INDEX idx_heartbeats_serial_time ON heartbeats(device_serial, received_at DESC)")
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# device_logs — partitioned by month on received_at
|
||||
# ------------------------------------------------------------------ #
|
||||
op.execute("""
|
||||
CREATE TABLE device_logs (
|
||||
id BIGSERIAL,
|
||||
device_serial TEXT NOT NULL,
|
||||
level TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
device_timestamp BIGINT,
|
||||
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (id, received_at)
|
||||
) PARTITION BY RANGE (received_at)
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE INDEX idx_device_logs_serial_time
|
||||
ON device_logs(device_serial, received_at DESC)
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE INDEX idx_device_logs_level
|
||||
ON device_logs(level, received_at DESC)
|
||||
""")
|
||||
|
||||
# Create partitions: 2025-01 through 2026-06 (covers all existing data + near future)
|
||||
partitions = [
|
||||
("2025_01", "2025-01-01", "2025-02-01"),
|
||||
("2025_02", "2025-02-01", "2025-03-01"),
|
||||
("2025_03", "2025-03-01", "2025-04-01"),
|
||||
("2025_04", "2025-04-01", "2025-05-01"),
|
||||
("2025_05", "2025-05-01", "2025-06-01"),
|
||||
("2025_06", "2025-06-01", "2025-07-01"),
|
||||
("2025_07", "2025-07-01", "2025-08-01"),
|
||||
("2025_08", "2025-08-01", "2025-09-01"),
|
||||
("2025_09", "2025-09-01", "2025-10-01"),
|
||||
("2025_10", "2025-10-01", "2025-11-01"),
|
||||
("2025_11", "2025-11-01", "2025-12-01"),
|
||||
("2025_12", "2025-12-01", "2026-01-01"),
|
||||
("2026_01", "2026-01-01", "2026-02-01"),
|
||||
("2026_02", "2026-02-01", "2026-03-01"),
|
||||
("2026_03", "2026-03-01", "2026-04-01"),
|
||||
("2026_04", "2026-04-01", "2026-05-01"),
|
||||
("2026_05", "2026-05-01", "2026-06-01"),
|
||||
("2026_06", "2026-06-01", "2026-07-01"),
|
||||
]
|
||||
for suffix, start, end in partitions:
|
||||
op.execute(f"""
|
||||
CREATE TABLE device_logs_{suffix} PARTITION OF device_logs
|
||||
FOR VALUES FROM ('{start}') TO ('{end}')
|
||||
""")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Drop in reverse dependency order
|
||||
op.execute("DROP TABLE IF EXISTS device_logs CASCADE") # drops all partitions too
|
||||
op.execute("DROP TABLE IF EXISTS heartbeats CASCADE")
|
||||
op.execute("DROP TABLE IF EXISTS commands CASCADE")
|
||||
op.drop_table("device_alerts")
|
||||
op.drop_table("mfg_audit_log")
|
||||
op.drop_table("built_melodies")
|
||||
op.drop_table("melody_drafts")
|
||||
op.drop_table("crm_quotation_items")
|
||||
op.drop_table("crm_quotations")
|
||||
op.drop_table("crm_sync_state")
|
||||
op.drop_table("crm_media")
|
||||
op.drop_table("crm_comms_log")
|
||||
op.drop_table("crm_orders")
|
||||
op.drop_table("crm_customers")
|
||||
op.drop_table("crm_products")
|
||||
op.drop_table("public_features")
|
||||
op.drop_table("console_settings")
|
||||
op.drop_table("staff")
|
||||
op.drop_table("audit_log")
|
||||
op.drop_table("_migration_runs")
|
||||
@@ -0,0 +1,78 @@
|
||||
"""mqtt v2 topic migration
|
||||
|
||||
Firmware moved to a new MQTT topic spec (project-vesper's
|
||||
docs/reference/vesper_mqtt_topic_spec_v2.md, feature-catalog F-062). Three
|
||||
schema changes needed to keep ingestion correct against the new payload shapes:
|
||||
|
||||
1. heartbeats.state / heartbeats.ok — the v2 heartbeat payload is flat (no more
|
||||
{"status":"INFO","type":"heartbeat","payload":{...}} wrapper) and adds two
|
||||
new fields: state ("idle"/"playing"/"paused"/"error"/"booting") and ok
|
||||
(overall health), both independently derived on the firmware side — not
|
||||
mirrored from status/playback or system/alerts. Nullable: older rows
|
||||
(pre-migration) and any device still reporting have no value for these.
|
||||
|
||||
2. device_diagnostics_reports gains bell_strikes / bell_loads / cooling_active.
|
||||
The 5-min diagnostics report moved from status/info to system/metrics and
|
||||
picked up per-bell strike/heat data along the way (the topic spec calls out
|
||||
"bell heat ratings" explicitly for this topic). Stored as JSON-encoded TEXT,
|
||||
matching this table's existing stack_high_water column — same reasoning:
|
||||
16 fixed bell slots, but keeping the encoding consistent with the sibling
|
||||
column is simpler than mixing raw JSONB and TEXT in one row shape.
|
||||
|
||||
3. device_reports — new table for the new control/reports topic. Board-
|
||||
initiated, unsolicited, critical events (currently only bell_overload).
|
||||
Distinct from device_alert_events (subsystem health transitions) and
|
||||
device_logs (routine log lines) — this is a narrow, insert-only table for
|
||||
a different kind of signal: urgent, bell-mechanism-specific events the
|
||||
physical tablets act on in real time. The console side is deliberately
|
||||
light for now — store + list for historical/audit purposes; the tablets
|
||||
are the real-time consumer of control/reports, not this console.
|
||||
|
||||
Revision ID: b8c9d0e1f2a3
|
||||
Revises: a7b8c9d0e1f2
|
||||
Create Date: 2026-09-21 00:00:00.000000
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "b8c9d0e1f2a3"
|
||||
down_revision: Union[str, None] = "a7b8c9d0e1f2"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("heartbeats", sa.Column("state", sa.String(16), nullable=True))
|
||||
op.add_column("heartbeats", sa.Column("ok", sa.Boolean(), nullable=True))
|
||||
|
||||
op.add_column("device_diagnostics_reports", sa.Column("bell_strikes", sa.Text(), nullable=True))
|
||||
op.add_column("device_diagnostics_reports", sa.Column("bell_loads", sa.Text(), nullable=True))
|
||||
op.add_column("device_diagnostics_reports", sa.Column("cooling_active", sa.Boolean(), nullable=True))
|
||||
|
||||
op.create_table(
|
||||
"device_reports",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("device_serial", sa.String(128), nullable=False),
|
||||
sa.Column("report_type", sa.String(64), nullable=False),
|
||||
sa.Column("payload", sa.Text(), nullable=True),
|
||||
sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index(
|
||||
"idx_device_reports_serial_occurred",
|
||||
"device_reports",
|
||||
["device_serial", sa.text("occurred_at DESC")],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("idx_device_reports_serial_occurred", table_name="device_reports")
|
||||
op.drop_table("device_reports")
|
||||
|
||||
op.drop_column("device_diagnostics_reports", "cooling_active")
|
||||
op.drop_column("device_diagnostics_reports", "bell_loads")
|
||||
op.drop_column("device_diagnostics_reports", "bell_strikes")
|
||||
|
||||
op.drop_column("heartbeats", "ok")
|
||||
op.drop_column("heartbeats", "state")
|
||||
@@ -0,0 +1,32 @@
|
||||
"""phase_3_staff_ui_prefs
|
||||
|
||||
Adds ui_prefs JSONB column to the staff table (Phase 3 — staff auth cutover).
|
||||
Also corrects permissions to be nullable (sysadmin/admin have NULL permissions).
|
||||
|
||||
Revision ID: c3d4e5f6a7b8
|
||||
Revises: b1c2d3e4f5a6
|
||||
Create Date: 2026-04-17 00:00:00.000000
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from alembic import op
|
||||
|
||||
revision: str = "c3d4e5f6a7b8"
|
||||
down_revision: Union[str, None] = "b1c2d3e4f5a6"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
"staff",
|
||||
sa.Column("ui_prefs", JSONB, nullable=False, server_default="{}"),
|
||||
)
|
||||
# permissions was NOT NULL DEFAULT '{}' — relax to nullable for sysadmin/admin
|
||||
op.alter_column("staff", "permissions", nullable=True)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("staff", "ui_prefs")
|
||||
op.alter_column("staff", "permissions", nullable=False)
|
||||
@@ -0,0 +1,32 @@
|
||||
"""boot event crash detail (firmware F-070)
|
||||
|
||||
Firmware F-070 enriches boot_report (and telemetry.get_boot_history entries)
|
||||
with a fuller `crash` object (backtrace, backtrace_corrupted, elf_sha256) and a
|
||||
new, independent `pre_crash` object (uptime/heap snapshot + optional
|
||||
abort_msg). Both are stored verbatim as JSONB so future additive fields don't
|
||||
need another migration. The existing flat crash_* columns stay and are still
|
||||
filled, so older rows and older firmware keep working unchanged.
|
||||
|
||||
Revision ID: c9d0e1f2a3b4
|
||||
Revises: b8c9d0e1f2a3
|
||||
Create Date: 2026-09-30 00:00:00.000000
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
from alembic import op
|
||||
|
||||
revision: str = "c9d0e1f2a3b4"
|
||||
down_revision: Union[str, None] = "b8c9d0e1f2a3"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("device_boot_events", sa.Column("crash", postgresql.JSONB(), nullable=True))
|
||||
op.add_column("device_boot_events", sa.Column("pre_crash", postgresql.JSONB(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("device_boot_events", "pre_crash")
|
||||
op.drop_column("device_boot_events", "crash")
|
||||
@@ -0,0 +1,48 @@
|
||||
"""device_alert_events
|
||||
|
||||
Adds an insert-only history log of device alert transitions (WARNING/CRITICAL/
|
||||
FAILED only — CLEARED is not logged here). device_alerts remains the current-
|
||||
state table and is untouched; this is purely additive, used to answer "when
|
||||
was the most recent issue on this device" even after it has been resolved.
|
||||
|
||||
Also adds an optional rssi column to heartbeats, for a signal-strength
|
||||
indicator once firmware starts reporting it on the heartbeat payload.
|
||||
|
||||
Revision ID: d4e5f6a7b8c9
|
||||
Revises: c3d4e5f6a7b8
|
||||
Create Date: 2026-07-13 00:00:00.000000
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "d4e5f6a7b8c9"
|
||||
down_revision: Union[str, None] = "c3d4e5f6a7b8"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"device_alert_events",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("device_serial", sa.String(128), nullable=False),
|
||||
sa.Column("subsystem", sa.String(128), nullable=False),
|
||||
sa.Column("state", sa.String(64), nullable=False),
|
||||
sa.Column("message", sa.Text(), nullable=True),
|
||||
sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index(
|
||||
"idx_device_alert_events_serial_occurred",
|
||||
"device_alert_events",
|
||||
["device_serial", sa.text("occurred_at DESC")],
|
||||
)
|
||||
|
||||
op.add_column("heartbeats", sa.Column("rssi", sa.Integer(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("heartbeats", "rssi")
|
||||
op.drop_index("idx_device_alert_events_serial_occurred", table_name="device_alert_events")
|
||||
op.drop_table("device_alert_events")
|
||||
@@ -0,0 +1,39 @@
|
||||
"""device_logs source column
|
||||
|
||||
Adds a 'source' column to device_logs distinguishing the debug log stream
|
||||
(vesper/{id}/logs, source='log') from the general info stream
|
||||
(vesper/{id}/status/info, source='info'), which was previously discarded
|
||||
after only being written to the server debug log. Existing rows default to
|
||||
'log' since that's the only source ever persisted before this migration.
|
||||
|
||||
Adding a column to a partitioned parent table applies it to all existing
|
||||
and future partitions automatically.
|
||||
|
||||
Revision ID: e5f6a7b8c9d0
|
||||
Revises: d4e5f6a7b8c9
|
||||
Create Date: 2026-07-14 00:00:00.000000
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "e5f6a7b8c9d0"
|
||||
down_revision: Union[str, None] = "d4e5f6a7b8c9"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute("""
|
||||
ALTER TABLE device_logs
|
||||
ADD COLUMN source TEXT NOT NULL DEFAULT 'log'
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE INDEX idx_device_logs_source
|
||||
ON device_logs(device_serial, source, received_at DESC)
|
||||
""")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute("DROP INDEX IF EXISTS idx_device_logs_source")
|
||||
op.execute("ALTER TABLE device_logs DROP COLUMN source")
|
||||
@@ -0,0 +1,82 @@
|
||||
"""device health tab — boot events, heartbeat free_heap, ping samples
|
||||
|
||||
Adds three pieces of schema needed for the device Health tab:
|
||||
|
||||
1. device_boot_events — structured, insert-only history of the firmware's
|
||||
boot_report MQTT event (vesper/{uid}/status/info, type="boot_report").
|
||||
Previously this payload was flattened into a single device_logs text line
|
||||
with all structured fields (boot_count, crash detail) discarded on arrival.
|
||||
This table gives the console a real timeline to query and chart against,
|
||||
instead of parsing log strings.
|
||||
|
||||
2. heartbeats.free_heap — firmware now includes free_heap on every 30s
|
||||
heartbeat (previously only available once per boot via boot_report), so
|
||||
the console can chart heap trend instead of seeing one point per boot.
|
||||
|
||||
3. device_ping_samples — backend-computed RTT samples. The firmware's ping
|
||||
command now echoes back a caller-supplied timestamp; the backend pings
|
||||
each online device on an interval and records (now - echoed_ts) here.
|
||||
A dedicated table rather than reusing `commands` because `commands` isn't
|
||||
shaped for time-series charting (mixed command types, no fast per-device
|
||||
time-range query path) and pruning ping history independently of other
|
||||
command history is desirable.
|
||||
|
||||
Revision ID: f6a7b8c9d0e1
|
||||
Revises: e5f6a7b8c9d0
|
||||
Create Date: 2026-07-16 00:00:00.000000
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "f6a7b8c9d0e1"
|
||||
down_revision: Union[str, None] = "e5f6a7b8c9d0"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"device_boot_events",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("device_serial", sa.String(128), nullable=False),
|
||||
sa.Column("boot_count", sa.Integer(), nullable=True),
|
||||
sa.Column("reset_reason", sa.String(64), nullable=True),
|
||||
sa.Column("is_fault", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("free_heap", sa.Integer(), nullable=True),
|
||||
sa.Column("crash_task", sa.String(64), nullable=True),
|
||||
sa.Column("crash_pc", sa.BigInteger(), nullable=True),
|
||||
sa.Column("crash_exc_cause", sa.Integer(), nullable=True),
|
||||
sa.Column("crash_exc_vaddr", sa.BigInteger(), nullable=True),
|
||||
sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index(
|
||||
"idx_device_boot_events_serial_occurred",
|
||||
"device_boot_events",
|
||||
["device_serial", sa.text("occurred_at DESC")],
|
||||
)
|
||||
|
||||
op.add_column("heartbeats", sa.Column("free_heap", sa.Integer(), nullable=True))
|
||||
|
||||
op.create_table(
|
||||
"device_ping_samples",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("device_serial", sa.String(128), nullable=False),
|
||||
sa.Column("rtt_ms", sa.Integer(), nullable=False),
|
||||
sa.Column("sampled_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index(
|
||||
"idx_device_ping_samples_serial_sampled",
|
||||
"device_ping_samples",
|
||||
["device_serial", sa.text("sampled_at DESC")],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("idx_device_ping_samples_serial_sampled", table_name="device_ping_samples")
|
||||
op.drop_table("device_ping_samples")
|
||||
op.drop_column("heartbeats", "free_heap")
|
||||
op.drop_index("idx_device_boot_events_serial_occurred", table_name="device_boot_events")
|
||||
op.drop_table("device_boot_events")
|
||||
@@ -0,0 +1,74 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import select, and_
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from database.postgres import get_pg_session
|
||||
from shared.orm import AuditLog
|
||||
from auth.dependencies import require_sysadmin
|
||||
from auth.models import TokenPayload
|
||||
|
||||
router = APIRouter(prefix="/api/audit-log", tags=["audit-log"])
|
||||
|
||||
_MAX_LIMIT = 200
|
||||
_DEFAULT_LIMIT = 50
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_audit_log(
|
||||
actor_id: Optional[str] = Query(None),
|
||||
entity_type: Optional[str] = Query(None),
|
||||
entity_id: Optional[str] = Query(None),
|
||||
action: Optional[str] = Query(None),
|
||||
from_date: Optional[datetime] = Query(None),
|
||||
to_date: Optional[datetime] = Query(None),
|
||||
limit: int = Query(_DEFAULT_LIMIT, ge=1, le=_MAX_LIMIT),
|
||||
offset: int = Query(0, ge=0),
|
||||
_user: TokenPayload = Depends(require_sysadmin),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
filters = []
|
||||
if actor_id:
|
||||
filters.append(AuditLog.actor_id == actor_id)
|
||||
if entity_type:
|
||||
filters.append(AuditLog.entity_type == entity_type)
|
||||
if entity_id:
|
||||
filters.append(AuditLog.entity_id == entity_id)
|
||||
if action:
|
||||
filters.append(AuditLog.action == action)
|
||||
if from_date:
|
||||
filters.append(AuditLog.occurred_at >= from_date)
|
||||
if to_date:
|
||||
filters.append(AuditLog.occurred_at <= to_date)
|
||||
|
||||
stmt = (
|
||||
select(AuditLog)
|
||||
.where(and_(*filters) if filters else True)
|
||||
.order_by(AuditLog.occurred_at.desc())
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
rows = result.scalars().all()
|
||||
|
||||
return {
|
||||
"entries": [
|
||||
{
|
||||
"id": r.id,
|
||||
"occurred_at": r.occurred_at.isoformat(),
|
||||
"actor_id": r.actor_id,
|
||||
"actor_name": r.actor_name,
|
||||
"action": r.action,
|
||||
"entity_type": r.entity_type,
|
||||
"entity_id": r.entity_id,
|
||||
"entity_label": r.entity_label,
|
||||
"changes": r.changes,
|
||||
"meta": r.meta,
|
||||
}
|
||||
for r in rows
|
||||
],
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
from fastapi import Depends
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from jose import JWTError
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from auth.utils import decode_access_token
|
||||
from auth.models import TokenPayload, Role
|
||||
from database.postgres import get_pg_session
|
||||
from staff.orm import Staff
|
||||
from shared.exceptions import AuthenticationError, AuthorizationError
|
||||
from shared.firebase import get_db
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
@@ -37,18 +41,15 @@ def require_roles(*allowed_roles: Role):
|
||||
return role_checker
|
||||
|
||||
|
||||
async def _get_user_permissions(user: TokenPayload) -> dict:
|
||||
"""Fetch permissions from Firestore for the given user."""
|
||||
async def _get_user_permissions(user: TokenPayload, db: AsyncSession) -> dict | None:
|
||||
"""Fetch permissions from Postgres for the given user."""
|
||||
if user.role in (Role.sysadmin, Role.admin):
|
||||
return None # Full access
|
||||
db = get_db()
|
||||
if not db:
|
||||
result = await db.execute(select(Staff).where(Staff.id == user.sub).limit(1))
|
||||
staff = result.scalar_one_or_none()
|
||||
if staff is None:
|
||||
raise AuthorizationError()
|
||||
doc = db.collection("admin_users").document(user.sub).get()
|
||||
if not doc.exists:
|
||||
raise AuthorizationError()
|
||||
data = doc.to_dict()
|
||||
return data.get("permissions")
|
||||
return staff.permissions
|
||||
|
||||
|
||||
def require_permission(section: str, action: str):
|
||||
@@ -58,17 +59,17 @@ def require_permission(section: str, action: str):
|
||||
"""
|
||||
async def permission_checker(
|
||||
current_user: TokenPayload = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
) -> TokenPayload:
|
||||
# sysadmin and admin have full access
|
||||
if current_user.role in (Role.sysadmin, Role.admin):
|
||||
return current_user
|
||||
|
||||
permissions = await _get_user_permissions(current_user)
|
||||
permissions = await _get_user_permissions(current_user, db)
|
||||
if not permissions:
|
||||
raise AuthorizationError()
|
||||
|
||||
if section == "mqtt":
|
||||
if not permissions.get("mqtt", False):
|
||||
if not permissions.get("mqtt", {}).get("access", False):
|
||||
raise AuthorizationError()
|
||||
return current_user
|
||||
|
||||
@@ -89,11 +90,7 @@ def require_permission(section: str, action: str):
|
||||
# Pre-built convenience dependencies
|
||||
require_sysadmin = require_roles(Role.sysadmin)
|
||||
require_admin_or_above = require_roles(Role.sysadmin, Role.admin)
|
||||
|
||||
# Staff management: only sysadmin and admin
|
||||
require_staff_management = require_roles(Role.sysadmin, Role.admin)
|
||||
|
||||
# Viewer-level: any authenticated user (actual permission check per-action)
|
||||
require_any_authenticated = require_roles(
|
||||
Role.sysadmin, Role.admin, Role.editor, Role.user,
|
||||
)
|
||||
|
||||
+47
-32
@@ -1,59 +1,74 @@
|
||||
from fastapi import APIRouter
|
||||
from shared.firebase import get_db
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from database.postgres import get_pg_session
|
||||
from staff.orm import Staff
|
||||
from auth.models import LoginRequest, TokenResponse
|
||||
from auth.utils import verify_password, create_access_token
|
||||
from shared.audit import log_action
|
||||
from shared.exceptions import AuthenticationError
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
_ROLE_MAP = {
|
||||
"superadmin": "sysadmin",
|
||||
"melody_editor": "editor",
|
||||
"device_manager": "editor",
|
||||
"user_manager": "editor",
|
||||
"viewer": "user",
|
||||
"staff": "user",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
async def login(body: LoginRequest):
|
||||
db = get_db()
|
||||
if not db:
|
||||
raise AuthenticationError("Service unavailable")
|
||||
async def login(
|
||||
body: LoginRequest,
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
result = await db.execute(
|
||||
select(Staff).where(Staff.email == body.email).limit(1)
|
||||
)
|
||||
staff = result.scalar_one_or_none()
|
||||
|
||||
users_ref = db.collection("admin_users")
|
||||
query = users_ref.where("email", "==", body.email).limit(1).get()
|
||||
|
||||
if not query:
|
||||
if staff is None:
|
||||
raise AuthenticationError("Invalid email or password")
|
||||
|
||||
doc = query[0]
|
||||
user_data = doc.to_dict()
|
||||
|
||||
if not user_data.get("is_active", True):
|
||||
if not staff.is_active:
|
||||
raise AuthenticationError("Account is disabled")
|
||||
|
||||
if not verify_password(body.password, user_data["hashed_password"]):
|
||||
if not verify_password(body.password, staff.hashed_password):
|
||||
raise AuthenticationError("Invalid email or password")
|
||||
|
||||
role = user_data["role"]
|
||||
# Map legacy roles to new roles
|
||||
role_mapping = {
|
||||
"superadmin": "sysadmin",
|
||||
"melody_editor": "editor",
|
||||
"device_manager": "editor",
|
||||
"user_manager": "editor",
|
||||
"viewer": "user",
|
||||
}
|
||||
role = role_mapping.get(role, role)
|
||||
role = _ROLE_MAP.get(staff.role, staff.role)
|
||||
|
||||
token = create_access_token({
|
||||
"sub": doc.id,
|
||||
"email": user_data["email"],
|
||||
"role": role,
|
||||
"name": user_data["name"],
|
||||
"sub": staff.id,
|
||||
"email": staff.email,
|
||||
"role": role,
|
||||
"name": staff.name,
|
||||
})
|
||||
|
||||
# Get permissions for editor/user roles
|
||||
permissions = None
|
||||
if role in ("editor", "user"):
|
||||
permissions = user_data.get("permissions")
|
||||
permissions = staff.permissions
|
||||
|
||||
await log_action(
|
||||
db,
|
||||
actor_id=staff.id,
|
||||
actor_name=staff.name,
|
||||
action="LOGIN",
|
||||
entity_type="staff",
|
||||
entity_id=staff.id,
|
||||
entity_label=staff.email,
|
||||
meta={"ip": request.client.host if request.client else None},
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
return TokenResponse(
|
||||
access_token=token,
|
||||
role=role,
|
||||
name=user_data["name"],
|
||||
name=staff.name,
|
||||
permissions=permissions,
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import FileResponse, PlainTextResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
from builder.models import (
|
||||
@@ -9,6 +10,8 @@ from builder.models import (
|
||||
BuiltMelodyListResponse,
|
||||
)
|
||||
from builder import service
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
|
||||
router = APIRouter(prefix="/api/builder/melodies", tags=["builder"])
|
||||
|
||||
@@ -54,8 +57,12 @@ async def get_built_melody(
|
||||
async def create_built_melody(
|
||||
body: BuiltMelodyCreate,
|
||||
_user: TokenPayload = Depends(require_permission("melodies", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return await service.create_built_melody(body)
|
||||
melody = await service.create_built_melody(body)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "archetype",
|
||||
str(melody.id), melody.name or str(melody.id))
|
||||
return melody
|
||||
|
||||
|
||||
@router.put("/{melody_id}", response_model=BuiltMelodyInDB)
|
||||
@@ -63,16 +70,31 @@ async def update_built_melody(
|
||||
melody_id: str,
|
||||
body: BuiltMelodyUpdate,
|
||||
_user: TokenPayload = Depends(require_permission("melodies", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return await service.update_built_melody(melody_id, body)
|
||||
old = await service.get_built_melody(melody_id)
|
||||
melody = await service.update_built_melody(melody_id, body)
|
||||
_SKIP = {"updated_at", "id", "steps", "builtin_code"}
|
||||
changes = {
|
||||
k: {"old": getattr(old, k, None), "new": getattr(melody, k, None)}
|
||||
for k in body.model_fields_set
|
||||
if k not in _SKIP and getattr(old, k, None) != getattr(melody, k, None)
|
||||
}
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "archetype",
|
||||
melody_id, melody.name or melody_id, changes=changes or None)
|
||||
return melody
|
||||
|
||||
|
||||
@router.delete("/{melody_id}", status_code=204)
|
||||
async def delete_built_melody(
|
||||
melody_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("melodies", "delete")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
melody = await service.get_built_melody(melody_id)
|
||||
await service.delete_built_melody(melody_id)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "DELETE", "archetype",
|
||||
melody_id, melody.name if melody else melody_id)
|
||||
|
||||
|
||||
@router.post("/{melody_id}/toggle-builtin", response_model=BuiltMelodyInDB)
|
||||
|
||||
@@ -19,6 +19,9 @@ class Settings(BaseSettings):
|
||||
mqtt_admin_username: str = "admin"
|
||||
mqtt_admin_password: str = ""
|
||||
mqtt_secret: str = "change-me-in-production"
|
||||
# Accept the old shared "vesper" password for device-shaped usernames
|
||||
# (boards on pre-HMAC firmware). Turn off once the logs show no users.
|
||||
mqtt_allow_legacy_password: bool = True
|
||||
mosquitto_password_file: str = "/etc/mosquitto/passwd"
|
||||
mqtt_client_id: str = "bellsystems-admin-panel"
|
||||
|
||||
@@ -26,10 +29,18 @@ class Settings(BaseSettings):
|
||||
sqlite_db_path: str = "./data/database.db"
|
||||
mqtt_data_retention_days: int = 90
|
||||
|
||||
# Postgres
|
||||
database_url: str = "postgresql+asyncpg://bellsystems_user:password@postgres:5432/bellsystems_db"
|
||||
|
||||
# Local file storage
|
||||
built_melodies_storage_path: str = "./storage/built_melodies"
|
||||
firmware_storage_path: str = "./storage/firmware"
|
||||
# xtensa-esp32-elf-addr2line for server-side crash decoding (firmware/elf_store.py).
|
||||
# Empty = look it up on PATH; if absent, the console shows a copy-paste command instead.
|
||||
addr2line_path: str = ""
|
||||
flash_assets_storage_path: str = "./storage/flash_assets"
|
||||
melody_binaries_storage_path: str = "./storage/melody_binaries"
|
||||
melody_download_base_url: str = "http://melodies.bellsystems.net/download"
|
||||
|
||||
# Email (Resend)
|
||||
resend_api_key: str = "re_placeholder_change_me"
|
||||
|
||||
@@ -28,6 +28,16 @@ class MailListResponse(BaseModel):
|
||||
total: int
|
||||
|
||||
|
||||
@router.get("/latest-batch", response_model=dict)
|
||||
async def latest_comm_batch(
|
||||
ids: str = Query(..., description="Comma-separated customer IDs"),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "view")),
|
||||
):
|
||||
"""Return the latest comm summary (id, type, occurred_at) keyed by customer_id."""
|
||||
customer_ids = [i.strip() for i in ids.split(",") if i.strip()]
|
||||
return await service.get_latest_comm_batch(customer_ids)
|
||||
|
||||
|
||||
@router.get("/all", response_model=CommListResponse)
|
||||
async def list_all_comms(
|
||||
type: Optional[str] = Query(None),
|
||||
|
||||
@@ -2,16 +2,86 @@ import asyncio
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends, Query, BackgroundTasks, Body
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
from crm.models import CustomerCreate, CustomerUpdate, CustomerInDB, CustomerListResponse, TransactionEntry
|
||||
from crm import service, nextcloud
|
||||
from config import settings
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
|
||||
router = APIRouter(prefix="/api/crm/customers", tags=["crm-customers"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Diff helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
_SCALAR_FIELDS = {
|
||||
"name", "surname", "title", "organization", "religion", "language",
|
||||
"relationship_status", "nextcloud_folder",
|
||||
}
|
||||
_SKIP_FIELDS = {"updated_at", "firestore_id", "id"}
|
||||
|
||||
|
||||
def _scalar_diff(old, new) -> dict:
|
||||
result = {}
|
||||
for f in _SCALAR_FIELDS:
|
||||
ov = getattr(old, f, None)
|
||||
nv = getattr(new, f, None)
|
||||
if ov != nv:
|
||||
result[f] = {"old": ov, "new": nv}
|
||||
return result
|
||||
|
||||
|
||||
def _list_diff(field: str, old_list: list, new_list: list, label_fn) -> dict:
|
||||
old_labels = {label_fn(i) for i in (old_list or [])}
|
||||
new_labels = {label_fn(i) for i in (new_list or [])}
|
||||
added = new_labels - old_labels
|
||||
removed = old_labels - new_labels
|
||||
result = {}
|
||||
if added:
|
||||
result[f"{field}.added"] = {"old": None, "new": sorted(added)}
|
||||
if removed:
|
||||
result[f"{field}.removed"] = {"old": sorted(removed), "new": None}
|
||||
return result
|
||||
|
||||
|
||||
def _customer_diff(old, new, changed_fields: set) -> dict:
|
||||
changes = _scalar_diff(old, new)
|
||||
|
||||
# contacts — keyed by type+value string
|
||||
if "contacts" in changed_fields:
|
||||
changes.update(_list_diff(
|
||||
"contacts",
|
||||
old.contacts or [],
|
||||
new.contacts or [],
|
||||
lambda c: f"{c.get('type','?')}:{c.get('value','?')}" if isinstance(c, dict)
|
||||
else f"{getattr(c,'type','?')}:{getattr(c,'value','?')}",
|
||||
))
|
||||
|
||||
# location — flatten to individual sub-fields
|
||||
if "location" in changed_fields:
|
||||
old_loc = old.location or {}
|
||||
new_loc = new.location or {}
|
||||
if isinstance(old_loc, object) and not isinstance(old_loc, dict):
|
||||
old_loc = old_loc.model_dump() if hasattr(old_loc, "model_dump") else {}
|
||||
if isinstance(new_loc, object) and not isinstance(new_loc, dict):
|
||||
new_loc = new_loc.model_dump() if hasattr(new_loc, "model_dump") else {}
|
||||
for k in set(old_loc) | set(new_loc):
|
||||
ov, nv = old_loc.get(k), new_loc.get(k)
|
||||
if ov != nv:
|
||||
changes[f"location.{k}"] = {"old": ov, "new": nv}
|
||||
|
||||
# tags
|
||||
if "tags" in changed_fields:
|
||||
old_tags = set(old.tags or [])
|
||||
new_tags = set(new.tags or [])
|
||||
if old_tags != new_tags:
|
||||
changes["tags"] = {"old": sorted(old_tags), "new": sorted(new_tags)}
|
||||
|
||||
return changes
|
||||
|
||||
|
||||
@router.get("", response_model=CustomerListResponse)
|
||||
async def list_customers(
|
||||
@@ -46,10 +116,14 @@ async def create_customer(
|
||||
body: CustomerCreate,
|
||||
background_tasks: BackgroundTasks,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
customer = service.create_customer(body)
|
||||
if settings.nextcloud_url:
|
||||
background_tasks.add_task(_init_nextcloud_folder, customer)
|
||||
label = " ".join(filter(None, [customer.name, customer.surname])) or customer.organization or customer.id
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "customer",
|
||||
customer.id, label)
|
||||
return customer
|
||||
|
||||
|
||||
@@ -65,12 +139,19 @@ async def _init_nextcloud_folder(customer) -> None:
|
||||
|
||||
|
||||
@router.put("/{customer_id}", response_model=CustomerInDB)
|
||||
def update_customer(
|
||||
async def update_customer(
|
||||
customer_id: str,
|
||||
body: CustomerUpdate,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return service.update_customer(customer_id, body)
|
||||
old = service.get_customer(customer_id)
|
||||
customer = service.update_customer(customer_id, body)
|
||||
label = " ".join(filter(None, [customer.name, customer.surname])) or customer.organization or customer_id
|
||||
changes = _customer_diff(old, customer, body.model_fields_set)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "customer",
|
||||
customer_id, label, changes=changes or None)
|
||||
return customer
|
||||
|
||||
|
||||
@router.delete("/{customer_id}", status_code=204)
|
||||
@@ -80,6 +161,7 @@ async def delete_customer(
|
||||
wipe_files: bool = Query(False),
|
||||
wipe_nextcloud: bool = Query(False),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
customer = service.delete_customer(customer_id)
|
||||
nc_path = service.get_customer_nc_path(customer)
|
||||
@@ -104,6 +186,10 @@ async def delete_customer(
|
||||
except Exception as e:
|
||||
logger.warning("Could not rename NC folder for customer %s: %s", customer_id, e)
|
||||
|
||||
label = " ".join(filter(None, [customer.name, customer.surname])) or customer.organization or customer_id
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "DELETE", "customer",
|
||||
customer_id, label)
|
||||
|
||||
|
||||
@router.get("/{customer_id}/last-comm-direction")
|
||||
async def get_last_comm_direction(
|
||||
@@ -117,12 +203,17 @@ async def get_last_comm_direction(
|
||||
# ── Relationship Status ───────────────────────────────────────────────────────
|
||||
|
||||
@router.patch("/{customer_id}/relationship-status", response_model=CustomerInDB)
|
||||
def update_relationship_status(
|
||||
async def update_relationship_status(
|
||||
customer_id: str,
|
||||
body: dict = Body(...),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return service.update_relationship_status(customer_id, body.get("status", ""))
|
||||
customer = service.update_relationship_status(customer_id, body.get("status", ""))
|
||||
label = " ".join(filter(None, [customer.name, customer.surname])) or customer.organization or customer_id
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "STATUS_CHANGE", "customer",
|
||||
customer_id, label, meta={"status": body.get("status", "")})
|
||||
return customer
|
||||
|
||||
|
||||
# ── Technical Issues ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
from crm.models import OrderCreate, OrderUpdate, OrderInDB, OrderListResponse
|
||||
from crm import service
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
|
||||
router = APIRouter(prefix="/api/crm/customers/{customer_id}/orders", tags=["crm-orders"])
|
||||
|
||||
@@ -29,27 +32,35 @@ def get_next_order_number(
|
||||
|
||||
|
||||
@router.post("/init-negotiations", response_model=OrderInDB, status_code=201)
|
||||
def init_negotiations(
|
||||
async def init_negotiations(
|
||||
customer_id: str,
|
||||
body: dict,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return service.init_negotiations(
|
||||
order = service.init_negotiations(
|
||||
customer_id=customer_id,
|
||||
title=body.get("title", ""),
|
||||
note=body.get("note", ""),
|
||||
date=body.get("date"),
|
||||
created_by=body.get("created_by", ""),
|
||||
)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "order",
|
||||
order.id, order.order_number or order.id, meta={"action_detail": "negotiations_started"})
|
||||
return order
|
||||
|
||||
|
||||
@router.post("", response_model=OrderInDB, status_code=201)
|
||||
def create_order(
|
||||
async def create_order(
|
||||
customer_id: str,
|
||||
body: OrderCreate,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return service.create_order(customer_id, body)
|
||||
order = service.create_order(customer_id, body)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "order",
|
||||
order.id, order.order_number or order.id)
|
||||
return order
|
||||
|
||||
|
||||
@router.get("/{order_id}", response_model=OrderInDB)
|
||||
@@ -62,22 +73,37 @@ def get_order(
|
||||
|
||||
|
||||
@router.patch("/{order_id}", response_model=OrderInDB)
|
||||
def update_order(
|
||||
async def update_order(
|
||||
customer_id: str,
|
||||
order_id: str,
|
||||
body: OrderUpdate,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return service.update_order(customer_id, order_id, body)
|
||||
old = service.get_order(customer_id, order_id)
|
||||
order = service.update_order(customer_id, order_id, body)
|
||||
action = "STATUS_CHANGE" if body.status is not None else "UPDATE"
|
||||
_SKIP = {"updated_at", "id", "customer_id", "items", "timeline", "discount", "shipping", "payment_status"}
|
||||
changes = {
|
||||
k: {"old": getattr(old, k, None), "new": getattr(order, k, None)}
|
||||
for k in body.model_fields_set
|
||||
if k not in _SKIP and getattr(old, k, None) != getattr(order, k, None)
|
||||
}
|
||||
await log_action(db, _user.sub, _user.name or _user.email, action, "order",
|
||||
order_id, order.order_number or order_id, changes=changes or None)
|
||||
return order
|
||||
|
||||
|
||||
@router.delete("/{order_id}", status_code=204)
|
||||
def delete_order(
|
||||
async def delete_order(
|
||||
customer_id: str,
|
||||
order_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
service.delete_order(customer_id, order_id)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "DELETE", "order",
|
||||
order_id, order_id)
|
||||
|
||||
|
||||
@router.post("/{order_id}/timeline", response_model=OrderInDB)
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import (
|
||||
BigInteger, Boolean, Column, DateTime, ForeignKey, Index, Integer,
|
||||
Numeric, String, Text, UniqueConstraint,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
|
||||
from sqlalchemy.orm import relationship
|
||||
from database.postgres import Base
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class CrmProduct(Base):
|
||||
__tablename__ = "crm_products"
|
||||
|
||||
id = Column(String(128), primary_key=True) # Firestore doc ID
|
||||
firestore_id = Column(String(128), unique=True) # same as id during transition
|
||||
name = Column(String(500), nullable=False)
|
||||
sku = Column(String(128))
|
||||
category = Column(String(128))
|
||||
description = Column(Text)
|
||||
unit_cost = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
currency = Column(String(10), nullable=False, default="EUR")
|
||||
unit_type = Column(String(32), nullable=False, default="pcs")
|
||||
is_active = Column(Boolean, nullable=False, default=True)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=_now)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
|
||||
|
||||
|
||||
class CrmCustomer(Base):
|
||||
__tablename__ = "crm_customers"
|
||||
__table_args__ = (
|
||||
Index("idx_crm_customers_rel_status", "relationship_status"),
|
||||
Index("idx_crm_customers_name", "name", "surname"),
|
||||
Index("idx_crm_customers_tags", "tags", postgresql_using="gin"),
|
||||
)
|
||||
|
||||
id = Column(String(128), primary_key=True) # Firestore doc ID
|
||||
firestore_id = Column(String(128), unique=True)
|
||||
title = Column(String(32))
|
||||
name = Column(String(255), nullable=False)
|
||||
surname = Column(String(255))
|
||||
organization = Column(String(500))
|
||||
religion = Column(String(64))
|
||||
language = Column(String(10), nullable=False, default="el")
|
||||
folder_id = Column(String(128), unique=True, nullable=False)
|
||||
relationship_status = Column(String(64), nullable=False, default="lead")
|
||||
nextcloud_folder = Column(String(500))
|
||||
contacts = Column(JSONB, nullable=False, default=list)
|
||||
notes = Column(JSONB, nullable=False, default=list)
|
||||
location = Column(JSONB)
|
||||
tags = Column(ARRAY(String), nullable=False, default=list)
|
||||
owned_items = Column(JSONB, nullable=False, default=list)
|
||||
linked_user_ids = Column(ARRAY(String), nullable=False, default=list)
|
||||
technical_issues = Column(JSONB, nullable=False, default=list)
|
||||
install_support = Column(JSONB, nullable=False, default=list)
|
||||
transaction_history = Column(JSONB, nullable=False, default=list)
|
||||
crm_summary = Column(JSONB)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
orders = relationship("CrmOrder", back_populates="customer",
|
||||
cascade="all, delete-orphan", lazy="noload")
|
||||
quotations = relationship("CrmQuotation", back_populates="customer",
|
||||
cascade="all, delete-orphan", lazy="noload")
|
||||
comms = relationship("CrmCommsLog", back_populates="customer",
|
||||
cascade="all, delete-orphan", lazy="noload")
|
||||
media = relationship("CrmMedia", back_populates="customer", lazy="noload")
|
||||
|
||||
|
||||
class CrmOrder(Base):
|
||||
__tablename__ = "crm_orders"
|
||||
__table_args__ = (
|
||||
Index("idx_crm_orders_customer", "customer_id"),
|
||||
Index("idx_crm_orders_status", "status"),
|
||||
)
|
||||
|
||||
id = Column(String(128), primary_key=True) # Firestore doc ID
|
||||
customer_id = Column(String(128), ForeignKey("crm_customers.id", ondelete="CASCADE"),
|
||||
nullable=False)
|
||||
order_number = Column(String(64), unique=True, nullable=False)
|
||||
title = Column(String(500))
|
||||
created_by = Column(String(128))
|
||||
status = Column(String(64), nullable=False, default="negotiating")
|
||||
status_updated_date = Column(DateTime(timezone=True))
|
||||
status_updated_by = Column(String(128))
|
||||
items = Column(JSONB, nullable=False, default=list)
|
||||
subtotal = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
discount = Column(JSONB)
|
||||
total_price = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
currency = Column(String(10), nullable=False, default="EUR")
|
||||
shipping = Column(JSONB)
|
||||
payment_status = Column(JSONB, nullable=False, default=dict)
|
||||
invoice_path = Column(String(500))
|
||||
notes = Column(Text)
|
||||
timeline = Column(JSONB, nullable=False, default=list)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
customer = relationship("CrmCustomer", back_populates="orders")
|
||||
|
||||
|
||||
class CrmCommsLog(Base):
|
||||
__tablename__ = "crm_comms_log"
|
||||
__table_args__ = (
|
||||
Index("idx_crm_comms_customer", "customer_id", "occurred_at"),
|
||||
)
|
||||
|
||||
id = Column(String(128), primary_key=True)
|
||||
customer_id = Column(String(128), ForeignKey("crm_customers.id", ondelete="SET NULL"),
|
||||
nullable=True)
|
||||
type = Column(String(32), nullable=False) # email | sms | call | note | ...
|
||||
mail_account = Column(String(256))
|
||||
direction = Column(String(16), nullable=False) # inbound | outbound
|
||||
subject = Column(String(500))
|
||||
body = Column(Text)
|
||||
body_html = Column(Text)
|
||||
attachments = Column(JSONB, nullable=False, default=list)
|
||||
ext_message_id = Column(String(500))
|
||||
from_addr = Column(String(500))
|
||||
to_addrs = Column(Text) # JSON array as text or comma-sep
|
||||
logged_by = Column(String(128))
|
||||
is_important = Column(Boolean, nullable=False, default=False)
|
||||
is_read = Column(Boolean, nullable=False, default=True)
|
||||
occurred_at = Column(DateTime(timezone=True), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=_now)
|
||||
|
||||
customer = relationship("CrmCustomer", back_populates="comms")
|
||||
|
||||
|
||||
class CrmMedia(Base):
|
||||
__tablename__ = "crm_media"
|
||||
__table_args__ = (
|
||||
Index("idx_crm_media_customer", "customer_id"),
|
||||
Index("idx_crm_media_order", "order_id"),
|
||||
)
|
||||
|
||||
id = Column(String(128), primary_key=True)
|
||||
customer_id = Column(String(128), ForeignKey("crm_customers.id", ondelete="SET NULL"),
|
||||
nullable=True)
|
||||
order_id = Column(String(128))
|
||||
filename = Column(String(500), nullable=False)
|
||||
nextcloud_path = Column(String(1000), nullable=False)
|
||||
thumbnail_path = Column(String(1000))
|
||||
mime_type = Column(String(128))
|
||||
direction = Column(String(16))
|
||||
tags = Column(JSONB, nullable=False, default=list)
|
||||
uploaded_by = Column(String(128))
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=_now)
|
||||
|
||||
customer = relationship("CrmCustomer", back_populates="media")
|
||||
|
||||
|
||||
class CrmSyncState(Base):
|
||||
__tablename__ = "crm_sync_state"
|
||||
|
||||
key = Column(String(128), primary_key=True)
|
||||
value = Column(Text)
|
||||
|
||||
|
||||
class CrmQuotation(Base):
|
||||
__tablename__ = "crm_quotations"
|
||||
__table_args__ = (
|
||||
Index("idx_crm_quotations_customer", "customer_id"),
|
||||
)
|
||||
|
||||
id = Column(String(128), primary_key=True)
|
||||
quotation_number = Column(String(64), unique=True, nullable=False)
|
||||
title = Column(String(500))
|
||||
subtitle = Column(String(500))
|
||||
customer_id = Column(String(128), ForeignKey("crm_customers.id", ondelete="CASCADE"),
|
||||
nullable=False)
|
||||
language = Column(String(10), nullable=False, default="en")
|
||||
status = Column(String(32), nullable=False, default="draft")
|
||||
order_type = Column(String(64))
|
||||
shipping_method = Column(String(64))
|
||||
estimated_shipping_date = Column(String(32)) # stored as DATE string
|
||||
global_discount_label = Column(String(128))
|
||||
global_discount_percent = Column(Numeric(8, 4), nullable=False, default=0)
|
||||
vat_percent = Column(Numeric(8, 4), nullable=False, default=24)
|
||||
global_vat_percent = Column(Numeric(8, 4), nullable=False, default=24)
|
||||
shipping_cost = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
shipping_cost_discount = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
install_cost = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
install_cost_discount = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
extras_label = Column(String(256))
|
||||
extras_cost = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
comments = Column(JSONB, nullable=False, default=list)
|
||||
quick_notes = Column(JSONB, nullable=False, default=dict)
|
||||
subtotal_before_discount = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
global_discount_amount = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
new_subtotal = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
vat_amount = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
final_total = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
nextcloud_pdf_path = Column(String(1000))
|
||||
nextcloud_pdf_url = Column(String(1000))
|
||||
# Client snapshot fields (denormalised for PDF generation)
|
||||
client_org = Column(String(500))
|
||||
client_name = Column(String(500))
|
||||
client_location = Column(String(500))
|
||||
client_phone = Column(String(64))
|
||||
client_email = Column(String(256))
|
||||
# Legacy quotation fields
|
||||
is_legacy = Column(Boolean, nullable=False, default=False)
|
||||
legacy_date = Column(String(32))
|
||||
legacy_pdf_path = Column(String(1000))
|
||||
created_at = Column(DateTime(timezone=True), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
customer = relationship("CrmCustomer", back_populates="quotations")
|
||||
items = relationship("CrmQuotationItem", back_populates="quotation",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="CrmQuotationItem.sort_order", lazy="noload")
|
||||
|
||||
|
||||
class CrmQuotationItem(Base):
|
||||
__tablename__ = "crm_quotation_items"
|
||||
__table_args__ = (
|
||||
Index("idx_crm_quotation_items_quotation", "quotation_id", "sort_order"),
|
||||
)
|
||||
|
||||
id = Column(String(128), primary_key=True)
|
||||
quotation_id = Column(String(128), ForeignKey("crm_quotations.id", ondelete="CASCADE"),
|
||||
nullable=False)
|
||||
product_id = Column(String(128))
|
||||
description = Column(Text)
|
||||
description_en = Column(Text)
|
||||
description_gr = Column(Text)
|
||||
unit_type = Column(String(32), nullable=False, default="pcs")
|
||||
unit_cost = Column(Numeric(12, 4), nullable=False, default=0)
|
||||
discount_percent = Column(Numeric(8, 4), nullable=False, default=0)
|
||||
vat_percent = Column(Numeric(8, 4), nullable=False, default=24)
|
||||
quantity = Column(Numeric(12, 4), nullable=False, default=1)
|
||||
line_total = Column(Numeric(12, 2), nullable=False, default=0)
|
||||
sort_order = Column(Integer, nullable=False, default=0)
|
||||
|
||||
quotation = relationship("CrmQuotation", back_populates="items")
|
||||
@@ -5,9 +5,10 @@ from pydantic import BaseModel
|
||||
|
||||
class QuotationStatus(str, Enum):
|
||||
draft = "draft"
|
||||
built = "built"
|
||||
sent = "sent"
|
||||
accepted = "accepted"
|
||||
rejected = "rejected"
|
||||
declined = "declined"
|
||||
|
||||
|
||||
class QuotationItemCreate(BaseModel):
|
||||
@@ -39,6 +40,7 @@ class QuotationCreate(BaseModel):
|
||||
estimated_shipping_date: Optional[str] = None
|
||||
global_discount_label: Optional[str] = None
|
||||
global_discount_percent: float = 0.0
|
||||
global_vat_percent: float = 24.0
|
||||
shipping_cost: float = 0.0
|
||||
shipping_cost_discount: float = 0.0
|
||||
install_cost: float = 0.0
|
||||
@@ -70,6 +72,7 @@ class QuotationUpdate(BaseModel):
|
||||
estimated_shipping_date: Optional[str] = None
|
||||
global_discount_label: Optional[str] = None
|
||||
global_discount_percent: Optional[float] = None
|
||||
global_vat_percent: Optional[float] = None
|
||||
shipping_cost: Optional[float] = None
|
||||
shipping_cost_discount: Optional[float] = None
|
||||
install_cost: Optional[float] = None
|
||||
@@ -104,6 +107,7 @@ class QuotationInDB(BaseModel):
|
||||
estimated_shipping_date: Optional[str] = None
|
||||
global_discount_label: Optional[str] = None
|
||||
global_discount_percent: float = 0.0
|
||||
global_vat_percent: float = 24.0
|
||||
shipping_cost: float = 0.0
|
||||
shipping_cost_discount: float = 0.0
|
||||
install_cost: float = 0.0
|
||||
|
||||
@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, Query, UploadFile, File
|
||||
from fastapi.responses import StreamingResponse
|
||||
from typing import Optional
|
||||
import io
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from auth.dependencies import require_permission
|
||||
from auth.models import TokenPayload
|
||||
@@ -13,6 +14,8 @@ from crm.quotation_models import (
|
||||
QuotationUpdate,
|
||||
)
|
||||
from crm import quotations_service as svc
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
|
||||
router = APIRouter(prefix="/api/crm/quotations", tags=["crm-quotations"])
|
||||
|
||||
@@ -72,11 +75,15 @@ async def create_quotation(
|
||||
body: QuotationCreate,
|
||||
generate_pdf: bool = Query(False),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""
|
||||
Create a quotation. Pass ?generate_pdf=true to immediately generate and upload the PDF.
|
||||
"""
|
||||
return await svc.create_quotation(body, generate_pdf=generate_pdf)
|
||||
q = await svc.create_quotation(body, generate_pdf=generate_pdf)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "quotation",
|
||||
str(q.id), q.quotation_number or str(q.id))
|
||||
return q
|
||||
|
||||
|
||||
@router.put("/{quotation_id}", response_model=QuotationInDB)
|
||||
@@ -85,19 +92,34 @@ async def update_quotation(
|
||||
body: QuotationUpdate,
|
||||
generate_pdf: bool = Query(False),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""
|
||||
Update a quotation. Pass ?generate_pdf=true to regenerate the PDF.
|
||||
"""
|
||||
return await svc.update_quotation(quotation_id, body, generate_pdf=generate_pdf)
|
||||
old = await svc.get_quotation(quotation_id)
|
||||
q = await svc.update_quotation(quotation_id, body, generate_pdf=generate_pdf)
|
||||
_SKIP = {"updated_at", "id", "items", "pdf_path"}
|
||||
changes = {
|
||||
k: {"old": getattr(old, k, None), "new": getattr(q, k, None)}
|
||||
for k in body.model_fields_set
|
||||
if k not in _SKIP and getattr(old, k, None) != getattr(q, k, None)
|
||||
}
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "quotation",
|
||||
quotation_id, q.quotation_number or quotation_id, changes=changes or None)
|
||||
return q
|
||||
|
||||
|
||||
@router.delete("/{quotation_id}", status_code=204)
|
||||
async def delete_quotation(
|
||||
quotation_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
q = await svc.get_quotation(quotation_id)
|
||||
await svc.delete_quotation(quotation_id)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "DELETE", "quotation",
|
||||
quotation_id, q.quotation_number if q else quotation_id)
|
||||
|
||||
|
||||
@router.post("/{quotation_id}/regenerate-pdf", response_model=QuotationInDB)
|
||||
|
||||
@@ -42,6 +42,7 @@ def _float(d: Decimal) -> float:
|
||||
def _calculate_totals(
|
||||
items: list,
|
||||
global_discount_percent: float,
|
||||
global_vat_percent: float,
|
||||
shipping_cost: float,
|
||||
shipping_cost_discount: float,
|
||||
install_cost: float,
|
||||
@@ -50,21 +51,20 @@ def _calculate_totals(
|
||||
) -> dict:
|
||||
"""
|
||||
Calculate all monetary totals using Decimal arithmetic (ROUND_HALF_UP).
|
||||
VAT is computed per-item from each item's vat_percent field.
|
||||
VAT is a single global rate applied to items only (not shipping or install).
|
||||
Shipping and install costs carry 0% VAT.
|
||||
Returns a dict of floats ready for DB storage.
|
||||
"""
|
||||
# Per-line totals and per-item VAT
|
||||
# Per-line totals (items only)
|
||||
item_totals = []
|
||||
item_vat = Decimal(0)
|
||||
for item in items:
|
||||
cost = _d(item.get("unit_cost", 0))
|
||||
qty = _d(item.get("quantity", 1))
|
||||
disc = _d(item.get("discount_percent", 0))
|
||||
net = cost * qty * (1 - disc / 100)
|
||||
item_totals.append(net)
|
||||
vat_pct = _d(item.get("vat_percent", 24))
|
||||
item_vat += net * (vat_pct / 100)
|
||||
|
||||
items_net = sum(item_totals, Decimal(0))
|
||||
|
||||
# Shipping net (VAT = 0%)
|
||||
ship_gross = _d(shipping_cost)
|
||||
@@ -76,16 +76,17 @@ def _calculate_totals(
|
||||
install_disc = _d(install_cost_discount)
|
||||
install_net = install_gross * (1 - install_disc / 100)
|
||||
|
||||
subtotal = sum(item_totals, Decimal(0)) + ship_net + install_net
|
||||
subtotal = items_net + ship_net + install_net
|
||||
|
||||
global_disc_pct = _d(global_discount_percent)
|
||||
global_disc_amount = subtotal * (global_disc_pct / 100)
|
||||
new_subtotal = subtotal - global_disc_amount
|
||||
|
||||
# Global discount proportionally reduces VAT too
|
||||
if subtotal > 0:
|
||||
disc_ratio = new_subtotal / subtotal
|
||||
vat_amount = item_vat * disc_ratio
|
||||
# VAT applies only to items portion, scaled by the global discount ratio
|
||||
vat_pct = _d(global_vat_percent)
|
||||
if subtotal > 0 and items_net > 0:
|
||||
items_ratio = items_net / subtotal
|
||||
vat_amount = new_subtotal * items_ratio * (vat_pct / 100)
|
||||
else:
|
||||
vat_amount = Decimal(0)
|
||||
|
||||
@@ -109,14 +110,16 @@ def _calc_line_total(item) -> float:
|
||||
|
||||
|
||||
async def _generate_quotation_number(db) -> str:
|
||||
year = datetime.utcnow().year
|
||||
prefix = f"QT-{year}-"
|
||||
now = datetime.utcnow()
|
||||
yy = now.strftime("%y")
|
||||
mm = now.strftime("%m")
|
||||
prefix = f"QT-{yy}-{mm}-"
|
||||
rows = await db.execute_fetchall(
|
||||
"SELECT quotation_number FROM crm_quotations WHERE quotation_number LIKE ? ORDER BY quotation_number DESC LIMIT 1",
|
||||
(f"{prefix}%",),
|
||||
)
|
||||
if rows:
|
||||
last_num = rows[0][0] # e.g. "QT-2026-012"
|
||||
last_num = rows[0][0] # e.g. "QT-26-04-012"
|
||||
try:
|
||||
seq = int(last_num[len(prefix):]) + 1
|
||||
except ValueError:
|
||||
@@ -174,13 +177,16 @@ async def list_all_quotations() -> list[dict]:
|
||||
doc = fstore.collection("crm_customers").document(cid).get()
|
||||
if doc.exists:
|
||||
d = doc.to_dict()
|
||||
parts = [d.get("name", ""), d.get("surname", ""), d.get("organization", "")]
|
||||
label = " ".join(p for p in parts if p).strip()
|
||||
customer_names[cid] = label or cid
|
||||
name_parts = [d.get("name", ""), d.get("surname", "")]
|
||||
full_name = " ".join(p for p in name_parts if p).strip()
|
||||
org = (d.get("organization", "") or "").strip()
|
||||
customer_names[cid] = {"name": full_name or cid, "org": org}
|
||||
except Exception:
|
||||
customer_names[cid] = cid
|
||||
customer_names[cid] = {"name": cid, "org": ""}
|
||||
for item in items:
|
||||
item["customer_name"] = customer_names.get(item["customer_id"], "")
|
||||
info = customer_names.get(item["customer_id"], {"name": "", "org": ""})
|
||||
item["customer_name"] = info["name"]
|
||||
item["customer_org"] = info["org"]
|
||||
return items
|
||||
|
||||
|
||||
@@ -222,6 +228,7 @@ async def create_quotation(data: QuotationCreate, generate_pdf: bool = False) ->
|
||||
totals = _calculate_totals(
|
||||
items_raw,
|
||||
data.global_discount_percent,
|
||||
data.global_vat_percent,
|
||||
data.shipping_cost,
|
||||
data.shipping_cost_discount,
|
||||
data.install_cost,
|
||||
@@ -236,7 +243,7 @@ async def create_quotation(data: QuotationCreate, generate_pdf: bool = False) ->
|
||||
"""INSERT INTO crm_quotations (
|
||||
id, quotation_number, title, subtitle, customer_id,
|
||||
language, status, order_type, shipping_method, estimated_shipping_date,
|
||||
global_discount_label, global_discount_percent,
|
||||
global_discount_label, global_discount_percent, global_vat_percent,
|
||||
shipping_cost, shipping_cost_discount, install_cost, install_cost_discount,
|
||||
extras_label, extras_cost, comments, quick_notes,
|
||||
subtotal_before_discount, global_discount_amount, new_subtotal, vat_amount, final_total,
|
||||
@@ -247,7 +254,7 @@ async def create_quotation(data: QuotationCreate, generate_pdf: bool = False) ->
|
||||
) VALUES (
|
||||
?, ?, ?, ?, ?,
|
||||
?, 'draft', ?, ?, ?,
|
||||
?, ?,
|
||||
?, ?, ?,
|
||||
?, ?, ?, ?,
|
||||
?, ?, ?, ?,
|
||||
?, ?, ?, ?, ?,
|
||||
@@ -259,7 +266,7 @@ async def create_quotation(data: QuotationCreate, generate_pdf: bool = False) ->
|
||||
(
|
||||
qid, quotation_number, data.title, data.subtitle, data.customer_id,
|
||||
data.language, data.order_type, data.shipping_method, data.estimated_shipping_date,
|
||||
data.global_discount_label, data.global_discount_percent,
|
||||
data.global_discount_label, data.global_discount_percent, data.global_vat_percent,
|
||||
data.shipping_cost, data.shipping_cost_discount, data.install_cost, data.install_cost_discount,
|
||||
data.extras_label, data.extras_cost, comments_json, quick_notes_json,
|
||||
totals["subtotal_before_discount"], totals["global_discount_amount"],
|
||||
@@ -317,7 +324,7 @@ async def update_quotation(quotation_id: str, data: QuotationUpdate, generate_pd
|
||||
|
||||
scalar_fields = [
|
||||
"title", "subtitle", "language", "status", "order_type", "shipping_method",
|
||||
"estimated_shipping_date", "global_discount_label", "global_discount_percent",
|
||||
"estimated_shipping_date", "global_discount_label", "global_discount_percent", "global_vat_percent",
|
||||
"shipping_cost", "shipping_cost_discount", "install_cost",
|
||||
"install_cost_discount", "extras_label", "extras_cost",
|
||||
"client_org", "client_name", "client_location", "client_phone", "client_email",
|
||||
@@ -352,6 +359,7 @@ async def update_quotation(quotation_id: str, data: QuotationUpdate, generate_pd
|
||||
totals = _calculate_totals(
|
||||
items_raw,
|
||||
float(merged.get("global_discount_percent", 0)),
|
||||
float(merged.get("global_vat_percent", 24)),
|
||||
float(merged.get("shipping_cost", 0)),
|
||||
float(merged.get("shipping_cost_discount", 0)),
|
||||
float(merged.get("install_cost", 0)),
|
||||
|
||||
+27
-5
@@ -3,11 +3,14 @@ from fastapi.responses import FileResponse
|
||||
from typing import Optional
|
||||
import os
|
||||
import shutil
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
from crm.models import ProductCreate, ProductUpdate, ProductInDB, ProductListResponse
|
||||
from crm import service
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
|
||||
router = APIRouter(prefix="/api/crm/products", tags=["crm-products"])
|
||||
|
||||
@@ -35,28 +38,47 @@ def get_product(
|
||||
|
||||
|
||||
@router.post("", response_model=ProductInDB, status_code=201)
|
||||
def create_product(
|
||||
async def create_product(
|
||||
body: ProductCreate,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return service.create_product(body)
|
||||
product = service.create_product(body)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "product",
|
||||
product.id, product.name)
|
||||
return product
|
||||
|
||||
|
||||
@router.put("/{product_id}", response_model=ProductInDB)
|
||||
def update_product(
|
||||
async def update_product(
|
||||
product_id: str,
|
||||
body: ProductUpdate,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return service.update_product(product_id, body)
|
||||
old = service.get_product(product_id)
|
||||
product = service.update_product(product_id, body)
|
||||
_SKIP = {"updated_at", "id", "photo_url"}
|
||||
changes = {
|
||||
k: {"old": getattr(old, k, None), "new": getattr(product, k, None)}
|
||||
for k in body.model_fields_set
|
||||
if k not in _SKIP and getattr(old, k, None) != getattr(product, k, None)
|
||||
}
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "product",
|
||||
product_id, product.name, changes=changes or None)
|
||||
return product
|
||||
|
||||
|
||||
@router.delete("/{product_id}", status_code=204)
|
||||
def delete_product(
|
||||
async def delete_product(
|
||||
product_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
product = service.get_product(product_id)
|
||||
service.delete_product(product_id)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "DELETE", "product",
|
||||
product_id, product.name)
|
||||
|
||||
|
||||
@router.post("/{product_id}/photo", response_model=ProductInDB)
|
||||
|
||||
@@ -305,6 +305,33 @@ async def get_last_comm_timestamp(customer_id: str) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
async def get_latest_comm_batch(customer_ids: list[str]) -> dict[str, dict]:
|
||||
"""Return a dict of customer_id → {id, type, occurred_at} for the latest comm per customer.
|
||||
Uses a single SQL query — no N+1 regardless of list size.
|
||||
"""
|
||||
if not customer_ids:
|
||||
return {}
|
||||
db = await mqtt_db.get_db()
|
||||
placeholders = ",".join("?" * len(customer_ids))
|
||||
rows = await db.execute_fetchall(
|
||||
f"""
|
||||
SELECT customer_id, id, type, COALESCE(occurred_at, created_at) AS ts
|
||||
FROM crm_comms_log
|
||||
WHERE customer_id IN ({placeholders})
|
||||
AND customer_id IS NOT NULL AND customer_id != ''
|
||||
ORDER BY ts DESC
|
||||
""",
|
||||
customer_ids,
|
||||
)
|
||||
# Keep only the first (latest) row per customer
|
||||
result: dict[str, dict] = {}
|
||||
for row in rows:
|
||||
cid = row[0]
|
||||
if cid not in result:
|
||||
result[cid] = {"id": row[1], "type": row[2], "occurred_at": row[3]}
|
||||
return result
|
||||
|
||||
|
||||
async def list_customers_sorted_by_latest_comm(customers: list[CustomerInDB]) -> list[CustomerInDB]:
|
||||
"""Re-sort a list of customers so those with the most recent comm come first."""
|
||||
timestamps = await asyncio.gather(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from database.core import (
|
||||
# MQTT live data — Phase 5: all functions now backed by Postgres
|
||||
from database.pg_mqtt import (
|
||||
init_db,
|
||||
close_db,
|
||||
get_db,
|
||||
purge_loop,
|
||||
purge_old_data,
|
||||
insert_log,
|
||||
@@ -12,12 +12,48 @@ from database.core import (
|
||||
get_heartbeats,
|
||||
get_commands,
|
||||
get_latest_heartbeats,
|
||||
get_latest_heartbeat,
|
||||
warm_latest_cache,
|
||||
get_pending_command,
|
||||
upsert_alert,
|
||||
delete_alert,
|
||||
get_alerts,
|
||||
insert_alert_event,
|
||||
get_latest_alert_events,
|
||||
get_latest_alert_event,
|
||||
get_alert_events,
|
||||
insert_boot_event,
|
||||
get_boot_events,
|
||||
get_latest_boot_event,
|
||||
merge_device_boot_history,
|
||||
get_crash_events,
|
||||
insert_ping_sample,
|
||||
get_ping_samples,
|
||||
get_latest_ping_samples,
|
||||
insert_diagnostics_report,
|
||||
get_diagnostics_reports,
|
||||
get_latest_diagnostics_report,
|
||||
get_latest_diagnostics_reports,
|
||||
insert_report,
|
||||
get_reports,
|
||||
delete_device_logs,
|
||||
delete_device_logs_filtered,
|
||||
delete_device_heartbeats,
|
||||
delete_device_commands,
|
||||
delete_device_alert_events,
|
||||
delete_device_current_alerts,
|
||||
delete_device_boot_events,
|
||||
delete_device_ping_samples,
|
||||
delete_device_diagnostics_reports,
|
||||
delete_device_reports,
|
||||
partition_manager_loop,
|
||||
ensure_current_partitions,
|
||||
)
|
||||
|
||||
# SQLite connection — still used by melodies, builder, manufacturing, and crm
|
||||
# modules that have not yet been cut over to Postgres.
|
||||
from database.core import get_db
|
||||
|
||||
__all__ = [
|
||||
"init_db",
|
||||
"close_db",
|
||||
@@ -32,8 +68,40 @@ __all__ = [
|
||||
"get_heartbeats",
|
||||
"get_commands",
|
||||
"get_latest_heartbeats",
|
||||
"get_latest_heartbeat",
|
||||
"warm_latest_cache",
|
||||
"get_pending_command",
|
||||
"upsert_alert",
|
||||
"delete_alert",
|
||||
"get_alerts",
|
||||
"insert_alert_event",
|
||||
"get_latest_alert_events",
|
||||
"get_latest_alert_event",
|
||||
"get_alert_events",
|
||||
"insert_boot_event",
|
||||
"get_boot_events",
|
||||
"get_latest_boot_event",
|
||||
"merge_device_boot_history",
|
||||
"get_crash_events",
|
||||
"insert_ping_sample",
|
||||
"get_ping_samples",
|
||||
"get_latest_ping_samples",
|
||||
"insert_diagnostics_report",
|
||||
"get_diagnostics_reports",
|
||||
"get_latest_diagnostics_report",
|
||||
"get_latest_diagnostics_reports",
|
||||
"insert_report",
|
||||
"get_reports",
|
||||
"delete_device_logs",
|
||||
"delete_device_logs_filtered",
|
||||
"delete_device_heartbeats",
|
||||
"delete_device_commands",
|
||||
"delete_device_alert_events",
|
||||
"delete_device_current_alerts",
|
||||
"delete_device_boot_events",
|
||||
"delete_device_ping_samples",
|
||||
"delete_device_diagnostics_reports",
|
||||
"delete_device_reports",
|
||||
"partition_manager_loop",
|
||||
"ensure_current_partitions",
|
||||
]
|
||||
|
||||
@@ -208,6 +208,7 @@ async def init_db():
|
||||
"ALTER TABLE crm_quotation_items ADD COLUMN description_en TEXT",
|
||||
"ALTER TABLE crm_quotation_items ADD COLUMN description_gr TEXT",
|
||||
"ALTER TABLE built_melodies ADD COLUMN is_builtin INTEGER NOT NULL DEFAULT 0",
|
||||
"ALTER TABLE crm_quotations ADD COLUMN global_vat_percent REAL NOT NULL DEFAULT 24",
|
||||
]
|
||||
for m in _migrations:
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""In-memory "latest row per device" cache for the fleet-wide status reads.
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
/mqtt/status (device list + device detail), /mqtt/latest-metrics and the
|
||||
backend ping loop all need "the newest heartbeat / alert event / ping sample /
|
||||
diagnostics report for every device". In Postgres that is a
|
||||
`SELECT DISTINCT ON (device_serial) ... ORDER BY device_serial, ts DESC`,
|
||||
which has to walk the entire history index — heartbeats alone grow by one row
|
||||
per device every 30s and are kept for the full retention window, so each call
|
||||
took seconds and the console showed empty status columns until it finished.
|
||||
|
||||
The MQTT ingest path already sees every new row as it is written, so instead
|
||||
we keep the newest row per device in memory:
|
||||
|
||||
* seed() — one DISTINCT ON query per kind, run once at startup (and lazily
|
||||
on first read if startup warming hasn't finished yet).
|
||||
* put() — called by every insert, keeps whichever row is newer, so rows
|
||||
written while the seed query is still running are never lost.
|
||||
* drop_device() / drop_older_than() — mirror per-device deletes (Reset
|
||||
Stats, Delete Logs) and the retention purge so the cache never
|
||||
shows a row the database no longer has.
|
||||
|
||||
Single process only: the backend runs one uvicorn worker that also owns the
|
||||
MQTT client (see main.py startup), so there is no cross-process staleness.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# kind -> timestamp column used to decide which row is newest
|
||||
TS_FIELD = {
|
||||
"heartbeat": "received_at",
|
||||
"alert_event": "occurred_at",
|
||||
"ping": "sampled_at",
|
||||
"diag": "received_at",
|
||||
}
|
||||
|
||||
_rows: dict[str, dict[str, dict]] = {kind: {} for kind in TS_FIELD}
|
||||
_warm: dict[str, bool] = {kind: False for kind in TS_FIELD}
|
||||
|
||||
|
||||
def _ts(kind: str, row: dict) -> datetime:
|
||||
raw = row.get(TS_FIELD[kind])
|
||||
if isinstance(raw, datetime):
|
||||
return raw if raw.tzinfo else raw.replace(tzinfo=timezone.utc)
|
||||
try:
|
||||
parsed = datetime.fromisoformat(raw)
|
||||
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
||||
except (TypeError, ValueError):
|
||||
return datetime.min.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def put(kind: str, row: dict) -> None:
|
||||
"""Record a row if it is the newest one seen for its device."""
|
||||
serial = row.get("device_serial")
|
||||
if not serial:
|
||||
return
|
||||
current = _rows[kind].get(serial)
|
||||
if current is None or _ts(kind, row) >= _ts(kind, current):
|
||||
_rows[kind][serial] = row
|
||||
|
||||
|
||||
def seed(kind: str, rows: list[dict]) -> None:
|
||||
for row in rows:
|
||||
put(kind, row)
|
||||
_warm[kind] = True
|
||||
|
||||
|
||||
def is_warm(kind: str) -> bool:
|
||||
return _warm[kind]
|
||||
|
||||
|
||||
def snapshot(kind: str) -> list[dict] | None:
|
||||
"""All cached rows for a kind, or None if the cache isn't seeded yet."""
|
||||
if not _warm[kind]:
|
||||
return None
|
||||
return list(_rows[kind].values())
|
||||
|
||||
|
||||
def get(kind: str, serial: str) -> dict | None:
|
||||
return _rows[kind].get(serial)
|
||||
|
||||
|
||||
def drop_device(kind: str, serial: str) -> None:
|
||||
_rows[kind].pop(serial, None)
|
||||
|
||||
|
||||
def drop_older_than(kind: str, cutoff: datetime) -> None:
|
||||
stale = [s for s, row in _rows[kind].items() if _ts(kind, row) < cutoff]
|
||||
for serial in stale:
|
||||
del _rows[kind][serial]
|
||||
@@ -0,0 +1,23 @@
|
||||
from database.postgres import Base # noqa: F401 — Base must be imported for Alembic autogenerate
|
||||
|
||||
# Import all ORM models here so Alembic autogenerate detects them.
|
||||
# Add each new model file as it is created.
|
||||
|
||||
# --- Existing ---
|
||||
from notes.orm import Entry, EntryLink # noqa: F401
|
||||
from tickets.orm import SupportTicket, TicketMessage # noqa: F401
|
||||
|
||||
# --- Phase 0 ---
|
||||
from shared.orm import MigrationRun, AuditLog # noqa: F401
|
||||
from crm.orm import ( # noqa: F401
|
||||
CrmProduct, CrmCustomer, CrmOrder,
|
||||
CrmCommsLog, CrmMedia, CrmSyncState,
|
||||
CrmQuotation, CrmQuotationItem,
|
||||
)
|
||||
from staff.orm import Staff # noqa: F401
|
||||
from settings.orm import ConsoleSetting, PublicFeature # noqa: F401
|
||||
from melodies.orm import MelodyDraft, BuiltMelody # noqa: F401
|
||||
from manufacturing.orm import MfgAuditLog # noqa: F401
|
||||
from devices.orm import DeviceAlert # noqa: F401
|
||||
# NOTE: device_logs, commands, heartbeats are partitioned/raw-SQL tables —
|
||||
# they are NOT ORM models and are created via op.execute() in the migration.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,16 @@
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
from config import settings
|
||||
|
||||
engine = create_async_engine(settings.database_url, pool_size=10, echo=False)
|
||||
AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
async def get_pg_session() -> AsyncSession:
|
||||
"""FastAPI dependency — yields a DB session and closes it after the request."""
|
||||
async with AsyncSessionLocal() as session:
|
||||
yield session
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Device documents <-> Firestore schema v1.
|
||||
|
||||
The contract lives in the bellsystems-schema repo (v1/firestore.schema.json). v1 is
|
||||
the shape the shipped tablet and phone apps read. FlutterFlow parses each document
|
||||
inside safeGet: ONE field of the wrong type makes the app silently drop the whole
|
||||
device from the user's list. So every console write to a device goes through
|
||||
`to_firestore`, and every read goes through `to_api`.
|
||||
|
||||
Rules enforced here (README "rules every writer must follow"):
|
||||
- Timestamps are Firestore Timestamps (datetime). Unset = None, never "".
|
||||
- IP addresses are dotted strings ("10.0.0.5"), never octet arrays.
|
||||
- Exact v1 key spelling: bellguardSafetyOn, usesStaticIP. The misspellings
|
||||
bellGuardSafetyOn / useStaticIP / users_list are converted or dropped.
|
||||
- device_id and serial_number are equal (decision D1); serial_number is canonical.
|
||||
- device_melodies_all items use the MelodyMainItem shape (mainInformation, ...).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from google.cloud.firestore_v1 import DocumentReference, GeoPoint
|
||||
|
||||
from shared.exceptions import ValidationError
|
||||
|
||||
# Keys inside device_attributes (and its nested maps) that hold Timestamps.
|
||||
TIMESTAMP_KEYS = {
|
||||
"towerClockTime",
|
||||
"daySilenceFrom", "daySilenceTo",
|
||||
"nightSilenceFrom", "nightSilenceTo",
|
||||
"backlightTurnOnTime", "backlightTurnOffTime",
|
||||
"subscrStart",
|
||||
"warrantyStart", "maintainedOn",
|
||||
}
|
||||
|
||||
IP_KEYS = {"ipAddress", "gateway", "subnet", "dns1", "dns2"}
|
||||
|
||||
# Misspelled key -> v1 key, per nested map. A value of None means "drop".
|
||||
LEGACY_KEYS: dict[str, dict[str, str | None]] = {
|
||||
# hw_type / hw_version: pre-2026-11-08 names; the firmware NVS uses hw_family / hw_revision.
|
||||
"": {"users_list": None, "hw_type": "hw_family", "hw_version": "hw_revision"},
|
||||
"device_attributes": {"bellGuardSafetyOn": "bellguardSafetyOn"},
|
||||
"device_attributes.networkSettings": {"useStaticIP": "usesStaticIP"},
|
||||
}
|
||||
|
||||
# Shape of a melody stored inside a device (MelodyMainItem) vs. a melodies/{id} doc.
|
||||
_MELODY_ITEM_FORBIDDEN = {"information", "default_settings", "url"}
|
||||
|
||||
# Format the console API used to serve before ISO 8601 ("15 January 2026 at 22:01:00 UTC+0000").
|
||||
# Still accepted on write so a browser tab opened before the deploy can't corrupt data.
|
||||
_LEGACY_DISPLAY_FMT = "%d %B %Y at %H:%M:%S UTC%z"
|
||||
|
||||
# Board family code: a BoardType value ("vesper_plus") or a bespoke UID. Never a display
|
||||
# label like "Bell Plus" — the firmware builds its OTA URL from this value.
|
||||
_HW_FAMILY = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
|
||||
|
||||
_IPV4 = re.compile(r"^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- write side
|
||||
|
||||
|
||||
def to_timestamp(value: Any, field: str) -> datetime | None:
|
||||
"""Coerce an API value into a Firestore Timestamp (tz-aware datetime) or None."""
|
||||
if value is None or value == "":
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
if isinstance(value, str):
|
||||
s = value.strip()
|
||||
try:
|
||||
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return datetime.strptime(s, _LEGACY_DISPLAY_FMT)
|
||||
except ValueError:
|
||||
pass
|
||||
raise ValidationError(f"{field}: expected an ISO 8601 timestamp or null, got {value!r}")
|
||||
|
||||
|
||||
def to_ipv4(value: Any, field: str) -> str:
|
||||
"""Coerce an API value into a dotted IPv4 string. "" means not set."""
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, (list, tuple)):
|
||||
parts = [str(p).strip() for p in value if str(p).strip() != ""]
|
||||
if not parts:
|
||||
return ""
|
||||
value = ".".join(parts)
|
||||
if isinstance(value, str):
|
||||
s = value.strip()
|
||||
if s == "" or _IPV4.match(s):
|
||||
return s
|
||||
raise ValidationError(f"{field}: expected a dotted IPv4 address like \"10.0.0.5\", got {value!r}")
|
||||
|
||||
|
||||
def _normalize_map(data: dict, path: str) -> dict:
|
||||
"""Recursively apply key renames, timestamp and IP coercion to one map."""
|
||||
renames = LEGACY_KEYS.get(path, {})
|
||||
out: dict = {}
|
||||
# v1 keys first, so a legacy duplicate never overwrites a correct value
|
||||
# that is also present in the same map.
|
||||
for key in sorted(data, key=lambda k: k in renames):
|
||||
value = data[key]
|
||||
if key in renames:
|
||||
target = renames[key]
|
||||
if target is None or target in out or target in data:
|
||||
continue # drop the legacy key (v1 key present, or field is retired)
|
||||
key = target
|
||||
child = f"{path}.{key}" if path else key
|
||||
if isinstance(value, dict):
|
||||
value = _normalize_map(value, child)
|
||||
elif key in TIMESTAMP_KEYS and path:
|
||||
value = to_timestamp(value, child)
|
||||
elif key in IP_KEYS and path.endswith("networkSettings"):
|
||||
value = to_ipv4(value, child)
|
||||
out[key] = value
|
||||
return out
|
||||
|
||||
|
||||
def _user_ref(db, entry) -> DocumentReference:
|
||||
if isinstance(entry, DocumentReference):
|
||||
return entry
|
||||
uid = str(entry).strip().split("/")[-1]
|
||||
if not uid:
|
||||
raise ValidationError(f"user_list: empty entry {entry!r}")
|
||||
return db.collection("users").document(uid)
|
||||
|
||||
|
||||
def _check_melodies(items: Any, db) -> list:
|
||||
if items is None:
|
||||
return []
|
||||
if not isinstance(items, list):
|
||||
raise ValidationError("device_melodies_all: expected a list")
|
||||
out = []
|
||||
for i, item in enumerate(items):
|
||||
if not isinstance(item, dict):
|
||||
raise ValidationError(f"device_melodies_all[{i}]: expected an object")
|
||||
bad = _MELODY_ITEM_FORBIDDEN & item.keys()
|
||||
if bad:
|
||||
raise ValidationError(
|
||||
f"device_melodies_all[{i}]: uses melodies-collection keys {sorted(bad)}; "
|
||||
"device melodies must use mainInformation / defaultSettings / settings / binaryUrl"
|
||||
)
|
||||
ref = item.get("melodyReference")
|
||||
if isinstance(ref, str) and db is not None:
|
||||
item = {**item, "melodyReference": db.collection("melodies").document(ref.split("/")[-1]) if ref else None}
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def to_firestore(data: dict, db=None) -> dict:
|
||||
"""Normalize a (partial) device document for writing to Firestore under v1.
|
||||
|
||||
Raises ValidationError (422) for values that cannot be represented in v1, instead
|
||||
of writing something the apps would choke on.
|
||||
"""
|
||||
out = _normalize_map(data, "")
|
||||
|
||||
# D1: device_id mirrors serial_number. Whichever one is being written, write both.
|
||||
sn, did = out.get("serial_number"), out.get("device_id")
|
||||
if sn and did and sn != did:
|
||||
raise ValidationError(f"device_id ({did}) must equal serial_number ({sn})")
|
||||
if sn or did:
|
||||
out["serial_number"] = out["device_id"] = sn or did
|
||||
|
||||
fam = out.get("hw_family")
|
||||
if fam not in (None, "") and not (isinstance(fam, str) and _HW_FAMILY.match(fam)):
|
||||
raise ValidationError(f"hw_family: expected a board family code like \"vesper_plus\", got {fam!r}")
|
||||
|
||||
if "user_list" in out and db is not None:
|
||||
refs, seen = [], set()
|
||||
for e in out["user_list"] or []:
|
||||
ref = _user_ref(db, e)
|
||||
if ref.id not in seen:
|
||||
seen.add(ref.id)
|
||||
refs.append(ref)
|
||||
out["user_list"] = refs
|
||||
|
||||
if "device_melodies_all" in out:
|
||||
out["device_melodies_all"] = _check_melodies(out["device_melodies_all"], db)
|
||||
|
||||
coords = out.get("device_location_coordinates")
|
||||
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
|
||||
out["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
|
||||
|
||||
return out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- read side
|
||||
|
||||
|
||||
def _api_value(v):
|
||||
if isinstance(v, datetime):
|
||||
dt = v if v.tzinfo else v.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
if isinstance(v, GeoPoint):
|
||||
return {"lat": v.latitude, "lng": v.longitude}
|
||||
if isinstance(v, DocumentReference):
|
||||
return v.path
|
||||
if isinstance(v, dict):
|
||||
return {k: _api_value(x) for k, x in v.items()}
|
||||
if isinstance(v, list):
|
||||
return [_api_value(x) for x in v]
|
||||
return v
|
||||
|
||||
|
||||
def to_api(raw: dict) -> dict:
|
||||
"""Firestore device doc -> JSON for the console frontend.
|
||||
|
||||
Timestamps become ISO 8601 UTC strings (round-trip safe with to_timestamp),
|
||||
references become paths, GeoPoints become {lat, lng}. Legacy misspelled keys
|
||||
are folded into their v1 names so the frontend only ever sees v1 names.
|
||||
"""
|
||||
return _api_value(_normalize_read(raw, ""))
|
||||
|
||||
|
||||
def _normalize_read(data: dict, path: str) -> dict:
|
||||
renames = LEGACY_KEYS.get(path, {})
|
||||
out = {}
|
||||
for key in sorted(data, key=lambda k: k in renames):
|
||||
value = data[key]
|
||||
if key in renames:
|
||||
target = renames[key]
|
||||
if target is None or target in data:
|
||||
continue
|
||||
key = target
|
||||
child = f"{path}.{key}" if path else key
|
||||
if isinstance(value, dict):
|
||||
value = _normalize_read(value, child)
|
||||
elif key in TIMESTAMP_KEYS and path and value == "":
|
||||
value = None # stored "" (pre-v1 bug) reads as unset
|
||||
elif key in IP_KEYS and path.endswith("networkSettings") and isinstance(value, list):
|
||||
parts = [str(p) for p in value if str(p) != ""]
|
||||
value = ".".join(parts) if parts else ""
|
||||
out[key] = value
|
||||
return out
|
||||
+116
-25
@@ -1,7 +1,12 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from typing import Any, Dict, List, Optional
|
||||
from enum import Enum
|
||||
|
||||
# Field names and types follow Firestore schema v1 (bellsystems-schema repo,
|
||||
# v1/firestore.schema.json) — the shape the shipped tablet/phone apps read.
|
||||
# Timestamps travel through the API as ISO 8601 strings and are unset as None
|
||||
# (never ""); devices/firestore_v1.py converts to/from Firestore.
|
||||
|
||||
|
||||
# --- Enums ---
|
||||
|
||||
@@ -30,12 +35,14 @@ class DeviceTiers(str, Enum):
|
||||
|
||||
class DeviceNetworkSettings(BaseModel):
|
||||
hostname: str = ""
|
||||
useStaticIP: bool = False
|
||||
ipAddress: Any = []
|
||||
gateway: Any = []
|
||||
subnet: Any = []
|
||||
dns1: Any = []
|
||||
dns2: Any = []
|
||||
usesStaticIP: bool = False
|
||||
# Dotted strings ("10.0.0.5"); "" = not set. The firmware's network.set_config
|
||||
# MQTT command uses its own names (useStaticIP / ip) — convert at that boundary.
|
||||
ipAddress: str = ""
|
||||
gateway: str = ""
|
||||
subnet: str = ""
|
||||
dns1: str = ""
|
||||
dns2: str = ""
|
||||
|
||||
|
||||
class DeviceClockSettings(BaseModel):
|
||||
@@ -49,14 +56,18 @@ class DeviceClockSettings(BaseModel):
|
||||
quarterAlertsBell: int = 0
|
||||
isDaySilenceOn: bool = False
|
||||
isNightSilenceOn: bool = False
|
||||
daySilenceFrom: str = ""
|
||||
daySilenceTo: str = ""
|
||||
nightSilenceFrom: str = ""
|
||||
nightSilenceTo: str = ""
|
||||
backlightTurnOnTime: str = ""
|
||||
backlightTurnOffTime: str = ""
|
||||
# Time of day carried in a Timestamp (v1 quirk); only the UTC time part matters.
|
||||
daySilenceFrom: Optional[str] = None
|
||||
daySilenceTo: Optional[str] = None
|
||||
nightSilenceFrom: Optional[str] = None
|
||||
nightSilenceTo: Optional[str] = None
|
||||
backlightTurnOnTime: Optional[str] = None
|
||||
backlightTurnOffTime: Optional[str] = None
|
||||
isBacklightAutomationOn: bool = False
|
||||
backlightOutput: int = 0
|
||||
# Firmware 3.2.0+ face sync policy (clock.set_config face_sync_mode / smart_max_wait_min)
|
||||
faceSyncMode: str = "force"
|
||||
smartMaxWaitMin: int = 61
|
||||
|
||||
|
||||
class DeviceAttributes(BaseModel):
|
||||
@@ -67,9 +78,9 @@ class DeviceAttributes(BaseModel):
|
||||
bellOutputs: List[int] = []
|
||||
hammerTimings: List[int] = []
|
||||
bellGuardOn: bool = False
|
||||
bellGuardSafetyOn: bool = False
|
||||
bellguardSafetyOn: bool = False # lower-case g: the exact key the apps read
|
||||
warningsOn: bool = False
|
||||
towerClockTime: str = ""
|
||||
towerClockTime: Optional[str] = None
|
||||
clockSettings: DeviceClockSettings = DeviceClockSettings()
|
||||
deviceLocale: HelperMelodyTypes = HelperMelodyTypes.all
|
||||
networkSettings: DeviceNetworkSettings = DeviceNetworkSettings()
|
||||
@@ -80,7 +91,7 @@ class DeviceAttributes(BaseModel):
|
||||
|
||||
class DeviceSubInformation(BaseModel):
|
||||
subscrTier: DeviceTiers = DeviceTiers.basic
|
||||
subscrStart: str = ""
|
||||
subscrStart: Optional[str] = None
|
||||
subscrDuration: int = 0
|
||||
maxUsers: int = 0
|
||||
maxOutputs: int = 0
|
||||
@@ -92,32 +103,74 @@ class DeviceStatistics(BaseModel):
|
||||
perBellStrikes: List[int] = []
|
||||
totalWarningsGiven: int = 0
|
||||
warrantyActive: bool = False
|
||||
warrantyStart: str = ""
|
||||
warrantyStart: Optional[str] = None
|
||||
warrantyPeriod: int = 0
|
||||
maintainedOn: str = ""
|
||||
maintainancePeriod: int = 0
|
||||
maintainedOn: Optional[str] = None
|
||||
maintainancePeriod: int = 0 # misspelled in v1 on purpose: the apps read this key
|
||||
|
||||
|
||||
class HealthThresholdTier(BaseModel):
|
||||
"""One severity tier's worth of metric thresholds. Two tiers (warning,
|
||||
critical) make up DeviceHealthSettings — see there for why."""
|
||||
restarts_per_week_threshold: int
|
||||
rssi_floor_dbm: int
|
||||
free_heap_floor_kb: int
|
||||
cpu_temp_ceiling_c: int
|
||||
|
||||
|
||||
class DeviceHealthSettings(BaseModel):
|
||||
"""Per-device alert thresholds shown/edited on the Health tab's Settings
|
||||
sub-tab. Purely advisory today — thresholds drive a client-computed
|
||||
ok/warning/critical status icon, not any server-side alerting yet (no
|
||||
email/push infra exists). Two severity tiers per metric (warning fires
|
||||
first, critical is the harder breach) so the header status icon can show
|
||||
orange vs. red rather than a single degraded/healthy binary.
|
||||
offline_timeout_sec also feeds the Health tab's chart gap detection
|
||||
(LineChart's gapThresholdMs) so both share one source of truth."""
|
||||
warning: HealthThresholdTier = HealthThresholdTier(
|
||||
restarts_per_week_threshold=6, rssi_floor_dbm=-80, free_heap_floor_kb=30, cpu_temp_ceiling_c=65,
|
||||
)
|
||||
critical: HealthThresholdTier = HealthThresholdTier(
|
||||
restarts_per_week_threshold=12, rssi_floor_dbm=-90, free_heap_floor_kb=15, cpu_temp_ceiling_c=80,
|
||||
)
|
||||
offline_timeout_sec: int = 90
|
||||
email_on_threshold: bool = False
|
||||
push_on_crash_boot: bool = False
|
||||
|
||||
|
||||
class MelodyMainItem(BaseModel):
|
||||
"""Mirrors the Melody schema used in the melodies collection."""
|
||||
information: dict = {}
|
||||
default_settings: dict = {}
|
||||
type: str = ""
|
||||
url: str = ""
|
||||
"""One melody as stored inside devices.device_melodies_all (v1 MelodyMainItem).
|
||||
|
||||
NOT the melodies/{id} document shape: the apps read camelCase keys here
|
||||
(mainInformation / defaultSettings / settings / binaryUrl / melodyReference).
|
||||
Extra keys are kept so a read-modify-write never drops data.
|
||||
"""
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
melodyReference: Optional[str] = None # path "melodies/{id}" in the API
|
||||
uid: str = ""
|
||||
pid: str = ""
|
||||
mainInformation: Dict[str, Any] = {}
|
||||
defaultSettings: Dict[str, Any] = {}
|
||||
settings: Dict[str, Any] = {}
|
||||
binaryUrl: str = ""
|
||||
|
||||
|
||||
# --- Request / Response schemas ---
|
||||
|
||||
class DeviceCreate(BaseModel):
|
||||
device_name: str = ""
|
||||
# Console-only friendly name — set by staff, independent of the name the
|
||||
# end user gave the device in the app. Never shown to app users, never
|
||||
# synced from/to device_name. Falls back to device_name when empty.
|
||||
console_name: str = ""
|
||||
device_photo: str = ""
|
||||
device_location: str = ""
|
||||
is_Online: bool = False
|
||||
device_attributes: DeviceAttributes = DeviceAttributes()
|
||||
device_subscription: DeviceSubInformation = DeviceSubInformation()
|
||||
device_stats: DeviceStatistics = DeviceStatistics()
|
||||
device_health_settings: DeviceHealthSettings = DeviceHealthSettings()
|
||||
events_on: bool = False
|
||||
device_location_coordinates: Any = None # GeoPoint dict {lat, lng} or legacy str
|
||||
device_melodies_all: List[MelodyMainItem] = []
|
||||
@@ -136,6 +189,7 @@ class DeviceCreate(BaseModel):
|
||||
|
||||
class DeviceUpdate(BaseModel):
|
||||
device_name: Optional[str] = None
|
||||
console_name: Optional[str] = None
|
||||
device_photo: Optional[str] = None
|
||||
device_location: Optional[str] = None
|
||||
is_Online: Optional[bool] = None
|
||||
@@ -143,6 +197,7 @@ class DeviceUpdate(BaseModel):
|
||||
device_attributes: Optional[Dict[str, Any]] = None
|
||||
device_subscription: Optional[Dict[str, Any]] = None
|
||||
device_stats: Optional[Dict[str, Any]] = None
|
||||
device_health_settings: Optional[Dict[str, Any]] = None
|
||||
events_on: Optional[bool] = None
|
||||
device_location_coordinates: Optional[Any] = None # dict {lat, lng} or legacy str
|
||||
device_melodies_all: Optional[List[MelodyMainItem]] = None
|
||||
@@ -179,7 +234,7 @@ class DeviceNoteUpdate(BaseModel):
|
||||
|
||||
|
||||
class DeviceUserInfo(BaseModel):
|
||||
"""User info resolved from device_users sub-collection or user_list."""
|
||||
"""User info resolved from the device's user_list (role from the device_users mirror)."""
|
||||
user_id: str = ""
|
||||
display_name: str = ""
|
||||
email: str = ""
|
||||
@@ -190,3 +245,39 @@ class DeviceUserInfo(BaseModel):
|
||||
class DeviceUsersResponse(BaseModel):
|
||||
users: List[DeviceUserInfo]
|
||||
total: int
|
||||
|
||||
|
||||
class ResetStatsRequest(BaseModel):
|
||||
"""Which categories of QA/bench test data to clear before shipping a
|
||||
device to a customer. Each flag is independent — callers check only the
|
||||
boxes they want. device_stats (Firestore) and current_alerts both default
|
||||
to False since they need extra care (current_alerts especially — see
|
||||
ResetStatsResult.current_alerts note)."""
|
||||
bell_stats: bool = False # Firestore device_stats: totalHammerStrikes, perBellStrikes
|
||||
playback_stats: bool = False # Firestore device_stats: totalPlaybacks, totalWarningsGiven
|
||||
device_logs: bool = False # Postgres device_logs
|
||||
heartbeats: bool = False # Postgres heartbeats
|
||||
commands: bool = False # Postgres commands
|
||||
boot_events: bool = False # Postgres device_boot_events (console-side history)
|
||||
alert_history: bool = False # Postgres device_alert_events
|
||||
ping_samples: bool = False # Postgres device_ping_samples
|
||||
diagnostics_reports: bool = False # Postgres device_diagnostics_reports
|
||||
reports: bool = False # Postgres device_reports (control/reports history, e.g. bell_overload)
|
||||
current_alerts: bool = False # Postgres device_alerts (LIVE state — opt-in only)
|
||||
|
||||
|
||||
class ResetStatsResult(BaseModel):
|
||||
"""Per-category outcome. Postgres/Firestore categories always run
|
||||
(device connectivity doesn't matter); counts are rows deleted, or null
|
||||
for categories that weren't requested."""
|
||||
bell_stats: Optional[bool] = None
|
||||
playback_stats: Optional[bool] = None
|
||||
device_logs: Optional[int] = None
|
||||
heartbeats: Optional[int] = None
|
||||
commands: Optional[int] = None
|
||||
boot_events: Optional[int] = None
|
||||
alert_history: Optional[int] = None
|
||||
ping_samples: Optional[int] = None
|
||||
diagnostics_reports: Optional[int] = None
|
||||
reports: Optional[int] = None
|
||||
current_alerts: Optional[int] = None
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import BigInteger, Column, DateTime, Index, String, Text, UniqueConstraint
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from database.postgres import Base
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class DeviceAlert(Base):
|
||||
"""Current alert state per device+subsystem (upserted, not appended)."""
|
||||
__tablename__ = "device_alerts"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("device_serial", "subsystem"),
|
||||
Index("idx_device_alerts_serial", "device_serial"),
|
||||
)
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
device_serial = Column(String(128), nullable=False)
|
||||
subsystem = Column(String(128), nullable=False)
|
||||
state = Column(String(64), nullable=False)
|
||||
message = Column(Text)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
|
||||
|
||||
|
||||
# NOTE: device_logs, commands, and heartbeats are NOT declared as ORM models here.
|
||||
# device_logs is a partitioned table — SQLAlchemy ORM does not support declarative
|
||||
# partitioned tables cleanly. All three tables are created via raw SQL in the
|
||||
# Alembic migration and accessed via raw queries in database/core.py (SQLite now)
|
||||
# and will be accessed via raw async SQL after Phase 5 cutover.
|
||||
+164
-29
@@ -3,17 +3,22 @@ from datetime import datetime
|
||||
from fastapi import APIRouter, Depends, Query, HTTPException
|
||||
from typing import Optional, List
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
from devices.models import (
|
||||
DeviceCreate, DeviceUpdate, DeviceInDB, DeviceListResponse,
|
||||
DeviceUsersResponse, DeviceUserInfo,
|
||||
DeviceNoteCreate, DeviceNoteUpdate,
|
||||
ResetStatsRequest, ResetStatsResult,
|
||||
)
|
||||
from devices import service
|
||||
from users import service as users_service
|
||||
import database as mqtt_db
|
||||
from mqtt.models import DeviceAlertEntry, DeviceAlertsResponse
|
||||
from shared.firebase import get_db as get_firestore
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
|
||||
router = APIRouter(prefix="/api/devices", tags=["devices"])
|
||||
|
||||
@@ -22,7 +27,7 @@ CRM_COLLECTION = "crm_customers"
|
||||
|
||||
|
||||
@router.get("", response_model=DeviceListResponse)
|
||||
async def list_devices(
|
||||
def list_devices(
|
||||
search: Optional[str] = Query(None),
|
||||
online: Optional[bool] = Query(None),
|
||||
tier: Optional[str] = Query(None),
|
||||
@@ -37,7 +42,7 @@ async def list_devices(
|
||||
|
||||
|
||||
@router.get("/{device_id}", response_model=DeviceInDB)
|
||||
async def get_device(
|
||||
def get_device(
|
||||
device_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||
):
|
||||
@@ -45,7 +50,7 @@ async def get_device(
|
||||
|
||||
|
||||
@router.get("/{device_id}/users", response_model=DeviceUsersResponse)
|
||||
async def get_device_users(
|
||||
def get_device_users(
|
||||
device_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||
):
|
||||
@@ -58,8 +63,12 @@ async def get_device_users(
|
||||
async def create_device(
|
||||
body: DeviceCreate,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "add")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return service.create_device(body)
|
||||
device = service.create_device(body)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "device",
|
||||
device.device_id, device.console_name or device.device_name or device.device_id)
|
||||
return device
|
||||
|
||||
|
||||
@router.put("/{device_id}", response_model=DeviceInDB)
|
||||
@@ -67,16 +76,32 @@ async def update_device(
|
||||
device_id: str,
|
||||
body: DeviceUpdate,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return service.update_device(device_id, body)
|
||||
old = service.get_device(device_id)
|
||||
device = service.update_device(device_id, body)
|
||||
_SKIP = {"updated_at", "device_id", "tags", "user_list"}
|
||||
changes = {
|
||||
k: {"old": getattr(old, k, None), "new": getattr(device, k, None)}
|
||||
for k in body.model_fields_set
|
||||
if k not in _SKIP and getattr(old, k, None) != getattr(device, k, None)
|
||||
}
|
||||
if "tags" in body.model_fields_set and (old.tags or []) != (device.tags or []):
|
||||
changes["tags"] = {"old": sorted(old.tags or []), "new": sorted(device.tags or [])}
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
|
||||
device_id, device.console_name or device.device_name or device_id, changes=changes or None)
|
||||
return device
|
||||
|
||||
|
||||
@router.delete("/{device_id}", status_code=204)
|
||||
async def delete_device(
|
||||
device_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "delete")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
service.delete_device(device_id)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "DELETE", "device",
|
||||
device_id, device_id)
|
||||
|
||||
|
||||
@router.get("/{device_id}/alerts", response_model=DeviceAlertsResponse)
|
||||
@@ -94,27 +119,27 @@ async def get_device_alerts(
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/{device_id}/notes")
|
||||
async def list_device_notes(
|
||||
def list_device_notes(
|
||||
device_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||
):
|
||||
"""List all notes for a device."""
|
||||
db = get_firestore()
|
||||
docs = db.collection(NOTES_COLLECTION).where("device_id", "==", device_id).order_by("created_at").stream()
|
||||
docs = db.collection(NOTES_COLLECTION).where("device_id", "==", device_id).stream()
|
||||
notes = []
|
||||
for doc in docs:
|
||||
note = doc.to_dict()
|
||||
note["id"] = doc.id
|
||||
# Convert Firestore Timestamps to ISO strings
|
||||
for f in ("created_at", "updated_at"):
|
||||
if hasattr(note.get(f), "isoformat"):
|
||||
note[f] = note[f].isoformat()
|
||||
notes.append(note)
|
||||
notes.sort(key=lambda n: n.get("created_at") or "", reverse=False)
|
||||
return {"notes": notes, "total": len(notes)}
|
||||
|
||||
|
||||
@router.post("/{device_id}/notes", status_code=201)
|
||||
async def create_device_note(
|
||||
def create_device_note(
|
||||
device_id: str,
|
||||
body: DeviceNoteCreate,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
@@ -138,7 +163,7 @@ async def create_device_note(
|
||||
|
||||
|
||||
@router.put("/{device_id}/notes/{note_id}")
|
||||
async def update_device_note(
|
||||
def update_device_note(
|
||||
device_id: str,
|
||||
note_id: str,
|
||||
body: DeviceNoteUpdate,
|
||||
@@ -162,7 +187,7 @@ async def update_device_note(
|
||||
|
||||
|
||||
@router.delete("/{device_id}/notes/{note_id}", status_code=204)
|
||||
async def delete_device_note(
|
||||
def delete_device_note(
|
||||
device_id: str,
|
||||
note_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
@@ -185,7 +210,7 @@ class TagsUpdate(BaseModel):
|
||||
|
||||
|
||||
@router.put("/{device_id}/tags", response_model=DeviceInDB)
|
||||
async def update_device_tags(
|
||||
def update_device_tags(
|
||||
device_id: str,
|
||||
body: TagsUpdate,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
@@ -211,7 +236,7 @@ class AssignCustomerBody(BaseModel):
|
||||
|
||||
|
||||
@router.get("/{device_id}/customer-search")
|
||||
async def search_customers_for_device(
|
||||
def search_customers_for_device(
|
||||
device_id: str,
|
||||
q: str = Query(""),
|
||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||
@@ -251,6 +276,7 @@ async def assign_device_to_customer(
|
||||
device_id: str,
|
||||
body: AssignCustomerBody,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Assign a device to a customer.
|
||||
|
||||
@@ -290,6 +316,9 @@ async def assign_device_to_customer(
|
||||
})
|
||||
customer_ref.update({"owned_items": owned_items})
|
||||
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
|
||||
device_id, device_id, meta={"action_detail": "assigned_to_customer",
|
||||
"customer_id": body.customer_id})
|
||||
return {"status": "assigned", "device_id": device_id, "customer_id": body.customer_id}
|
||||
|
||||
|
||||
@@ -298,6 +327,7 @@ async def unassign_device_from_customer(
|
||||
device_id: str,
|
||||
customer_id: str = Query(...),
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Remove device assignment from a customer."""
|
||||
db = get_firestore()
|
||||
@@ -317,13 +347,17 @@ async def unassign_device_from_customer(
|
||||
]
|
||||
customer_ref.update({"owned_items": owned_items})
|
||||
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
|
||||
device_id, device_id, meta={"action_detail": "unassigned_from_customer",
|
||||
"customer_id": customer_id})
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Customer detail (for Owner display in fleet)
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/{device_id}/customer")
|
||||
async def get_device_customer(
|
||||
def get_device_customer(
|
||||
device_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||
):
|
||||
@@ -365,7 +399,7 @@ class UserSearchResult(BaseModel):
|
||||
|
||||
|
||||
@router.get("/{device_id}/user-search")
|
||||
async def search_users_for_device(
|
||||
def search_users_for_device(
|
||||
device_id: str,
|
||||
q: str = Query(""),
|
||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||
@@ -402,16 +436,17 @@ async def add_user_to_device(
|
||||
device_id: str,
|
||||
body: AddUserBody,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Add a user reference to the device's user_list field."""
|
||||
db = get_firestore()
|
||||
device_ref = db.collection("devices").document(device_id)
|
||||
fs = get_firestore()
|
||||
device_ref = fs.collection("devices").document(device_id)
|
||||
device_doc = device_ref.get()
|
||||
if not device_doc.exists:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
|
||||
# Verify user exists
|
||||
user_doc = db.collection("users").document(body.user_id).get()
|
||||
user_doc = fs.collection("users").document(body.user_id).get()
|
||||
if not user_doc.exists:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
@@ -427,11 +462,21 @@ async def add_user_to_device(
|
||||
elif isinstance(entry, str):
|
||||
existing_ids.add(entry.split("/")[-1])
|
||||
|
||||
# user_list, the user's device_serials (MQTT ACL lookup) and the
|
||||
# device_users mirror commit together.
|
||||
user_ref = fs.collection("users").document(body.user_id)
|
||||
batch = fs.batch()
|
||||
if body.user_id not in existing_ids:
|
||||
user_ref = db.collection("users").document(body.user_id)
|
||||
user_list.append(user_ref)
|
||||
device_ref.update({"user_list": user_list})
|
||||
batch.update(device_ref, {"user_list": user_list})
|
||||
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=True)
|
||||
service.stage_device_users_mirror(batch, device_ref, user_ref, linked=True)
|
||||
batch.commit()
|
||||
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
|
||||
device_id, device_id, meta={"action_detail": "user_added",
|
||||
"user_id": body.user_id})
|
||||
return {"status": "added", "user_id": body.user_id}
|
||||
|
||||
|
||||
@@ -440,10 +485,11 @@ async def remove_user_from_device(
|
||||
device_id: str,
|
||||
user_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Remove a user reference from the device's user_list field."""
|
||||
db = get_firestore()
|
||||
device_ref = db.collection("devices").document(device_id)
|
||||
fs = get_firestore()
|
||||
device_ref = fs.collection("devices").document(device_id)
|
||||
device_doc = device_ref.get()
|
||||
if not device_doc.exists:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
@@ -451,11 +497,100 @@ async def remove_user_from_device(
|
||||
data = device_doc.to_dict() or {}
|
||||
user_list = data.get("user_list", []) or []
|
||||
|
||||
# Remove any entry that resolves to this user_id
|
||||
new_list = [
|
||||
entry for entry in user_list
|
||||
if not (isinstance(entry, str) and entry.split("/")[-1] == user_id)
|
||||
]
|
||||
device_ref.update({"user_list": new_list})
|
||||
from google.cloud.firestore_v1 import DocumentReference as DocRef
|
||||
|
||||
return {"status": "removed", "user_id": user_id}
|
||||
def resolves_to(entry, uid: str) -> bool:
|
||||
if isinstance(entry, DocRef):
|
||||
return entry.id == uid
|
||||
if isinstance(entry, str):
|
||||
return entry.split("/")[-1] == uid
|
||||
return False
|
||||
|
||||
# Remove any entry that resolves to this user_id (handles both DocRef and string paths)
|
||||
new_list = [entry for entry in user_list if not resolves_to(entry, user_id)]
|
||||
batch = fs.batch()
|
||||
batch.update(device_ref, {"user_list": new_list})
|
||||
user_ref = fs.collection("users").document(user_id)
|
||||
user_doc = user_ref.get()
|
||||
if user_doc.exists:
|
||||
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=False)
|
||||
service.stage_device_users_mirror(batch, device_ref, user_ref, linked=False)
|
||||
batch.commit()
|
||||
if user_doc.exists:
|
||||
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
|
||||
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
|
||||
device_id, device_id, meta={"action_detail": "user_removed",
|
||||
"user_id": user_id})
|
||||
|
||||
|
||||
@router.post("/{device_id}/reset-stats", response_model=ResetStatsResult)
|
||||
async def reset_device_stats(
|
||||
device_id: str,
|
||||
body: ResetStatsRequest,
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Clears QA/bench test data accumulated before a device ships to a
|
||||
customer. Only handles categories that don't require the device itself
|
||||
to be online — Postgres history tables and Firestore device_stats
|
||||
counters. The two firmware-side resets (telemetry.reset_boot_data,
|
||||
logs.clear) are sent directly by the frontend over MQTT via the existing
|
||||
command-ack flow, since they need the device online and this console
|
||||
already has that round-trip built (see DeviceDetail.jsx's
|
||||
sendMqttCommand) — duplicating it backend-side would just be a second,
|
||||
inferior implementation of the same wait-for-device-reply logic.
|
||||
|
||||
Nothing here touches device identity, customer assignment, notes, tags,
|
||||
warranty/maintenance fields, or audit logs — see ResetStatsRequest's
|
||||
field list for exactly what's in scope.
|
||||
"""
|
||||
device = service.get_device(device_id)
|
||||
serial = device.serial_number or device.device_id
|
||||
|
||||
result = ResetStatsResult()
|
||||
|
||||
# Firestore device_stats — field-level only. DeviceStatistics mixes true
|
||||
# counters with warranty/maintenance fields in one object; a blanket
|
||||
# clear would destroy warranty data, so only the 4 named counter fields
|
||||
# are ever sent here (service.update_device writes field paths only, so
|
||||
# every other key is untouched, including warrantyActive/warrantyStart/etc.).
|
||||
stats_update = {}
|
||||
if body.bell_stats:
|
||||
stats_update["totalHammerStrikes"] = 0
|
||||
stats_update["perBellStrikes"] = []
|
||||
if body.playback_stats:
|
||||
stats_update["totalPlaybacks"] = 0
|
||||
stats_update["totalWarningsGiven"] = 0
|
||||
if stats_update:
|
||||
service.update_device(device_id, DeviceUpdate(device_stats=stats_update))
|
||||
if body.bell_stats:
|
||||
result.bell_stats = True
|
||||
if body.playback_stats:
|
||||
result.playback_stats = True
|
||||
|
||||
# Postgres — pure history/telemetry tables, per-device row deletes.
|
||||
if body.device_logs:
|
||||
result.device_logs = await mqtt_db.delete_device_logs(serial)
|
||||
if body.heartbeats:
|
||||
result.heartbeats = await mqtt_db.delete_device_heartbeats(serial)
|
||||
if body.commands:
|
||||
result.commands = await mqtt_db.delete_device_commands(serial)
|
||||
if body.boot_events:
|
||||
result.boot_events = await mqtt_db.delete_device_boot_events(serial)
|
||||
if body.alert_history:
|
||||
result.alert_history = await mqtt_db.delete_device_alert_events(serial)
|
||||
if body.ping_samples:
|
||||
result.ping_samples = await mqtt_db.delete_device_ping_samples(serial)
|
||||
if body.diagnostics_reports:
|
||||
result.diagnostics_reports = await mqtt_db.delete_device_diagnostics_reports(serial)
|
||||
if body.reports:
|
||||
result.reports = await mqtt_db.delete_device_reports(serial)
|
||||
if body.current_alerts:
|
||||
result.current_alerts = await mqtt_db.delete_device_current_alerts(serial)
|
||||
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "device",
|
||||
device_id, device.console_name or device.device_name or serial,
|
||||
meta={"action_detail": "reset_stats", "categories": body.model_dump()})
|
||||
|
||||
return result
|
||||
|
||||
+155
-164
@@ -1,11 +1,12 @@
|
||||
import secrets
|
||||
import string
|
||||
|
||||
from datetime import datetime
|
||||
from google.cloud.firestore_v1 import GeoPoint, DocumentReference
|
||||
from google.cloud.firestore_v1 import DocumentReference
|
||||
from google.cloud.firestore_v1.field_path import FieldPath
|
||||
|
||||
from shared.firebase import get_db
|
||||
from shared.exceptions import NotFoundError
|
||||
from devices import firestore_v1
|
||||
from devices.models import DeviceCreate, DeviceUpdate, DeviceInDB
|
||||
|
||||
COLLECTION = "devices"
|
||||
@@ -14,34 +15,6 @@ COLLECTION = "devices"
|
||||
SN_CHARS = string.ascii_uppercase + string.digits
|
||||
SN_SEGMENT_LEN = 4
|
||||
|
||||
# Clock/silence/backlight fields stored as Firestore Timestamps (written as datetime)
|
||||
_TIMESTAMP_FIELD_NAMES = {
|
||||
"daySilenceFrom", "daySilenceTo",
|
||||
"nightSilenceFrom", "nightSilenceTo",
|
||||
"backlightTurnOnTime", "backlightTurnOffTime",
|
||||
}
|
||||
|
||||
|
||||
def _restore_timestamps(d: dict) -> dict:
|
||||
"""Recursively convert ISO 8601 strings for known timestamp fields to datetime objects.
|
||||
|
||||
Firestore stores Python datetime objects as native Timestamps, which Flutter
|
||||
reads as DateTime. Plain strings would break the Flutter app.
|
||||
"""
|
||||
result = {}
|
||||
for k, v in d.items():
|
||||
if isinstance(v, dict):
|
||||
result[k] = _restore_timestamps(v)
|
||||
elif isinstance(v, str) and k in _TIMESTAMP_FIELD_NAMES:
|
||||
try:
|
||||
result[k] = datetime.fromisoformat(v.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
result[k] = v
|
||||
else:
|
||||
result[k] = v
|
||||
return result
|
||||
|
||||
|
||||
def _generate_serial_number() -> str:
|
||||
"""Generate a unique serial number in the format BS-XXXX-XXXX."""
|
||||
seg1 = "".join(secrets.choice(SN_CHARS) for _ in range(SN_SEGMENT_LEN))
|
||||
@@ -66,36 +39,6 @@ def _ensure_unique_serial(db) -> str:
|
||||
raise RuntimeError("Could not generate a unique serial number after 100 attempts")
|
||||
|
||||
|
||||
def _convert_firestore_value(val):
|
||||
"""Convert Firestore-specific types (Timestamp, GeoPoint, DocumentReference) to strings."""
|
||||
if isinstance(val, datetime):
|
||||
# Firestore DatetimeWithNanoseconds is a datetime subclass
|
||||
return val.strftime("%d %B %Y at %H:%M:%S UTC%z")
|
||||
if isinstance(val, GeoPoint):
|
||||
return {"lat": val.latitude, "lng": val.longitude}
|
||||
if isinstance(val, DocumentReference):
|
||||
# Store the document path (e.g. "users/abc123")
|
||||
return val.path
|
||||
return val
|
||||
|
||||
|
||||
def _sanitize_dict(d: dict) -> dict:
|
||||
"""Recursively convert Firestore-native types in a dict to plain strings."""
|
||||
result = {}
|
||||
for k, v in d.items():
|
||||
if isinstance(v, dict):
|
||||
result[k] = _sanitize_dict(v)
|
||||
elif isinstance(v, list):
|
||||
result[k] = [
|
||||
_sanitize_dict(item) if isinstance(item, dict)
|
||||
else _convert_firestore_value(item)
|
||||
for item in v
|
||||
]
|
||||
else:
|
||||
result[k] = _convert_firestore_value(v)
|
||||
return result
|
||||
|
||||
|
||||
def _auto_upgrade_claimed(doc_ref, data: dict) -> dict:
|
||||
"""If the device has entries in user_list and isn't already claimed/decommissioned,
|
||||
upgrade mfg_status to 'claimed' automatically and return the updated data dict."""
|
||||
@@ -117,7 +60,7 @@ def _doc_to_device(doc) -> DeviceInDB:
|
||||
"""
|
||||
raw = doc.to_dict()
|
||||
raw = _auto_upgrade_claimed(doc.reference, raw)
|
||||
data = _sanitize_dict(raw)
|
||||
data = firestore_v1.to_api(raw)
|
||||
return DeviceInDB(id=doc.id, **data)
|
||||
|
||||
|
||||
@@ -158,9 +101,10 @@ def list_devices(
|
||||
if search:
|
||||
search_lower = search.lower()
|
||||
name_match = search_lower in (device.device_name or "").lower()
|
||||
console_name_match = search_lower in (device.console_name or "").lower()
|
||||
location_match = search_lower in (device.device_location or "").lower()
|
||||
sn_match = search_lower in (device.serial_number or "").lower()
|
||||
if not (name_match or location_match or sn_match):
|
||||
if not (name_match or console_name_match or location_match or sn_match):
|
||||
continue
|
||||
|
||||
results.append(device)
|
||||
@@ -185,22 +129,31 @@ def create_device(data: DeviceCreate) -> DeviceInDB:
|
||||
serial_number = _ensure_unique_serial(db)
|
||||
|
||||
doc_data = data.model_dump()
|
||||
doc_data["device_id"] = serial_number
|
||||
doc_data["serial_number"] = serial_number # D1: canonical id; to_firestore mirrors it to device_id
|
||||
doc_data.pop("device_id", None)
|
||||
doc_data = firestore_v1.to_firestore(doc_data, db)
|
||||
|
||||
_, doc_ref = db.collection(COLLECTION).add(doc_data)
|
||||
|
||||
return DeviceInDB(id=doc_ref.id, **doc_data)
|
||||
return _doc_to_device(doc_ref.get())
|
||||
|
||||
|
||||
def _deep_merge(base: dict, overrides: dict) -> dict:
|
||||
"""Recursively merge overrides into base, preserving unmentioned nested keys."""
|
||||
result = dict(base)
|
||||
for k, v in overrides.items():
|
||||
if isinstance(v, dict) and isinstance(result.get(k), dict):
|
||||
result[k] = _deep_merge(result[k], v)
|
||||
def _leaf_field_paths(value: dict, prefix: tuple = ()) -> dict:
|
||||
"""Flatten a nested map into {firestore field path: leaf value}.
|
||||
|
||||
Lists and scalars are leaves; a non-empty map is descended into, so writing
|
||||
{"device_attributes": {"hasBells": True}} touches ONLY
|
||||
device_attributes.hasBells — never the sibling fields of the parent map.
|
||||
An empty map is kept as a leaf (it explicitly sets that map to {}).
|
||||
"""
|
||||
out: dict = {}
|
||||
for k, v in value.items():
|
||||
path = prefix + (k,)
|
||||
if isinstance(v, dict) and v:
|
||||
out.update(_leaf_field_paths(v, path))
|
||||
else:
|
||||
result[k] = v
|
||||
return result
|
||||
out[FieldPath(*path).to_api_repr()] = v
|
||||
return out
|
||||
|
||||
|
||||
def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
||||
@@ -211,34 +164,122 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
|
||||
if not doc.exists:
|
||||
raise NotFoundError("Device")
|
||||
|
||||
update_data = data.model_dump(exclude_none=True)
|
||||
# Top-level None still means "not sent" (unchanged API behaviour). Inside the
|
||||
# nested maps an explicit null is kept: it clears that field, e.g. a silence
|
||||
# time being switched off — the v1 way to say "unset" (never "").
|
||||
sent = data.model_dump(exclude_unset=True)
|
||||
update_data = firestore_v1.to_firestore({k: v for k, v in sent.items() if v is not None}, db)
|
||||
|
||||
# Convert {lat, lng} dict to a Firestore GeoPoint
|
||||
coords = update_data.get("device_location_coordinates")
|
||||
if isinstance(coords, dict) and "lat" in coords and "lng" in coords:
|
||||
update_data["device_location_coordinates"] = GeoPoint(coords["lat"], coords["lng"])
|
||||
|
||||
# Deep-merge nested structs so unmentioned sub-fields are preserved
|
||||
# Nested structs are written field-by-field (dotted paths), so only the
|
||||
# exact leaves the caller sent are touched. Rewriting the whole parent map
|
||||
# (the old read-merge-write) clobbered sibling fields whenever two writes
|
||||
# raced, or the FlutterFlow apps wrote in between our read and our write.
|
||||
existing = doc.to_dict()
|
||||
nested_keys = (
|
||||
"device_attributes", "device_subscription", "device_stats",
|
||||
"device_attributes", "device_subscription", "device_stats", "device_health_settings",
|
||||
)
|
||||
for key in nested_keys:
|
||||
if key in update_data and isinstance(existing.get(key), dict):
|
||||
update_data[key] = _deep_merge(existing[key], update_data[key])
|
||||
if isinstance(update_data.get(key), dict) and update_data[key]:
|
||||
update_data.update(_leaf_field_paths(update_data.pop(key), (key,)))
|
||||
|
||||
update_data = _restore_timestamps(update_data)
|
||||
doc_ref.update(update_data)
|
||||
if "user_list" not in update_data:
|
||||
doc_ref.update(update_data)
|
||||
else:
|
||||
# A user_list change must also update each affected user's
|
||||
# device_serials (MQTT ACL) and the device_users mirror, in the
|
||||
# same atomic batch.
|
||||
from users import service as users_service
|
||||
|
||||
new_ids = []
|
||||
for e in update_data["user_list"]:
|
||||
uid = user_list_entry_id(e)
|
||||
if uid and uid not in new_ids:
|
||||
new_ids.append(uid)
|
||||
# Stored as DocumentReferences, the format the FlutterFlow app writes.
|
||||
update_data["user_list"] = [db.collection("users").document(uid) for uid in new_ids]
|
||||
|
||||
old_ids = {user_list_entry_id(e) for e in (existing.get("user_list") or [])} - {""}
|
||||
serial = users_service.device_serial_of(existing)
|
||||
mirror = device_users_by_user(doc_ref)
|
||||
|
||||
batch = db.batch()
|
||||
batch.update(doc_ref, update_data)
|
||||
touched = []
|
||||
for user_id in (old_ids ^ set(new_ids)):
|
||||
linked = user_id in new_ids
|
||||
user_ref = db.collection("users").document(user_id)
|
||||
user_doc = user_ref.get()
|
||||
if not user_doc.exists:
|
||||
if not linked:
|
||||
stage_device_users_mirror(batch, doc_ref, user_ref, linked=False, existing=mirror)
|
||||
continue # dangling reference — no user doc to sync
|
||||
users_service.stage_device_serial_link(batch, user_ref, serial, linked=linked)
|
||||
stage_device_users_mirror(batch, doc_ref, user_ref, linked=linked, existing=mirror)
|
||||
touched.append(user_doc.to_dict())
|
||||
batch.commit()
|
||||
for user_data in touched:
|
||||
users_service.invalidate_mqtt_acl_cache(user_data)
|
||||
|
||||
updated_doc = doc_ref.get()
|
||||
return _doc_to_device(updated_doc)
|
||||
|
||||
|
||||
def get_device_users(device_doc_id: str) -> list[dict]:
|
||||
"""Get users assigned to a device from the device_users sub-collection.
|
||||
def user_list_entry_id(entry) -> str:
|
||||
"""user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
|
||||
if isinstance(entry, DocumentReference):
|
||||
return entry.id
|
||||
if isinstance(entry, str):
|
||||
return entry.strip().split("/")[-1]
|
||||
return ""
|
||||
|
||||
Falls back to the user_list field on the device document if the
|
||||
sub-collection is empty.
|
||||
|
||||
# ─── device_users sub-collection mirror ──────────────────────────────────────
|
||||
# The device's `user_list` field is the single source of truth for who is
|
||||
# assigned to a device. The older `device_users` sub-collection
|
||||
# ({role, user_reference}) is kept as a write-only mirror in case the phone
|
||||
# app still reads it, and is slated for removal. Never read assignments from it.
|
||||
|
||||
DEVICE_USERS_SUBCOLLECTION = "device_users"
|
||||
# Every existing device_users doc (2026-11) has role "admin".
|
||||
DEFAULT_DEVICE_USER_ROLE = "admin"
|
||||
|
||||
|
||||
def device_users_by_user(device_ref) -> dict[str, list]:
|
||||
"""user doc id -> the device_users snapshots that point at that user."""
|
||||
out: dict[str, list] = {}
|
||||
for snap in device_ref.collection(DEVICE_USERS_SUBCOLLECTION).stream():
|
||||
uid = user_list_entry_id((snap.to_dict() or {}).get("user_reference"))
|
||||
if uid:
|
||||
out.setdefault(uid, []).append(snap)
|
||||
return out
|
||||
|
||||
|
||||
def stage_device_users_mirror(batch, device_ref, user_ref, linked: bool, existing: dict | None = None) -> None:
|
||||
"""Add (linked=True) or remove the user's device_users mirror doc inside the
|
||||
caller's batch, so it commits together with the `user_list` change.
|
||||
|
||||
`existing` is a pre-fetched device_users_by_user() map, for callers that
|
||||
touch several users of one device.
|
||||
"""
|
||||
if existing is None:
|
||||
existing = device_users_by_user(device_ref)
|
||||
current = existing.get(user_ref.id, [])
|
||||
if linked:
|
||||
if not current:
|
||||
batch.set(device_ref.collection(DEVICE_USERS_SUBCOLLECTION).document(), {
|
||||
"role": DEFAULT_DEVICE_USER_ROLE,
|
||||
"user_reference": user_ref,
|
||||
})
|
||||
else:
|
||||
for snap in current:
|
||||
batch.delete(snap.reference)
|
||||
|
||||
|
||||
def get_device_users(device_doc_id: str) -> list[dict]:
|
||||
"""Users assigned to a device, read from the device's `user_list` field.
|
||||
|
||||
`role` is taken from the device_users mirror when one exists for the user
|
||||
(that's the only place a role is stored); otherwise it is "".
|
||||
"""
|
||||
db = get_db()
|
||||
doc_ref = db.collection(COLLECTION).document(device_doc_id)
|
||||
@@ -246,83 +287,33 @@ def get_device_users(device_doc_id: str) -> list[dict]:
|
||||
if not doc.exists:
|
||||
raise NotFoundError("Device")
|
||||
|
||||
# Try sub-collection first
|
||||
sub_docs = list(doc_ref.collection("device_users").stream())
|
||||
roles = {
|
||||
uid: (snaps[0].to_dict() or {}).get("role", "")
|
||||
for uid, snaps in device_users_by_user(doc_ref).items()
|
||||
}
|
||||
|
||||
users = []
|
||||
|
||||
if sub_docs:
|
||||
for sub_doc in sub_docs:
|
||||
sub_data = sub_doc.to_dict()
|
||||
role = sub_data.get("role", "")
|
||||
user_ref = sub_data.get("user_reference")
|
||||
|
||||
# Resolve user reference
|
||||
user_id = ""
|
||||
display_name = ""
|
||||
email = ""
|
||||
photo_url = ""
|
||||
|
||||
if isinstance(user_ref, DocumentReference):
|
||||
try:
|
||||
user_doc = user_ref.get()
|
||||
if user_doc.exists:
|
||||
user_data = user_doc.to_dict()
|
||||
user_id = user_doc.id
|
||||
display_name = user_data.get("display_name", "")
|
||||
email = user_data.get("email", "")
|
||||
photo_url = user_data.get("photo_url", "")
|
||||
except Exception as e:
|
||||
print(f"[devices] Error resolving user reference: {e}")
|
||||
continue
|
||||
elif isinstance(user_ref, str):
|
||||
# String path like "users/abc123"
|
||||
try:
|
||||
ref_doc = db.document(user_ref).get()
|
||||
if ref_doc.exists:
|
||||
user_data = ref_doc.to_dict()
|
||||
user_id = ref_doc.id
|
||||
display_name = user_data.get("display_name", "")
|
||||
email = user_data.get("email", "")
|
||||
photo_url = user_data.get("photo_url", "")
|
||||
except Exception as e:
|
||||
print(f"[devices] Error resolving user path: {e}")
|
||||
continue
|
||||
|
||||
users.append({
|
||||
"user_id": user_id,
|
||||
"display_name": display_name,
|
||||
"email": email,
|
||||
"role": role,
|
||||
"photo_url": photo_url,
|
||||
})
|
||||
else:
|
||||
# Fallback to user_list field
|
||||
device_data = doc.to_dict()
|
||||
user_list = device_data.get("user_list", [])
|
||||
for entry in user_list:
|
||||
try:
|
||||
if isinstance(entry, DocumentReference):
|
||||
user_doc = entry.get()
|
||||
elif isinstance(entry, str) and entry.strip():
|
||||
# Could be a path like "users/abc" or a raw doc ID
|
||||
if "/" in entry:
|
||||
user_doc = db.document(entry).get()
|
||||
else:
|
||||
user_doc = db.collection("users").document(entry).get()
|
||||
else:
|
||||
continue
|
||||
|
||||
if user_doc.exists:
|
||||
user_data = user_doc.to_dict()
|
||||
users.append({
|
||||
"user_id": user_doc.id,
|
||||
"display_name": user_data.get("display_name", ""),
|
||||
"email": user_data.get("email", ""),
|
||||
"role": "",
|
||||
"photo_url": user_data.get("photo_url", ""),
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[devices] Error resolving user_list entry: {e}")
|
||||
seen = set()
|
||||
for entry in (doc.to_dict() or {}).get("user_list") or []:
|
||||
uid = user_list_entry_id(entry)
|
||||
if not uid or uid in seen:
|
||||
continue
|
||||
seen.add(uid)
|
||||
try:
|
||||
user_doc = db.collection("users").document(uid).get()
|
||||
except Exception as e:
|
||||
print(f"[devices] Error resolving user_list entry {uid}: {e}")
|
||||
continue
|
||||
if not user_doc.exists:
|
||||
continue
|
||||
user_data = user_doc.to_dict() or {}
|
||||
users.append({
|
||||
"user_id": user_doc.id,
|
||||
"display_name": user_data.get("display_name", ""),
|
||||
"email": user_data.get("email", ""),
|
||||
"role": roles.get(uid, ""),
|
||||
"photo_url": user_data.get("photo_url", ""),
|
||||
})
|
||||
|
||||
return users
|
||||
|
||||
|
||||
@@ -48,7 +48,8 @@ def _resolve_names(db, device_id: str | None, user_id: str | None) -> tuple[str,
|
||||
if device_id and isinstance(device_id, str) and device_id.strip():
|
||||
device_doc = db.collection("devices").document(device_id.strip()).get()
|
||||
if device_doc.exists:
|
||||
device_name = device_doc.to_dict().get("device_name", "")
|
||||
device_data = device_doc.to_dict()
|
||||
device_name = device_data.get("console_name") or device_data.get("device_name", "")
|
||||
|
||||
if user_id and isinstance(user_id, str) and user_id.strip():
|
||||
user_doc = db.collection("users").document(user_id.strip()).get()
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Firmware ELF symbol store + server-side crash decoding (firmware F-070).
|
||||
|
||||
Crash reports carry `elf_sha256`: the first 16 hex chars of the SHA-256 of the
|
||||
crashing build's firmware.elf. ELFs uploaded here are stored under that same
|
||||
key, so a crash can be matched to its exact build and its PC/backtrace
|
||||
addresses decoded to function + file:line with xtensa addr2line.
|
||||
|
||||
Decoding is optional: it needs a matching ELF AND the xtensa-esp32-elf-addr2line
|
||||
binary in the backend container (settings.addr2line_path, or on PATH). When
|
||||
either is missing the console falls back to a copy-paste addr2line command.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from config import settings
|
||||
from shared.exceptions import NotFoundError, ValidationError
|
||||
|
||||
ADDR2LINE_NAME = "xtensa-esp32-elf-addr2line"
|
||||
_SHA_PREFIX = re.compile(r"^[0-9a-f]{16}$")
|
||||
_MAX_ADDRESSES = 40
|
||||
|
||||
|
||||
def _elf_dir() -> Path:
|
||||
return Path(settings.firmware_storage_path) / "elf"
|
||||
|
||||
|
||||
def elf_sha_prefix(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()[:16]
|
||||
|
||||
|
||||
def _check_sha(sha: str) -> str:
|
||||
sha = (sha or "").lower()
|
||||
if not _SHA_PREFIX.match(sha):
|
||||
raise ValidationError("elf_sha256 must be 16 hex characters.")
|
||||
return sha
|
||||
|
||||
|
||||
def addr2line_path() -> str | None:
|
||||
configured = getattr(settings, "addr2line_path", "") or ""
|
||||
if configured and Path(configured).is_file():
|
||||
return configured
|
||||
return shutil.which(ADDR2LINE_NAME)
|
||||
|
||||
|
||||
def validate_elf(data: bytes) -> None:
|
||||
if not data.startswith(b"\x7fELF"):
|
||||
raise ValidationError("Not an ELF file — upload the firmware.elf from the build, not the .bin.")
|
||||
|
||||
|
||||
def save_elf(data: bytes, filename: str | None, uploaded_by: str | None,
|
||||
firmware: dict | None = None) -> dict:
|
||||
"""Store an ELF keyed by its sha256 prefix. Re-uploading the same file is a
|
||||
no-op overwrite. `firmware` optionally records which release it belongs to."""
|
||||
validate_elf(data)
|
||||
sha = elf_sha_prefix(data)
|
||||
d = _elf_dir()
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / f"{sha}.elf").write_bytes(data)
|
||||
meta = {
|
||||
"elf_sha256": sha,
|
||||
"filename": filename or "firmware.elf",
|
||||
"size": len(data),
|
||||
"uploaded_at": datetime.now(timezone.utc).isoformat(),
|
||||
"uploaded_by": uploaded_by,
|
||||
"firmware": firmware,
|
||||
}
|
||||
(d / f"{sha}.json").write_text(json.dumps(meta), encoding="utf-8")
|
||||
return meta
|
||||
|
||||
|
||||
def get_elf_info(sha: str) -> dict:
|
||||
"""Whether a matching ELF exists and whether the decoder is installed —
|
||||
the crash view uses this to pick decode-in-console vs. copy-command."""
|
||||
sha = _check_sha(sha)
|
||||
meta_path = _elf_dir() / f"{sha}.json"
|
||||
meta = None
|
||||
if (_elf_dir() / f"{sha}.elf").is_file():
|
||||
try:
|
||||
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
meta = {"elf_sha256": sha}
|
||||
return {
|
||||
"elf_sha256": sha,
|
||||
"exists": meta is not None,
|
||||
"meta": meta,
|
||||
"decoder_available": addr2line_path() is not None,
|
||||
}
|
||||
|
||||
|
||||
def decode(sha: str, addresses: list[int]) -> list[dict]:
|
||||
"""Run addr2line -pfiaC over the addresses. Returns one entry per address:
|
||||
{"address": "0x400D8A3F", "frames": ["func at file:line", "(inlined by) ..."]}."""
|
||||
sha = _check_sha(sha)
|
||||
elf = _elf_dir() / f"{sha}.elf"
|
||||
if not elf.is_file():
|
||||
raise NotFoundError("ELF")
|
||||
tool = addr2line_path()
|
||||
if tool is None:
|
||||
raise ValidationError(f"{ADDR2LINE_NAME} is not installed on the server.")
|
||||
|
||||
addrs = [a for a in addresses if isinstance(a, int) and 0 <= a <= 0xFFFFFFFF][:_MAX_ADDRESSES]
|
||||
if not addrs:
|
||||
return []
|
||||
hex_addrs = [f"0x{a:08X}" for a in addrs]
|
||||
proc = subprocess.run(
|
||||
[tool, "-pfiaC", "-e", str(elf), *hex_addrs],
|
||||
capture_output=True, text=True, timeout=20,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise ValidationError(f"addr2line failed: {proc.stderr.strip()[:300]}")
|
||||
|
||||
# With -a each address starts a new block "0x400d8a3f: func at file:line";
|
||||
# -i adds " (inlined by) ..." continuation lines under it.
|
||||
results: list[dict] = []
|
||||
for line in proc.stdout.splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
m = re.match(r"^(0x[0-9a-fA-F]+):\s*(.*)$", line)
|
||||
if m:
|
||||
results.append({"address": f"0x{int(m.group(1), 16):08X}", "frames": [m.group(2).strip()]})
|
||||
elif results:
|
||||
results[-1]["frames"].append(line.strip())
|
||||
return results
|
||||
@@ -3,11 +3,14 @@ from fastapi.responses import FileResponse, PlainTextResponse
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
import logging
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
from firmware.models import FirmwareVersion, FirmwareListResponse, FirmwareMetadataResponse, UpdateType
|
||||
from firmware import service
|
||||
from firmware import service, elf_store
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -26,10 +29,16 @@ async def upload_firmware(
|
||||
release_note: Optional[str] = Form(None),
|
||||
bespoke_uid: Optional[str] = Form(None),
|
||||
file: UploadFile = File(...),
|
||||
elf_file: Optional[UploadFile] = File(None),
|
||||
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
file_bytes = await file.read()
|
||||
return service.upload_firmware(
|
||||
elf_bytes = await elf_file.read() if elf_file and elf_file.filename else None
|
||||
if elf_bytes is not None:
|
||||
# Validate before the release is created, so a wrong file doesn't leave a half-done upload.
|
||||
elf_store.validate_elf(elf_bytes)
|
||||
fw = service.upload_firmware(
|
||||
hw_type=hw_type,
|
||||
channel=channel,
|
||||
version=version,
|
||||
@@ -40,6 +49,46 @@ async def upload_firmware(
|
||||
release_note=release_note,
|
||||
bespoke_uid=bespoke_uid,
|
||||
)
|
||||
if elf_bytes is not None:
|
||||
elf_store.save_elf(elf_bytes, elf_file.filename, _user.name or _user.email,
|
||||
firmware={"id": fw.id, "hw_type": hw_type, "channel": channel, "version": version})
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "firmware",
|
||||
fw.id, f"{hw_type} v{version} ({channel})")
|
||||
return fw
|
||||
|
||||
|
||||
# ── Firmware ELF symbols (crash decoding, F-070) ─────────────────────────────
|
||||
# Registered before the /{hw_type}/... routes. Viewing/decoding is gated on
|
||||
# mqtt:view like the crash data itself; uploading is a firmware-release action.
|
||||
|
||||
class ElfDecodeRequest(BaseModel):
|
||||
addresses: list[int]
|
||||
|
||||
|
||||
@router.post("/elf", status_code=201)
|
||||
async def upload_elf(
|
||||
file: UploadFile = File(...),
|
||||
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
||||
):
|
||||
data = await file.read()
|
||||
return elf_store.save_elf(data, file.filename, _user.name or _user.email)
|
||||
|
||||
|
||||
@router.get("/elf/{elf_sha256}")
|
||||
def get_elf_info(
|
||||
elf_sha256: str,
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
return elf_store.get_elf_info(elf_sha256)
|
||||
|
||||
|
||||
@router.post("/elf/{elf_sha256}/decode")
|
||||
def decode_addresses(
|
||||
elf_sha256: str,
|
||||
body: ElfDecodeRequest,
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
return {"elf_sha256": elf_sha256.lower(), "results": elf_store.decode(elf_sha256, body.addresses)}
|
||||
|
||||
|
||||
@router.get("", response_model=FirmwareListResponse)
|
||||
@@ -107,10 +156,15 @@ async def edit_firmware(
|
||||
release_note: Optional[str] = Form(None),
|
||||
bespoke_uid: Optional[str] = Form(None),
|
||||
file: Optional[UploadFile] = File(None),
|
||||
elf_file: Optional[UploadFile] = File(None),
|
||||
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
file_bytes = await file.read() if file and file.filename else None
|
||||
return service.edit_firmware(
|
||||
elf_bytes = await elf_file.read() if elf_file and elf_file.filename else None
|
||||
if elf_bytes is not None:
|
||||
elf_store.validate_elf(elf_bytes)
|
||||
fw = service.edit_firmware(
|
||||
doc_id=firmware_id,
|
||||
channel=channel,
|
||||
version=version,
|
||||
@@ -121,14 +175,26 @@ async def edit_firmware(
|
||||
bespoke_uid=bespoke_uid,
|
||||
file_bytes=file_bytes,
|
||||
)
|
||||
if elf_bytes is not None:
|
||||
elf_store.save_elf(elf_bytes, elf_file.filename, _user.name or _user.email,
|
||||
firmware={"id": firmware_id, "hw_type": fw.hw_type if fw else None,
|
||||
"channel": fw.channel if fw else None, "version": fw.version if fw else None})
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "firmware",
|
||||
firmware_id, f"{fw.hw_type} v{fw.version} ({fw.channel})" if fw else firmware_id)
|
||||
return fw
|
||||
|
||||
|
||||
@router.delete("/{firmware_id}", status_code=204)
|
||||
def delete_firmware(
|
||||
async def delete_firmware(
|
||||
firmware_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("manufacturing", "delete")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
fw = service.get_firmware(firmware_id) if hasattr(service, "get_firmware") else None
|
||||
service.delete_firmware(firmware_id)
|
||||
label = f"{fw.hw_type} v{fw.version} ({fw.channel})" if fw else firmware_id
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "DELETE", "firmware",
|
||||
firmware_id, label)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -50,7 +50,8 @@ def _resolve_device_name(db, device_id: str) -> str:
|
||||
try:
|
||||
doc = db.collection("devices").document(device_id.strip()).get()
|
||||
if doc.exists:
|
||||
return doc.to_dict().get("device_name", "")
|
||||
data = doc.to_dict()
|
||||
return data.get("console_name") or data.get("device_name", "")
|
||||
except Exception as e:
|
||||
print(f"[helpdesk] Error resolving device name: {e}")
|
||||
return ""
|
||||
|
||||
+20
-2
@@ -25,6 +25,11 @@ from crm.media_router import router as crm_media_router
|
||||
from crm.nextcloud_router import router as crm_nextcloud_router
|
||||
from crm.quotations_router import router as crm_quotations_router
|
||||
from public.router import router as public_router
|
||||
from notes.router import router as notes_router
|
||||
from tickets.router import router as tickets_router
|
||||
from audit.router import router as audit_router
|
||||
from search.router import router as search_router
|
||||
from timezones.router import router as timezones_router
|
||||
from crm.nextcloud import close_client as close_nextcloud_client, keepalive_ping as nextcloud_keepalive
|
||||
from crm.mail_accounts import get_mail_accounts
|
||||
from mqtt.client import mqtt_manager
|
||||
@@ -70,6 +75,11 @@ app.include_router(crm_media_router)
|
||||
app.include_router(crm_nextcloud_router)
|
||||
app.include_router(crm_quotations_router)
|
||||
app.include_router(public_router)
|
||||
app.include_router(notes_router)
|
||||
app.include_router(tickets_router)
|
||||
app.include_router(audit_router)
|
||||
app.include_router(search_router)
|
||||
app.include_router(timezones_router)
|
||||
|
||||
|
||||
async def nextcloud_keepalive_loop():
|
||||
@@ -102,10 +112,17 @@ async def crm_poll_loop():
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
init_firebase()
|
||||
await db.init_db()
|
||||
from database.core import init_db as sqlite_init_db
|
||||
await sqlite_init_db()
|
||||
await melody_service.migrate_from_firestore()
|
||||
mqtt_manager.start(asyncio.get_event_loop())
|
||||
# Seed the in-memory latest-status cache in the background so the first
|
||||
# device list / detail load after a restart doesn't pay for the slow
|
||||
# fleet-wide DISTINCT ON scans (see database/latest_cache.py).
|
||||
asyncio.create_task(db.warm_latest_cache())
|
||||
asyncio.create_task(db.partition_manager_loop())
|
||||
asyncio.create_task(db.purge_loop())
|
||||
asyncio.create_task(mqtt_manager.ping_loop())
|
||||
asyncio.create_task(nextcloud_keepalive_loop())
|
||||
asyncio.create_task(crm_poll_loop())
|
||||
sync_accounts = [a for a in get_mail_accounts() if a.get("sync_inbound") and a.get("imap_host")]
|
||||
@@ -119,7 +136,8 @@ async def startup():
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown():
|
||||
mqtt_manager.stop()
|
||||
await db.close_db()
|
||||
from database.core import close_db as sqlite_close_db
|
||||
await sqlite_close_db()
|
||||
await close_nextcloud_client()
|
||||
|
||||
|
||||
|
||||
@@ -80,20 +80,33 @@ class BatchResponse(BaseModel):
|
||||
created_at: str
|
||||
|
||||
|
||||
class DeviceUserSummary(BaseModel):
|
||||
user_id: str
|
||||
display_name: str = ""
|
||||
email: str = ""
|
||||
|
||||
|
||||
class DeviceInventoryItem(BaseModel):
|
||||
id: str
|
||||
serial_number: str
|
||||
hw_type: str
|
||||
hw_version: str
|
||||
hw_family: str # board family code (BoardType value or bespoke UID) = firmware NVS "hw_family"
|
||||
hw_revision: str # hardware revision, e.g. "1.0" = firmware NVS "hw_revision"
|
||||
mfg_status: str
|
||||
mfg_batch_id: Optional[str] = None
|
||||
created_at: Optional[str] = None
|
||||
owner: Optional[str] = None
|
||||
assigned_to: Optional[str] = None
|
||||
device_name: Optional[str] = None
|
||||
# Console-only friendly name (mirrors devices.models.DeviceCreate.console_name).
|
||||
# Only populated once a device has been claimed/onboarded in the app — null
|
||||
# for freshly manufactured inventory, which is expected and should render
|
||||
# as a graceful fallback (e.g. serial number) on the frontend.
|
||||
console_name: Optional[str] = None
|
||||
lifecycle_history: Optional[List["LifecycleEntry"]] = None
|
||||
customer_id: Optional[str] = None
|
||||
customer_name: Optional[str] = None
|
||||
user_list: Optional[List[str]] = None
|
||||
users: Optional[List[DeviceUserSummary]] = None
|
||||
|
||||
|
||||
class DeviceInventoryListResponse(BaseModel):
|
||||
@@ -121,7 +134,7 @@ class CustomerSearchResult(BaseModel):
|
||||
|
||||
class RecentActivityItem(BaseModel):
|
||||
serial_number: str
|
||||
hw_type: str
|
||||
hw_family: str
|
||||
mfg_status: str
|
||||
owner: Optional[str] = None
|
||||
updated_at: Optional[str] = None
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import BigInteger, Column, DateTime, Index, String, Text
|
||||
from database.postgres import Base
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class MfgAuditLog(Base):
|
||||
__tablename__ = "mfg_audit_log"
|
||||
__table_args__ = (
|
||||
Index("idx_mfg_audit_time", "timestamp"),
|
||||
Index("idx_mfg_audit_action", "action"),
|
||||
)
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
timestamp = Column(DateTime(timezone=True), nullable=False, default=_now)
|
||||
admin_user = Column(String(256), nullable=False)
|
||||
action = Column(String(128), nullable=False)
|
||||
serial_number = Column(String(128))
|
||||
detail = Column(Text)
|
||||
+148
-71
@@ -3,6 +3,7 @@ from fastapi.responses import Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
@@ -13,9 +14,10 @@ from manufacturing.models import (
|
||||
ManufacturingStats,
|
||||
)
|
||||
from manufacturing import service
|
||||
from manufacturing import audit
|
||||
from shared.audit import log_action
|
||||
from shared.exceptions import NotFoundError
|
||||
from shared.firebase import get_db as get_firestore
|
||||
from database.postgres import get_pg_session
|
||||
|
||||
|
||||
class LifecycleEntryPatch(BaseModel):
|
||||
@@ -43,26 +45,21 @@ def get_stats(
|
||||
return service.get_stats()
|
||||
|
||||
|
||||
@router.get("/audit-log")
|
||||
async def get_audit_log(
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
_user: TokenPayload = Depends(require_permission("manufacturing", "view")),
|
||||
):
|
||||
entries = await audit.get_recent(limit=limit)
|
||||
return {"entries": entries}
|
||||
|
||||
|
||||
@router.post("/batch", response_model=BatchResponse, status_code=201)
|
||||
async def create_batch(
|
||||
body: BatchCreate,
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
result = service.create_batch(body)
|
||||
await audit.log_action(
|
||||
admin_user=user.email,
|
||||
action="batch_created",
|
||||
detail={
|
||||
"batch_id": result.batch_id,
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="CREATE",
|
||||
entity_type="device_batch",
|
||||
entity_id=result.batch_id,
|
||||
entity_label=f"Batch {result.batch_id} ({result.board_type}, qty {len(result.serial_numbers)})",
|
||||
meta={
|
||||
"board_type": result.board_type,
|
||||
"board_version": result.board_version,
|
||||
"quantity": len(result.serial_numbers),
|
||||
@@ -74,7 +71,9 @@ async def create_batch(
|
||||
@router.get("/devices", response_model=DeviceInventoryListResponse)
|
||||
def list_devices(
|
||||
status: Optional[str] = Query(None),
|
||||
hw_type: Optional[str] = Query(None),
|
||||
hw_family: Optional[str] = Query(None),
|
||||
hw_families: Optional[list[str]] = Query(None, description="Multi-select board family filter — repeat param, e.g. ?hw_families=vesper&hw_families=chronos"),
|
||||
has_users: Optional[bool] = Query(None, description="Filter by whether the device has any app users assigned"),
|
||||
search: Optional[str] = Query(None),
|
||||
limit: int = Query(100, ge=1, le=500),
|
||||
offset: int = Query(0, ge=0),
|
||||
@@ -82,7 +81,9 @@ def list_devices(
|
||||
):
|
||||
items = service.list_devices(
|
||||
status=status,
|
||||
hw_type=hw_type,
|
||||
hw_family=hw_family,
|
||||
hw_families=hw_families,
|
||||
has_users=has_users,
|
||||
search=search,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
@@ -137,6 +138,7 @@ async def update_status(
|
||||
sn: str,
|
||||
body: DeviceStatusUpdate,
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
# Guard: claimed requires at least one user in user_list
|
||||
# (allow if explicitly force_claimed=true, which the mfg UI sets after adding a user manually)
|
||||
@@ -167,11 +169,13 @@ async def update_status(
|
||||
)
|
||||
|
||||
result = service.update_device_status(sn, body, set_by=user.email)
|
||||
await audit.log_action(
|
||||
admin_user=user.email,
|
||||
action="status_updated",
|
||||
serial_number=sn,
|
||||
detail={"status": body.status.value, "note": body.note},
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="STATUS_CHANGE",
|
||||
entity_type="device",
|
||||
entity_id=sn,
|
||||
entity_label=sn,
|
||||
meta={"status": body.status.value, "note": body.note},
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -181,10 +185,11 @@ async def patch_lifecycle_entry(
|
||||
sn: str,
|
||||
body: LifecycleEntryPatch,
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Edit the date and/or note of a lifecycle history entry by index."""
|
||||
db = get_firestore()
|
||||
docs = list(db.collection("devices").where("serial_number", "==", sn).limit(1).stream())
|
||||
fs = get_firestore()
|
||||
docs = list(fs.collection("devices").where("serial_number", "==", sn).limit(1).stream())
|
||||
if not docs:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
doc_ref = docs[0].reference
|
||||
@@ -198,7 +203,16 @@ async def patch_lifecycle_entry(
|
||||
history[body.index]["note"] = body.note
|
||||
doc_ref.update({"lifecycle_history": history})
|
||||
from manufacturing.service import _doc_to_inventory_item
|
||||
return _doc_to_inventory_item(doc_ref.get())
|
||||
result = _doc_to_inventory_item(doc_ref.get())
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="UPDATE",
|
||||
entity_type="device",
|
||||
entity_id=sn,
|
||||
entity_label=sn,
|
||||
meta={"lifecycle_index": body.index, "date": body.date, "note": body.note},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/devices/{sn}/lifecycle", response_model=DeviceInventoryItem, status_code=200)
|
||||
@@ -206,6 +220,7 @@ async def create_lifecycle_entry(
|
||||
sn: str,
|
||||
body: LifecycleEntryCreate,
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Upsert a lifecycle history entry for the given status_id.
|
||||
|
||||
@@ -214,8 +229,8 @@ async def create_lifecycle_entry(
|
||||
a status is visited more than once (max one entry per status).
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
db = get_firestore()
|
||||
docs = list(db.collection("devices").where("serial_number", "==", sn).limit(1).stream())
|
||||
fs = get_firestore()
|
||||
docs = list(fs.collection("devices").where("serial_number", "==", sn).limit(1).stream())
|
||||
if not docs:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
doc_ref = docs[0].reference
|
||||
@@ -229,19 +244,28 @@ async def create_lifecycle_entry(
|
||||
"set_by": user.email,
|
||||
}
|
||||
|
||||
# Overwrite existing entry for this status if present, else append
|
||||
existing_idx = next(
|
||||
(i for i, e in enumerate(history) if e.get("status_id") == body.status_id),
|
||||
None,
|
||||
)
|
||||
if existing_idx is not None:
|
||||
is_update = existing_idx is not None
|
||||
if is_update:
|
||||
history[existing_idx] = new_entry
|
||||
else:
|
||||
history.append(new_entry)
|
||||
|
||||
doc_ref.update({"lifecycle_history": history})
|
||||
from manufacturing.service import _doc_to_inventory_item
|
||||
return _doc_to_inventory_item(doc_ref.get())
|
||||
result = _doc_to_inventory_item(doc_ref.get())
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="UPDATE" if is_update else "CREATE",
|
||||
entity_type="device",
|
||||
entity_id=sn,
|
||||
entity_label=sn,
|
||||
meta={"lifecycle_status": body.status_id, "date": new_entry["date"], "note": body.note},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@router.delete("/devices/{sn}/lifecycle/{index}", response_model=DeviceInventoryItem)
|
||||
@@ -249,10 +273,11 @@ async def delete_lifecycle_entry(
|
||||
sn: str,
|
||||
index: int,
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Delete a lifecycle history entry by index. Cannot delete the entry for the current status."""
|
||||
db = get_firestore()
|
||||
docs = list(db.collection("devices").where("serial_number", "==", sn).limit(1).stream())
|
||||
fs = get_firestore()
|
||||
docs = list(fs.collection("devices").where("serial_number", "==", sn).limit(1).stream())
|
||||
if not docs:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
doc_ref = docs[0].reference
|
||||
@@ -261,12 +286,22 @@ async def delete_lifecycle_entry(
|
||||
if index < 0 or index >= len(history):
|
||||
raise HTTPException(status_code=400, detail="Invalid lifecycle entry index")
|
||||
current_status = data.get("mfg_status", "")
|
||||
if history[index].get("status_id") == current_status:
|
||||
deleted_entry = history[index]
|
||||
if deleted_entry.get("status_id") == current_status:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete the entry for the current status. Change the status first.")
|
||||
history.pop(index)
|
||||
doc_ref.update({"lifecycle_history": history})
|
||||
from manufacturing.service import _doc_to_inventory_item
|
||||
return _doc_to_inventory_item(doc_ref.get())
|
||||
result = _doc_to_inventory_item(doc_ref.get())
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="DELETE",
|
||||
entity_type="device",
|
||||
entity_id=sn,
|
||||
entity_label=sn,
|
||||
meta={"lifecycle_status": deleted_entry.get("status_id"), "index": index},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/devices/{sn}/nvs.bin")
|
||||
@@ -274,13 +309,18 @@ async def download_nvs(
|
||||
sn: str,
|
||||
hw_type_override: Optional[str] = Query(None, description="Override hw_type written to NVS (for bespoke firmware)"),
|
||||
hw_revision_override: Optional[str] = Query(None, description="Override hw_revision written to NVS (for bespoke firmware)"),
|
||||
nvs_schema: Optional[str] = Query(None, description="NVS schema to use: 'legacy' or 'new' (default)"),
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "view")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
binary = service.get_nvs_binary(sn, hw_type_override=hw_type_override, hw_revision_override=hw_revision_override)
|
||||
await audit.log_action(
|
||||
admin_user=user.email,
|
||||
action="device_flashed",
|
||||
serial_number=sn,
|
||||
binary = service.get_nvs_binary(sn, hw_type_override=hw_type_override, hw_revision_override=hw_revision_override, legacy=(nvs_schema == "legacy"))
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="COMMAND",
|
||||
entity_type="device",
|
||||
entity_id=sn,
|
||||
entity_label=sn,
|
||||
meta={"command": "nvs_flash", "hw_type_override": hw_type_override, "nvs_schema": nvs_schema or "new"},
|
||||
)
|
||||
return Response(
|
||||
content=binary,
|
||||
@@ -294,16 +334,19 @@ async def assign_device(
|
||||
sn: str,
|
||||
body: DeviceAssign,
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
try:
|
||||
result = service.assign_device(sn, body)
|
||||
except NotFoundError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
await audit.log_action(
|
||||
admin_user=user.email,
|
||||
action="device_assigned",
|
||||
serial_number=sn,
|
||||
detail={"customer_id": body.customer_id},
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="UPDATE",
|
||||
entity_type="device",
|
||||
entity_id=sn,
|
||||
entity_label=sn,
|
||||
meta={"customer_id": body.customer_id},
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -313,6 +356,7 @@ async def delete_device(
|
||||
sn: str,
|
||||
force: bool = Query(False, description="Required to delete sold/claimed devices"),
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "delete")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Delete a device. Sold/claimed devices require force=true."""
|
||||
try:
|
||||
@@ -321,11 +365,13 @@ async def delete_device(
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
except PermissionError as e:
|
||||
raise HTTPException(status_code=403, detail=str(e))
|
||||
await audit.log_action(
|
||||
admin_user=user.email,
|
||||
action="device_deleted",
|
||||
serial_number=sn,
|
||||
detail={"force": force},
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="DELETE",
|
||||
entity_type="device",
|
||||
entity_id=sn,
|
||||
entity_label=sn,
|
||||
meta={"force": force},
|
||||
)
|
||||
|
||||
|
||||
@@ -333,6 +379,7 @@ async def delete_device(
|
||||
async def send_manufactured_email(
|
||||
sn: str,
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Send the 'device manufactured' notification to the assigned customer's email."""
|
||||
db = get_firestore()
|
||||
@@ -360,11 +407,13 @@ async def send_manufactured_email(
|
||||
device_name=hw_family.replace("_", " ").title(),
|
||||
customer_name=customer_name,
|
||||
)
|
||||
await audit.log_action(
|
||||
admin_user=user.email,
|
||||
action="email_manufactured_sent",
|
||||
serial_number=sn,
|
||||
detail={"recipient": email},
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="COMMAND",
|
||||
entity_type="device",
|
||||
entity_id=sn,
|
||||
entity_label=sn,
|
||||
meta={"command": "email_manufactured", "recipient": email},
|
||||
)
|
||||
|
||||
|
||||
@@ -372,6 +421,7 @@ async def send_manufactured_email(
|
||||
async def send_assigned_email(
|
||||
sn: str,
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Send the 'device assigned / app instructions' email to the assigned user(s)."""
|
||||
db = get_firestore()
|
||||
@@ -406,24 +456,30 @@ async def send_assigned_email(
|
||||
errors.append(str(exc))
|
||||
if errors:
|
||||
raise HTTPException(status_code=500, detail=f"Some emails failed: {'; '.join(errors)}")
|
||||
await audit.log_action(
|
||||
admin_user=user.email,
|
||||
action="email_assigned_sent",
|
||||
serial_number=sn,
|
||||
detail={"user_count": len(user_list)},
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="COMMAND",
|
||||
entity_type="device",
|
||||
entity_id=sn,
|
||||
entity_label=sn,
|
||||
meta={"command": "email_assigned", "user_count": len(user_list)},
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/devices", status_code=200)
|
||||
async def delete_unprovisioned(
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "delete")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Delete all devices with status 'manufactured' (never provisioned)."""
|
||||
deleted = service.delete_unprovisioned_devices()
|
||||
await audit.log_action(
|
||||
admin_user=user.email,
|
||||
action="bulk_delete_unprovisioned",
|
||||
detail={"count": len(deleted), "serial_numbers": deleted},
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="DELETE",
|
||||
entity_type="device_batch",
|
||||
entity_id="bulk_unprovisioned",
|
||||
entity_label=f"Bulk delete unprovisioned ({len(deleted)} devices)",
|
||||
meta={"count": len(deleted), "serial_numbers": deleted},
|
||||
)
|
||||
return {"deleted": deleted, "count": len(deleted)}
|
||||
|
||||
@@ -465,6 +521,7 @@ async def delete_flash_asset(
|
||||
hw_type: str,
|
||||
asset: str,
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "delete")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Delete a single flash asset file (bootloader.bin or partitions.bin)."""
|
||||
if asset not in VALID_FLASH_ASSETS:
|
||||
@@ -473,10 +530,13 @@ async def delete_flash_asset(
|
||||
service.delete_flash_asset(hw_type, asset)
|
||||
except NotFoundError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
await audit.log_action(
|
||||
admin_user=user.email,
|
||||
action="flash_asset_deleted",
|
||||
detail={"hw_type": hw_type, "asset": asset},
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="DELETE",
|
||||
entity_type="firmware",
|
||||
entity_id=f"{hw_type}/{asset}",
|
||||
entity_label=f"{hw_type} / {asset}",
|
||||
meta={"hw_type": hw_type, "asset": asset},
|
||||
)
|
||||
|
||||
|
||||
@@ -488,7 +548,8 @@ class FlashAssetNoteBody(BaseModel):
|
||||
async def set_flash_asset_note(
|
||||
hw_type: str,
|
||||
body: FlashAssetNoteBody,
|
||||
_user: TokenPayload = Depends(require_permission("manufacturing", "edit")),
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Save (or overwrite) the note for a hw_type's flash asset set.
|
||||
|
||||
@@ -496,6 +557,14 @@ async def set_flash_asset_note(
|
||||
Pass an empty string to clear the note.
|
||||
"""
|
||||
service.set_flash_asset_note(hw_type, body.note)
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="UPDATE",
|
||||
entity_type="firmware",
|
||||
entity_id=hw_type,
|
||||
entity_label=hw_type,
|
||||
meta={"note": body.note},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/flash-assets/{hw_type}/{asset}", status_code=204)
|
||||
@@ -503,7 +572,8 @@ async def upload_flash_asset(
|
||||
hw_type: str,
|
||||
asset: str,
|
||||
file: UploadFile = File(...),
|
||||
_user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
||||
user: TokenPayload = Depends(require_permission("manufacturing", "add")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Upload a bootloader.bin or partitions.bin for a given hw_type.
|
||||
|
||||
@@ -511,13 +581,20 @@ async def upload_flash_asset(
|
||||
and .pio/build/{env}/partitions.bin). Upload them once per hw_type after
|
||||
each PlatformIO build that changes the partition layout.
|
||||
"""
|
||||
# hw_type can be a standard board type OR a bespoke UID (any non-empty slug)
|
||||
if not hw_type or len(hw_type) > 128:
|
||||
raise HTTPException(status_code=400, detail="Invalid hw_type/bespoke UID.")
|
||||
if asset not in VALID_FLASH_ASSETS:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid asset. Must be one of: {', '.join(sorted(VALID_FLASH_ASSETS))}")
|
||||
data = await file.read()
|
||||
service.save_flash_asset(hw_type, asset, data)
|
||||
await log_action(
|
||||
db, user.sub, user.email,
|
||||
action="CREATE",
|
||||
entity_type="firmware",
|
||||
entity_id=f"{hw_type}/{asset}",
|
||||
entity_label=f"{hw_type} / {asset}",
|
||||
meta={"hw_type": hw_type, "asset": asset, "size_bytes": len(data)},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/devices/{sn}/bootloader.bin")
|
||||
@@ -528,7 +605,7 @@ def download_bootloader(
|
||||
):
|
||||
"""Return the bootloader.bin for this device's hw_type (flashed at 0x1000)."""
|
||||
item = service.get_device_by_sn(sn)
|
||||
hw_type = hw_type_override or item.hw_type
|
||||
hw_type = hw_type_override or item.hw_family
|
||||
try:
|
||||
data = service.get_flash_asset(hw_type, "bootloader.bin")
|
||||
except NotFoundError as e:
|
||||
@@ -548,7 +625,7 @@ def download_partitions(
|
||||
):
|
||||
"""Return the partitions.bin for this device's hw_type (flashed at 0x8000)."""
|
||||
item = service.get_device_by_sn(sn)
|
||||
hw_type = hw_type_override or item.hw_type
|
||||
hw_type = hw_type_override or item.hw_family
|
||||
try:
|
||||
data = service.get_flash_asset(hw_type, "partitions.bin")
|
||||
except NotFoundError as e:
|
||||
|
||||
@@ -11,9 +11,11 @@ from shared.firebase import get_db
|
||||
from shared.exceptions import NotFoundError
|
||||
from utils.serial_number import generate_serial
|
||||
from utils.nvs_generator import generate as generate_nvs_binary
|
||||
from manufacturing.models import BatchCreate, BatchResponse, DeviceInventoryItem, DeviceStatusUpdate, DeviceAssign, ManufacturingStats, RecentActivityItem, BOARD_TYPE_LABELS
|
||||
from manufacturing.models import BatchCreate, BatchResponse, DeviceInventoryItem, DeviceStatusUpdate, DeviceAssign, ManufacturingStats, RecentActivityItem, BOARD_TYPE_LABELS, DeviceUserSummary
|
||||
|
||||
COLLECTION = "devices"
|
||||
CRM_COLLECTION = "crm_customers"
|
||||
USERS_COLLECTION = "users"
|
||||
_BATCH_ID_CHARS = string.ascii_uppercase + string.digits
|
||||
|
||||
|
||||
@@ -45,7 +47,7 @@ def _resolve_user_list(raw_list: list) -> list[str]:
|
||||
return result
|
||||
|
||||
|
||||
def _doc_to_inventory_item(doc) -> DeviceInventoryItem:
|
||||
def _doc_to_inventory_item(doc, customer_names: dict | None = None, user_infos: dict | None = None) -> DeviceInventoryItem:
|
||||
data = doc.to_dict() or {}
|
||||
created_raw = data.get("created_at")
|
||||
if isinstance(created_raw, datetime):
|
||||
@@ -53,23 +55,68 @@ def _doc_to_inventory_item(doc) -> DeviceInventoryItem:
|
||||
else:
|
||||
created_str = str(created_raw) if created_raw else None
|
||||
|
||||
customer_names = customer_names or {}
|
||||
user_infos = user_infos or {}
|
||||
|
||||
user_ids = _resolve_user_list(data.get("user_list") or [])
|
||||
users = [user_infos[uid] for uid in user_ids if uid in user_infos]
|
||||
|
||||
customer_id = data.get("customer_id")
|
||||
|
||||
return DeviceInventoryItem(
|
||||
id=doc.id,
|
||||
serial_number=data.get("serial_number", ""),
|
||||
hw_type=data.get("hw_type", ""),
|
||||
hw_version=data.get("hw_version", ""),
|
||||
# hw_type / hw_version: names used before 2026-11-08 (kept as read fallback)
|
||||
hw_family=data.get("hw_family") or data.get("hw_type", ""),
|
||||
hw_revision=data.get("hw_revision") or data.get("hw_version", ""),
|
||||
mfg_status=data.get("mfg_status", "manufactured"),
|
||||
mfg_batch_id=data.get("mfg_batch_id"),
|
||||
created_at=created_str,
|
||||
owner=data.get("owner"),
|
||||
assigned_to=data.get("assigned_to"),
|
||||
device_name=data.get("device_name") or None,
|
||||
console_name=data.get("console_name") or None,
|
||||
lifecycle_history=data.get("lifecycle_history") or [],
|
||||
customer_id=data.get("customer_id"),
|
||||
user_list=_resolve_user_list(data.get("user_list") or []),
|
||||
customer_id=customer_id,
|
||||
customer_name=customer_names.get(customer_id) if customer_id else None,
|
||||
user_list=user_ids,
|
||||
users=users,
|
||||
)
|
||||
|
||||
|
||||
def _bulk_resolve_names(db, docs_data: list[dict]) -> tuple[dict, dict]:
|
||||
"""Batch-resolve customer names and user summaries referenced across a
|
||||
list of device docs, so listing N devices costs a handful of get_all()
|
||||
calls instead of an N+1 Firestore round trip per device."""
|
||||
customer_ids = {d.get("customer_id") for d in docs_data if d.get("customer_id")}
|
||||
user_ids = {uid for d in docs_data for uid in _resolve_user_list(d.get("user_list") or [])}
|
||||
|
||||
customer_names: dict[str, str] = {}
|
||||
if customer_ids:
|
||||
refs = [db.collection(CRM_COLLECTION).document(cid) for cid in customer_ids]
|
||||
for snap in db.get_all(refs):
|
||||
if not snap.exists:
|
||||
continue
|
||||
cdata = snap.to_dict() or {}
|
||||
name = " ".join(filter(None, [cdata.get("name"), cdata.get("surname")])) or cdata.get("email") or snap.id
|
||||
customer_names[snap.id] = name
|
||||
|
||||
user_infos: dict[str, DeviceUserSummary] = {}
|
||||
if user_ids:
|
||||
refs = [db.collection(USERS_COLLECTION).document(uid) for uid in user_ids]
|
||||
for snap in db.get_all(refs):
|
||||
if not snap.exists:
|
||||
continue
|
||||
udata = snap.to_dict() or {}
|
||||
user_infos[snap.id] = DeviceUserSummary(
|
||||
user_id=snap.id,
|
||||
display_name=udata.get("display_name") or "",
|
||||
email=udata.get("email") or "",
|
||||
)
|
||||
|
||||
return customer_names, user_infos
|
||||
|
||||
|
||||
def create_batch(data: BatchCreate) -> BatchResponse:
|
||||
db = get_db()
|
||||
existing_sns = _get_existing_sns(db)
|
||||
@@ -88,8 +135,11 @@ def create_batch(data: BatchCreate) -> BatchResponse:
|
||||
|
||||
db.collection(COLLECTION).add({
|
||||
"serial_number": sn,
|
||||
"hw_type": data.board_type.value,
|
||||
"hw_version": data.board_version,
|
||||
"device_id": sn, # schema v1 / D1: both apps connect over MQTT with device_id
|
||||
|
||||
# Same names as the firmware NVS keys.
|
||||
"hw_family": data.board_type.value,
|
||||
"hw_revision": data.board_version,
|
||||
"mfg_status": "manufactured",
|
||||
"mfg_batch_id": batch_id,
|
||||
"created_at": now,
|
||||
@@ -122,7 +172,9 @@ def create_batch(data: BatchCreate) -> BatchResponse:
|
||||
|
||||
def list_devices(
|
||||
status: str | None = None,
|
||||
hw_type: str | None = None,
|
||||
hw_family: str | None = None,
|
||||
hw_families: list[str] | None = None,
|
||||
has_users: bool | None = None,
|
||||
search: str | None = None,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
@@ -132,11 +184,28 @@ def list_devices(
|
||||
|
||||
if status:
|
||||
query = query.where("mfg_status", "==", status)
|
||||
if hw_type:
|
||||
query = query.where("hw_type", "==", hw_type)
|
||||
if hw_family:
|
||||
query = query.where("hw_family", "==", hw_family)
|
||||
|
||||
docs = list(query.stream())
|
||||
items = [_doc_to_inventory_item(doc) for doc in docs]
|
||||
docs_data = [doc.to_dict() or {} for doc in docs]
|
||||
|
||||
if hw_families:
|
||||
family_set = set(hw_families)
|
||||
keep = [i for i, d in enumerate(docs_data) if d.get("hw_family") in family_set]
|
||||
docs = [docs[i] for i in keep]
|
||||
docs_data = [docs_data[i] for i in keep]
|
||||
|
||||
if has_users is not None:
|
||||
keep = [
|
||||
i for i, d in enumerate(docs_data)
|
||||
if bool(d.get("user_list")) == has_users
|
||||
]
|
||||
docs = [docs[i] for i in keep]
|
||||
docs_data = [docs_data[i] for i in keep]
|
||||
|
||||
customer_names, user_infos = _bulk_resolve_names(db, docs_data)
|
||||
items = [_doc_to_inventory_item(doc, customer_names, user_infos) for doc in docs]
|
||||
|
||||
if search:
|
||||
search_lower = search.lower()
|
||||
@@ -145,6 +214,10 @@ def list_devices(
|
||||
if search_lower in (item.serial_number or "").lower()
|
||||
or search_lower in (item.owner or "").lower()
|
||||
or search_lower in (item.mfg_batch_id or "").lower()
|
||||
or search_lower in (item.device_name or "").lower()
|
||||
or search_lower in (item.console_name or "").lower()
|
||||
or search_lower in (item.customer_name or "").lower()
|
||||
or any(search_lower in (u.display_name or "").lower() or search_lower in (u.email or "").lower() for u in (item.users or []))
|
||||
]
|
||||
|
||||
return items[offset: offset + limit]
|
||||
@@ -155,7 +228,9 @@ def get_device_by_sn(sn: str) -> DeviceInventoryItem:
|
||||
docs = list(db.collection(COLLECTION).where("serial_number", "==", sn).limit(1).stream())
|
||||
if not docs:
|
||||
raise NotFoundError("Device")
|
||||
return _doc_to_inventory_item(docs[0])
|
||||
doc = docs[0]
|
||||
customer_names, user_infos = _bulk_resolve_names(db, [doc.to_dict() or {}])
|
||||
return _doc_to_inventory_item(doc, customer_names, user_infos)
|
||||
|
||||
|
||||
def update_device_status(sn: str, data: DeviceStatusUpdate, set_by: str | None = None) -> DeviceInventoryItem:
|
||||
@@ -197,12 +272,13 @@ def update_device_status(sn: str, data: DeviceStatusUpdate, set_by: str | None =
|
||||
return _doc_to_inventory_item(doc_ref.get())
|
||||
|
||||
|
||||
def get_nvs_binary(sn: str, hw_type_override: str | None = None, hw_revision_override: str | None = None) -> bytes:
|
||||
def get_nvs_binary(sn: str, hw_type_override: str | None = None, hw_revision_override: str | None = None, legacy: bool = False) -> bytes:
|
||||
item = get_device_by_sn(sn)
|
||||
return generate_nvs_binary(
|
||||
serial_number=item.serial_number,
|
||||
hw_family=hw_type_override if hw_type_override else item.hw_type,
|
||||
hw_revision=hw_revision_override if hw_revision_override else item.hw_version,
|
||||
hw_family=hw_type_override if hw_type_override else item.hw_family,
|
||||
hw_revision=hw_revision_override if hw_revision_override else item.hw_revision,
|
||||
legacy=legacy,
|
||||
)
|
||||
|
||||
|
||||
@@ -259,7 +335,7 @@ def assign_device(sn: str, data: DeviceAssign) -> DeviceInventoryItem:
|
||||
for item in owned_items
|
||||
)
|
||||
if not already_assigned:
|
||||
device_name = doc_data.get("device_name") or BOARD_TYPE_LABELS.get(doc_data.get("hw_type", ""), sn)
|
||||
device_name = doc_data.get("device_name") or BOARD_TYPE_LABELS.get(doc_data.get("hw_family") or doc_data.get("hw_type", ""), sn)
|
||||
owned_items.append({
|
||||
"type": "console_device",
|
||||
"console_device": {
|
||||
@@ -329,7 +405,7 @@ def get_stats() -> ManufacturingStats:
|
||||
|
||||
activity_candidates.append(RecentActivityItem(
|
||||
serial_number=data.get("serial_number", ""),
|
||||
hw_type=data.get("hw_type", ""),
|
||||
hw_family=data.get("hw_family") or data.get("hw_type", ""),
|
||||
mfg_status=status,
|
||||
owner=data.get("owner"),
|
||||
updated_at=ts_str,
|
||||
@@ -489,7 +565,6 @@ def get_firmware_url(sn: str) -> str:
|
||||
"""Return the FastAPI download URL for the latest stable firmware for this device's hw_type."""
|
||||
from firmware.service import get_latest
|
||||
item = get_device_by_sn(sn)
|
||||
hw_type = item.hw_type.lower()
|
||||
latest = get_latest(hw_type, "stable")
|
||||
latest = get_latest(item.hw_family.lower(), "stable")
|
||||
# download_url is a relative path like /api/firmware/vs/stable/1.4.2/firmware.bin
|
||||
return latest.download_url
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import Boolean, Column, DateTime, Index, String, Text
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from database.postgres import Base
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class MelodyDraft(Base):
|
||||
__tablename__ = "melody_drafts"
|
||||
__table_args__ = (
|
||||
Index("idx_melody_drafts_status", "status"),
|
||||
)
|
||||
|
||||
id = Column(String(128), primary_key=True)
|
||||
status = Column(String(32), nullable=False, default="draft")
|
||||
# 'data' stores the full melody definition as JSON (was TEXT/JSON in SQLite)
|
||||
data = Column(JSONB, nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=_now)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
|
||||
|
||||
|
||||
class BuiltMelody(Base):
|
||||
__tablename__ = "built_melodies"
|
||||
|
||||
id = Column(String(128), primary_key=True)
|
||||
name = Column(String(500), nullable=False)
|
||||
pid = Column(String(128), nullable=False)
|
||||
# 'steps' is a JSON array of step definitions
|
||||
steps = Column(JSONB, nullable=False)
|
||||
binary_path = Column(String(1000))
|
||||
progmem_code = Column(Text)
|
||||
# JSON array of melody IDs this built melody is assigned to
|
||||
assigned_melody_ids = Column(JSONB, nullable=False, default=list)
|
||||
is_builtin = Column(Boolean, nullable=False, default=False)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=_now)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
|
||||
+75
-16
@@ -1,15 +1,35 @@
|
||||
from fastapi import APIRouter, Depends, UploadFile, File, Query, HTTPException, Response
|
||||
from fastapi.responses import FileResponse
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
from melodies.models import (
|
||||
MelodyCreate, MelodyUpdate, MelodyInDB, MelodyListResponse, MelodyInfo,
|
||||
)
|
||||
from melodies import service
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
|
||||
router = APIRouter(prefix="/api/melodies", tags=["melodies"])
|
||||
|
||||
|
||||
@router.get("/download/{pid}")
|
||||
async def download_binary_by_pid(pid: str):
|
||||
"""Download a melody's .bsm binary by PID over plain HTTP.
|
||||
|
||||
No auth — ESP32 devices call this directly and can't afford a TLS client's
|
||||
memory footprint, so this is served from a plain-HTTP-only host
|
||||
(melodies.bellsystems.net) rather than the HTTPS console domain.
|
||||
"""
|
||||
path = await service.get_binary_path_by_pid(pid)
|
||||
return FileResponse(
|
||||
path=str(path),
|
||||
media_type="application/octet-stream",
|
||||
filename=f"{pid}.bsm",
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=MelodyListResponse)
|
||||
async def list_melodies(
|
||||
search: Optional[str] = Query(None),
|
||||
@@ -42,8 +62,12 @@ async def create_melody(
|
||||
body: MelodyCreate,
|
||||
publish: bool = Query(False),
|
||||
_user: TokenPayload = Depends(require_permission("melodies", "add")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return await service.create_melody(body, publish=publish, actor_name=_user.name)
|
||||
melody = await service.create_melody(body, publish=publish, actor_name=_user.name)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "melody",
|
||||
melody.id, melody.information.name if melody.information else melody.id)
|
||||
return melody
|
||||
|
||||
|
||||
@router.put("/{melody_id}", response_model=MelodyInDB)
|
||||
@@ -51,32 +75,61 @@ async def update_melody(
|
||||
melody_id: str,
|
||||
body: MelodyUpdate,
|
||||
_user: TokenPayload = Depends(require_permission("melodies", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return await service.update_melody(melody_id, body, actor_name=_user.name)
|
||||
old = await service.get_melody(melody_id)
|
||||
melody = await service.update_melody(melody_id, body, actor_name=_user.name)
|
||||
_SKIP = {"updated_at", "id", "metadata", "information", "noteAssignments"}
|
||||
changes = {
|
||||
k: {"old": getattr(old, k, None), "new": getattr(melody, k, None)}
|
||||
for k in body.model_fields_set
|
||||
if k not in _SKIP and getattr(old, k, None) != getattr(melody, k, None)
|
||||
}
|
||||
# Surface the name change from inside the information sub-object
|
||||
old_name = old.information.name if old.information else None
|
||||
new_name = melody.information.name if melody.information else None
|
||||
if old_name != new_name:
|
||||
changes["name"] = {"old": old_name, "new": new_name}
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "melody",
|
||||
melody_id, new_name or melody_id, changes=changes or None)
|
||||
return melody
|
||||
|
||||
|
||||
@router.delete("/{melody_id}", status_code=204)
|
||||
async def delete_melody(
|
||||
melody_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("melodies", "delete")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
melody = await service.get_melody(melody_id)
|
||||
label = melody.information.name if melody.information else melody_id
|
||||
await service.delete_melody(melody_id)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "DELETE", "melody",
|
||||
melody_id, label)
|
||||
|
||||
|
||||
@router.post("/{melody_id}/publish", response_model=MelodyInDB)
|
||||
async def publish_melody(
|
||||
melody_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("melodies", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return await service.publish_melody(melody_id)
|
||||
melody = await service.publish_melody(melody_id)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "PUBLISH", "melody",
|
||||
melody_id, melody.information.name if melody.information else melody_id)
|
||||
return melody
|
||||
|
||||
|
||||
@router.post("/{melody_id}/unpublish", response_model=MelodyInDB)
|
||||
async def unpublish_melody(
|
||||
melody_id: str,
|
||||
_user: TokenPayload = Depends(require_permission("melodies", "edit")),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
return await service.unpublish_melody(melody_id)
|
||||
melody = await service.unpublish_melody(melody_id)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UNPUBLISH", "melody",
|
||||
melody_id, melody.information.name if melody.information else melody_id)
|
||||
return melody
|
||||
|
||||
|
||||
@router.post("/{melody_id}/upload/{file_type}")
|
||||
@@ -98,15 +151,21 @@ async def upload_file(
|
||||
|
||||
if file_type == "binary":
|
||||
content_type = "application/octet-stream"
|
||||
|
||||
url = service.upload_file_for_melody(
|
||||
melody_id=melody_id,
|
||||
melody_uid=melody.uid,
|
||||
melody_pid=melody.pid,
|
||||
file_bytes=contents,
|
||||
filename=file.filename,
|
||||
content_type=content_type,
|
||||
)
|
||||
if not melody.pid:
|
||||
raise HTTPException(status_code=400, detail="Melody must have a PID before uploading a binary")
|
||||
url = service.save_binary_for_melody(
|
||||
pid=melody.pid,
|
||||
file_bytes=contents,
|
||||
)
|
||||
else:
|
||||
url = service.upload_file_for_melody(
|
||||
melody_id=melody_id,
|
||||
melody_uid=melody.uid,
|
||||
melody_pid=melody.pid,
|
||||
file_bytes=contents,
|
||||
filename=file.filename,
|
||||
content_type=content_type,
|
||||
)
|
||||
|
||||
# Update the melody document with the file URL
|
||||
if file_type == "preview":
|
||||
@@ -133,7 +192,7 @@ async def delete_file(
|
||||
raise HTTPException(status_code=400, detail="file_type must be 'binary' or 'preview'")
|
||||
|
||||
melody = await service.get_melody(melody_id)
|
||||
service.delete_file(melody_id, file_type, melody.uid)
|
||||
await service.delete_file(melody_id, file_type, melody.uid, melody.pid)
|
||||
|
||||
|
||||
@router.get("/{melody_id}/files")
|
||||
@@ -143,7 +202,7 @@ async def get_files(
|
||||
):
|
||||
"""Get storage file URLs for a melody."""
|
||||
melody = await service.get_melody(melody_id)
|
||||
return service.get_storage_files(melody_id, melody.uid)
|
||||
return service.get_storage_files(melody_id, melody.uid, melody.pid)
|
||||
|
||||
|
||||
@router.patch("/{melody_id}/set-outdated", response_model=MelodyInDB)
|
||||
@@ -170,7 +229,7 @@ async def download_binary_file(
|
||||
):
|
||||
"""Download current melody binary with a PID-based filename."""
|
||||
melody = await service.get_melody(melody_id)
|
||||
file_bytes, content_type = service.get_binary_file_bytes(melody_id, melody.uid)
|
||||
file_bytes, content_type = service.get_binary_file_bytes(melody_id, melody.pid)
|
||||
filename = f"{(melody.pid or 'binary')}.bsm"
|
||||
headers = {"Content-Disposition": f'attachment; filename="{filename}"'}
|
||||
return Response(content=file_bytes, media_type=content_type, headers=headers)
|
||||
|
||||
+108
-36
@@ -2,15 +2,39 @@ import json
|
||||
import uuid
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from shared.firebase import get_db as get_firestore, get_bucket
|
||||
from shared.exceptions import NotFoundError
|
||||
from melodies.models import MelodyCreate, MelodyUpdate, MelodyInDB
|
||||
from melodies import database as melody_db
|
||||
from config import settings
|
||||
|
||||
COLLECTION = "melodies"
|
||||
logger = logging.getLogger("melodies.service")
|
||||
|
||||
# Local disk storage for melody .bsm binaries — served over plain HTTP for ESP32 compatibility.
|
||||
# The audio preview file still goes to Firebase Storage (only ever fetched by the browser admin UI).
|
||||
BINARY_STORAGE_DIR = Path(settings.melody_binaries_storage_path)
|
||||
|
||||
|
||||
def _ensure_binary_storage_dir():
|
||||
BINARY_STORAGE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def _binary_file_path(pid: str) -> Path:
|
||||
"""Path to the local .bsm file for a given archetype PID.
|
||||
|
||||
Keyed on pid, not melody uid: pid identifies the underlying archetype binary
|
||||
(raw note sequence). Multiple melodies can legitimately share one pid — each
|
||||
melody remaps those notes to actual bells via its own noteAssignments/speed/
|
||||
duration settings — so several melodies writing/reading the same {pid}.bsm
|
||||
file is expected, not a collision.
|
||||
"""
|
||||
return BINARY_STORAGE_DIR / f"{pid}.bsm"
|
||||
|
||||
|
||||
def _parse_localized_string(value: str) -> dict:
|
||||
"""Parse a JSON-encoded localized string into a dict. Returns {} on failure."""
|
||||
@@ -232,12 +256,50 @@ async def delete_melody(melody_id: str) -> None:
|
||||
doc_ref.delete()
|
||||
|
||||
# Delete storage files
|
||||
_delete_storage_files(melody_id, row["data"].get("uid"))
|
||||
await _delete_storage_files(melody_id, row["data"].get("uid"), row["data"].get("pid"))
|
||||
|
||||
# Delete from SQLite
|
||||
await melody_db.delete_melody(melody_id)
|
||||
|
||||
|
||||
def save_binary_for_melody(pid: str, file_bytes: bytes) -> str:
|
||||
"""Save an archetype binary to local disk under its pid, replacing any previous
|
||||
file for that pid. Multiple melodies can share one pid (they remap the same
|
||||
underlying note sequence via their own noteAssignments/speed/duration), so
|
||||
writing the same {pid}.bsm from a different melody is expected — not a collision.
|
||||
|
||||
Returns the plain-HTTP download URL devices use (served from melody_download_base_url,
|
||||
not Firebase — ESP32 devices can't afford the RAM for a TLS client).
|
||||
"""
|
||||
_ensure_binary_storage_dir()
|
||||
path = _binary_file_path(pid)
|
||||
path.write_bytes(file_bytes)
|
||||
return f"{settings.melody_download_base_url}/{pid}"
|
||||
|
||||
|
||||
async def get_binary_path_by_pid(pid: str) -> Path:
|
||||
"""Resolve a pid to its local .bsm file path. Used by the unauthenticated
|
||||
device-facing download route."""
|
||||
path = _binary_file_path(pid)
|
||||
if path.exists():
|
||||
return path
|
||||
raise NotFoundError("Binary file")
|
||||
|
||||
|
||||
def delete_local_binary(pid: str) -> None:
|
||||
"""Delete the local .bsm binary file for a pid, if present.
|
||||
|
||||
Only call this when no other melody still references this pid — since the
|
||||
file may be shared by multiple melodies, deleting one melody shouldn't
|
||||
reflexively delete a binary others still use.
|
||||
"""
|
||||
if not pid:
|
||||
return
|
||||
path = _binary_file_path(pid)
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
|
||||
|
||||
def upload_file(melody_id: str, file_bytes: bytes, filename: str, content_type: str) -> str:
|
||||
"""Upload a file to Firebase Storage under melodies/{melody_id}/."""
|
||||
bucket = get_bucket()
|
||||
@@ -334,32 +396,32 @@ def upload_file_for_melody(melody_id: str, melody_uid: str | None, melody_pid: s
|
||||
return blob.public_url
|
||||
|
||||
|
||||
def get_binary_file_bytes(melody_id: str, melody_uid: str | None = None) -> tuple[bytes, str]:
|
||||
"""Fetch current binary bytes for a melody from Firebase Storage."""
|
||||
bucket = get_bucket()
|
||||
if not bucket:
|
||||
raise RuntimeError("Firebase Storage not initialized")
|
||||
|
||||
prefixes = _storage_prefixes(melody_id, melody_uid)
|
||||
blobs = [b for b in _list_blobs_for_prefixes(bucket, prefixes) if _is_binary_blob_name(b.name)]
|
||||
if not blobs:
|
||||
raise NotFoundError("Binary file")
|
||||
|
||||
# Prefer explicit binary.* naming, then newest.
|
||||
blobs.sort(
|
||||
key=lambda b: (
|
||||
0 if "binary" in b.name.rsplit("/", 1)[-1].lower() else 1,
|
||||
-(int(b.time_created.timestamp()) if getattr(b, "time_created", None) else 0),
|
||||
)
|
||||
async def _pid_used_by_other_melody(pid: str, exclude_melody_id: str) -> bool:
|
||||
"""Check whether any melody other than exclude_melody_id still references this pid."""
|
||||
if not pid:
|
||||
return False
|
||||
rows = await melody_db.list_melodies()
|
||||
return any(
|
||||
row["id"] != exclude_melody_id and row["data"].get("pid") == pid
|
||||
for row in rows
|
||||
)
|
||||
chosen = blobs[0]
|
||||
data = chosen.download_as_bytes()
|
||||
content_type = chosen.content_type or "application/octet-stream"
|
||||
return data, content_type
|
||||
|
||||
|
||||
def delete_file(melody_id: str, file_type: str, melody_uid: str | None = None) -> None:
|
||||
def get_binary_file_bytes(melody_id: str, melody_pid: str | None = None) -> tuple[bytes, str]:
|
||||
"""Fetch current binary bytes for a melody from local disk storage."""
|
||||
path = _binary_file_path(melody_pid) if melody_pid else None
|
||||
if not path or not path.exists():
|
||||
raise NotFoundError("Binary file")
|
||||
return path.read_bytes(), "application/octet-stream"
|
||||
|
||||
|
||||
async def delete_file(melody_id: str, file_type: str, melody_uid: str | None = None, melody_pid: str | None = None) -> None:
|
||||
"""Delete a specific file from storage. file_type is 'binary' or 'preview'."""
|
||||
if file_type == "binary":
|
||||
if melody_pid and not await _pid_used_by_other_melody(melody_pid, melody_id):
|
||||
delete_local_binary(melody_pid)
|
||||
return
|
||||
|
||||
bucket = get_bucket()
|
||||
if not bucket:
|
||||
return
|
||||
@@ -368,14 +430,19 @@ def delete_file(melody_id: str, file_type: str, melody_uid: str | None = None) -
|
||||
blobs = _list_blobs_for_prefixes(bucket, prefixes)
|
||||
|
||||
for blob in blobs:
|
||||
if file_type == "binary" and "binary" in blob.name:
|
||||
blob.delete()
|
||||
elif file_type == "preview" and "preview" in blob.name:
|
||||
if file_type == "preview" and "preview" in blob.name:
|
||||
blob.delete()
|
||||
|
||||
|
||||
def _delete_storage_files(melody_id: str, melody_uid: str | None = None) -> None:
|
||||
"""Delete all storage files for a melody."""
|
||||
async def _delete_storage_files(melody_id: str, melody_uid: str | None = None, melody_pid: str | None = None) -> None:
|
||||
"""Delete all storage files for a melody (local binary + Firebase preview).
|
||||
|
||||
The local binary is only deleted if no other melody still references the same
|
||||
pid — multiple melodies can share one archetype binary by design.
|
||||
"""
|
||||
if melody_pid and not await _pid_used_by_other_melody(melody_pid, melody_id):
|
||||
delete_local_binary(melody_pid)
|
||||
|
||||
bucket = get_bucket()
|
||||
if not bucket:
|
||||
return
|
||||
@@ -383,24 +450,29 @@ def _delete_storage_files(melody_id: str, melody_uid: str | None = None) -> None
|
||||
prefixes = _storage_prefixes(melody_id, melody_uid)
|
||||
blobs = _list_blobs_for_prefixes(bucket, prefixes)
|
||||
for blob in blobs:
|
||||
if _is_binary_blob_name(blob.name):
|
||||
continue # legacy Firebase binaries, if any, are no longer authoritative
|
||||
blob.delete()
|
||||
|
||||
|
||||
def get_storage_files(melody_id: str, melody_uid: str | None = None) -> dict:
|
||||
"""List storage files for a melody, returning URLs."""
|
||||
def get_storage_files(melody_id: str, melody_uid: str | None = None, melody_pid: str | None = None) -> dict:
|
||||
"""List storage files for a melody, returning URLs. Binary comes from local disk,
|
||||
preview still comes from Firebase Storage."""
|
||||
result = {"binary_url": None, "preview_url": None}
|
||||
|
||||
if melody_pid and _binary_file_path(melody_pid).exists():
|
||||
result["binary_url"] = f"{settings.melody_download_base_url}/{melody_pid}"
|
||||
|
||||
bucket = get_bucket()
|
||||
if not bucket:
|
||||
return {"binary_url": None, "preview_url": None}
|
||||
return result
|
||||
|
||||
prefixes = _storage_prefixes(melody_id, melody_uid)
|
||||
blobs = _list_blobs_for_prefixes(bucket, prefixes)
|
||||
|
||||
result = {"binary_url": None, "preview_url": None}
|
||||
for blob in blobs:
|
||||
blob.make_public()
|
||||
if _is_binary_blob_name(blob.name):
|
||||
result["binary_url"] = blob.public_url
|
||||
elif "preview" in blob.name:
|
||||
if "preview" in blob.name:
|
||||
blob.make_public()
|
||||
result["preview_url"] = blob.public_url
|
||||
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
Phase 1 — Step 1.2: built_melodies (SQLite → Postgres)
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_built_melodies
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from melodies.orm import BuiltMelody
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, parse_json, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_built_melodies"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM built_melodies")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} built_melodies rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = []
|
||||
for r in rows:
|
||||
records.append({
|
||||
"id": r["id"],
|
||||
"name": r["name"],
|
||||
"pid": r["pid"],
|
||||
"steps": parse_json(r["steps"], default=[]),
|
||||
"binary_path": r["binary_path"],
|
||||
"progmem_code": r["progmem_code"],
|
||||
"assigned_melody_ids": parse_json(r["assigned_melody_ids"], default=[]),
|
||||
"is_builtin": bool(r["is_builtin"]) if r["is_builtin"] is not None else False,
|
||||
"created_at": parse_dt(r["created_at"]),
|
||||
"updated_at": parse_dt(r["updated_at"]),
|
||||
})
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
stmt = pg_insert(BuiltMelody).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "built_melodies")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
Phase 1 — Step 1.10: commands (SQLite → Postgres)
|
||||
|
||||
commands is a raw-SQL table (no ORM model). BIGSERIAL PK — SQLite integer IDs
|
||||
are NOT preserved; rows are inserted in sent_at order.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_commands
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_commands"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM commands ORDER BY sent_at")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} commands rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = [
|
||||
{
|
||||
"device_serial": r["device_serial"],
|
||||
"command_name": r["command_name"],
|
||||
"command_payload": r["command_payload"],
|
||||
"status": r["status"] or "pending",
|
||||
"response_payload": r["response_payload"],
|
||||
"sent_at": parse_dt(r["sent_at"]),
|
||||
"responded_at": parse_dt(r["responded_at"]),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO commands
|
||||
(device_serial, command_name, command_payload, status,
|
||||
response_payload, sent_at, responded_at)
|
||||
VALUES
|
||||
(:device_serial, :command_name, :command_payload, :status,
|
||||
:response_payload, :sent_at, :responded_at)
|
||||
"""),
|
||||
records,
|
||||
)
|
||||
dest_count = await pg_count(session, "commands")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
Phase 1 — Step 1.9: crm_comms_log (SQLite → Postgres)
|
||||
|
||||
FK to crm_customers(id) (nullable, ON DELETE SET NULL) — FK enforcement
|
||||
suppressed until Phase 2 populates crm_customers.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_crm_comms_log
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from crm.orm import CrmCommsLog
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, parse_json, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_crm_comms_log"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM crm_comms_log ORDER BY occurred_at")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} crm_comms_log rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = []
|
||||
for r in rows:
|
||||
# attachments stored as JSON text in SQLite
|
||||
attachments = parse_json(r["attachments"], default=[])
|
||||
|
||||
# is_important / is_read stored as INTEGER (0/1) in SQLite
|
||||
is_important = bool(r["is_important"]) if r["is_important"] is not None else False
|
||||
is_read = bool(r["is_read"]) if r["is_read"] is not None else True
|
||||
|
||||
records.append({
|
||||
"id": r["id"],
|
||||
"customer_id": r["customer_id"],
|
||||
"type": r["type"],
|
||||
"mail_account": r["mail_account"],
|
||||
"direction": r["direction"],
|
||||
"subject": r["subject"],
|
||||
"body": r["body"],
|
||||
"body_html": r["body_html"],
|
||||
"attachments": attachments,
|
||||
"ext_message_id": r["ext_message_id"],
|
||||
"from_addr": r["from_addr"],
|
||||
"to_addrs": r["to_addrs"],
|
||||
"logged_by": r["logged_by"],
|
||||
"is_important": is_important,
|
||||
"is_read": is_read,
|
||||
"occurred_at": parse_dt(r["occurred_at"]),
|
||||
"created_at": parse_dt(r["created_at"]),
|
||||
})
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
await session.execute(text("SET LOCAL session_replication_role = replica"))
|
||||
stmt = pg_insert(CrmCommsLog).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "crm_comms_log")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,172 @@
|
||||
"""
|
||||
Phase 2 — Step 2.4: crm_customers (Firestore → Postgres)
|
||||
|
||||
Reads the 'crm_customers' Firestore collection.
|
||||
- Strips legacy fields: 'negotiating', 'has_problem'
|
||||
- Converts Firestore DatetimeWithNanoseconds → UTC datetime
|
||||
- Converts nested dicts/lists → JSONB-ready Python objects
|
||||
|
||||
After this runs, the FK constraints on crm_quotations, crm_comms_log,
|
||||
crm_media, and crm_orders (all inserted in Phase 1 with FK enforcement
|
||||
suppressed) become valid.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_crm_customers
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from crm.orm import CrmCustomer
|
||||
from shared.firebase import init_firebase, get_db as get_firestore
|
||||
from migration.utils import AsyncPgSession, parse_dt, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_crm_customers"
|
||||
COLLECTION = "crm_customers"
|
||||
|
||||
_LEGACY_FIELDS = {"negotiating", "has_problem"}
|
||||
|
||||
_VALID_STATUSES = {
|
||||
"lead", "active", "inactive", "archived",
|
||||
"prospect", "churned", "vip",
|
||||
}
|
||||
|
||||
|
||||
def _now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _coerce_dt(val) -> datetime | None:
|
||||
"""Handle both Firestore DatetimeWithNanoseconds and ISO strings."""
|
||||
if val is None:
|
||||
return None
|
||||
if isinstance(val, datetime):
|
||||
return val.replace(tzinfo=timezone.utc) if val.tzinfo is None else val
|
||||
return parse_dt(str(val))
|
||||
|
||||
|
||||
def _coerce_list(val, default=None) -> list:
|
||||
if isinstance(val, list):
|
||||
return val
|
||||
return default if default is not None else []
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
init_firebase()
|
||||
fs = get_firestore()
|
||||
if fs is None:
|
||||
print("ERROR: Firebase not initialised.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
docs = list(fs.collection(COLLECTION).stream())
|
||||
source_count = len(docs)
|
||||
print(f"Source (Firestore): {source_count} crm_customers documents")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = []
|
||||
skipped = 0
|
||||
for doc in docs:
|
||||
d = doc.to_dict()
|
||||
|
||||
# Strip legacy fields
|
||||
for f in _LEGACY_FIELDS:
|
||||
d.pop(f, None)
|
||||
|
||||
# folder_id is NOT NULL UNIQUE — skip docs missing it
|
||||
folder_id = d.get("folder_id") or ""
|
||||
if not folder_id:
|
||||
print(f" WARNING: customer {doc.id} has no folder_id — skipping", file=sys.stderr)
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# relationship_status — normalise unknown values to 'lead'
|
||||
rel_status = d.get("relationship_status") or "lead"
|
||||
if rel_status not in _VALID_STATUSES:
|
||||
rel_status = "lead"
|
||||
|
||||
# contacts / notes — Firestore stores as list of maps
|
||||
contacts = _coerce_list(d.get("contacts"))
|
||||
# Serialise nested Pydantic-style objects to plain dicts
|
||||
contacts = [c if isinstance(c, dict) else vars(c) for c in contacts]
|
||||
|
||||
notes = _coerce_list(d.get("notes"))
|
||||
notes = [n if isinstance(n, dict) else vars(n) for n in notes]
|
||||
|
||||
# location — may be a map or None
|
||||
location = d.get("location")
|
||||
if location and not isinstance(location, dict):
|
||||
location = vars(location)
|
||||
|
||||
tags = _coerce_list(d.get("tags"))
|
||||
owned_items = _coerce_list(d.get("owned_items"))
|
||||
owned_items = [o if isinstance(o, dict) else vars(o) for o in owned_items]
|
||||
|
||||
linked_user_ids = _coerce_list(d.get("linked_user_ids"))
|
||||
|
||||
technical_issues = _coerce_list(d.get("technical_issues"))
|
||||
install_support = _coerce_list(d.get("install_support"))
|
||||
transaction_history = _coerce_list(d.get("transaction_history"))
|
||||
|
||||
crm_summary = d.get("crm_summary")
|
||||
if crm_summary and not isinstance(crm_summary, dict):
|
||||
crm_summary = vars(crm_summary)
|
||||
|
||||
created_at = _coerce_dt(d.get("created_at")) or _now_utc()
|
||||
updated_at = _coerce_dt(d.get("updated_at")) or _now_utc()
|
||||
|
||||
records.append({
|
||||
"id": doc.id,
|
||||
"firestore_id": doc.id,
|
||||
"title": d.get("title"),
|
||||
"name": d.get("name") or "",
|
||||
"surname": d.get("surname"),
|
||||
"organization": d.get("organization"),
|
||||
"religion": d.get("religion"),
|
||||
"language": d.get("language") or "el",
|
||||
"folder_id": folder_id,
|
||||
"relationship_status": rel_status,
|
||||
"nextcloud_folder": d.get("nextcloud_folder"),
|
||||
"contacts": contacts,
|
||||
"notes": notes,
|
||||
"location": location,
|
||||
"tags": tags,
|
||||
"owned_items": owned_items,
|
||||
"linked_user_ids": linked_user_ids,
|
||||
"technical_issues": technical_issues,
|
||||
"install_support": install_support,
|
||||
"transaction_history": transaction_history,
|
||||
"crm_summary": crm_summary,
|
||||
"created_at": created_at,
|
||||
"updated_at": updated_at,
|
||||
})
|
||||
|
||||
actual_source = source_count - skipped
|
||||
print(f" {skipped} skipped (missing folder_id), {actual_source} to insert")
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
stmt = pg_insert(CrmCustomer).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "crm_customers")
|
||||
|
||||
if dest_count < actual_source:
|
||||
msg = f"Count mismatch: expected>={actual_source} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count,
|
||||
notes=f"{skipped} skipped (no folder_id)" if skipped else None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
Phase 1 — Step 1.8: crm_media (SQLite → Postgres)
|
||||
|
||||
FK to crm_customers(id) (nullable) — FK enforcement suppressed until Phase 2
|
||||
populates crm_customers.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_crm_media
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from crm.orm import CrmMedia
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, parse_json, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_crm_media"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM crm_media ORDER BY created_at")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} crm_media rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = []
|
||||
for r in rows:
|
||||
# SQLite stores tags as JSON text; Postgres column is JSONB
|
||||
tags_raw = r["tags"]
|
||||
tags = parse_json(tags_raw, default=[])
|
||||
|
||||
records.append({
|
||||
"id": r["id"],
|
||||
"customer_id": r["customer_id"],
|
||||
"order_id": r["order_id"],
|
||||
"filename": r["filename"],
|
||||
"nextcloud_path": r["nextcloud_path"],
|
||||
"thumbnail_path": r["thumbnail_path"],
|
||||
"mime_type": r["mime_type"],
|
||||
"direction": r["direction"],
|
||||
"tags": tags,
|
||||
"uploaded_by": r["uploaded_by"],
|
||||
"created_at": parse_dt(r["created_at"]),
|
||||
})
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
await session.execute(text("SET LOCAL session_replication_role = replica"))
|
||||
stmt = pg_insert(CrmMedia).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "crm_media")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,156 @@
|
||||
"""
|
||||
Phase 2 — Step 2.5: crm_orders (Firestore → Postgres)
|
||||
|
||||
Orders are stored as a subcollection under each customer:
|
||||
crm_customers/{customer_id}/orders/{order_id}
|
||||
|
||||
Uses collection_group("orders") to fetch all orders in one pass,
|
||||
then inserts into crm_orders. crm_customers MUST already be in Postgres
|
||||
(step 2.4) so the FK constraint is satisfied.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_crm_orders
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from crm.orm import CrmOrder
|
||||
from shared.firebase import init_firebase, get_db as get_firestore
|
||||
from migration.utils import AsyncPgSession, parse_dt, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_crm_orders"
|
||||
|
||||
|
||||
def _now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _coerce_dt(val) -> datetime | None:
|
||||
if val is None:
|
||||
return None
|
||||
if isinstance(val, datetime):
|
||||
return val.replace(tzinfo=timezone.utc) if val.tzinfo is None else val
|
||||
return parse_dt(str(val))
|
||||
|
||||
|
||||
def _coerce_list(val) -> list:
|
||||
return val if isinstance(val, list) else []
|
||||
|
||||
|
||||
def _coerce_dict(val) -> dict:
|
||||
return val if isinstance(val, dict) else {}
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
init_firebase()
|
||||
fs = get_firestore()
|
||||
if fs is None:
|
||||
print("ERROR: Firebase not initialised.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# collection_group fetches from ALL customers' 'orders' subcollections
|
||||
docs = list(fs.collection_group("orders").stream())
|
||||
source_count = len(docs)
|
||||
print(f"Source (Firestore): {source_count} order documents (via collection_group)")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
# First, collect all customer IDs already in Postgres so we can skip
|
||||
# orphaned orders whose customer didn't migrate (missing folder_id edge case)
|
||||
async with AsyncPgSession() as session:
|
||||
from sqlalchemy import text
|
||||
result = await session.execute(text("SELECT id FROM crm_customers"))
|
||||
valid_customer_ids = {row[0] for row in result.fetchall()}
|
||||
|
||||
records = []
|
||||
skipped = 0
|
||||
seen_order_numbers: set[str] = set()
|
||||
for doc in docs:
|
||||
d = doc.to_dict()
|
||||
|
||||
# Extract customer_id from the document path:
|
||||
# crm_customers/{customer_id}/orders/{order_id}
|
||||
path_parts = doc.reference.path.split("/")
|
||||
# path: crm_customers / <cid> / orders / <oid>
|
||||
try:
|
||||
customer_id = path_parts[1]
|
||||
except IndexError:
|
||||
print(f" WARNING: cannot parse customer_id from path {doc.reference.path} — skipping")
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
if customer_id not in valid_customer_ids:
|
||||
print(f" WARNING: order {doc.id} references unknown customer {customer_id} — skipping")
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
order_number = d.get("order_number") or f"ORD-LEGACY-{doc.id}"
|
||||
# Deduplicate: if this order_number was already seen in this batch,
|
||||
# make it unique by appending the doc ID suffix.
|
||||
if order_number in seen_order_numbers:
|
||||
order_number = f"{order_number}-{doc.id[:8]}"
|
||||
print(f" INFO: duplicate order_number — renamed to {order_number}")
|
||||
seen_order_numbers.add(order_number)
|
||||
|
||||
created_at = _coerce_dt(d.get("created_at")) or _now_utc()
|
||||
updated_at = _coerce_dt(d.get("updated_at")) or _now_utc()
|
||||
status_updated_date = _coerce_dt(d.get("status_updated_date"))
|
||||
|
||||
records.append({
|
||||
"id": doc.id,
|
||||
"customer_id": customer_id,
|
||||
"order_number": order_number,
|
||||
"title": d.get("title"),
|
||||
"created_by": d.get("created_by"),
|
||||
"status": d.get("status") or "negotiating",
|
||||
"status_updated_date": status_updated_date,
|
||||
"status_updated_by": d.get("status_updated_by"),
|
||||
"items": _coerce_list(d.get("items")),
|
||||
"subtotal": float(d.get("subtotal") or 0),
|
||||
"discount": d.get("discount") if isinstance(d.get("discount"), dict) else None,
|
||||
"total_price": float(d.get("total_price") or 0),
|
||||
"currency": d.get("currency") or "EUR",
|
||||
"shipping": d.get("shipping") if isinstance(d.get("shipping"), dict) else None,
|
||||
"payment_status": _coerce_dict(d.get("payment_status")),
|
||||
"invoice_path": d.get("invoice_path"),
|
||||
"notes": d.get("notes") if isinstance(d.get("notes"), str) else None,
|
||||
"timeline": _coerce_list(d.get("timeline")),
|
||||
"created_at": created_at,
|
||||
"updated_at": updated_at,
|
||||
})
|
||||
|
||||
actual_source = source_count - skipped
|
||||
print(f" {skipped} skipped (orphaned/bad path), {actual_source} to insert")
|
||||
|
||||
if not records:
|
||||
print("Nothing valid to insert.")
|
||||
await log_run(SCRIPT, source_count, 0, notes=f"{skipped} all skipped")
|
||||
return
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
stmt = pg_insert(CrmOrder).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "crm_orders")
|
||||
|
||||
if dest_count < actual_source:
|
||||
msg = f"Count mismatch: expected>={actual_source} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count,
|
||||
notes=f"{skipped} skipped" if skipped else None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
Phase 2 — Step 2.3: crm_products (Firestore → Postgres)
|
||||
|
||||
Reads the 'crm_products' Firestore collection. The Firestore schema is richer
|
||||
than the Postgres target (has costs, stock, name_en, etc.) — we extract only
|
||||
what the Postgres ORM model covers. The rest stays in Firestore until the
|
||||
service is fully cut over.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_crm_products
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from crm.orm import CrmProduct
|
||||
from shared.firebase import init_firebase, get_db as get_firestore
|
||||
from migration.utils import AsyncPgSession, parse_dt, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_crm_products"
|
||||
COLLECTION = "crm_products"
|
||||
|
||||
_LEGACY_STATUS_MAP = {
|
||||
"active": True,
|
||||
"discontinued": False,
|
||||
"planned": True,
|
||||
}
|
||||
|
||||
|
||||
def _now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
init_firebase()
|
||||
fs = get_firestore()
|
||||
if fs is None:
|
||||
print("ERROR: Firebase not initialised.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
docs = list(fs.collection(COLLECTION).stream())
|
||||
source_count = len(docs)
|
||||
print(f"Source (Firestore): {source_count} crm_products documents")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = []
|
||||
for doc in docs:
|
||||
d = doc.to_dict()
|
||||
|
||||
# is_active: prefer 'active' bool field, fall back to 'status' string
|
||||
if "active" in d:
|
||||
is_active = bool(d["active"])
|
||||
else:
|
||||
is_active = _LEGACY_STATUS_MAP.get(d.get("status", "active"), True)
|
||||
|
||||
# unit_cost: Firestore uses 'price'
|
||||
unit_cost = d.get("unit_cost") or d.get("price") or 0
|
||||
|
||||
created_at = parse_dt(d.get("created_at")) or _now_utc()
|
||||
updated_at = parse_dt(d.get("updated_at")) or _now_utc()
|
||||
|
||||
records.append({
|
||||
"id": doc.id,
|
||||
"firestore_id": doc.id,
|
||||
"name": d.get("name") or d.get("name_en") or "",
|
||||
"sku": d.get("sku"),
|
||||
"category": d.get("category"),
|
||||
"description": d.get("description") or d.get("description_en"),
|
||||
"unit_cost": unit_cost,
|
||||
"currency": d.get("currency") or "EUR",
|
||||
"unit_type": d.get("unit_type") or "pcs",
|
||||
"is_active": is_active,
|
||||
"created_at": created_at,
|
||||
"updated_at": updated_at,
|
||||
})
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
stmt = pg_insert(CrmProduct).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "crm_products")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
Phase 1 — Step 1.7: crm_quotation_items (SQLite → Postgres)
|
||||
|
||||
FK to crm_quotations(id) — quotations must be migrated first (step 1.6).
|
||||
FK enforcement suppressed via session_replication_role for the same reason
|
||||
as in migrate_crm_quotations (parent crm_customers not yet in PG).
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_crm_quotation_items
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from crm.orm import CrmQuotationItem
|
||||
from migration.utils import open_sqlite, AsyncPgSession, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_crm_quotation_items"
|
||||
|
||||
|
||||
def _dec(val, default="0") -> Decimal:
|
||||
try:
|
||||
return Decimal(str(val)) if val is not None else Decimal(default)
|
||||
except Exception:
|
||||
return Decimal(default)
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall(
|
||||
"SELECT * FROM crm_quotation_items ORDER BY quotation_id, sort_order"
|
||||
)
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} crm_quotation_items rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = []
|
||||
for r in rows:
|
||||
records.append({
|
||||
"id": r["id"],
|
||||
"quotation_id": r["quotation_id"],
|
||||
"product_id": r["product_id"],
|
||||
"description": r["description"],
|
||||
"description_en": r["description_en"],
|
||||
"description_gr": r["description_gr"],
|
||||
"unit_type": r["unit_type"] or "pcs",
|
||||
"unit_cost": _dec(r["unit_cost"]),
|
||||
"discount_percent": _dec(r["discount_percent"]),
|
||||
"vat_percent": _dec(r["vat_percent"], "24"),
|
||||
"quantity": _dec(r["quantity"], "1"),
|
||||
"line_total": _dec(r["line_total"]),
|
||||
"sort_order": int(r["sort_order"]) if r["sort_order"] is not None else 0,
|
||||
})
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
await session.execute(text("SET LOCAL session_replication_role = replica"))
|
||||
stmt = pg_insert(CrmQuotationItem).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "crm_quotation_items")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
Phase 1 — Step 1.6: crm_quotations (SQLite → Postgres)
|
||||
|
||||
NOTE: crm_quotations has a FK to crm_customers(id).
|
||||
The customer rows DO NOT exist in Postgres yet (they migrate in Phase 2).
|
||||
To avoid FK violations, this script temporarily disables FK checks for the
|
||||
session using SET CONSTRAINTS ALL DEFERRED — but since customer_id is a real
|
||||
FK with ON DELETE CASCADE, we instead insert with the constraint deferred.
|
||||
|
||||
Safer approach used here: insert with `customer_id` as-is and rely on the
|
||||
fact that crm_customers will be populated in Phase 2 before any service
|
||||
reads join across the two tables. The FK is not deferred — instead we disable
|
||||
the FK constraint enforcement for this transaction only via a session-level
|
||||
SET session_replication_role = replica; which suppresses FK checks in Postgres.
|
||||
We restore it immediately after the transaction.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_crm_quotations
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from crm.orm import CrmQuotation
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, parse_json, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_crm_quotations"
|
||||
|
||||
|
||||
def _dec(val, default="0") -> Decimal:
|
||||
try:
|
||||
return Decimal(str(val)) if val is not None else Decimal(default)
|
||||
except Exception:
|
||||
return Decimal(default)
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM crm_quotations ORDER BY created_at")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} crm_quotations rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = []
|
||||
for r in rows:
|
||||
records.append({
|
||||
"id": r["id"],
|
||||
"quotation_number": r["quotation_number"],
|
||||
"title": r["title"],
|
||||
"subtitle": r["subtitle"],
|
||||
"customer_id": r["customer_id"],
|
||||
"language": r["language"] or "en",
|
||||
"status": r["status"] or "draft",
|
||||
"order_type": r["order_type"],
|
||||
"shipping_method": r["shipping_method"],
|
||||
"estimated_shipping_date": r["estimated_shipping_date"],
|
||||
"global_discount_label": r["global_discount_label"],
|
||||
"global_discount_percent": _dec(r["global_discount_percent"]),
|
||||
"vat_percent": _dec(r["vat_percent"], "24"),
|
||||
"global_vat_percent": _dec(r["global_vat_percent"], "24"),
|
||||
"shipping_cost": _dec(r["shipping_cost"]),
|
||||
"shipping_cost_discount": _dec(r["shipping_cost_discount"]),
|
||||
"install_cost": _dec(r["install_cost"]),
|
||||
"install_cost_discount": _dec(r["install_cost_discount"]),
|
||||
"extras_label": r["extras_label"],
|
||||
"extras_cost": _dec(r["extras_cost"]),
|
||||
"comments": parse_json(r["comments"], default=[]),
|
||||
"quick_notes": parse_json(r["quick_notes"], default={}),
|
||||
"subtotal_before_discount": _dec(r["subtotal_before_discount"]),
|
||||
"global_discount_amount": _dec(r["global_discount_amount"]),
|
||||
"new_subtotal": _dec(r["new_subtotal"]),
|
||||
"vat_amount": _dec(r["vat_amount"]),
|
||||
"final_total": _dec(r["final_total"]),
|
||||
"nextcloud_pdf_path": r["nextcloud_pdf_path"],
|
||||
"nextcloud_pdf_url": r["nextcloud_pdf_url"],
|
||||
"client_org": r["client_org"],
|
||||
"client_name": r["client_name"],
|
||||
"client_location": r["client_location"],
|
||||
"client_phone": r["client_phone"],
|
||||
"client_email": r["client_email"],
|
||||
"is_legacy": bool(r["is_legacy"]) if r["is_legacy"] is not None else False,
|
||||
"legacy_date": r["legacy_date"],
|
||||
"legacy_pdf_path": r["legacy_pdf_path"],
|
||||
"created_at": parse_dt(r["created_at"]),
|
||||
"updated_at": parse_dt(r["updated_at"]),
|
||||
})
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
# Disable FK enforcement so we can insert before crm_customers arrives in Phase 2.
|
||||
await session.execute(text("SET LOCAL session_replication_role = replica"))
|
||||
stmt = pg_insert(CrmQuotation).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "crm_quotations")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
Phase 1 — Step 1.5: crm_sync_state (SQLite → Postgres)
|
||||
|
||||
Simple key/value table — small, no FK deps.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_crm_sync_state
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from crm.orm import CrmSyncState
|
||||
from migration.utils import open_sqlite, AsyncPgSession, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_crm_sync_state"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM crm_sync_state")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} crm_sync_state rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = [{"key": r["key"], "value": r["value"]} for r in rows]
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
stmt = pg_insert(CrmSyncState).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["key"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "crm_sync_state")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,69 @@
|
||||
"""
|
||||
Phase 1 — Step 1.4: device_alerts (SQLite → Postgres)
|
||||
|
||||
device_alerts is a "current state" table — one row per (device_serial, subsystem).
|
||||
The SQLite PK is (device_serial, subsystem); Postgres adds a BIGSERIAL surrogate PK
|
||||
with a unique constraint on the pair.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_device_alerts
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_device_alerts"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM device_alerts")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} device_alerts rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = [
|
||||
{
|
||||
"device_serial": r["device_serial"],
|
||||
"subsystem": r["subsystem"],
|
||||
"state": r["state"],
|
||||
"message": r["message"],
|
||||
"updated_at": parse_dt(r["updated_at"]),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO device_alerts (device_serial, subsystem, state, message, updated_at)
|
||||
VALUES (:device_serial, :subsystem, :state, :message, :updated_at)
|
||||
ON CONFLICT (device_serial, subsystem) DO NOTHING
|
||||
"""),
|
||||
records,
|
||||
)
|
||||
dest_count = await pg_count(session, "device_alerts")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
Phase 1 — Step 1.12: device_logs (SQLite → Postgres)
|
||||
|
||||
Largest table — migrated in batches of 10,000 rows to avoid memory issues.
|
||||
device_logs is a partitioned table; rows route automatically to the correct
|
||||
monthly partition based on received_at.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_device_logs
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_device_logs"
|
||||
BATCH_SIZE = 10_000
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
|
||||
# Total count first
|
||||
count_row = await sqlite.execute_fetchall("SELECT COUNT(*) FROM device_logs")
|
||||
source_count = count_row[0][0]
|
||||
print(f"Source (SQLite): {source_count} device_logs rows")
|
||||
|
||||
if source_count == 0:
|
||||
await sqlite.close()
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
offset = 0
|
||||
total_inserted = 0
|
||||
|
||||
while offset < source_count:
|
||||
rows = await sqlite.execute_fetchall(
|
||||
"SELECT * FROM device_logs ORDER BY received_at LIMIT ? OFFSET ?",
|
||||
(BATCH_SIZE, offset),
|
||||
)
|
||||
if not rows:
|
||||
break
|
||||
|
||||
records = [
|
||||
{
|
||||
"device_serial": r["device_serial"],
|
||||
"level": r["level"],
|
||||
"message": r["message"],
|
||||
"device_timestamp": r["device_timestamp"],
|
||||
"received_at": parse_dt(r["received_at"]),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO device_logs
|
||||
(device_serial, level, message, device_timestamp, received_at)
|
||||
VALUES
|
||||
(:device_serial, :level, :message, :device_timestamp, :received_at)
|
||||
"""),
|
||||
records,
|
||||
)
|
||||
|
||||
total_inserted += len(records)
|
||||
offset += BATCH_SIZE
|
||||
pct = min(100, int(total_inserted / source_count * 100))
|
||||
print(f" {total_inserted}/{source_count} rows inserted ({pct}%)")
|
||||
|
||||
await sqlite.close()
|
||||
|
||||
# Final count verify
|
||||
async with AsyncPgSession() as session:
|
||||
dest_count = await pg_count(session, "device_logs")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
Phase 1 — Step 1.11: heartbeats (SQLite → Postgres)
|
||||
|
||||
Raw-SQL table (no ORM model). BIGSERIAL PK — SQLite IDs not preserved.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_heartbeats
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_heartbeats"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM heartbeats ORDER BY received_at")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} heartbeats rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = [
|
||||
{
|
||||
"device_serial": r["device_serial"],
|
||||
"device_id": r["device_id"],
|
||||
"firmware_version": r["firmware_version"],
|
||||
"ip_address": r["ip_address"],
|
||||
"gateway": r["gateway"],
|
||||
"uptime_ms": r["uptime_ms"],
|
||||
"uptime_display": r["uptime_display"],
|
||||
"received_at": parse_dt(r["received_at"]),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO heartbeats
|
||||
(device_serial, device_id, firmware_version, ip_address,
|
||||
gateway, uptime_ms, uptime_display, received_at)
|
||||
VALUES
|
||||
(:device_serial, :device_id, :firmware_version, :ip_address,
|
||||
:gateway, :uptime_ms, :uptime_display, :received_at)
|
||||
"""),
|
||||
records,
|
||||
)
|
||||
dest_count = await pg_count(session, "heartbeats")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
Phase 1 — Step 1.1: melody_drafts (SQLite → Postgres)
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_melody_drafts
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from melodies.orm import MelodyDraft
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, parse_json, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_melody_drafts"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM melody_drafts")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} melody_drafts rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = []
|
||||
for r in rows:
|
||||
data_raw = r["data"]
|
||||
# SQLite stores data as JSON text; Postgres column is JSONB
|
||||
data = parse_json(data_raw, default={})
|
||||
|
||||
records.append({
|
||||
"id": r["id"],
|
||||
"status": r["status"] or "draft",
|
||||
"data": data,
|
||||
"created_at": parse_dt(r["created_at"]),
|
||||
"updated_at": parse_dt(r["updated_at"]),
|
||||
})
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
stmt = pg_insert(MelodyDraft).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "melody_drafts")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,67 @@
|
||||
"""
|
||||
Phase 1 — Step 1.3: mfg_audit_log (SQLite → Postgres)
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_mfg_audit_log
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from migration.utils import open_sqlite, AsyncPgSession, parse_dt, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_mfg_audit_log"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
sqlite = await open_sqlite()
|
||||
rows = await sqlite.execute_fetchall("SELECT * FROM mfg_audit_log ORDER BY id")
|
||||
await sqlite.close()
|
||||
|
||||
source_count = len(rows)
|
||||
print(f"Source (SQLite): {source_count} mfg_audit_log rows")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
# mfg_audit_log uses a BIGSERIAL PK — we don't preserve SQLite integer IDs
|
||||
# because the Postgres sequence will assign new ones. We insert in the same
|
||||
# timestamp order so the audit trail remains coherent.
|
||||
records = [
|
||||
{
|
||||
"timestamp": parse_dt(r["timestamp"]),
|
||||
"admin_user": r["admin_user"],
|
||||
"action": r["action"],
|
||||
"serial_number": r["serial_number"],
|
||||
"detail": r["detail"],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO mfg_audit_log (timestamp, admin_user, action, serial_number, detail)
|
||||
VALUES (:timestamp, :admin_user, :action, :serial_number, :detail)
|
||||
"""),
|
||||
records,
|
||||
)
|
||||
dest_count = await pg_count(session, "mfg_audit_log")
|
||||
|
||||
if dest_count < source_count:
|
||||
msg = f"Count mismatch: source={source_count} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
Phase 2 — Step 2.2: public_features (Firestore → Postgres)
|
||||
|
||||
Reads the single 'admin_settings/public_features' doc from Firestore and
|
||||
flattens each field into a key/value row in public_features.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_public_features
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from settings.orm import PublicFeature
|
||||
from shared.firebase import init_firebase, get_db as get_firestore
|
||||
from migration.utils import AsyncPgSession, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_public_features"
|
||||
COLLECTION = "admin_settings"
|
||||
DOC_ID = "public_features"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
init_firebase()
|
||||
fs = get_firestore()
|
||||
if fs is None:
|
||||
print("ERROR: Firebase not initialised — check service account path.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
doc = fs.collection(COLLECTION).document(DOC_ID).get()
|
||||
if not doc.exists:
|
||||
print("No public_features document found in Firestore — skipping.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source doc not found")
|
||||
return
|
||||
|
||||
data = doc.to_dict()
|
||||
source_count = len(data)
|
||||
print(f"Source (Firestore): {source_count} fields in {COLLECTION}/{DOC_ID}")
|
||||
|
||||
records = [{"key": k, "value": v} for k, v in data.items()]
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
stmt = pg_insert(PublicFeature).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["key"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "public_features")
|
||||
|
||||
print(f"Postgres public_features: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
Phase 2 — Step 2.1: console_settings (Firestore → Postgres)
|
||||
|
||||
Reads the single 'admin_settings/melody_settings' doc from Firestore and
|
||||
flattens each field into a key/value row in console_settings.
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_settings
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from settings.orm import ConsoleSetting
|
||||
from shared.firebase import init_firebase, get_db as get_firestore
|
||||
from migration.utils import AsyncPgSession, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_settings"
|
||||
COLLECTION = "admin_settings"
|
||||
DOC_ID = "melody_settings"
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
init_firebase()
|
||||
fs = get_firestore()
|
||||
if fs is None:
|
||||
print("ERROR: Firebase not initialised — check service account path.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
doc = fs.collection(COLLECTION).document(DOC_ID).get()
|
||||
if not doc.exists:
|
||||
print("No melody_settings document found in Firestore — skipping.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source doc not found")
|
||||
return
|
||||
|
||||
data = doc.to_dict()
|
||||
source_count = len(data)
|
||||
print(f"Source (Firestore): {source_count} fields in {COLLECTION}/{DOC_ID}")
|
||||
|
||||
records = [{"key": k, "value": v} for k, v in data.items()]
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
stmt = pg_insert(ConsoleSetting).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["key"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "console_settings")
|
||||
|
||||
print(f"Postgres console_settings: {dest_count} rows ✓")
|
||||
await log_run(SCRIPT, source_count, dest_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
Phase 3 — Step 3.1: admin_users (Firestore → Postgres staff table)
|
||||
|
||||
Reads every document in the 'admin_users' Firestore collection and inserts
|
||||
a matching row into the Postgres 'staff' table.
|
||||
|
||||
Key transformations:
|
||||
- Legacy role names mapped to canonical roles (superadmin→sysadmin, etc.)
|
||||
- permissions=None stored as JSONB null (sysadmin/admin have no permission map)
|
||||
- ui_prefs column NOT migrated (not part of the Postgres schema — dropped)
|
||||
- Firestore doc ID preserved as staff.id and staff.firestore_id
|
||||
- created_at/updated_at default to now() if missing from Firestore doc
|
||||
|
||||
Run on VPS:
|
||||
docker compose exec backend python -m migration.migrate_staff
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from staff.orm import Staff
|
||||
from shared.firebase import init_firebase, get_db as get_firestore
|
||||
from migration.utils import AsyncPgSession, parse_dt, log_run, pg_count
|
||||
|
||||
SCRIPT = "migrate_staff"
|
||||
COLLECTION = "admin_users"
|
||||
|
||||
_ROLE_MAP = {
|
||||
"superadmin": "sysadmin",
|
||||
"melody_editor": "editor",
|
||||
"device_manager": "editor",
|
||||
"user_manager": "editor",
|
||||
"viewer": "user",
|
||||
# canonical roles pass through unchanged
|
||||
"sysadmin": "sysadmin",
|
||||
"admin": "admin",
|
||||
"editor": "editor",
|
||||
"user": "user",
|
||||
"staff": "user",
|
||||
}
|
||||
|
||||
|
||||
def _now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _coerce_dt(val) -> datetime | None:
|
||||
if val is None:
|
||||
return None
|
||||
if isinstance(val, datetime):
|
||||
return val.replace(tzinfo=timezone.utc) if val.tzinfo is None else val
|
||||
return parse_dt(str(val))
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
init_firebase()
|
||||
fs = get_firestore()
|
||||
if fs is None:
|
||||
print("ERROR: Firebase not initialised.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
docs = list(fs.collection(COLLECTION).stream())
|
||||
source_count = len(docs)
|
||||
print(f"Source (Firestore): {source_count} admin_users documents")
|
||||
|
||||
if source_count == 0:
|
||||
print("Nothing to migrate.")
|
||||
await log_run(SCRIPT, 0, 0, notes="source empty")
|
||||
return
|
||||
|
||||
records = []
|
||||
skipped = 0
|
||||
|
||||
for doc in docs:
|
||||
d = doc.to_dict()
|
||||
|
||||
hashed_password = d.get("hashed_password") or ""
|
||||
if not hashed_password:
|
||||
print(f" WARNING: {doc.id} ({d.get('email')}) has no hashed_password — skipping",
|
||||
file=sys.stderr)
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
email = d.get("email") or ""
|
||||
if not email:
|
||||
print(f" WARNING: {doc.id} has no email — skipping", file=sys.stderr)
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
raw_role = d.get("role") or "user"
|
||||
role = _ROLE_MAP.get(raw_role, "user")
|
||||
|
||||
# sysadmin/admin have no permission map
|
||||
permissions = d.get("permissions")
|
||||
if role in ("sysadmin", "admin"):
|
||||
permissions = None
|
||||
|
||||
now = _now_utc()
|
||||
records.append({
|
||||
"id": doc.id,
|
||||
"firestore_id": doc.id,
|
||||
"email": email,
|
||||
"name": d.get("name") or "",
|
||||
"role": role,
|
||||
"permissions": permissions,
|
||||
"hashed_password": hashed_password,
|
||||
"is_active": bool(d.get("is_active", True)),
|
||||
"created_at": _coerce_dt(d.get("created_at")) or now,
|
||||
"updated_at": _coerce_dt(d.get("updated_at")) or now,
|
||||
})
|
||||
|
||||
actual_source = source_count - skipped
|
||||
print(f" {skipped} skipped (missing email or password), {actual_source} to insert")
|
||||
|
||||
if not records:
|
||||
print("Nothing to insert after filtering.")
|
||||
await log_run(SCRIPT, source_count, 0, success=False,
|
||||
notes="all docs skipped — missing required fields")
|
||||
sys.exit(1)
|
||||
|
||||
async with AsyncPgSession() as session:
|
||||
async with session.begin():
|
||||
stmt = pg_insert(Staff).values(records)
|
||||
stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
|
||||
await session.execute(stmt)
|
||||
dest_count = await pg_count(session, "staff")
|
||||
|
||||
if dest_count < actual_source:
|
||||
msg = f"Count mismatch: expected>={actual_source} postgres={dest_count}"
|
||||
print(f"ERROR: {msg}", file=sys.stderr)
|
||||
await log_run(SCRIPT, source_count, dest_count, success=False, notes=msg)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Postgres: {dest_count} rows ✓")
|
||||
note = f"{skipped} skipped (missing fields)" if skipped else None
|
||||
await log_run(SCRIPT, source_count, dest_count, notes=note)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
Shared helpers for all Phase 1 SQLite → Postgres migration scripts.
|
||||
|
||||
Usage in each script:
|
||||
from migration.utils import open_sqlite, get_pg, log_run, parse_dt, parse_json
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import aiosqlite
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
||||
|
||||
from config import settings
|
||||
|
||||
|
||||
# ── SQLite ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async def open_sqlite() -> aiosqlite.Connection:
|
||||
"""Open the SQLite database (read-only; no writes during migration)."""
|
||||
db_path = Path(settings.sqlite_db_path)
|
||||
if not db_path.exists():
|
||||
print(f"ERROR: SQLite database not found at {db_path.resolve()}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
conn = await aiosqlite.connect(str(db_path))
|
||||
conn.row_factory = aiosqlite.Row
|
||||
return conn
|
||||
|
||||
|
||||
# ── Postgres ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def _make_pg_session() -> async_sessionmaker:
|
||||
engine = create_async_engine(settings.database_url, pool_size=5, echo=False)
|
||||
return async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
|
||||
AsyncPgSession = _make_pg_session()
|
||||
|
||||
|
||||
# ── Type helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
def parse_dt(value: str | None) -> datetime | None:
|
||||
"""Parse a SQLite TEXT timestamp → timezone-aware datetime (UTC)."""
|
||||
if not value:
|
||||
return None
|
||||
for fmt in (
|
||||
"%Y-%m-%dT%H:%M:%S.%f",
|
||||
"%Y-%m-%dT%H:%M:%S",
|
||||
"%Y-%m-%d %H:%M:%S.%f",
|
||||
"%Y-%m-%d %H:%M:%S",
|
||||
"%Y-%m-%d",
|
||||
):
|
||||
try:
|
||||
dt = datetime.strptime(value, fmt)
|
||||
return dt.replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
continue
|
||||
# ISO format with offset — let fromisoformat handle it
|
||||
try:
|
||||
dt = datetime.fromisoformat(value)
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt
|
||||
except ValueError:
|
||||
pass
|
||||
print(f"WARNING: could not parse timestamp {value!r} — using now()", file=sys.stderr)
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def parse_json(value: str | None, default=None):
|
||||
"""Parse a SQLite TEXT JSON column → Python object."""
|
||||
if value is None:
|
||||
return default
|
||||
try:
|
||||
return json.loads(value)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return default
|
||||
|
||||
|
||||
# ── Migration run log ─────────────────────────────────────────────────────────
|
||||
|
||||
async def log_run(
|
||||
script_name: str,
|
||||
source_rows: int,
|
||||
dest_rows: int,
|
||||
success: bool = True,
|
||||
notes: str | None = None,
|
||||
) -> None:
|
||||
"""Insert a row into _migration_runs recording this script's execution."""
|
||||
async with AsyncPgSession() as session:
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO _migration_runs
|
||||
(script_name, ran_at, source_rows, dest_rows, success, notes)
|
||||
VALUES
|
||||
(:script_name, now(), :source_rows, :dest_rows, :success, :notes)
|
||||
"""),
|
||||
{
|
||||
"script_name": script_name,
|
||||
"source_rows": source_rows,
|
||||
"dest_rows": dest_rows,
|
||||
"success": "ok" if success else "error",
|
||||
"notes": notes,
|
||||
},
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
|
||||
# ── Count helper ──────────────────────────────────────────────────────────────
|
||||
|
||||
async def pg_count(session: AsyncSession, table: str) -> int:
|
||||
row = await session.execute(text(f"SELECT COUNT(*) FROM {table}"))
|
||||
return row.scalar()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
Firebase app-user lookup for the MQTT auth/ACL endpoints.
|
||||
|
||||
App users connect to Mosquitto as "app_<firebase_uid>". Their allowed
|
||||
devices come from the `device_serials` array on their `users` doc.
|
||||
|
||||
User docs are resolved by the `uid` FIELD, never by document ID: docs created
|
||||
by the Console (users.service.create_user) get random IDs via .add(), while
|
||||
FlutterFlow uses the Firebase uid as the doc ID.
|
||||
|
||||
Per-message ACL checks would otherwise hit Firestore on every publish and
|
||||
delivery, so lookups are cached in-process for CACHE_TTL_SECONDS. Anything
|
||||
that changes a user's device_serials or status calls invalidate(uid).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
from shared.firebase import get_db
|
||||
|
||||
logger = logging.getLogger("mqtt.app_users")
|
||||
|
||||
USERS_COLLECTION = "users"
|
||||
CACHE_TTL_SECONDS = 60.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AppUser:
|
||||
uid: str
|
||||
blocked: bool
|
||||
device_serials: frozenset[str]
|
||||
|
||||
|
||||
_cache: dict[str, tuple[float, AppUser | None]] = {}
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def _load(uid: str) -> AppUser | None:
|
||||
db = get_db()
|
||||
if db is None:
|
||||
raise RuntimeError("Firestore not initialized")
|
||||
|
||||
docs = list(db.collection(USERS_COLLECTION).where("uid", "==", uid).limit(5).stream())
|
||||
if not docs:
|
||||
return None
|
||||
if len(docs) > 1:
|
||||
# Duplicate profiles for one Firebase account: be conservative on
|
||||
# blocked, permissive on devices (union), and make it visible.
|
||||
logger.warning("Multiple user docs share uid=%s: %s", uid, [d.id for d in docs])
|
||||
|
||||
blocked = False
|
||||
serials: set[str] = set()
|
||||
for doc in docs:
|
||||
data = doc.to_dict() or {}
|
||||
if data.get("status") == "blocked":
|
||||
blocked = True
|
||||
serials.update(s for s in (data.get("device_serials") or []) if isinstance(s, str) and s)
|
||||
|
||||
return AppUser(uid=uid, blocked=blocked, device_serials=frozenset(serials))
|
||||
|
||||
|
||||
def get_app_user(uid: str, *, use_cache: bool = True) -> AppUser | None:
|
||||
"""Return the app user for a Firebase uid, or None if no user doc has that uid.
|
||||
|
||||
use_cache=False forces a Firestore read (and refreshes the cache).
|
||||
"""
|
||||
now = time.monotonic()
|
||||
if use_cache:
|
||||
with _lock:
|
||||
hit = _cache.get(uid)
|
||||
if hit and hit[0] > now:
|
||||
return hit[1]
|
||||
|
||||
user = _load(uid)
|
||||
with _lock:
|
||||
_cache[uid] = (now + CACHE_TTL_SECONDS, user)
|
||||
return user
|
||||
|
||||
|
||||
def invalidate(uid: str) -> None:
|
||||
with _lock:
|
||||
_cache.pop(uid, None)
|
||||
|
||||
|
||||
def clear_cache() -> None:
|
||||
with _lock:
|
||||
_cache.clear()
|
||||
+178
-12
@@ -9,8 +9,10 @@ Password strategy: HMAC-SHA256(MQTT_SECRET, username)[:32]
|
||||
- Deterministic: no storage needed, re-derive on every auth check
|
||||
- Rotating MQTT_SECRET invalidates all passwords at once if needed
|
||||
|
||||
Transition support: during rollout, the legacy password "vesper" is also
|
||||
accepted so that devices still on old firmware stay connected.
|
||||
Transition support: while MQTT_ALLOW_LEGACY_PASSWORD is on (default), the
|
||||
legacy password "vesper" is also accepted for device-shaped usernames so
|
||||
boards still on old firmware stay connected. Each such login is logged
|
||||
(once per username per hour) to show which boards still depend on it.
|
||||
|
||||
User types handled:
|
||||
- Device users (e.g. "PV25L22BP01R01", "PV-26A18-BC02R-X7KQA"):
|
||||
@@ -18,21 +20,49 @@ User types handled:
|
||||
- Kiosk users (e.g. "PV25L22BP01R01-kiosk"):
|
||||
Same HMAC auth derived from the full kiosk username.
|
||||
ACL: allowed to access topics of their base device (suffix stripped).
|
||||
- App users (e.g. "app_<firebase_uid>"):
|
||||
Remote phone app. Password = a Firebase ID token, verified with
|
||||
firebase_admin (revocation checked). No per-user MQTT accounts exist.
|
||||
Never accepted via HMAC or the legacy password.
|
||||
- admin, bonamin, NodeRED, and other non-device users:
|
||||
These connect via the passwd file backend (go-auth file backend).
|
||||
They never reach this HTTP backend — go-auth resolves them first.
|
||||
The ACL endpoint below handles them defensively anyway (superuser list).
|
||||
|
||||
The handlers are plain `def` on purpose: they make blocking Firestore /
|
||||
Firebase Auth calls, which FastAPI then runs in its threadpool instead of
|
||||
stalling the event loop.
|
||||
"""
|
||||
|
||||
import hmac
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Form, Response
|
||||
from firebase_admin import auth as firebase_auth
|
||||
|
||||
from config import settings
|
||||
from mqtt import app_users
|
||||
|
||||
logger = logging.getLogger("mqtt.auth")
|
||||
|
||||
router = APIRouter(prefix="/mqtt/auth", tags=["mqtt-auth"])
|
||||
|
||||
LEGACY_PASSWORD = "vesper"
|
||||
|
||||
APP_USER_PREFIX = "app_"
|
||||
|
||||
# Uppercase alphanumeric segments joined by "-", optional "-kiosk" suffix.
|
||||
# Covers PV25L22BP01R01, PV-26A18-BC02R-X7KQA, BSVSPR-26C13X-STD01R-X7KQA.
|
||||
DEVICE_USERNAME_RE = re.compile(r"[A-Z0-9]{2,}(?:-[A-Z0-9]+)*(?:-kiosk)?")
|
||||
|
||||
LEGACY_LOG_INTERVAL_SECONDS = 3600
|
||||
_legacy_log_last: dict[str, float] = {}
|
||||
_legacy_log_lock = threading.Lock()
|
||||
|
||||
# Users authenticated via passwd file (go-auth file backend).
|
||||
# If they somehow reach the HTTP ACL endpoint, grant full access.
|
||||
SUPERUSERS = {"admin", "bonamin", "NodeRED"}
|
||||
@@ -47,18 +77,44 @@ def _derive_password(username: str) -> str:
|
||||
).hexdigest()[:32]
|
||||
|
||||
|
||||
def _is_device_username(username: str) -> bool:
|
||||
"""Board serial (optionally with -kiosk), e.g. "PV25L22BP01R01",
|
||||
"BSVSPR-26C13X-STD01R-X7KQA", "PV25L22BP01R01-kiosk"."""
|
||||
return bool(DEVICE_USERNAME_RE.fullmatch(username))
|
||||
|
||||
|
||||
def _log_legacy_auth(username: str) -> None:
|
||||
"""Log a legacy-password login, at most once per username per interval."""
|
||||
now = time.monotonic()
|
||||
with _legacy_log_lock:
|
||||
last = _legacy_log_last.get(username)
|
||||
if last is not None and now - last < LEGACY_LOG_INTERVAL_SECONDS:
|
||||
return
|
||||
_legacy_log_last[username] = now
|
||||
logger.warning("MQTT legacy password accepted for %s — board still on pre-HMAC firmware", username)
|
||||
|
||||
|
||||
def _is_valid_password(username: str, password: str) -> bool:
|
||||
"""
|
||||
Accept the password if it matches either:
|
||||
- The HMAC-derived password (new firmware)
|
||||
- The legacy hardcoded "vesper" password (old firmware, transition period)
|
||||
|
||||
Remove the legacy check in Stage 7 once all devices are on new firmware.
|
||||
- The legacy hardcoded "vesper" password (old firmware, transition period),
|
||||
only when MQTT_ALLOW_LEGACY_PASSWORD is on and the username is
|
||||
device-shaped (never app_ users or unknown shapes).
|
||||
"""
|
||||
expected = _derive_password(username)
|
||||
hmac_ok = hmac.compare_digest(expected, password)
|
||||
legacy_ok = hmac.compare_digest(LEGACY_PASSWORD, password)
|
||||
return hmac_ok or legacy_ok
|
||||
if hmac.compare_digest(expected, password):
|
||||
return True
|
||||
|
||||
if (
|
||||
settings.mqtt_allow_legacy_password
|
||||
and _is_device_username(username)
|
||||
and hmac.compare_digest(LEGACY_PASSWORD, password)
|
||||
):
|
||||
_log_legacy_auth(username)
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _base_sn(username: str) -> str:
|
||||
@@ -72,8 +128,52 @@ def _base_sn(username: str) -> str:
|
||||
return username
|
||||
|
||||
|
||||
def _deny_app(username: str, reason: str) -> Response:
|
||||
# Never log the password — for app users it is a bearer token.
|
||||
logger.warning("MQTT app auth denied for %s: %s", username, reason)
|
||||
return Response(status_code=403)
|
||||
|
||||
|
||||
def _auth_app_user(username: str, token: str) -> Response:
|
||||
"""Authenticate "app_<firebase_uid>" with a Firebase ID token as password."""
|
||||
uid = username[len(APP_USER_PREFIX):]
|
||||
if not uid:
|
||||
return _deny_app(username, "empty uid")
|
||||
if not token:
|
||||
return _deny_app(username, "empty token")
|
||||
|
||||
try:
|
||||
decoded = firebase_auth.verify_id_token(token, check_revoked=True)
|
||||
except firebase_auth.RevokedIdTokenError:
|
||||
return _deny_app(username, "token revoked")
|
||||
except firebase_auth.ExpiredIdTokenError:
|
||||
return _deny_app(username, "token expired")
|
||||
except firebase_auth.UserDisabledError:
|
||||
return _deny_app(username, "firebase account disabled")
|
||||
except firebase_auth.InvalidIdTokenError as e:
|
||||
return _deny_app(username, f"invalid token ({type(e).__name__})")
|
||||
except Exception as e:
|
||||
return _deny_app(username, f"token verification failed ({type(e).__name__})")
|
||||
|
||||
if decoded.get("uid") != uid:
|
||||
return _deny_app(username, "token uid does not match username")
|
||||
|
||||
try:
|
||||
# Fresh read on CONNECT (also refreshes the ACL cache).
|
||||
user = app_users.get_app_user(uid, use_cache=False)
|
||||
except Exception as e:
|
||||
return _deny_app(username, f"user lookup failed ({type(e).__name__})")
|
||||
|
||||
if user is None:
|
||||
return _deny_app(username, "no user doc with this uid")
|
||||
if user.blocked:
|
||||
return _deny_app(username, "user is blocked")
|
||||
|
||||
return Response(status_code=200)
|
||||
|
||||
|
||||
@router.post("/user")
|
||||
async def mqtt_auth_user(
|
||||
def mqtt_auth_user(
|
||||
username: str = Form(...),
|
||||
password: str = Form(...),
|
||||
clientid: str = Form(default=""),
|
||||
@@ -84,37 +184,103 @@ async def mqtt_auth_user(
|
||||
|
||||
Username = device SN (new format: "PV-26A18-BC02R-X7KQA", old format: "PV25L22BP01R01")
|
||||
or kiosk variant: "PV25L22BP01R01-kiosk"
|
||||
or app user: "app_<firebase_uid>"
|
||||
Password = HMAC-derived (new firmware) or "vesper" (legacy firmware)
|
||||
or, for app users, a Firebase ID token
|
||||
|
||||
Note: admin, bonamin and NodeRED authenticate via the go-auth passwd file backend
|
||||
and never reach this endpoint.
|
||||
"""
|
||||
if username.startswith(APP_USER_PREFIX):
|
||||
return _auth_app_user(username, password)
|
||||
|
||||
if _is_valid_password(username, password):
|
||||
return Response(status_code=200)
|
||||
|
||||
return Response(status_code=403)
|
||||
|
||||
|
||||
# Mosquitto access values as passed through by go-auth (`acc`).
|
||||
ACC_READ = 1 # message delivery to the client
|
||||
ACC_WRITE = 2 # publish
|
||||
ACC_SUBSCRIBE = 4 # subscribe
|
||||
|
||||
# App-user topic allowlist, relative to vesper/{serial}/
|
||||
APP_WRITE_TOPICS = frozenset({"control/command"})
|
||||
APP_READ_TOPICS = frozenset({"control/ack", "status/heartbeat", "status/playback"})
|
||||
|
||||
|
||||
def _app_acl_allowed(username: str, clientid: str, topic: str, acc: int) -> tuple[bool, str]:
|
||||
"""ACL decision for "app_<uid>". Returns (allowed, reason)."""
|
||||
uid = username[len(APP_USER_PREFIX):]
|
||||
if not uid:
|
||||
return False, "empty uid"
|
||||
|
||||
# Client id must be owned by this user, so one user can't take over
|
||||
# (and disconnect) another user's session by reusing its client id.
|
||||
if not clientid.startswith(f"{APP_USER_PREFIX}{uid}_"):
|
||||
return False, f"clientid {clientid!r} not prefixed with app_<uid>_"
|
||||
|
||||
if "+" in topic or "#" in topic:
|
||||
return False, "wildcards not allowed"
|
||||
|
||||
parts = topic.split("/")
|
||||
if len(parts) != 4 or parts[0] != "vesper" or not parts[1]:
|
||||
return False, "topic not vesper/{serial}/<a>/<b>"
|
||||
serial, leaf = parts[1], f"{parts[2]}/{parts[3]}"
|
||||
|
||||
if acc == ACC_WRITE:
|
||||
if leaf not in APP_WRITE_TOPICS:
|
||||
return False, "publish not allowed on this topic"
|
||||
elif acc in (ACC_READ, ACC_SUBSCRIBE):
|
||||
if leaf not in APP_READ_TOPICS:
|
||||
return False, "read/subscribe not allowed on this topic"
|
||||
else:
|
||||
return False, f"unsupported acc={acc}"
|
||||
|
||||
try:
|
||||
user = app_users.get_app_user(uid)
|
||||
except Exception as e:
|
||||
return False, f"user lookup failed ({type(e).__name__})"
|
||||
if user is None:
|
||||
return False, "no user doc with this uid"
|
||||
if user.blocked:
|
||||
return False, "user is blocked"
|
||||
if serial not in user.device_serials:
|
||||
return False, "serial not assigned to user"
|
||||
|
||||
return True, ""
|
||||
|
||||
|
||||
@router.post("/acl")
|
||||
async def mqtt_auth_acl(
|
||||
def mqtt_auth_acl(
|
||||
username: str = Form(...),
|
||||
topic: str = Form(...),
|
||||
clientid: str = Form(default=""),
|
||||
acc: int = Form(...), # 1 = subscribe, 2 = publish, 3 = subscribe+publish
|
||||
acc: int = Form(...), # 1 = read (delivery), 2 = write (publish), 4 = subscribe
|
||||
):
|
||||
"""
|
||||
Called by Mosquitto on every SUBSCRIBE and PUBLISH.
|
||||
Called by Mosquitto on every SUBSCRIBE, PUBLISH and message delivery.
|
||||
Returns 200 to allow, 403 to deny.
|
||||
|
||||
Topic pattern: vesper/{sn}/...
|
||||
- Device users: may only access their own SN segment
|
||||
- Kiosk users: stripped of -kiosk suffix, then same rule applies
|
||||
- App users (app_<uid>): only their assigned serials, only the
|
||||
command/ack/heartbeat/playback topics — see _app_acl_allowed
|
||||
- Superusers (bonamin, NodeRED): full access
|
||||
"""
|
||||
# Superusers get full access (shouldn't reach here but handled defensively)
|
||||
if username in SUPERUSERS:
|
||||
return Response(status_code=200)
|
||||
|
||||
if username.startswith(APP_USER_PREFIX):
|
||||
allowed, reason = _app_acl_allowed(username, clientid, topic, acc)
|
||||
if allowed:
|
||||
return Response(status_code=200)
|
||||
logger.info("MQTT app ACL denied for %s (acc=%s, topic=%s): %s", username, acc, topic, reason)
|
||||
return Response(status_code=403)
|
||||
|
||||
# Derive the base SN (handles -kiosk suffix)
|
||||
base = _base_sn(username)
|
||||
|
||||
|
||||
+68
-9
@@ -1,12 +1,19 @@
|
||||
import json
|
||||
import logging
|
||||
import asyncio
|
||||
import time
|
||||
from typing import Set
|
||||
import paho.mqtt.client as paho_mqtt
|
||||
from config import settings
|
||||
|
||||
logger = logging.getLogger("mqtt.client")
|
||||
|
||||
PING_INTERVAL_SECONDS = 60
|
||||
# Only devices heard from within this window get pinged — no point spending
|
||||
# broker traffic/RTT samples on a device that's already known offline; its
|
||||
# heartbeat-derived "online" state will already reflect that on the console.
|
||||
PING_ONLINE_WINDOW_SECONDS = 90
|
||||
|
||||
|
||||
class MqttManager:
|
||||
"""Singleton MQTT client manager."""
|
||||
@@ -61,12 +68,17 @@ class MqttManager:
|
||||
if reason_code == 0:
|
||||
self._connected = True
|
||||
logger.info("MQTT connected, subscribing to topics")
|
||||
# v2 topic set — see vesper_mqtt_topic_spec_v2.md in the firmware repo.
|
||||
# control/command is inbound-to-device only; the console never subscribes to it.
|
||||
client.subscribe([
|
||||
("vesper/+/data", 1),
|
||||
("vesper/+/control/ack", 1),
|
||||
("vesper/+/control/reports", 1),
|
||||
("vesper/+/status/heartbeat", 1),
|
||||
("vesper/+/status/alerts", 1),
|
||||
("vesper/+/status/info", 0),
|
||||
("vesper/+/logs", 1),
|
||||
("vesper/+/status/playback", 1),
|
||||
("vesper/+/system/alerts", 1),
|
||||
("vesper/+/system/info", 1),
|
||||
("vesper/+/system/logs", 0),
|
||||
("vesper/+/system/metrics", 0),
|
||||
])
|
||||
else:
|
||||
logger.error(f"MQTT connection failed: {reason_code}")
|
||||
@@ -87,10 +99,17 @@ class MqttManager:
|
||||
|
||||
serial = parts[1]
|
||||
topic_type = "/".join(parts[2:])
|
||||
# The broker sets retain=1 only on a message it replays from its
|
||||
# retained store because we just (re)subscribed: a stale snapshot
|
||||
# of the device's last state, not something that just happened.
|
||||
# Live publishes always arrive with retain=0, even on topics the
|
||||
# firmware publishes retained. Every backend restart (and every
|
||||
# uvicorn --reload) replays these for every device.
|
||||
retained = bool(msg.retain)
|
||||
|
||||
if self._loop and self._loop.is_running():
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self._process_message(serial, topic_type, payload, topic),
|
||||
self._process_message(serial, topic_type, payload, topic, retained),
|
||||
self._loop,
|
||||
)
|
||||
except json.JSONDecodeError:
|
||||
@@ -99,15 +118,16 @@ class MqttManager:
|
||||
logger.error(f"Error processing MQTT message: {e}")
|
||||
|
||||
async def _process_message(self, serial: str, topic_type: str,
|
||||
payload: dict, raw_topic: str):
|
||||
payload: dict, raw_topic: str, retained: bool = False):
|
||||
from mqtt.logger import handle_message
|
||||
await handle_message(serial, topic_type, payload)
|
||||
await handle_message(serial, topic_type, payload, retained=retained)
|
||||
|
||||
ws_data = {
|
||||
"type": topic_type,
|
||||
"device_serial": serial,
|
||||
"payload": payload,
|
||||
"topic": raw_topic,
|
||||
"retained": retained,
|
||||
}
|
||||
await self._broadcast_ws(ws_data)
|
||||
|
||||
@@ -132,10 +152,49 @@ class MqttManager:
|
||||
if not self._client or not self._connected:
|
||||
return False
|
||||
|
||||
topic = f"vesper/{device_serial}/control"
|
||||
payload = json.dumps({"cmd": cmd, "contents": contents})
|
||||
topic = f"vesper/{device_serial}/control/command"
|
||||
payload = json.dumps({"v": 2, "cmd": cmd, "contents": contents})
|
||||
result = self._client.publish(topic, payload, qos=1)
|
||||
return result.rc == paho_mqtt.MQTT_ERR_SUCCESS
|
||||
|
||||
async def ping_loop(self):
|
||||
"""Periodically pings every recently-online device with a client
|
||||
timestamp so mqtt/logger.py::_handle_data_response can compute RTT
|
||||
from the echoed pong. Deliberately bypasses db.insert_command — this
|
||||
is a background health check, not a user-initiated command, and
|
||||
shouldn't clutter the Control tab's command history.
|
||||
|
||||
Only available on RTC-equipped firmware builds (see API Reference —
|
||||
ping is compiled out on agnus/agnus-mini). A pong simply never
|
||||
arrives for those devices, so no ping-latency samples accumulate for
|
||||
them; the Health tab handles an empty series as "unsupported".
|
||||
"""
|
||||
while True:
|
||||
await asyncio.sleep(PING_INTERVAL_SECONDS)
|
||||
try:
|
||||
await self._ping_online_devices()
|
||||
except Exception as e:
|
||||
logger.error(f"Ping loop error: {e}")
|
||||
|
||||
async def _ping_online_devices(self):
|
||||
import database as db
|
||||
from mqtt import presence
|
||||
heartbeats = await db.get_latest_heartbeats()
|
||||
now = time.time()
|
||||
for hb in heartbeats:
|
||||
try:
|
||||
from datetime import datetime
|
||||
received = datetime.fromisoformat(hb["received_at"])
|
||||
age = now - received.timestamp()
|
||||
except (ValueError, TypeError, KeyError):
|
||||
continue
|
||||
if age > PING_ONLINE_WINDOW_SECONDS or presence.is_marked_offline(hb["device_serial"]):
|
||||
continue
|
||||
self.publish_command(
|
||||
device_serial=hb["device_serial"],
|
||||
cmd="ping",
|
||||
contents={"ts": int(now * 1000)},
|
||||
)
|
||||
|
||||
|
||||
mqtt_manager = MqttManager()
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Fleet-wide crash grouping (firmware F-070).
|
||||
|
||||
Groups fault boots so recurring crash types are visible across devices:
|
||||
- with an abort_msg: by the message with hex addresses stripped, since the
|
||||
same assert/abort reports different addresses per build;
|
||||
- otherwise: by faulting task + Xtensa exception cause;
|
||||
- fault resets with no coredump and no abort_msg: by reset reason alone.
|
||||
|
||||
When abort_msg is present, pc/exc_cause/exc_vaddr describe the abort()
|
||||
mechanism (always StoreProhibited at 0x0), so they must NOT drive the grouping.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# Xtensa EXCCAUSE values the ESP32 actually produces.
|
||||
EXC_CAUSE_NAMES = {
|
||||
0: "IllegalInstruction",
|
||||
2: "InstructionFetchError",
|
||||
3: "LoadStoreError",
|
||||
6: "IntegerDivideByZero",
|
||||
9: "LoadStoreAlignment",
|
||||
28: "LoadProhibited",
|
||||
29: "StoreProhibited",
|
||||
}
|
||||
|
||||
_HEX = re.compile(r"0x[0-9a-fA-F]+")
|
||||
_SPACES = re.compile(r"\s+")
|
||||
|
||||
|
||||
def normalize_abort_msg(msg: str) -> str:
|
||||
return _SPACES.sub(" ", _HEX.sub("0x…", msg)).strip()
|
||||
|
||||
|
||||
def exc_cause_name(cause) -> str:
|
||||
if cause is None:
|
||||
return "Unknown exception"
|
||||
return EXC_CAUSE_NAMES.get(cause, f"Exception cause {cause}")
|
||||
|
||||
|
||||
def group_key(event: dict) -> tuple[str, str, str]:
|
||||
"""(key, kind, title) for one boot event."""
|
||||
crash = event.get("crash") or {}
|
||||
pre = event.get("pre_crash") or {}
|
||||
abort_msg = pre.get("abort_msg")
|
||||
if abort_msg:
|
||||
norm = normalize_abort_msg(abort_msg)
|
||||
return f"abort:{norm}", "abort", norm
|
||||
|
||||
task = crash.get("task", event.get("crash_task"))
|
||||
cause = crash.get("exc_cause", event.get("crash_exc_cause"))
|
||||
if task is not None or cause is not None:
|
||||
title = f"{exc_cause_name(cause)} in {task or 'unknown task'}"
|
||||
return f"exc:{task}:{cause}", "exception", title
|
||||
|
||||
reason = event.get("reset_reason") or "UNKNOWN"
|
||||
return f"reason:{reason}", "reason", f"{reason.replace('_', ' ')} (no coredump)"
|
||||
|
||||
|
||||
def group_crashes(events: list[dict]) -> list[dict]:
|
||||
"""events must be newest-first (as get_crash_events returns them)."""
|
||||
groups: dict[str, dict] = {}
|
||||
for ev in events:
|
||||
key, kind, title = group_key(ev)
|
||||
g = groups.get(key)
|
||||
if g is None:
|
||||
g = groups[key] = {
|
||||
"key": key,
|
||||
"kind": kind,
|
||||
"title": title,
|
||||
"count": 0,
|
||||
"first_at": ev["occurred_at"],
|
||||
"last_at": ev["occurred_at"],
|
||||
"latest": ev,
|
||||
"devices": {},
|
||||
}
|
||||
g["count"] += 1
|
||||
g["first_at"] = ev["occurred_at"] # newest-first input, so the last seen is the oldest
|
||||
d = g["devices"].setdefault(ev["device_serial"], {
|
||||
"device_serial": ev["device_serial"], "count": 0, "last_at": ev["occurred_at"],
|
||||
})
|
||||
d["count"] += 1
|
||||
|
||||
result = []
|
||||
for g in groups.values():
|
||||
devices = sorted(g["devices"].values(), key=lambda d: (-d["count"], d["device_serial"]))
|
||||
result.append({**g, "devices": devices, "device_count": len(devices)})
|
||||
# Most frequent first; ties broken by most recent (two stable sorts).
|
||||
result.sort(key=lambda g: g["last_at"], reverse=True)
|
||||
result.sort(key=lambda g: g["count"], reverse=True)
|
||||
return result
|
||||
+199
-25
@@ -1,5 +1,7 @@
|
||||
import logging
|
||||
import time
|
||||
import database as db
|
||||
from mqtt import presence
|
||||
|
||||
logger = logging.getLogger("mqtt.logger")
|
||||
|
||||
@@ -14,36 +16,70 @@ LEVEL_MAP = {
|
||||
}
|
||||
|
||||
|
||||
async def handle_message(serial: str, topic_type: str, payload: dict):
|
||||
async def handle_message(serial: str, topic_type: str, payload: dict,
|
||||
retained: bool = False):
|
||||
"""`retained` is True when the broker replayed this from its retained store
|
||||
on (re)subscribe: a stale copy of the device's last message, NOT a new
|
||||
event. The firmware publishes status/heartbeat, system/alerts, system/info
|
||||
and status/playback retained, so every backend restart replays them for
|
||||
every device that ever connected. Handlers for those topics must never
|
||||
record a retained replay as something that just happened."""
|
||||
try:
|
||||
# v2 topic set — see project-vesper's vesper_mqtt_topic_spec_v2.md.
|
||||
if topic_type == "status/heartbeat":
|
||||
await _handle_heartbeat(serial, payload)
|
||||
elif topic_type == "status/alerts":
|
||||
await _handle_alerts(serial, payload)
|
||||
elif topic_type == "status/info":
|
||||
await _handle_info(serial, payload)
|
||||
elif topic_type == "logs":
|
||||
await _handle_heartbeat(serial, payload, retained)
|
||||
elif topic_type == "system/alerts":
|
||||
await _handle_alerts(serial, payload, retained)
|
||||
elif topic_type == "system/info":
|
||||
await _handle_info(serial, payload, retained)
|
||||
elif topic_type == "system/logs":
|
||||
await _handle_log(serial, payload)
|
||||
elif topic_type == "data":
|
||||
await _handle_data_response(serial, payload)
|
||||
elif topic_type == "system/metrics":
|
||||
await _handle_metrics(serial, payload)
|
||||
elif topic_type == "control/ack":
|
||||
await _handle_ack(serial, payload)
|
||||
elif topic_type == "control/reports":
|
||||
await _handle_report(serial, payload)
|
||||
elif topic_type == "status/playback":
|
||||
pass # no console-side storage needed — WS broadcast already carries it live
|
||||
else:
|
||||
logger.debug(f"Unhandled topic type: {topic_type} for {serial}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error handling {topic_type} for {serial}: {e}")
|
||||
|
||||
|
||||
async def _handle_heartbeat(serial: str, payload: dict):
|
||||
async def _handle_heartbeat(serial: str, payload: dict, retained: bool = False):
|
||||
# Online status is "a heartbeat row newer than 90s", so only a live sign of
|
||||
# life may be stored:
|
||||
# - retained replay: the device's last heartbeat from whenever. Storing it
|
||||
# with received_at=now() marked every device ever seen (even long-dead
|
||||
# ones) online for 90s after each backend restart.
|
||||
# - state "offline": the LWT / graceful-disconnect marker published when
|
||||
# the device goes AWAY. Not a heartbeat, but it IS current state even
|
||||
# when replayed (a retained message is the device's last word).
|
||||
if payload.get("state") == "offline":
|
||||
presence.mark_offline(serial)
|
||||
return
|
||||
if retained:
|
||||
return
|
||||
presence.mark_alive(serial)
|
||||
# Store silently — do not log as a visible event.
|
||||
# The console surfaces an alert only when the device goes silent (no heartbeat for 90s).
|
||||
inner = payload.get("payload", {})
|
||||
# v2 heartbeat payload is FLAT — no {"status","type","payload"} wrapper,
|
||||
# and field names changed: firmware_version -> fw_version, timestamp -> uptime_human.
|
||||
# See vesper_mqtt_topic_spec_v2.md and mqtt-events.md for the full shape.
|
||||
await db.insert_heartbeat(
|
||||
device_serial=serial,
|
||||
device_id=inner.get("device_id", ""),
|
||||
firmware_version=inner.get("firmware_version", ""),
|
||||
ip_address=inner.get("ip_address", ""),
|
||||
gateway=inner.get("gateway", ""),
|
||||
uptime_ms=inner.get("uptime_ms", 0),
|
||||
uptime_display=inner.get("timestamp", ""),
|
||||
device_id=payload.get("device_id", ""),
|
||||
firmware_version=payload.get("fw_version", ""),
|
||||
ip_address=payload.get("ip_address", ""),
|
||||
gateway=payload.get("gateway", ""),
|
||||
uptime_ms=payload.get("uptime_ms", 0),
|
||||
uptime_display=payload.get("uptime_human", ""),
|
||||
rssi=payload.get("rssi"),
|
||||
free_heap=payload.get("free_heap"),
|
||||
state=payload.get("state"),
|
||||
ok=payload.get("ok"),
|
||||
)
|
||||
|
||||
|
||||
@@ -58,10 +94,11 @@ async def _handle_log(serial: str, payload: dict):
|
||||
level=level,
|
||||
message=message,
|
||||
device_timestamp=device_timestamp,
|
||||
source="log",
|
||||
)
|
||||
|
||||
|
||||
async def _handle_alerts(serial: str, payload: dict):
|
||||
async def _handle_alerts(serial: str, payload: dict, retained: bool = False):
|
||||
subsystem = payload.get("subsystem", "")
|
||||
state = payload.get("state", "")
|
||||
if not subsystem or not state:
|
||||
@@ -71,24 +108,161 @@ async def _handle_alerts(serial: str, payload: dict):
|
||||
if state == "CLEARED":
|
||||
await db.delete_alert(serial, subsystem)
|
||||
else:
|
||||
await db.upsert_alert(serial, subsystem, state, payload.get("msg"))
|
||||
# Retained replays still sync the current-alert row, so a fresh DB
|
||||
# learns about alerts raised while the backend was down.
|
||||
changed = await db.upsert_alert(serial, subsystem, state, payload.get("msg"))
|
||||
# Append-only history — survives past the alert being resolved, used to
|
||||
# answer "when was the most recent issue" even once it's cleared.
|
||||
# A live alert is always a new occurrence (the same fault can recur);
|
||||
# a retained replay only counts if it isn't already the current state.
|
||||
if changed or not retained:
|
||||
await db.insert_alert_event(serial, subsystem, state, payload.get("msg"))
|
||||
|
||||
|
||||
async def _handle_info(serial: str, payload: dict):
|
||||
async def _handle_info(serial: str, payload: dict, retained: bool = False):
|
||||
event_type = payload.get("type", "")
|
||||
|
||||
# boot_report carries structured fields (boot_count, crash detail, etc.) —
|
||||
# parsed into device_boot_events instead of flattened into a text log line,
|
||||
# so the Health tab can query/chart it. Not routed through insert_log at
|
||||
# all: a text summary here would just duplicate the structured row.
|
||||
#
|
||||
# Note: diagnostics_report used to also arrive here (F-056) but moved to
|
||||
# its own system/metrics topic in the v2 spec — see _handle_metrics below.
|
||||
if event_type == "boot_report":
|
||||
await _handle_boot_report(serial, payload, retained)
|
||||
return
|
||||
|
||||
# Any other info event replayed from the retained store (e.g. an old
|
||||
# playback_started) already happened in the past — don't log it again.
|
||||
if retained:
|
||||
return
|
||||
|
||||
data = payload.get("payload", {})
|
||||
|
||||
if event_type == "playback_started":
|
||||
logger.debug(f"{serial}: playback started — melody_uid={data.get('melody_uid')}")
|
||||
message = f"Playback started — melody_uid={data.get('melody_uid')}"
|
||||
elif event_type == "playback_stopped":
|
||||
logger.debug(f"{serial}: playback stopped")
|
||||
message = "Playback stopped"
|
||||
else:
|
||||
logger.debug(f"{serial}: info event '{event_type}'")
|
||||
message = f"Info event '{event_type}'" + (f" — {data}" if data else "")
|
||||
|
||||
await db.insert_log(
|
||||
device_serial=serial,
|
||||
level="INFO",
|
||||
message=message,
|
||||
source="info",
|
||||
)
|
||||
|
||||
|
||||
async def _handle_data_response(serial: str, payload: dict):
|
||||
async def _handle_boot_report(serial: str, payload: dict, retained: bool = False):
|
||||
"""Parses the firmware's consolidated boot_report event (see
|
||||
CommunicationRouter::reportBootOnce() / publishInfo()) into
|
||||
device_boot_events. Like all status/info events, the report fields are
|
||||
nested under "payload" — CommunicationRouter::publishInfo() wraps every
|
||||
info event as { "type": ..., "payload": {...} }.
|
||||
"""
|
||||
data = payload.get("payload", {})
|
||||
# F-070: `crash` (coredump summary, now incl. backtrace/elf_sha256) and
|
||||
# `pre_crash` (heap/uptime snapshot + optional abort_msg) are stored
|
||||
# verbatim. Older firmware omits them / sends the 4-field crash only.
|
||||
crash = data.get("crash") if isinstance(data.get("crash"), dict) else None
|
||||
pre_crash = data.get("pre_crash") if isinstance(data.get("pre_crash"), dict) else None
|
||||
await db.insert_boot_event(
|
||||
device_serial=serial,
|
||||
boot_count=data.get("boot_count"),
|
||||
reset_reason=data.get("reset_reason"),
|
||||
is_fault=bool(data.get("is_fault", False)),
|
||||
free_heap=data.get("free_heap"),
|
||||
crash=crash,
|
||||
pre_crash=pre_crash,
|
||||
# A live boot_report is always a new boot. A retained replay is the
|
||||
# device's last boot, recorded only if we missed it while down.
|
||||
skip_if_latest=retained,
|
||||
)
|
||||
|
||||
|
||||
async def _handle_metrics(serial: str, payload: dict):
|
||||
"""Parses the firmware's periodic metrics payload (see
|
||||
CommunicationRouter::reportDiagnosticsIfDue() in project-vesper) into
|
||||
device_diagnostics_reports. Unlike status/info events, system/metrics has
|
||||
NO {"type","payload"} wrapper — the payload IS the metrics object,
|
||||
flat at the top level. See vesper_mqtt_topic_spec_v2.md / mqtt-events.md.
|
||||
|
||||
cpu_temp is entirely absent from the firmware payload (not present as a
|
||||
key at all, not present-with-nulls) when no samples were taken yet this
|
||||
window — .get() on a missing "cpu_temp" key correctly falls back to {}
|
||||
below, leaving every cpu_temp_* column null for that row.
|
||||
"""
|
||||
cpu_temp = payload.get("cpu_temp") or {}
|
||||
wifi = payload.get("wifi_reconnects") or {}
|
||||
ota = payload.get("ota") or {}
|
||||
stack = payload.get("stack_high_water") or {}
|
||||
bell_strikes = payload.get("bell_strikes") or {}
|
||||
bell_loads = payload.get("bell_loads") or {}
|
||||
|
||||
await db.insert_diagnostics_report(
|
||||
device_serial=serial,
|
||||
cpu_temp_avg=cpu_temp.get("avg"),
|
||||
cpu_temp_min=cpu_temp.get("min"),
|
||||
cpu_temp_max=cpu_temp.get("max"),
|
||||
cpu_temp_samples=cpu_temp.get("samples"),
|
||||
wifi_reconnect_count=wifi.get("lifetime_count"),
|
||||
wifi_last_disconnect_reason=wifi.get("last_reason"),
|
||||
wifi_last_disconnect_uptime_ms=wifi.get("last_at_uptime_ms"),
|
||||
ota_current_version=ota.get("current_version"),
|
||||
ota_update_available=ota.get("update_available"),
|
||||
ota_available_version=ota.get("available_version"),
|
||||
ota_last_check_uptime_ms=ota.get("last_check_uptime_ms"),
|
||||
ota_last_error=ota.get("last_error"),
|
||||
stack_high_water=stack if stack else None,
|
||||
bell_strikes=bell_strikes if bell_strikes else None,
|
||||
bell_loads=bell_loads if bell_loads else None,
|
||||
cooling_active=payload.get("cooling_active"),
|
||||
)
|
||||
|
||||
|
||||
async def _handle_report(serial: str, payload: dict):
|
||||
"""Parses control/reports — critical, unsolicited board-initiated events
|
||||
(currently only bell_overload). Console-side storage is intentionally
|
||||
light: history/audit only. The tablets are the real-time consumer."""
|
||||
report_type = payload.get("type", "")
|
||||
if not report_type:
|
||||
logger.warning(f"Malformed report payload from {serial}: {payload}")
|
||||
return
|
||||
|
||||
await db.insert_report(
|
||||
device_serial=serial,
|
||||
report_type=report_type,
|
||||
payload=payload.get("payload"),
|
||||
)
|
||||
logger.warning(f"Report '{report_type}' received from {serial}: {payload.get('payload')}")
|
||||
|
||||
|
||||
async def _handle_ack(serial: str, payload: dict):
|
||||
status = payload.get("status", "")
|
||||
|
||||
# Health-check pings (see MqttManager.ping_loop) are published directly,
|
||||
# bypassing db.insert_command, so scheduled liveness checks don't clutter
|
||||
# the user-facing command history. The device echoes the caller's own
|
||||
# send-time ("ts", epoch-ms) back unchanged, so RTT is computed here
|
||||
# without needing to correlate against any pending-command bookkeeping.
|
||||
if payload.get("type") == "pong":
|
||||
ts = (payload.get("data") or {}).get("ts")
|
||||
if isinstance(ts, (int, float)):
|
||||
rtt_ms = max(0, int(time.time() * 1000) - int(ts))
|
||||
await db.insert_ping_sample(device_serial=serial, rtt_ms=rtt_ms)
|
||||
return
|
||||
|
||||
# The device's own SD boot log — merged into device_boot_events whoever
|
||||
# asked for it (Health tab "Sync from device", API reference, Control tab),
|
||||
# so crash detail for boots we never saw live isn't lost.
|
||||
if payload.get("type") == "telemetry.get_boot_history" and status == "SUCCESS":
|
||||
boots = (payload.get("data") or {}).get("boots")
|
||||
if isinstance(boots, list):
|
||||
result = await db.merge_device_boot_history(serial, boots)
|
||||
logger.info(f"Merged device boot history for {serial}: {result}")
|
||||
|
||||
pending = await db.get_pending_command(serial)
|
||||
if pending:
|
||||
cmd_status = "success" if status == "SUCCESS" else "error"
|
||||
@@ -98,4 +272,4 @@ async def _handle_data_response(serial: str, payload: dict):
|
||||
response_payload=payload,
|
||||
)
|
||||
else:
|
||||
logger.debug(f"Received data response for {serial} with no pending command")
|
||||
logger.debug(f"Received control/ack for {serial} with no pending command")
|
||||
|
||||
@@ -27,6 +27,7 @@ class DeviceLogEntry(BaseModel):
|
||||
level: str
|
||||
message: str
|
||||
device_timestamp: Optional[int] = None
|
||||
source: str = "log"
|
||||
received_at: str
|
||||
|
||||
|
||||
@@ -39,6 +40,10 @@ class HeartbeatEntry(BaseModel):
|
||||
gateway: Optional[str] = None
|
||||
uptime_ms: Optional[int] = None
|
||||
uptime_display: Optional[str] = None
|
||||
rssi: Optional[int] = None
|
||||
free_heap: Optional[int] = None
|
||||
state: Optional[str] = None # "idle" | "playing" | "paused" | "error" | "booting" (v2 firmware only)
|
||||
ok: Optional[bool] = None # overall device health, independent of playback state (v2 firmware only)
|
||||
received_at: str
|
||||
|
||||
|
||||
@@ -53,11 +58,21 @@ class CommandEntry(BaseModel):
|
||||
responded_at: Optional[str] = None
|
||||
|
||||
|
||||
class AlertEventEntry(BaseModel):
|
||||
id: int
|
||||
device_serial: str
|
||||
subsystem: str
|
||||
state: str
|
||||
message: Optional[str] = None
|
||||
occurred_at: str
|
||||
|
||||
|
||||
class DeviceMqttStatus(BaseModel):
|
||||
device_serial: str
|
||||
online: bool
|
||||
last_heartbeat: Optional[HeartbeatEntry] = None
|
||||
seconds_since_heartbeat: Optional[int] = None
|
||||
last_alert_event: Optional[AlertEventEntry] = None
|
||||
|
||||
|
||||
class MqttStatusResponse(BaseModel):
|
||||
@@ -96,3 +111,125 @@ class DeviceAlertEntry(BaseModel):
|
||||
|
||||
class DeviceAlertsResponse(BaseModel):
|
||||
alerts: List[DeviceAlertEntry]
|
||||
|
||||
|
||||
class AlertEventListResponse(BaseModel):
|
||||
events: List[AlertEventEntry]
|
||||
total: int
|
||||
|
||||
|
||||
class BootEventEntry(BaseModel):
|
||||
id: int
|
||||
device_serial: str
|
||||
boot_count: Optional[int] = None
|
||||
reset_reason: Optional[str] = None
|
||||
is_fault: bool = False
|
||||
free_heap: Optional[int] = None
|
||||
crash_task: Optional[str] = None
|
||||
crash_pc: Optional[int] = None
|
||||
crash_exc_cause: Optional[int] = None
|
||||
crash_exc_vaddr: Optional[int] = None
|
||||
# Firmware F-070 objects, verbatim — None for older firmware/rows.
|
||||
crash: Optional[Dict[str, Any]] = None
|
||||
pre_crash: Optional[Dict[str, Any]] = None
|
||||
occurred_at: str
|
||||
|
||||
|
||||
class BootEventListResponse(BaseModel):
|
||||
events: List[BootEventEntry]
|
||||
total: int
|
||||
|
||||
|
||||
class CrashGroupDevice(BaseModel):
|
||||
device_serial: str
|
||||
count: int
|
||||
last_at: str
|
||||
|
||||
|
||||
class CrashGroup(BaseModel):
|
||||
key: str
|
||||
kind: str # "abort" | "exception" | "reason"
|
||||
title: str
|
||||
count: int
|
||||
device_count: int
|
||||
first_at: str
|
||||
last_at: str
|
||||
latest: BootEventEntry
|
||||
devices: List[CrashGroupDevice]
|
||||
|
||||
|
||||
class CrashGroupListResponse(BaseModel):
|
||||
groups: List[CrashGroup]
|
||||
total_crashes: int
|
||||
|
||||
|
||||
class PingSampleEntry(BaseModel):
|
||||
id: int
|
||||
device_serial: str
|
||||
rtt_ms: int
|
||||
sampled_at: str
|
||||
|
||||
|
||||
class PingSampleListResponse(BaseModel):
|
||||
samples: List[PingSampleEntry]
|
||||
total: int
|
||||
|
||||
|
||||
class DiagnosticsReportEntry(BaseModel):
|
||||
id: int
|
||||
device_serial: str
|
||||
cpu_temp_avg: Optional[float] = None
|
||||
cpu_temp_min: Optional[float] = None
|
||||
cpu_temp_max: Optional[float] = None
|
||||
cpu_temp_samples: Optional[int] = None
|
||||
wifi_reconnect_count: Optional[int] = None
|
||||
wifi_last_disconnect_reason: Optional[str] = None
|
||||
wifi_last_disconnect_uptime_ms: Optional[int] = None
|
||||
ota_current_version: Optional[str] = None
|
||||
ota_update_available: Optional[bool] = None
|
||||
ota_available_version: Optional[str] = None
|
||||
ota_last_check_uptime_ms: Optional[int] = None
|
||||
ota_last_error: Optional[str] = None
|
||||
stack_high_water: Optional[str] = None # JSON-encoded string — see insert_diagnostics_report
|
||||
bell_strikes: Optional[str] = None # JSON-encoded string, {"0": count, ...} — v2 firmware only
|
||||
bell_loads: Optional[str] = None # JSON-encoded string, {"0": load, ...} — v2 firmware only
|
||||
cooling_active: Optional[bool] = None # v2 firmware only
|
||||
received_at: str
|
||||
|
||||
|
||||
class DiagnosticsReportListResponse(BaseModel):
|
||||
reports: List[DiagnosticsReportEntry]
|
||||
total: int
|
||||
|
||||
|
||||
class DeviceReportEntry(BaseModel):
|
||||
"""A control/reports event (currently only bell_overload) — see
|
||||
project-vesper's vesper_mqtt_topic_spec_v2.md. Console-side storage is
|
||||
intentionally light: history/audit only, not a real-time UI surface."""
|
||||
id: int
|
||||
device_serial: str
|
||||
report_type: str
|
||||
payload: Optional[str] = None # JSON-encoded string
|
||||
occurred_at: str
|
||||
|
||||
|
||||
class DeviceReportListResponse(BaseModel):
|
||||
reports: List[DeviceReportEntry]
|
||||
total: int
|
||||
|
||||
|
||||
class LatestDiagnosticsEntry(BaseModel):
|
||||
device_serial: str
|
||||
cpu_temp_avg: Optional[float] = None
|
||||
received_at: str
|
||||
|
||||
|
||||
class LatestPingEntry(BaseModel):
|
||||
device_serial: str
|
||||
rtt_ms: int
|
||||
sampled_at: str
|
||||
|
||||
|
||||
class LatestMetricsResponse(BaseModel):
|
||||
diagnostics: List[LatestDiagnosticsEntry]
|
||||
pings: List[LatestPingEntry]
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Devices that announced they went offline.
|
||||
|
||||
The firmware's LWT (unclean disconnect) and its graceful-disconnect message both
|
||||
publish {"state": "offline", "ok": false} to status/heartbeat, retained. Online
|
||||
status is otherwise "a heartbeat newer than 90s", which would keep showing a
|
||||
device that just dropped as online for up to 90s. This remembers the marker so
|
||||
/mqtt/status and the ping loop treat the device as offline right away.
|
||||
|
||||
In-memory only, which is enough: on backend start the broker replays each
|
||||
device's retained heartbeat, so a device whose last word was "offline" gets
|
||||
re-marked, and any live heartbeat clears the mark.
|
||||
"""
|
||||
|
||||
_offline: set[str] = set()
|
||||
|
||||
|
||||
def mark_offline(serial: str) -> None:
|
||||
_offline.add(serial)
|
||||
|
||||
|
||||
def mark_alive(serial: str) -> None:
|
||||
_offline.discard(serial)
|
||||
|
||||
|
||||
def is_marked_offline(serial: str) -> bool:
|
||||
return serial in _offline
|
||||
+202
-40
@@ -1,48 +1,90 @@
|
||||
from fastapi import APIRouter, Depends, Query, WebSocket, WebSocketDisconnect
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from typing import Optional, List
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
from mqtt.models import (
|
||||
MqttCommandRequest, CommandSendResponse, MqttStatusResponse,
|
||||
DeviceMqttStatus, LogListResponse, HeartbeatListResponse,
|
||||
CommandListResponse, HeartbeatEntry,
|
||||
CommandListResponse, HeartbeatEntry, AlertEventEntry,
|
||||
AlertEventListResponse, BootEventListResponse, PingSampleListResponse,
|
||||
DiagnosticsReportListResponse, LatestMetricsResponse,
|
||||
LatestDiagnosticsEntry, LatestPingEntry, DeviceReportListResponse,
|
||||
CrashGroupListResponse,
|
||||
)
|
||||
from mqtt.crash_groups import group_crashes
|
||||
from mqtt.client import mqtt_manager
|
||||
from mqtt import presence
|
||||
import database as db
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
from datetime import datetime, timezone
|
||||
|
||||
router = APIRouter(prefix="/api/mqtt", tags=["mqtt"])
|
||||
|
||||
|
||||
def _device_status(hb: dict, alert_event: dict | None, now: datetime) -> DeviceMqttStatus:
|
||||
try:
|
||||
received = datetime.fromisoformat(hb["received_at"])
|
||||
if received.tzinfo is None:
|
||||
received = received.replace(tzinfo=timezone.utc)
|
||||
seconds_ago = int((now - received).total_seconds())
|
||||
except (ValueError, TypeError):
|
||||
seconds_ago = 9999
|
||||
return DeviceMqttStatus(
|
||||
device_serial=hb["device_serial"],
|
||||
online=seconds_ago < 90 and not presence.is_marked_offline(hb["device_serial"]),
|
||||
last_heartbeat=HeartbeatEntry(**hb),
|
||||
seconds_since_heartbeat=seconds_ago,
|
||||
last_alert_event=AlertEventEntry(**alert_event) if alert_event else None,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/status", response_model=MqttStatusResponse)
|
||||
async def get_all_device_status(
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
# Both reads come from database/latest_cache.py (kept current by the MQTT
|
||||
# ingest), so this answers instantly instead of scanning history tables.
|
||||
heartbeats = await db.get_latest_heartbeats()
|
||||
alert_events = await db.get_latest_alert_events()
|
||||
alert_by_serial = {a["device_serial"]: a for a in alert_events}
|
||||
now = datetime.now(timezone.utc)
|
||||
devices = []
|
||||
for hb in heartbeats:
|
||||
received_str = hb["received_at"]
|
||||
try:
|
||||
received = datetime.fromisoformat(received_str)
|
||||
if received.tzinfo is None:
|
||||
received = received.replace(tzinfo=timezone.utc)
|
||||
seconds_ago = int((now - received).total_seconds())
|
||||
except (ValueError, TypeError):
|
||||
seconds_ago = 9999
|
||||
|
||||
devices.append(DeviceMqttStatus(
|
||||
device_serial=hb["device_serial"],
|
||||
online=seconds_ago < 90,
|
||||
last_heartbeat=HeartbeatEntry(**hb),
|
||||
seconds_since_heartbeat=seconds_ago,
|
||||
))
|
||||
return MqttStatusResponse(
|
||||
devices=devices,
|
||||
devices=[_device_status(hb, alert_by_serial.get(hb["device_serial"]), now) for hb in heartbeats],
|
||||
broker_connected=mqtt_manager.connected,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/status/{device_serial}", response_model=Optional[DeviceMqttStatus])
|
||||
async def get_device_status(
|
||||
device_serial: str,
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
"""One device's live status — what DeviceDetail needs, without shipping
|
||||
the whole fleet. null when the device has never sent a heartbeat."""
|
||||
hb = await db.get_latest_heartbeat(device_serial)
|
||||
if not hb:
|
||||
return None
|
||||
alert_event = await db.get_latest_alert_event(device_serial)
|
||||
return _device_status(hb, alert_event, datetime.now(timezone.utc))
|
||||
|
||||
|
||||
@router.get("/latest-metrics", response_model=LatestMetricsResponse)
|
||||
async def get_latest_metrics(
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
# Fleet-wide "last known" CPU temp + ping RTT, one query each — used by
|
||||
# DeviceList to render optional columns without polling any device.
|
||||
# Uptime/firmware/RSSI don't need this: they're already in /mqtt/status.
|
||||
diag_reports = await db.get_latest_diagnostics_reports()
|
||||
ping_samples = await db.get_latest_ping_samples()
|
||||
return LatestMetricsResponse(
|
||||
diagnostics=[LatestDiagnosticsEntry(**d) for d in diag_reports],
|
||||
pings=[LatestPingEntry(**p) for p in ping_samples],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/command/{device_serial}", response_model=CommandSendResponse)
|
||||
async def send_command(
|
||||
device_serial: str,
|
||||
@@ -81,27 +123,58 @@ async def send_command(
|
||||
async def get_device_logs(
|
||||
device_serial: str,
|
||||
level: Optional[str] = Query(None, description="Filter: INFO, WARN, ERROR"),
|
||||
min_level: bool = Query(False, description="If true, level is a floor — also includes higher-severity levels"),
|
||||
search: Optional[str] = Query(None),
|
||||
source: Optional[List[str]] = Query(None, description="Filter by source: log, info. Repeat param to include several."),
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
offset: int = Query(0, ge=0),
|
||||
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
|
||||
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
logs, total = await db.get_logs(
|
||||
device_serial, level=level, search=search,
|
||||
limit=limit, offset=offset,
|
||||
device_serial, level=level, search=search, source=source,
|
||||
min_level=min_level, limit=limit, offset=offset, since=since, until=until,
|
||||
)
|
||||
return LogListResponse(logs=logs, total=total)
|
||||
|
||||
|
||||
@router.delete("/logs/{device_serial}")
|
||||
async def delete_device_logs(
|
||||
device_serial: str,
|
||||
source: Optional[List[str]] = Query(None, description="Only these sources: log, info. Repeat param for several. Omit for all."),
|
||||
level: Optional[List[str]] = Query(None, description="Only these levels: INFO, WARN, ERROR. Repeat param for several. Omit for all."),
|
||||
until: Optional[datetime] = Query(None, description="Only rows at/before this ISO timestamp"),
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
pg: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Delete console-stored log rows for one device (Health tab → Logs →
|
||||
Delete Logs). Narrowed by source/level/time when given. Heartbeats,
|
||||
alert history and commands are cleared through the existing
|
||||
POST /api/devices/{id}/reset-stats instead."""
|
||||
bad_sources = [s for s in (source or []) if s not in ("log", "info")]
|
||||
bad_levels = [l for l in (level or []) if l not in ("INFO", "WARN", "ERROR")]
|
||||
if bad_sources or bad_levels:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid filter: {bad_sources + bad_levels}")
|
||||
deleted = await db.delete_device_logs_filtered(device_serial, sources=source, levels=level, until=until)
|
||||
await log_action(pg, _user.sub, _user.name or _user.email, "DELETE", "device_logs",
|
||||
device_serial, device_serial,
|
||||
meta={"sources": source, "levels": level,
|
||||
"until": until.isoformat() if until else None, "deleted": deleted})
|
||||
return {"deleted": deleted}
|
||||
|
||||
|
||||
@router.get("/heartbeats/{device_serial}", response_model=HeartbeatListResponse)
|
||||
async def get_device_heartbeats(
|
||||
device_serial: str,
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
limit: int = Query(100, ge=1, le=5000),
|
||||
offset: int = Query(0, ge=0),
|
||||
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
|
||||
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
heartbeats, total = await db.get_heartbeats(
|
||||
device_serial, limit=limit, offset=offset,
|
||||
device_serial, limit=limit, offset=offset, since=since, until=until,
|
||||
)
|
||||
return HeartbeatListResponse(heartbeats=heartbeats, total=total)
|
||||
|
||||
@@ -119,6 +192,93 @@ async def get_device_commands(
|
||||
return CommandListResponse(commands=commands, total=total)
|
||||
|
||||
|
||||
@router.get("/alert-events/{device_serial}", response_model=AlertEventListResponse)
|
||||
async def get_device_alert_events(
|
||||
device_serial: str,
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
offset: int = Query(0, ge=0),
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
events, total = await db.get_alert_events(
|
||||
device_serial, limit=limit, offset=offset,
|
||||
)
|
||||
return AlertEventListResponse(events=events, total=total)
|
||||
|
||||
|
||||
@router.get("/boot-events/{device_serial}", response_model=BootEventListResponse)
|
||||
async def get_device_boot_events(
|
||||
device_serial: str,
|
||||
limit: int = Query(100, ge=1, le=2000),
|
||||
offset: int = Query(0, ge=0),
|
||||
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
|
||||
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
events, total = await db.get_boot_events(
|
||||
device_serial, limit=limit, offset=offset, since=since, until=until,
|
||||
)
|
||||
return BootEventListResponse(events=events, total=total)
|
||||
|
||||
|
||||
@router.get("/crash-groups", response_model=CrashGroupListResponse)
|
||||
async def get_crash_groups(
|
||||
since: Optional[datetime] = Query(None, description="ISO timestamp — only crashes at/after this time"),
|
||||
until: Optional[datetime] = Query(None, description="ISO timestamp — only crashes at/before this time"),
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
"""Fault boots across the whole fleet, grouped by crash signature."""
|
||||
events = await db.get_crash_events(since=since, until=until)
|
||||
return CrashGroupListResponse(groups=group_crashes(events), total_crashes=len(events))
|
||||
|
||||
|
||||
@router.get("/ping-samples/{device_serial}", response_model=PingSampleListResponse)
|
||||
async def get_device_ping_samples(
|
||||
device_serial: str,
|
||||
limit: int = Query(200, ge=1, le=5000),
|
||||
offset: int = Query(0, ge=0),
|
||||
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
|
||||
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
samples, total = await db.get_ping_samples(
|
||||
device_serial, limit=limit, offset=offset, since=since, until=until,
|
||||
)
|
||||
return PingSampleListResponse(samples=samples, total=total)
|
||||
|
||||
|
||||
@router.get("/diagnostics-reports/{device_serial}", response_model=DiagnosticsReportListResponse)
|
||||
async def get_device_diagnostics_reports(
|
||||
device_serial: str,
|
||||
limit: int = Query(200, ge=1, le=5000),
|
||||
offset: int = Query(0, ge=0),
|
||||
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
|
||||
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
reports, total = await db.get_diagnostics_reports(
|
||||
device_serial, limit=limit, offset=offset, since=since, until=until,
|
||||
)
|
||||
return DiagnosticsReportListResponse(reports=reports, total=total)
|
||||
|
||||
|
||||
@router.get("/reports/{device_serial}", response_model=DeviceReportListResponse)
|
||||
async def get_device_reports(
|
||||
device_serial: str,
|
||||
limit: int = Query(200, ge=1, le=2000),
|
||||
offset: int = Query(0, ge=0),
|
||||
since: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/after this time"),
|
||||
until: Optional[datetime] = Query(None, description="ISO timestamp — only rows at/before this time"),
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
"""Critical, unsolicited board-initiated events from control/reports
|
||||
(currently only bell_overload). History/audit only — the tablets are the
|
||||
real-time consumer of this data, not the console."""
|
||||
reports, total = await db.get_reports(
|
||||
device_serial, limit=limit, offset=offset, since=since, until=until,
|
||||
)
|
||||
return DeviceReportListResponse(reports=reports, total=total)
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def mqtt_websocket(websocket: WebSocket):
|
||||
"""Live MQTT data stream. Auth via query param: ?token=JWT"""
|
||||
@@ -129,27 +289,29 @@ async def mqtt_websocket(websocket: WebSocket):
|
||||
|
||||
try:
|
||||
from auth.utils import decode_access_token
|
||||
from shared.firebase import get_db
|
||||
from sqlalchemy import select
|
||||
from database.postgres import AsyncSessionLocal
|
||||
from staff.orm import Staff
|
||||
|
||||
payload = decode_access_token(token)
|
||||
role = payload.get("role", "")
|
||||
|
||||
# sysadmin and admin always have MQTT access
|
||||
if role not in ("sysadmin", "admin"):
|
||||
# Check MQTT permission for editor/user
|
||||
user_sub = payload.get("sub", "")
|
||||
db_inst = get_db()
|
||||
if db_inst:
|
||||
doc = db_inst.collection("admin_users").document(user_sub).get()
|
||||
if doc.exists:
|
||||
perms = doc.to_dict().get("permissions", {})
|
||||
if not perms.get("mqtt", False):
|
||||
await websocket.close(code=4003, reason="MQTT access denied")
|
||||
return
|
||||
else:
|
||||
await websocket.close(code=4003, reason="User not found")
|
||||
return
|
||||
else:
|
||||
await websocket.close(code=4003, reason="Service unavailable")
|
||||
async with AsyncSessionLocal() as session:
|
||||
result = await session.execute(
|
||||
select(Staff).where(Staff.id == user_sub).limit(1)
|
||||
)
|
||||
staff = result.scalar_one_or_none()
|
||||
|
||||
if staff is None:
|
||||
await websocket.close(code=4003, reason="User not found")
|
||||
return
|
||||
|
||||
perms = staff.permissions or {}
|
||||
if not perms.get("mqtt", {}).get("access", False):
|
||||
await websocket.close(code=4003, reason="MQTT access denied")
|
||||
return
|
||||
except Exception:
|
||||
await websocket.close(code=4001, reason="Invalid token")
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from typing import Optional, List
|
||||
from uuid import UUID
|
||||
from datetime import datetime
|
||||
|
||||
VALID_TYPES = {"note", "issue"}
|
||||
VALID_STATUSES = {"open", "researching", "resolved"}
|
||||
VALID_SEVERITIES = {"low", "medium", "high", "critical"}
|
||||
VALID_CATEGORIES = {"technical", "install_support", "general"}
|
||||
VALID_ENTITIES = {"device", "app_user", "customer"}
|
||||
|
||||
|
||||
class EntryLinkIn(BaseModel):
|
||||
entity_type: str
|
||||
entity_id: str
|
||||
|
||||
@field_validator("entity_type")
|
||||
@classmethod
|
||||
def check_entity_type(cls, v):
|
||||
if v not in VALID_ENTITIES:
|
||||
raise ValueError(f"entity_type must be one of {VALID_ENTITIES}")
|
||||
return v
|
||||
|
||||
|
||||
class EntryCreate(BaseModel):
|
||||
type: str
|
||||
title: str = Field(..., max_length=500)
|
||||
body: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
severity: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
links: List[EntryLinkIn] = []
|
||||
|
||||
@field_validator("type")
|
||||
@classmethod
|
||||
def check_type(cls, v):
|
||||
if v not in VALID_TYPES:
|
||||
raise ValueError(f"type must be one of {VALID_TYPES}")
|
||||
return v
|
||||
|
||||
@field_validator("status")
|
||||
@classmethod
|
||||
def check_status(cls, v):
|
||||
if v is not None and v not in VALID_STATUSES:
|
||||
raise ValueError(f"status must be one of {VALID_STATUSES}")
|
||||
return v
|
||||
|
||||
@field_validator("severity")
|
||||
@classmethod
|
||||
def check_severity(cls, v):
|
||||
if v is not None and v not in VALID_SEVERITIES:
|
||||
raise ValueError(f"severity must be one of {VALID_SEVERITIES}")
|
||||
return v
|
||||
|
||||
@field_validator("category")
|
||||
@classmethod
|
||||
def check_category(cls, v):
|
||||
if v is not None and v not in VALID_CATEGORIES:
|
||||
raise ValueError(f"category must be one of {VALID_CATEGORIES}")
|
||||
return v
|
||||
|
||||
|
||||
class EntryUpdate(BaseModel):
|
||||
title: Optional[str] = Field(None, max_length=500)
|
||||
body: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
severity: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
|
||||
|
||||
class EntryLinkOut(BaseModel):
|
||||
id: UUID
|
||||
entity_type: str
|
||||
entity_id: str
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class EntryOut(BaseModel):
|
||||
id: UUID
|
||||
type: str
|
||||
title: str
|
||||
body: Optional[str]
|
||||
status: Optional[str]
|
||||
severity: Optional[str]
|
||||
category: Optional[str]
|
||||
author_id: str
|
||||
author_name: Optional[str]
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
links: List[EntryLinkOut] = []
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class EntryListResponse(BaseModel):
|
||||
data: List[EntryOut]
|
||||
pagination: dict
|
||||
|
||||
|
||||
class LinksReplaceIn(BaseModel):
|
||||
links: List[EntryLinkIn]
|
||||
@@ -0,0 +1,42 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import Column, String, Text, DateTime, ForeignKey, UniqueConstraint
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import relationship
|
||||
from database.postgres import Base
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class Entry(Base):
|
||||
__tablename__ = "crm_entries"
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
type = Column(String(10), nullable=False) # 'note' | 'issue'
|
||||
title = Column(String(500), nullable=False)
|
||||
body = Column(Text, nullable=True)
|
||||
status = Column(String(20), nullable=True) # null for notes; open/researching/resolved for issues
|
||||
severity = Column(String(10), nullable=True) # null | low | medium | high | critical
|
||||
category = Column(String(30), nullable=True) # null for notes; technical | install_support | general
|
||||
author_id = Column(String(128), nullable=False) # staff user ID from JWT
|
||||
author_name = Column(String(255), nullable=True) # denormalized for display
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=_now)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, default=_now, onupdate=_now)
|
||||
|
||||
links = relationship("EntryLink", back_populates="entry", cascade="all, delete-orphan", lazy="noload")
|
||||
|
||||
|
||||
class EntryLink(Base):
|
||||
__tablename__ = "crm_entry_links"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("entry_id", "entity_type", "entity_id"),
|
||||
)
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
entry_id = Column(UUID(as_uuid=True), ForeignKey("crm_entries.id", ondelete="CASCADE"), nullable=False)
|
||||
entity_type = Column(String(20), nullable=False) # 'device' | 'app_user' | 'customer'
|
||||
entity_id = Column(String(128), nullable=False) # Firestore ID or Postgres UUID as string
|
||||
|
||||
entry = relationship("Entry", back_populates="links")
|
||||
@@ -0,0 +1,93 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from uuid import UUID
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from database.postgres import get_pg_session
|
||||
from auth.dependencies import require_permission
|
||||
from auth.models import TokenPayload
|
||||
from notes import service
|
||||
from notes.models import EntryCreate, EntryUpdate, EntryOut, EntryListResponse, LinksReplaceIn
|
||||
from shared.audit import log_action
|
||||
|
||||
router = APIRouter(prefix="/api/notes", tags=["notes"])
|
||||
|
||||
|
||||
@router.get("", response_model=EntryListResponse)
|
||||
async def list_entries(
|
||||
type: str | None = Query(None),
|
||||
status: str | None = Query(None),
|
||||
severity: str | None = Query(None),
|
||||
category: str | None = Query(None),
|
||||
page: int = Query(1, ge=1),
|
||||
limit: int = Query(25, ge=1, le=100),
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "view")),
|
||||
):
|
||||
rows, total = await service.list_entries(db, type, status, severity, category, page, limit)
|
||||
return {"data": rows, "pagination": {"page": page, "limit": limit, "total": total}}
|
||||
|
||||
|
||||
@router.get("/by-entity/{entity_type}/{entity_id}", response_model=list[EntryOut])
|
||||
async def list_by_entity(
|
||||
entity_type: str, entity_id: str,
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "view")),
|
||||
):
|
||||
return await service.list_entries_for_entity(db, entity_type, entity_id)
|
||||
|
||||
|
||||
@router.get("/{entry_id}", response_model=EntryOut)
|
||||
async def get_entry(
|
||||
entry_id: UUID,
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "view")),
|
||||
):
|
||||
return await service.get_entry(db, entry_id)
|
||||
|
||||
|
||||
@router.post("", response_model=EntryOut, status_code=201)
|
||||
async def create_entry(
|
||||
body: EntryCreate,
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "add")),
|
||||
):
|
||||
entry = await service.create_entry(db, body, _user.sub, _user.name or _user.email)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "CREATE", "note",
|
||||
str(entry.id), entry.title or entry.type)
|
||||
return entry
|
||||
|
||||
|
||||
@router.patch("/{entry_id}", response_model=EntryOut)
|
||||
async def update_entry(
|
||||
entry_id: UUID, body: EntryUpdate,
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
):
|
||||
entry = await service.update_entry(db, entry_id, body)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "note",
|
||||
str(entry_id), entry.title or entry.type)
|
||||
return entry
|
||||
|
||||
|
||||
@router.patch("/{entry_id}/links", response_model=EntryOut)
|
||||
async def replace_links(
|
||||
entry_id: UUID, body: LinksReplaceIn,
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "edit")),
|
||||
):
|
||||
entry = await service.replace_links(db, entry_id, body.links)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "UPDATE", "note",
|
||||
str(entry_id), entry.title or entry.type,
|
||||
meta={"action_detail": "links_updated"})
|
||||
return entry
|
||||
|
||||
|
||||
@router.delete("/{entry_id}", status_code=204)
|
||||
async def delete_entry(
|
||||
entry_id: UUID,
|
||||
db: AsyncSession = Depends(get_pg_session),
|
||||
_user: TokenPayload = Depends(require_permission("crm", "delete")),
|
||||
):
|
||||
entry = await service.get_entry(db, entry_id)
|
||||
await service.delete_entry(db, entry_id)
|
||||
await log_action(db, _user.sub, _user.name or _user.email, "DELETE", "note",
|
||||
str(entry_id), entry.title or entry.type if entry else str(entry_id))
|
||||
@@ -0,0 +1,93 @@
|
||||
import uuid
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, delete, func
|
||||
from sqlalchemy.orm import selectinload
|
||||
from notes.orm import Entry, EntryLink
|
||||
from notes.models import EntryCreate, EntryUpdate, EntryLinkIn
|
||||
from shared.exceptions import NotFoundError
|
||||
|
||||
|
||||
async def create_entry(db: AsyncSession, data: EntryCreate, author_id: str, author_name: str) -> Entry:
|
||||
entry = Entry(
|
||||
type=data.type,
|
||||
title=data.title,
|
||||
body=data.body,
|
||||
status=data.status if data.type == "issue" else None,
|
||||
severity=data.severity if data.type == "issue" else None,
|
||||
category=data.category if data.type == "issue" else None,
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
)
|
||||
db.add(entry)
|
||||
await db.flush() # get the ID before inserting links
|
||||
|
||||
for link_in in data.links:
|
||||
db.add(EntryLink(entry_id=entry.id, entity_type=link_in.entity_type, entity_id=link_in.entity_id))
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(entry)
|
||||
return await _get_entry_with_links(db, entry.id)
|
||||
|
||||
|
||||
async def get_entry(db: AsyncSession, entry_id: uuid.UUID) -> Entry:
|
||||
return await _get_entry_with_links(db, entry_id)
|
||||
|
||||
|
||||
async def list_entries(
|
||||
db: AsyncSession,
|
||||
type: str | None, status: str | None, severity: str | None, category: str | None,
|
||||
page: int, limit: int,
|
||||
) -> tuple[list[Entry], int]:
|
||||
limit = min(100, max(1, limit))
|
||||
offset = (max(1, page) - 1) * limit
|
||||
|
||||
q = select(Entry).options(selectinload(Entry.links))
|
||||
if type: q = q.where(Entry.type == type)
|
||||
if status: q = q.where(Entry.status == status)
|
||||
if severity: q = q.where(Entry.severity == severity)
|
||||
if category: q = q.where(Entry.category == category)
|
||||
|
||||
total_q = select(func.count()).select_from(q.subquery())
|
||||
total = (await db.execute(total_q)).scalar()
|
||||
rows = (await db.execute(q.order_by(Entry.created_at.desc()).limit(limit).offset(offset))).scalars().all()
|
||||
return rows, total
|
||||
|
||||
|
||||
async def update_entry(db: AsyncSession, entry_id: uuid.UUID, data: EntryUpdate) -> Entry:
|
||||
entry = await _get_entry_with_links(db, entry_id)
|
||||
for field, value in data.model_dump(exclude_unset=True).items():
|
||||
setattr(entry, field, value)
|
||||
await db.commit()
|
||||
return await _get_entry_with_links(db, entry_id)
|
||||
|
||||
|
||||
async def delete_entry(db: AsyncSession, entry_id: uuid.UUID):
|
||||
entry = await _get_entry_with_links(db, entry_id)
|
||||
await db.delete(entry)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def replace_links(db: AsyncSession, entry_id: uuid.UUID, links: list[EntryLinkIn]) -> Entry:
|
||||
await _get_entry_with_links(db, entry_id) # raises 404 if not found
|
||||
await db.execute(delete(EntryLink).where(EntryLink.entry_id == entry_id))
|
||||
for link_in in links:
|
||||
db.add(EntryLink(entry_id=entry_id, entity_type=link_in.entity_type, entity_id=link_in.entity_id))
|
||||
await db.commit()
|
||||
return await _get_entry_with_links(db, entry_id)
|
||||
|
||||
|
||||
async def list_entries_for_entity(db: AsyncSession, entity_type: str, entity_id: str) -> list[Entry]:
|
||||
link_sq = select(EntryLink.entry_id).where(
|
||||
EntryLink.entity_type == entity_type,
|
||||
EntryLink.entity_id == entity_id,
|
||||
).subquery()
|
||||
q = select(Entry).options(selectinload(Entry.links)).where(Entry.id.in_(select(link_sq)))
|
||||
return (await db.execute(q.order_by(Entry.created_at.desc()))).scalars().all()
|
||||
|
||||
|
||||
async def _get_entry_with_links(db: AsyncSession, entry_id: uuid.UUID) -> Entry:
|
||||
q = select(Entry).options(selectinload(Entry.links)).where(Entry.id == entry_id)
|
||||
result = (await db.execute(q)).scalar_one_or_none()
|
||||
if not result:
|
||||
raise NotFoundError("Entry")
|
||||
return result
|
||||
@@ -109,9 +109,9 @@ async def validate_serial(serial_number: str):
|
||||
device = get_device_by_sn(sn)
|
||||
return SerialValidationResult(
|
||||
valid=True,
|
||||
hw_type=device.hw_type,
|
||||
hw_type_label=HW_TYPE_LABELS.get(device.hw_type, device.hw_type.replace("_", " ").title()),
|
||||
hw_version=device.hw_version,
|
||||
hw_type=device.hw_family,
|
||||
hw_type_label=HW_TYPE_LABELS.get(device.hw_family, device.hw_family.replace("_", " ").title()),
|
||||
hw_version=device.hw_revision,
|
||||
)
|
||||
except Exception:
|
||||
return SerialValidationResult(valid=False)
|
||||
|
||||
@@ -15,3 +15,8 @@ weasyprint>=62.0
|
||||
jinja2>=3.1.0
|
||||
Pillow>=10.0.0
|
||||
pdf2image>=1.17.0
|
||||
asyncpg==0.30.0
|
||||
sqlalchemy[asyncio]==2.0.36
|
||||
alembic==1.14.0
|
||||
# IANA tz database for the device timezone table (timezones/). Bump to pick up new DST rules.
|
||||
tzdata==2026.6
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
Backfill `device_serials` on Firestore `users` docs from the devices' `user_list`.
|
||||
|
||||
`device_serials` is what the MQTT ACL uses to decide which vesper/{serial}/...
|
||||
topics an app user may reach (see mqtt/app_users.py). New assignments keep it
|
||||
in sync automatically; this script builds it for assignments that predate that.
|
||||
|
||||
The devices' user_list is treated as the source of truth: each user's
|
||||
device_serials is set to exactly the serials of the devices that list them.
|
||||
Running it twice is a no-op the second time.
|
||||
|
||||
Also reports:
|
||||
- users whose document ID != their `uid` field (or who have no uid) — the
|
||||
MQTT layer resolves users by the uid field, so this is informational,
|
||||
but a user without a uid can never connect via the app
|
||||
- devices that have users but no serial (can't be reached over MQTT)
|
||||
- user_list entries that point to users that don't exist
|
||||
|
||||
Run from backend/ (locally or inside the backend container):
|
||||
|
||||
python scripts/backfill_user_device_serials.py # dry run
|
||||
python scripts/backfill_user_device_serials.py --apply # write changes
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from google.cloud.firestore_v1 import DocumentReference # noqa: E402
|
||||
|
||||
from shared.firebase import init_firebase, get_db # noqa: E402
|
||||
from users.service import device_serial_of # noqa: E402
|
||||
|
||||
BATCH_SIZE = 400 # Firestore batch limit is 500 writes
|
||||
|
||||
|
||||
def _entry_user_id(entry) -> str:
|
||||
"""user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
|
||||
if isinstance(entry, DocumentReference):
|
||||
return entry.id
|
||||
if isinstance(entry, str) and entry.strip():
|
||||
return entry.strip().split("/")[-1]
|
||||
return ""
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--apply", action="store_true", help="write changes (default: dry run)")
|
||||
args = parser.parse_args()
|
||||
|
||||
init_firebase()
|
||||
db = get_db()
|
||||
if db is None:
|
||||
print("[ERROR] Firebase not initialized — check FIREBASE_SERVICE_ACCOUNT_PATH")
|
||||
return 1
|
||||
|
||||
mode = "APPLY" if args.apply else "DRY RUN"
|
||||
print(f"=== backfill device_serials ({mode}) ===\n")
|
||||
|
||||
# 1. devices -> {user_doc_id: {serials}}
|
||||
wanted: dict[str, set[str]] = defaultdict(set)
|
||||
devices_without_serial = []
|
||||
device_count = 0
|
||||
for doc in db.collection("devices").stream():
|
||||
device_count += 1
|
||||
data = doc.to_dict() or {}
|
||||
user_ids = [u for u in (_entry_user_id(e) for e in (data.get("user_list") or [])) if u]
|
||||
if not user_ids:
|
||||
continue
|
||||
serial = device_serial_of(data)
|
||||
if not serial:
|
||||
devices_without_serial.append(doc.id)
|
||||
continue
|
||||
for uid in user_ids:
|
||||
wanted[uid].add(serial)
|
||||
|
||||
# 2. users
|
||||
users = {doc.id: (doc.reference, doc.to_dict() or {}) for doc in db.collection("users").stream()}
|
||||
by_uid_field = {data.get("uid"): doc_id for doc_id, (_, data) in users.items() if data.get("uid")}
|
||||
|
||||
# user_list entries that don't match a doc ID but do match a uid field
|
||||
dangling = []
|
||||
for ref_id in list(wanted):
|
||||
if ref_id in users:
|
||||
continue
|
||||
if ref_id in by_uid_field:
|
||||
wanted[by_uid_field[ref_id]].update(wanted.pop(ref_id))
|
||||
else:
|
||||
dangling.append((ref_id, sorted(wanted.pop(ref_id))))
|
||||
|
||||
id_mismatch = []
|
||||
no_uid = []
|
||||
changes = []
|
||||
for doc_id, (ref, data) in sorted(users.items()):
|
||||
uid = data.get("uid") or ""
|
||||
if not uid:
|
||||
no_uid.append(doc_id)
|
||||
elif uid != doc_id:
|
||||
id_mismatch.append((doc_id, uid))
|
||||
|
||||
current = data.get("device_serials")
|
||||
desired = sorted(wanted.get(doc_id, set()))
|
||||
if current is None and not desired:
|
||||
continue # nothing assigned and field absent — leave the doc alone
|
||||
if list(current or []) != desired:
|
||||
changes.append((doc_id, ref, list(current or []), desired))
|
||||
|
||||
# 3. report
|
||||
print(f"Scanned {device_count} devices, {len(users)} users.\n")
|
||||
|
||||
print(f"Users to update: {len(changes)}")
|
||||
for doc_id, _, current, desired in changes:
|
||||
print(f" users/{doc_id}: {current} -> {desired}")
|
||||
|
||||
print(f"\nUsers whose doc ID != uid: {len(id_mismatch)}")
|
||||
for doc_id, uid in id_mismatch:
|
||||
print(f" users/{doc_id} uid={uid}")
|
||||
|
||||
print(f"\nUsers with no uid field (cannot use app MQTT login): {len(no_uid)}")
|
||||
for doc_id in no_uid:
|
||||
print(f" users/{doc_id}")
|
||||
|
||||
print(f"\nDevices with users but no serial_number/device_id: {len(devices_without_serial)}")
|
||||
for doc_id in devices_without_serial:
|
||||
print(f" devices/{doc_id}")
|
||||
|
||||
print(f"\nuser_list entries pointing to missing users: {len(dangling)}")
|
||||
for ref_id, serials in dangling:
|
||||
print(f" {ref_id} (on devices {serials})")
|
||||
|
||||
# 4. write
|
||||
if not args.apply:
|
||||
print("\nDry run — nothing written. Re-run with --apply to write.")
|
||||
return 0
|
||||
|
||||
for i in range(0, len(changes), BATCH_SIZE):
|
||||
batch = db.batch()
|
||||
for _, ref, _, desired in changes[i:i + BATCH_SIZE]:
|
||||
batch.update(ref, {"device_serials": desired})
|
||||
batch.commit()
|
||||
print(f"\nWrote device_serials on {len(changes)} user docs.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
Fixup: call make_public() on every .bsm binary blob under melodies/ in Firebase Storage.
|
||||
Run this if blobs were uploaded but are returning AccessDenied.
|
||||
|
||||
docker exec -it bellsystems-backend python scripts/fix_storage_acl.py --dry-run
|
||||
docker exec -it bellsystems-backend python scripts/fix_storage_acl.py
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env loader
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _load_env() -> dict:
|
||||
search = Path(__file__).resolve().parent
|
||||
for _ in range(4):
|
||||
env_file = search / ".env"
|
||||
if env_file.exists():
|
||||
result = {}
|
||||
for line in env_file.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, val = line.partition("=")
|
||||
result[key.strip()] = val.strip().strip('"').strip("'")
|
||||
print(f"[INFO] Loaded config from {env_file}")
|
||||
return result
|
||||
search = search.parent
|
||||
return {}
|
||||
|
||||
_env = _load_env()
|
||||
|
||||
def _cfg(key: str, default: str = "") -> str:
|
||||
return _env.get(key) or os.environ.get(key) or default
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def run(dry_run: bool = False):
|
||||
label = "[DRY-RUN]" if dry_run else "[LIVE]"
|
||||
|
||||
sa_path = _cfg("FIREBASE_SERVICE_ACCOUNT_PATH", "./firebase-service-account.json")
|
||||
bucket_name = _cfg("FIREBASE_STORAGE_BUCKET")
|
||||
|
||||
if not bucket_name:
|
||||
print("ERROR: FIREBASE_STORAGE_BUCKET not set in .env")
|
||||
sys.exit(1)
|
||||
|
||||
import firebase_admin
|
||||
from firebase_admin import credentials, storage as fb_storage
|
||||
|
||||
cred = credentials.Certificate(sa_path)
|
||||
firebase_admin.initialize_app(cred, {"storageBucket": bucket_name})
|
||||
bucket = fb_storage.bucket()
|
||||
|
||||
print(f"\n{label} Scanning melodies/ in bucket: {bucket_name}\n")
|
||||
|
||||
blobs = list(bucket.list_blobs(prefix="melodies/"))
|
||||
bsm_blobs = [b for b in blobs if b.name.lower().endswith(".bsm")]
|
||||
|
||||
print(f"Found {len(bsm_blobs)} .bsm blob(s)\n")
|
||||
|
||||
fixed = 0
|
||||
for blob in bsm_blobs:
|
||||
print(f" {'[skip] ' if dry_run else '[fix] '}{blob.name}")
|
||||
if not dry_run:
|
||||
try:
|
||||
blob.make_public()
|
||||
fixed += 1
|
||||
except Exception as e:
|
||||
print(f" ERROR: {e}")
|
||||
|
||||
print(f"\n{label} Done. {fixed if not dry_run else len(bsm_blobs)} blob(s) {'would be ' if dry_run else ''}made public.")
|
||||
if dry_run:
|
||||
print("Run without --dry-run to apply.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Make all melody .bsm blobs public in Firebase Storage")
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args()
|
||||
run(dry_run=args.dry_run)
|
||||
@@ -0,0 +1,262 @@
|
||||
"""
|
||||
One-time migration: move every melody's .bsm binary off Firebase Storage and
|
||||
onto local disk, updating melody.url to point at our own plain-HTTP download
|
||||
endpoint instead of the Firebase public URL.
|
||||
|
||||
Background: ESP32 devices can't afford the RAM for a TLS client, so melody
|
||||
binaries are now served from ./storage/melody_binaries via
|
||||
GET /api/melodies/download/{pid} (exposed publicly as
|
||||
melodies.bellsystems.net/download/{pid}) instead of Firebase Storage's
|
||||
HTTPS-only URLs. This script backfills existing melodies created before that
|
||||
change — melodies created/edited after the change already use the new path
|
||||
automatically (via "Select Archetype" / "Build on the Fly").
|
||||
|
||||
What this script does, for every melody whose url points at Firebase Storage:
|
||||
1. Downloads the .bsm bytes from the Firebase Storage URL
|
||||
2. Writes them to ./storage/melody_binaries/{pid}.bsm
|
||||
3. Updates melody.url -> http://melodies.bellsystems.net/download/{pid}
|
||||
4. Updates both SQLite (melody_drafts) and Firestore (if published)
|
||||
|
||||
Storage is keyed on pid, not melody uid: pid identifies the underlying
|
||||
archetype binary, and multiple melodies legitimately share one pid (each
|
||||
remaps the same note sequence to different bells/speed/duration). The script
|
||||
downloads each distinct pid's binary only once (from whichever melody it
|
||||
encounters first) and reuses it for every other melody sharing that pid.
|
||||
|
||||
CAVEAT: some existing melodies share a pid despite pointing at *different*
|
||||
Firebase source files (observed in practice — e.g. voice-count variants like
|
||||
1N_/2N_/3N_/4N_-prefixed filenames all filed under one pid). This script does
|
||||
NOT attempt to detect or fix that — it flags it in the output (see "WARNING:
|
||||
also seen with a different source file") so you can review and re-assign the
|
||||
correct archetype per melody afterward using the in-app playback button. This
|
||||
is a pre-existing PID data issue, not something safe to silently resolve here.
|
||||
|
||||
Melodies with no pid are skipped and reported, since the new URL scheme
|
||||
requires one (pid is the public lookup key for the download route).
|
||||
|
||||
Run from the backend/ directory (or scripts/ — it searches upward for .env):
|
||||
|
||||
docker exec -it bellsystems-backend python scripts/migrate_melody_binaries_to_local.py --dry-run
|
||||
docker exec -it bellsystems-backend python scripts/migrate_melody_binaries_to_local.py
|
||||
|
||||
Requires: firebase-admin, requests (both already in the backend image).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
# Melody names may contain Greek/non-ASCII text — force UTF-8 stdout so this
|
||||
# doesn't crash on Windows consoles defaulting to cp1252.
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env loader — searches upward from script location for a .env file
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _load_env() -> dict:
|
||||
search = Path(__file__).resolve().parent
|
||||
for _ in range(4):
|
||||
env_file = search / ".env"
|
||||
if env_file.exists():
|
||||
result = {}
|
||||
for line in env_file.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, val = line.partition("=")
|
||||
result[key.strip()] = val.strip().strip('"').strip("'")
|
||||
print(f"[INFO] Loaded config from {env_file}")
|
||||
return result
|
||||
search = search.parent
|
||||
print("[WARN] No .env file found — relying on environment variables")
|
||||
return {}
|
||||
|
||||
|
||||
_env = _load_env()
|
||||
|
||||
|
||||
def _cfg(key: str, default: str = "") -> str:
|
||||
return _env.get(key) or os.environ.get(key) or default
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Firebase (only needed to read Firestore for published melodies)
|
||||
# ---------------------------------------------------------------------------
|
||||
try:
|
||||
import firebase_admin
|
||||
from firebase_admin import credentials, firestore
|
||||
|
||||
_fb_app = None
|
||||
|
||||
def _init_firebase(sa_path: str, bucket_name: str):
|
||||
global _fb_app
|
||||
if _fb_app is not None:
|
||||
return
|
||||
cred = credentials.Certificate(sa_path)
|
||||
_fb_app = firebase_admin.initialize_app(cred, {"storageBucket": bucket_name})
|
||||
|
||||
def get_firestore(sa_path: str, bucket_name: str):
|
||||
_init_firebase(sa_path, bucket_name)
|
||||
return firestore.client()
|
||||
|
||||
FIREBASE_AVAILABLE = True
|
||||
except Exception as _fb_err:
|
||||
print(f"[WARN] Firebase unavailable: {_fb_err}")
|
||||
FIREBASE_AVAILABLE = False
|
||||
|
||||
def get_firestore(sa_path: str, bucket_name: str):
|
||||
return None
|
||||
|
||||
|
||||
def _is_firebase_url(url: str) -> bool:
|
||||
return bool(url) and ("firebasestorage" in url or "storage.googleapis.com" in url)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main migration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def run(dry_run: bool = False, db_path: str = "", storage_dir: str = "", base_url: str = ""):
|
||||
label = "[DRY-RUN]" if dry_run else "[LIVE]"
|
||||
db_path = db_path or _cfg("SQLITE_DB_PATH", "./data/database.db")
|
||||
storage_dir = Path(storage_dir or _cfg("MELODY_BINARIES_STORAGE_PATH", "./storage/melody_binaries"))
|
||||
base_url = base_url or _cfg("MELODY_DOWNLOAD_BASE_URL", "http://melodies.bellsystems.net/download")
|
||||
sa_path = _cfg("FIREBASE_SERVICE_ACCOUNT_PATH", "./firebase-service-account.json")
|
||||
bucket_name = _cfg("FIREBASE_STORAGE_BUCKET")
|
||||
|
||||
print(f"\n{label} Database: {db_path}")
|
||||
print(f"{label} Local binary storage: {storage_dir}")
|
||||
print(f"{label} New base URL: {base_url}\n")
|
||||
|
||||
firestore_db = get_firestore(sa_path, bucket_name) if FIREBASE_AVAILABLE and bucket_name else None
|
||||
|
||||
con = sqlite3.connect(db_path)
|
||||
con.row_factory = sqlite3.Row
|
||||
|
||||
rows = con.execute("SELECT * FROM melody_drafts").fetchall()
|
||||
candidates = []
|
||||
for row in rows:
|
||||
data = json.loads(row["data"])
|
||||
if _is_firebase_url(data.get("url", "")):
|
||||
candidates.append((dict(row), data))
|
||||
|
||||
if not candidates:
|
||||
print("No melodies with a Firebase Storage url found. Nothing to do.")
|
||||
con.close()
|
||||
return
|
||||
|
||||
print(f"Found {len(candidates)} melody(ies) with a Firebase Storage binary url:\n")
|
||||
|
||||
if not dry_run:
|
||||
storage_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
migrated = 0
|
||||
skipped_no_pid = 0
|
||||
failed = 0
|
||||
downloaded_pids: dict[str, bool] = {} # pid -> whether the local file is ready to use
|
||||
pid_source_urls: dict[str, str] = {} # pid -> first-seen Firebase source url, to detect mismatches
|
||||
mismatch_warnings = []
|
||||
|
||||
for row, data in candidates:
|
||||
melody_id = row["id"]
|
||||
pid = data.get("pid")
|
||||
old_url = data.get("url")
|
||||
name = (data.get("information") or {}).get("name", "")
|
||||
|
||||
label_id = f"[{melody_id[:8]}]"
|
||||
|
||||
if not pid:
|
||||
print(f" {label_id} SKIPPED: no pid set — the new download route requires one (name: {name})")
|
||||
skipped_no_pid += 1
|
||||
continue
|
||||
|
||||
print(f" {label_id} {name!r} pid={pid}")
|
||||
print(f" {old_url}")
|
||||
|
||||
first_seen_url = pid_source_urls.get(pid)
|
||||
if first_seen_url and first_seen_url != old_url:
|
||||
warning = (f"pid '{pid}': melody {label_id} points at a DIFFERENT Firebase file "
|
||||
f"than the one already saved for this pid — only the first one encountered "
|
||||
f"is kept as {pid}.bsm. Verify with the playback button after migrating.")
|
||||
print(f" WARNING: also seen with a different source file! {warning}")
|
||||
mismatch_warnings.append(warning)
|
||||
else:
|
||||
pid_source_urls[pid] = old_url
|
||||
|
||||
dest = storage_dir / f"{pid}.bsm"
|
||||
new_url = f"{base_url}/{pid}"
|
||||
|
||||
if dry_run:
|
||||
if pid in downloaded_pids:
|
||||
print(f" -> pid already handled by another melody in this run, would reuse {dest}")
|
||||
else:
|
||||
print(f" -> would download and save to {dest}")
|
||||
print(f" -> would set url = {new_url}")
|
||||
downloaded_pids[pid] = True
|
||||
continue
|
||||
|
||||
if pid not in downloaded_pids:
|
||||
try:
|
||||
resp = requests.get(old_url, timeout=30)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
print(f" ERROR downloading binary: {e}")
|
||||
failed += 1
|
||||
continue
|
||||
dest.write_bytes(resp.content)
|
||||
print(f" saved {len(resp.content)} bytes -> {dest}")
|
||||
downloaded_pids[pid] = True
|
||||
else:
|
||||
print(f" reusing already-downloaded {dest} (shared pid)")
|
||||
|
||||
print(f" url -> {new_url}")
|
||||
|
||||
data["url"] = new_url
|
||||
con.execute(
|
||||
"UPDATE melody_drafts SET data=? WHERE id=?",
|
||||
(json.dumps(data), melody_id),
|
||||
)
|
||||
con.commit()
|
||||
|
||||
if row["status"] == "published":
|
||||
if firestore_db:
|
||||
try:
|
||||
firestore_db.collection("melodies").document(melody_id).update({"url": new_url})
|
||||
print(f" Firestore updated")
|
||||
except Exception as e:
|
||||
print(f" ERROR updating Firestore: {e}")
|
||||
else:
|
||||
print(f" WARNING: melody is published but Firestore unavailable!")
|
||||
|
||||
migrated += 1
|
||||
|
||||
con.close()
|
||||
print(f"\n{'-'*60}")
|
||||
print(f"{label} Done. Migrated: {migrated}, skipped (no pid): {skipped_no_pid}, failed: {failed}")
|
||||
if mismatch_warnings:
|
||||
print(f"\n{len(mismatch_warnings)} pid(s) had melodies pointing at different source files "
|
||||
f"— please review these with the playback button:")
|
||||
for w in mismatch_warnings:
|
||||
print(f" - {w}")
|
||||
if dry_run:
|
||||
print("\nThis was a dry run. No changes were made. Run without --dry-run to apply.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Migrate melody .bsm binaries from Firebase Storage to local disk"
|
||||
)
|
||||
parser.add_argument("--dry-run", action="store_true", help="Preview changes without writing anything")
|
||||
parser.add_argument("--db", default="", help="Override SQLite database path (default: read from .env)")
|
||||
parser.add_argument("--storage-dir", default="", help="Override local binary storage dir (default: read from .env)")
|
||||
parser.add_argument("--base-url", default="", help="Override download base URL (default: read from .env)")
|
||||
args = parser.parse_args()
|
||||
run(dry_run=args.dry_run, db_path=args.db, storage_dir=args.storage_dir, base_url=args.base_url)
|
||||
@@ -0,0 +1,408 @@
|
||||
"""
|
||||
One-time migration: replace hyphens with underscores in archetype PIDs and all
|
||||
melody PIDs/URLs that reference them.
|
||||
|
||||
What this script does:
|
||||
1. Renames each archetype's PID in SQLite (built_melodies.pid)
|
||||
2. Renames the local .bsm binary file on disk
|
||||
3. Updates built_melodies.binary_path in SQLite
|
||||
4. Regenerates built_melodies.progmem_code
|
||||
5. For every melody assigned to that archetype:
|
||||
a. Downloads the .bsm bytes from Firebase Storage
|
||||
b. Deletes the old blob
|
||||
c. Re-uploads under the new PID name -> gets new public URL
|
||||
d. Updates melody.pid (if it matched old archetype PID)
|
||||
e. Updates melody.url -> new Firebase URL
|
||||
f. Updates both SQLite AND Firestore (if melody is published)
|
||||
|
||||
Run from the backend/ directory (or scripts/ — it searches upward for .env):
|
||||
|
||||
python scripts/migrate_pids_hyphens_to_underscores.py --dry-run
|
||||
python scripts/migrate_pids_hyphens_to_underscores.py
|
||||
|
||||
All config is auto-loaded from the project .env file. No extra arguments needed.
|
||||
Optional overrides:
|
||||
--db Override SQLite database path
|
||||
--dry-run Preview changes without writing anything
|
||||
|
||||
Requires only: firebase-admin (pip install firebase-admin)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env loader — searches upward from script location for a .env file
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _load_env() -> dict:
|
||||
"""Parse key=value pairs from the nearest .env file up the directory tree."""
|
||||
search = Path(__file__).resolve().parent
|
||||
for _ in range(4): # look up to 4 levels up
|
||||
env_file = search / ".env"
|
||||
if env_file.exists():
|
||||
result = {}
|
||||
for line in env_file.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, val = line.partition("=")
|
||||
result[key.strip()] = val.strip().strip('"').strip("'")
|
||||
print(f"[INFO] Loaded config from {env_file}")
|
||||
return result
|
||||
search = search.parent
|
||||
print("[WARN] No .env file found — relying on environment variables")
|
||||
return {}
|
||||
|
||||
|
||||
_env = _load_env()
|
||||
|
||||
|
||||
def _cfg(key: str, default: str = "") -> str:
|
||||
"""Get a config value: .env first, then os.environ, then default."""
|
||||
return _env.get(key) or os.environ.get(key) or default
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Firebase (optional – skipped if not configured)
|
||||
# ---------------------------------------------------------------------------
|
||||
try:
|
||||
import firebase_admin
|
||||
from firebase_admin import credentials, firestore, storage as fb_storage
|
||||
|
||||
_fb_app = None
|
||||
|
||||
def _init_firebase(sa_path: str, bucket_name: str):
|
||||
global _fb_app
|
||||
if _fb_app is not None:
|
||||
return
|
||||
cred = credentials.Certificate(sa_path)
|
||||
_fb_app = firebase_admin.initialize_app(cred, {
|
||||
"storageBucket": bucket_name,
|
||||
})
|
||||
|
||||
def get_firestore(sa_path: str, bucket_name: str):
|
||||
_init_firebase(sa_path, bucket_name)
|
||||
return firestore.client()
|
||||
|
||||
def get_bucket(sa_path: str, bucket_name: str):
|
||||
_init_firebase(sa_path, bucket_name)
|
||||
return fb_storage.bucket()
|
||||
|
||||
FIREBASE_AVAILABLE = True
|
||||
except Exception as _fb_err:
|
||||
print(f"[WARN] Firebase unavailable: {_fb_err}")
|
||||
FIREBASE_AVAILABLE = False
|
||||
|
||||
def get_firestore(sa_path: str, bucket_name: str):
|
||||
return None
|
||||
|
||||
def get_bucket(sa_path: str, bucket_name: str):
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def fix_pid(pid: str) -> str:
|
||||
"""Replace hyphens with underscores in a PID string."""
|
||||
return pid.replace("-", "_")
|
||||
|
||||
|
||||
def needs_fix(pid: str) -> bool:
|
||||
return pid is not None and "-" in pid
|
||||
|
||||
|
||||
def _is_binary_blob(name: str) -> bool:
|
||||
lower = (name or "").lower()
|
||||
base = lower.rsplit("/", 1)[-1]
|
||||
if "preview" in base:
|
||||
return False
|
||||
return ("binary" in base) or base.endswith(".bin") or base.endswith(".bsm")
|
||||
|
||||
|
||||
def _safe_seg(raw: str | None, fallback: str) -> str:
|
||||
value = (raw or "").strip() or fallback
|
||||
chars = []
|
||||
for ch in value:
|
||||
if ch.isalnum() or ch in ("-", "_", "."):
|
||||
chars.append(ch)
|
||||
else:
|
||||
chars.append("_")
|
||||
cleaned = "".join(chars).strip("._")
|
||||
return cleaned or fallback
|
||||
|
||||
|
||||
def _storage_prefixes(melody_id: str, melody_uid: str | None) -> list[str]:
|
||||
uid_seg = _safe_seg(melody_uid, melody_id)
|
||||
id_seg = _safe_seg(melody_id, melody_id)
|
||||
prefixes = [f"melodies/{uid_seg}/"]
|
||||
if uid_seg != id_seg:
|
||||
prefixes.append(f"melodies/{id_seg}/")
|
||||
return prefixes
|
||||
|
||||
|
||||
def _progmem_array(name: str, values: list[int], vpl: int = 8) -> str:
|
||||
array_name = f"melody_builtin_{name.lower()}"
|
||||
lines = [f"const uint16_t PROGMEM {array_name}[] = {{"]
|
||||
for i in range(0, len(values), vpl):
|
||||
chunk = values[i: i + vpl]
|
||||
hex_vals = [f"0x{v:04X}" for v in chunk]
|
||||
suffix = "," if i + len(chunk) < len(values) else ""
|
||||
lines.append(" " + ", ".join(hex_vals) + suffix)
|
||||
lines.append("};")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _parse_notation(token: str) -> int:
|
||||
token = token.strip()
|
||||
if not token or token == "0":
|
||||
return 0
|
||||
v = 0
|
||||
for part in token.split("+"):
|
||||
try:
|
||||
n = int(part.strip())
|
||||
if 1 <= n <= 16:
|
||||
v |= 1 << (n - 1)
|
||||
except ValueError:
|
||||
pass
|
||||
return v
|
||||
|
||||
|
||||
def _steps_to_values(steps: str) -> list[int]:
|
||||
return [_parse_notation(s) for s in steps.split(",")]
|
||||
|
||||
|
||||
def _regenerate_progmem(name: str, pid: str, steps: str) -> str:
|
||||
values = _steps_to_values(steps)
|
||||
array_name = f"melody_builtin_{name.lower()}"
|
||||
id_name = pid if pid else f"builtin_{name.lower()}"
|
||||
display_name = name.replace("_", " ").title()
|
||||
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
parts = [
|
||||
f"// Generated: {ts}",
|
||||
f"// Melody: {display_name} | PID: {id_name}",
|
||||
"",
|
||||
_progmem_array(name, values),
|
||||
"",
|
||||
"// --- Add this entry to your MELODY_LIBRARY[] array: ---",
|
||||
"// {",
|
||||
f'// "{display_name}",',
|
||||
f'// "{id_name}",',
|
||||
f"// {array_name},",
|
||||
f"// sizeof({array_name}) / sizeof(uint16_t)",
|
||||
"// }",
|
||||
]
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main migration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def run(dry_run: bool = False, db_path: str = ""):
|
||||
label = "[DRY-RUN]" if dry_run else "[LIVE]"
|
||||
db_path = db_path or _cfg("SQLITE_DB_PATH", "./data/database.db")
|
||||
sa_path = _cfg("FIREBASE_SERVICE_ACCOUNT_PATH", "./firebase-service-account.json")
|
||||
bucket_name = _cfg("FIREBASE_STORAGE_BUCKET")
|
||||
print(f"\n{label} Database: {db_path}")
|
||||
print(f"{label} Firebase available: {FIREBASE_AVAILABLE}, bucket: {bucket_name or '(not set)'}\n")
|
||||
|
||||
con = sqlite3.connect(db_path)
|
||||
con.row_factory = sqlite3.Row
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# Step 1: collect archetypes that need fixing
|
||||
# -----------------------------------------------------------------------
|
||||
archetypes = con.execute("SELECT * FROM built_melodies").fetchall()
|
||||
to_fix = [dict(a) for a in archetypes if needs_fix(a["pid"])]
|
||||
|
||||
if not to_fix:
|
||||
print("No archetypes with hyphens in PID found. Nothing to do.")
|
||||
con.close()
|
||||
return
|
||||
|
||||
print(f"Found {len(to_fix)} archetype(s) with hyphens in PID:\n")
|
||||
for a in to_fix:
|
||||
print(f" [{a['id'][:8]}...] '{a['pid']}' → '{fix_pid(a['pid'])}' (name: {a['name']})")
|
||||
print()
|
||||
|
||||
bucket = get_bucket(sa_path, bucket_name) if FIREBASE_AVAILABLE and bucket_name else None
|
||||
firestore_db = get_firestore(sa_path, bucket_name) if FIREBASE_AVAILABLE and bucket_name else None
|
||||
|
||||
total_melodies_updated = 0
|
||||
|
||||
for archetype in to_fix:
|
||||
old_pid = archetype["pid"]
|
||||
new_pid = fix_pid(old_pid)
|
||||
arch_id = archetype["id"]
|
||||
arch_name = archetype["name"]
|
||||
assigned_ids: list[str] = json.loads(archetype["assigned_melody_ids"] or "[]")
|
||||
|
||||
print(f"━━━ Archetype: {arch_name} ({old_pid} → {new_pid}) ━━━")
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Step 2: rename local .bsm file
|
||||
# -------------------------------------------------------------------
|
||||
old_path = Path(archetype["binary_path"]) if archetype.get("binary_path") else None
|
||||
new_path = None
|
||||
|
||||
if old_path and old_path.exists():
|
||||
new_path = old_path.parent / f"{new_pid}.bsm"
|
||||
print(f" [BSM] {old_path.name} → {new_path.name}")
|
||||
if not dry_run:
|
||||
shutil.move(str(old_path), str(new_path))
|
||||
elif old_path:
|
||||
# File expected but missing — still derive new path so DB is correct
|
||||
new_path = old_path.parent / f"{new_pid}.bsm"
|
||||
print(f" [BSM] WARNING: expected file not found: {old_path}")
|
||||
else:
|
||||
print(f" [BSM] No binary_path recorded, skipping file rename")
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Step 3 & 4: update SQLite — pid, binary_path, progmem_code
|
||||
# -------------------------------------------------------------------
|
||||
new_progmem = _regenerate_progmem(arch_name, new_pid, archetype["steps"])
|
||||
print(f" [DB] Updating archetype record in SQLite")
|
||||
if not dry_run:
|
||||
con.execute(
|
||||
"UPDATE built_melodies SET pid=?, binary_path=?, progmem_code=?, updated_at=? WHERE id=?",
|
||||
(new_pid, str(new_path) if new_path else archetype["binary_path"],
|
||||
new_progmem, datetime.utcnow().isoformat(), arch_id),
|
||||
)
|
||||
con.commit()
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# Step 5–7: update each assigned melody
|
||||
# -------------------------------------------------------------------
|
||||
if not assigned_ids:
|
||||
print(f" [MELODIES] No assigned melodies, skipping.\n")
|
||||
continue
|
||||
|
||||
print(f" [MELODIES] Processing {len(assigned_ids)} assigned melody(ies)...")
|
||||
|
||||
for melody_id in assigned_ids:
|
||||
row = con.execute("SELECT * FROM melody_drafts WHERE id=?", (melody_id,)).fetchone()
|
||||
if not row:
|
||||
print(f" [{melody_id[:8]}] WARNING: melody not found in SQLite, skipping")
|
||||
continue
|
||||
|
||||
row = dict(row)
|
||||
melody_data: dict = json.loads(row["data"]) if isinstance(row["data"], str) else row["data"]
|
||||
melody_uid = melody_data.get("uid")
|
||||
melody_pid = melody_data.get("pid", "")
|
||||
melody_url = melody_data.get("url", "")
|
||||
status = row.get("status", "draft")
|
||||
|
||||
# Determine if this melody's pid also has hyphens matching old archetype pid
|
||||
new_melody_pid = fix_pid(melody_pid) if melody_pid and "-" in melody_pid else melody_pid
|
||||
|
||||
new_url = melody_url # will be updated if Firebase succeeds
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# Firebase Storage: delete old blob, re-upload under new name
|
||||
# ---------------------------------------------------------------
|
||||
if bucket and melody_url:
|
||||
try:
|
||||
prefixes = _storage_prefixes(melody_id, melody_uid)
|
||||
primary_prefix = prefixes[0]
|
||||
|
||||
# Find and download the current binary blob
|
||||
all_blobs = []
|
||||
for prefix in prefixes:
|
||||
all_blobs.extend(list(bucket.list_blobs(prefix=prefix)))
|
||||
binary_blobs = [b for b in all_blobs if _is_binary_blob(b.name)]
|
||||
|
||||
if binary_blobs:
|
||||
# Download bytes from the first (should only be one)
|
||||
src_blob = binary_blobs[0]
|
||||
binary_bytes = src_blob.download_as_bytes()
|
||||
|
||||
new_storage_path = f"{primary_prefix}{new_pid}.bsm"
|
||||
print(f" [{melody_id[:8]}] Storage: {src_blob.name.split('/')[-1]} → {new_pid}.bsm")
|
||||
|
||||
if not dry_run:
|
||||
# Delete old blob(s)
|
||||
for b in binary_blobs:
|
||||
b.delete()
|
||||
|
||||
# Upload under new name
|
||||
new_blob = bucket.blob(new_storage_path)
|
||||
new_blob.upload_from_string(binary_bytes, content_type="application/octet-stream")
|
||||
new_blob.make_public()
|
||||
new_url = new_blob.public_url
|
||||
else:
|
||||
print(f" [{melody_id[:8]}] WARNING: no binary blob found in storage for this melody")
|
||||
|
||||
except Exception as e:
|
||||
print(f" [{melody_id[:8]}] ERROR during Firebase Storage operation: {e}")
|
||||
elif not bucket:
|
||||
print(f" [{melody_id[:8]}] Firebase not available, skipping storage rename")
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# Update melody data
|
||||
# ---------------------------------------------------------------
|
||||
changed = False
|
||||
if new_melody_pid != melody_pid:
|
||||
print(f" [{melody_id[:8]}] PID: '{melody_pid}' → '{new_melody_pid}'")
|
||||
melody_data["pid"] = new_melody_pid
|
||||
changed = True
|
||||
|
||||
if new_url != melody_url:
|
||||
print(f" [{melody_id[:8]}] URL updated")
|
||||
melody_data["url"] = new_url
|
||||
changed = True
|
||||
|
||||
if not changed and new_url == melody_url:
|
||||
print(f" [{melody_id[:8]}] No data changes needed")
|
||||
continue
|
||||
|
||||
if not dry_run:
|
||||
# Update SQLite
|
||||
con.execute(
|
||||
"UPDATE melody_drafts SET data=? WHERE id=?",
|
||||
(json.dumps(melody_data), melody_id),
|
||||
)
|
||||
con.commit()
|
||||
|
||||
# Update Firestore if published
|
||||
if status == "published" and firestore_db:
|
||||
try:
|
||||
doc_ref = firestore_db.collection("melodies").document(melody_id)
|
||||
update_fields = {}
|
||||
if new_melody_pid != melody_pid:
|
||||
update_fields["pid"] = new_melody_pid
|
||||
if new_url != melody_url:
|
||||
update_fields["url"] = new_url
|
||||
if update_fields:
|
||||
doc_ref.update(update_fields)
|
||||
print(f" [{melody_id[:8]}] Firestore updated")
|
||||
except Exception as e:
|
||||
print(f" [{melody_id[:8]}] ERROR updating Firestore: {e}")
|
||||
elif status == "published" and not firestore_db:
|
||||
print(f" [{melody_id[:8]}] WARNING: melody is published but Firestore unavailable!")
|
||||
|
||||
total_melodies_updated += 1
|
||||
|
||||
print()
|
||||
|
||||
con.close()
|
||||
print(f"{'━'*60}")
|
||||
print(f"{label} Done. Archetypes fixed: {len(to_fix)}, Melody records updated: {total_melodies_updated}")
|
||||
if dry_run:
|
||||
print("\nThis was a dry run. No changes were made. Run without --dry-run to apply.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Migrate archetype/melody PIDs: replace hyphens with underscores")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Preview changes without writing anything")
|
||||
parser.add_argument("--db", default="", help="Override SQLite database path (default: read from .env)")
|
||||
args = parser.parse_args()
|
||||
run(dry_run=args.dry_run, db_path=args.db)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
Make every device's `device_users` sub-collection mirror its `user_list`.
|
||||
|
||||
`user_list` is the source of truth for device assignments. The Console keeps
|
||||
`device_users` ({role, user_reference}) only as a write-only mirror in case the
|
||||
phone app still reads it. Before 2026-11 the Console read `device_users` first
|
||||
and never wrote it, so the two drifted. This script lists the drift and, with
|
||||
--apply, fixes the mirror:
|
||||
|
||||
- users in user_list with no device_users doc -> doc added (role "admin")
|
||||
- device_users docs for users NOT in user_list -> doc deleted
|
||||
|
||||
It never changes `user_list` or `device_serials`. Check the dry-run output
|
||||
first: if a user only appears in device_users and should keep the device,
|
||||
assign them in the Console (Manage tab) before running --apply, or they will be
|
||||
dropped from the mirror. Running it twice is a no-op the second time.
|
||||
|
||||
Run from backend/ (locally or inside the backend container):
|
||||
|
||||
python scripts/sync_device_users_mirror.py # dry run
|
||||
python scripts/sync_device_users_mirror.py --apply # write changes
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from shared.firebase import init_firebase, get_db # noqa: E402
|
||||
from devices.service import ( # noqa: E402
|
||||
DEFAULT_DEVICE_USER_ROLE, DEVICE_USERS_SUBCOLLECTION, device_users_by_user, user_list_entry_id,
|
||||
)
|
||||
|
||||
BATCH_SIZE = 400 # Firestore batch limit is 500 writes
|
||||
|
||||
|
||||
def _label(db, uid: str) -> str:
|
||||
snap = db.collection("users").document(uid).get()
|
||||
if not snap.exists:
|
||||
return f"{uid} (no user doc)"
|
||||
data = snap.to_dict() or {}
|
||||
return f"{uid} ({data.get('display_name') or data.get('email') or '?'})"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--apply", action="store_true", help="write changes (default: dry run)")
|
||||
args = parser.parse_args()
|
||||
|
||||
init_firebase()
|
||||
db = get_db()
|
||||
if db is None:
|
||||
print("[ERROR] Firebase not initialized — check FIREBASE_SERVICE_ACCOUNT_PATH")
|
||||
return 1
|
||||
|
||||
print(f"=== sync device_users mirror — {'APPLY' if args.apply else 'DRY RUN'} ===")
|
||||
writes = [] # (op, ref, data)
|
||||
for dev in db.collection("devices").stream():
|
||||
data = dev.to_dict() or {}
|
||||
wanted = {user_list_entry_id(e) for e in data.get("user_list") or []} - {""}
|
||||
mirror = device_users_by_user(dev.reference)
|
||||
to_add = sorted(u for u in wanted - mirror.keys()
|
||||
if db.collection("users").document(u).get().exists)
|
||||
to_del = sorted(mirror.keys() - wanted)
|
||||
if not to_add and not to_del:
|
||||
continue
|
||||
serial = data.get("serial_number") or data.get("device_id") or "?"
|
||||
print(f"\n{dev.id} {serial} {data.get('device_name') or ''}")
|
||||
for u in to_add:
|
||||
print(f" + add mirror {_label(db, u)}")
|
||||
writes.append(("set", dev.reference.collection(DEVICE_USERS_SUBCOLLECTION).document(), {
|
||||
"role": DEFAULT_DEVICE_USER_ROLE,
|
||||
"user_reference": db.collection("users").document(u),
|
||||
}))
|
||||
for u in to_del:
|
||||
print(f" - remove mirror {_label(db, u)} <- only in device_users, not in user_list")
|
||||
writes.extend(("delete", snap.reference, None) for snap in mirror[u])
|
||||
|
||||
print(f"\n{len(writes)} write(s) needed.")
|
||||
if not args.apply or not writes:
|
||||
if writes:
|
||||
print("Dry run — nothing written. Re-run with --apply to write.")
|
||||
return 0
|
||||
|
||||
for i in range(0, len(writes), BATCH_SIZE):
|
||||
batch = db.batch()
|
||||
for op, ref, payload in writes[i:i + BATCH_SIZE]:
|
||||
batch.set(ref, payload) if op == "set" else batch.delete(ref)
|
||||
batch.commit()
|
||||
print("Done.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user