velxio/backend/app/models/project.py

44 lines
2.3 KiB
Python
Raw Normal View History

import uuid
from datetime import datetime, timezone
2026-04-26 05:46:52 +07:00
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.session import Base
class Project(Base):
__tablename__ = "projects"
__table_args__ = (UniqueConstraint("user_id", "slug", name="uq_user_slug"),)
id: Mapped[str] = mapped_column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
user_id: Mapped[str] = mapped_column(String, ForeignKey("users.id"), nullable=False, index=True)
name: Mapped[str] = mapped_column(String(120), nullable=False)
slug: Mapped[str] = mapped_column(String(120), nullable=False)
description: Mapped[str | None] = mapped_column(String(500), nullable=True)
is_public: Mapped[bool] = mapped_column(Boolean, default=True)
board_type: Mapped[str] = mapped_column(String(50), default="arduino-uno")
code: Mapped[str] = mapped_column(Text, default="")
components_json: Mapped[str] = mapped_column(Text, default="[]")
wires_json: Mapped[str] = mapped_column(Text, default="[]")
feat: persist multi-board projects + add auto-save The project save/load pipeline only persisted a single `board_type`, so multi-board workspaces silently lost every board except the active one on save, and wires referencing the dropped boards' IDs orphaned to the canvas corner on reload. An audit of the production backup found 74/306 projects (24%) with at least one orphaned wire and 174/301 non-trivial projects whose code was still the default Blink template — strong signal that users save once and never re-save. Backend - Add `boards_json` column on `projects` with idempotent ALTER TABLE in the lifespan migration list. - New `FileGroup` schema + `file_groups` array on ProjectCreate/Update/Response. Legacy `files`/`code` kept for back-compat. - `project_files.py` now uses `{pid}/{groupId}/{filename}` subdirs via `read_groups`/`write_groups`. Legacy flat layouts are auto-promoted on read; legacy single-list `files` only updates the active group, leaving other boards' files intact. - `_persist_files_from_body` honors file_groups → files → code priority. Frontend - `useSimulatorStore.addBoard` accepts an optional `explicitId` so saved board IDs can be restored verbatim (wires reference IDs literally). - New `loadProjectState({boards, fileGroups, components, wires, activeBoardId})` action: tears down current boards, recreates from the payload, restores file groups atomically, recalculates wire positions on the next frame, and refreshes the Interconnect. - `useEditorStore.replaceFileGroups` for atomic multi-group restore. - `SaveProjectModal` and `ProjectByIdPage`/`ProjectPage` now go through `buildSavePayload` / `buildLoadPayload` (handles pre-backfill projects by synthesising a default board from `board_type`). Auto-save (#useAutoSaveProject hook) - 2.5s debounced silent PUT triggered ONLY when an authenticated user has a `currentProject` with a UUID. State hash detects real changes vs. UI-only churn; baseline is reset on project load so the just-loaded state isn't immediately re-saved. - `beforeunload` flush via `fetch keepalive: true` (supports PUT + credentials, survives unload). - Compact status indicator in `AppHeader` (idle/dirty/saving/saved/error). Backfill script (one-off, idempotent) - `backend/scripts/backfill_boards_2026_05.py` populates `boards_json` for legacy projects. Heuristic per project, based on which board IDs the wires reference: Case A — wires only ref 'arduino-uno' but board_type ≠ uno: rename id→board_type and rewrite wire endpoints. Case B — single-board normal: keep verbatim. Case C — multi-board: recreate one board per distinct ref, infer kind by stripping trailing -N suffix. Also moves any flat files into the active board's group subdir. Stdlib-only, runs from host or `docker exec`. Docker - `Dockerfile.standalone` now copies `backend/scripts/` into the image so the backfill is callable via `docker exec velxio-app python /app/scripts/backfill_boards_2026_05.py --apply`. Verified locally on the restored production backup (363 projects): 33 Case A, 316 Case B, 14 Case C, 135 wire endpoints renamed, 0 orphans. Re-running the script after apply skips all 363 (idempotent). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 23:43:33 +07:00
# Multi-board state — array of {id, boardKind, x, y, activeFileGroupId, ...}
boards_json: Mapped[str] = mapped_column(Text, default="[]")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
onupdate=lambda: datetime.now(timezone.utc),
)
2026-04-26 05:46:52 +07:00
# Aggregate usage counters (kept in sync by MetricsService for O(1) reads)
compile_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
compile_error_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
run_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
update_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
last_compiled_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_run_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
owner: Mapped["User"] = relationship("User", back_populates="projects") # noqa: F821