"""Application configuration: code vs persistent user data. Layout (portable-friendly):: /app/ application code, templates, template_docs /data/ persistent user data (never shipped in the app package) work_tracker.db SQLite database uploads/ Excel imports and project-import archives storage/ document artifacts and Daily Report photos /backups/ pre-migration and manual backup archives Overrides (environment): WORK_TRACKER_DATA_DIR data root (default /data) DOCUMENT_STORAGE_ROOT storage root (default /storage) WORK_TRACKER_BACKUPS_DIR backups root (default /backups) Legacy locations (pre-portable tree) are copied into the new layout once by :meth:`migrate_legacy_data`. Sources are never deleted. """ from __future__ import annotations import os import shutil import sqlite3 from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path APP_DIR = Path(__file__).resolve().parent PROJECT_ROOT = APP_DIR.parent ENV_DATA_DIR = "WORK_TRACKER_DATA_DIR" ENV_DOCUMENT_STORAGE_ROOT = "DOCUMENT_STORAGE_ROOT" ENV_BACKUPS_DIR = "WORK_TRACKER_BACKUPS_DIR" # Legacy locations kept only as migration sources. _LEGACY_DATABASE_PATH = APP_DIR / "database" / "work_tracker.db" _LEGACY_UPLOADS_DIR = APP_DIR / "uploads" _LEGACY_STORAGE_DIR = PROJECT_ROOT / "storage" def data_root() -> Path: """Persistent user-data root (DB, uploads, storage).""" override = os.environ.get(ENV_DATA_DIR, "").strip() if override: return Path(override).expanduser().resolve() return (PROJECT_ROOT / "data").resolve() def database_path() -> Path: return data_root() / "work_tracker.db" def uploads_dir() -> Path: return data_root() / "uploads" def import_uploads_dir() -> Path: return uploads_dir() / "project_import" def document_storage_root() -> Path: """Document/photo storage root without creating it. DOCUMENT_STORAGE_ROOT keeps its historical meaning and wins over the default data-root layout so existing tests and deployments keep working. """ override = os.environ.get(ENV_DOCUMENT_STORAGE_ROOT, "").strip() if override: return Path(override).expanduser().resolve() return (data_root() / "storage").resolve() def backups_dir() -> Path: override = os.environ.get(ENV_BACKUPS_DIR, "").strip() if override: return Path(override).expanduser().resolve() return (PROJECT_ROOT / "backups").resolve() def ensure_data_layout() -> None: """Create the persistent data directories. Idempotent.""" data_root().mkdir(parents=True, exist_ok=True) uploads_dir().mkdir(parents=True, exist_ok=True) import_uploads_dir().mkdir(parents=True, exist_ok=True) document_storage_root().mkdir(parents=True, exist_ok=True) backups_dir().mkdir(parents=True, exist_ok=True) @dataclass class MigrationReport: """Outcome of one idempotent legacy → data/ migration pass.""" db_copied: bool = False uploads_copied: int = 0 storage_copied: int = 0 backup_path: str | None = None skipped: bool = False notes: list[str] = field(default_factory=list) errors: list[str] = field(default_factory=list) @property def ok(self) -> bool: return not self.errors def _copy_file_safe(src: Path, dest: Path, report: MigrationReport) -> bool: """Copy one file without overwriting an existing destination.""" if dest.exists(): report.notes.append(f"skip existing {dest}") return False dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dest) return True def _copy_tree_safe(src: Path, dest: Path, report: MigrationReport) -> int: """Copy files from src to dest without overwriting existing files.""" if not src.is_dir(): return 0 copied = 0 for path in src.rglob("*"): if path.is_dir(): continue rel = path.relative_to(src) target = dest / rel if target.exists(): continue target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, target) copied += 1 return copied def _sqlite_integrity_ok(db_file: Path) -> tuple[bool, str]: """Open a SQLite file read-only and run integrity_check.""" try: uri = db_file.resolve().as_uri() + "?mode=ro" conn = sqlite3.connect(uri, uri=True) try: row = conn.execute("PRAGMA integrity_check").fetchone() ok = bool(row) and str(row[0]).lower() == "ok" return ok, str(row[0]) if row else "empty result" finally: conn.close() except sqlite3.Error as exc: return False, f"{type(exc).__name__}: {exc}" def _backup_legacy_sources(legacy_db: Path, report: MigrationReport) -> Path | None: """Snapshot legacy DB (+WAL/SHM) into backups/ before copying.""" if not legacy_db.is_file(): return None stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") dest = backups_dir() / f"pre-migrate-{stamp}" dest.mkdir(parents=True, exist_ok=True) for name in (legacy_db.name, legacy_db.name + "-wal", legacy_db.name + "-shm"): src = legacy_db.parent / name if src.is_file(): shutil.copy2(src, dest / name) report.backup_path = str(dest) return dest def migrate_legacy_data() -> MigrationReport: """Copy legacy DB/uploads/storage into the new data layout. Idempotent. Safety rules: - never delete or overwrite sources; - never overwrite an existing file in the destination; - snapshot the legacy database into backups/ before copying; - verify the copied database with PRAGMA integrity_check; - on verification failure the destination copy is removed and the source is left untouched. """ report = MigrationReport() ensure_data_layout() dest_db = database_path() # --- database --- if dest_db.is_file(): report.skipped = True report.notes.append(f"destination DB already present: {dest_db}") elif _LEGACY_DATABASE_PATH.is_file(): _backup_legacy_sources(_LEGACY_DATABASE_PATH, report) sidecars = [ _LEGACY_DATABASE_PATH, Path(str(_LEGACY_DATABASE_PATH) + "-wal"), Path(str(_LEGACY_DATABASE_PATH) + "-shm"), ] try: for src in sidecars: if src.is_file(): target = dest_db.parent / src.name if _copy_file_safe(src, target, report): if src.name == _LEGACY_DATABASE_PATH.name: report.db_copied = True if report.db_copied: ok, detail = _sqlite_integrity_ok(dest_db) if not ok: # Roll back only the copy we just made; source stays. for name in ( dest_db.name, dest_db.name + "-wal", dest_db.name + "-shm", ): p = dest_db.parent / name if p.is_file(): p.unlink() report.db_copied = False report.errors.append(f"integrity_check failed for copied DB: {detail}") else: report.notes.append(f"integrity_check ok: {dest_db}") except OSError as exc: report.errors.append(f"database copy failed: {type(exc).__name__}: {exc}") else: report.notes.append("no legacy database; fresh data directory") # --- uploads --- try: report.uploads_copied = _copy_tree_safe(_LEGACY_UPLOADS_DIR, uploads_dir(), report) except OSError as exc: report.errors.append(f"uploads copy failed: {type(exc).__name__}: {exc}") # --- storage --- # Prefer the configured storage root as destination; if the user pointed # DOCUMENT_STORAGE_ROOT outside data/, still copy into that root. try: dest_storage = document_storage_root() report.storage_copied = _copy_tree_safe(_LEGACY_STORAGE_DIR, dest_storage, report) except OSError as exc: report.errors.append(f"storage copy failed: {type(exc).__name__}: {exc}") return report