53 lines
1.6 KiB
Python
53 lines
1.6 KiB
Python
"""Small, local GUI preferences for the active Blueforce identity."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from bfos.operations import dealer_is_valid
|
||
|
||
PREFERENCES_FILENAME = "blueforce-gui.json"
|
||
|
||
|
||
def preferences_path() -> Path:
|
||
base = os.environ.get("XDG_CONFIG_HOME")
|
||
if base:
|
||
return Path(base) / "blueforce" / PREFERENCES_FILENAME
|
||
return Path.home() / ".config" / "blueforce" / PREFERENCES_FILENAME
|
||
|
||
|
||
def load_preferences(path: Path | None = None) -> dict[str, str]:
|
||
target = path or preferences_path()
|
||
try:
|
||
data: Any = json.loads(target.read_text(encoding="utf-8"))
|
||
except (OSError, ValueError):
|
||
return {}
|
||
if not isinstance(data, dict):
|
||
return {}
|
||
dealer = str(data.get("dealer_id", "")).strip()
|
||
if not dealer_is_valid(dealer):
|
||
return {}
|
||
return {"dealer_id": dealer, "active_user": f"bf-{dealer}"}
|
||
|
||
|
||
def save_dealer(dealer_id: str, path: Path | None = None) -> dict[str, str]:
|
||
if not dealer_is_valid(dealer_id):
|
||
raise ValueError("Bayi numarası tam 8 rakam olmalıdır.")
|
||
target = path or preferences_path()
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
data = {"dealer_id": dealer_id, "active_user": f"bf-{dealer_id}"}
|
||
temporary = target.with_suffix(target.suffix + ".tmp")
|
||
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||
os.replace(temporary, target)
|
||
return data
|
||
|
||
|
||
def clear_dealer(path: Path | None = None) -> None:
|
||
target = path or preferences_path()
|
||
try:
|
||
target.unlink()
|
||
except FileNotFoundError:
|
||
pass
|