rpg-westreiche/tools/build_item_catalog.py
torsten 5f01146d4b Charakterverwalter: Ausrüstungskatalog mit Selektor im Inventar
- data/item_catalog.csv als kuratierbare Master-Liste (481 Gegenstände nach
  OSE-Kernlisten plus Hausrat, Handel und Schatz), Preise in Silbertalern
  (OSE-Goldmünzen 1:1), Art aus WS_ITEM_CATEGORIES, Verfügbarkeit gestaffelt
  (Methaven/Garana/selten)
- tools/build_item_catalog.py erzeugt app/item_catalog_data.php und
  sql/seed_items.sql; item_catalog_sync() spiegelt den Katalog in die neue
  Tabelle item_catalog (Migration 3)
- Selektor-Dialog im Inventar filtert serverseitig nach Art, Verfügbarkeit und
  Suche (GET item_kind/item_avail/item_q) und übernimmt die Auswahl als
  Inventarzeile (POST /characters/{id}/items/from-catalog)
- Admin-Ansicht Ausrüstung listet den Katalog und liest die CSV neu ein
2026-11-21 14:31:29 +01:00

141 lines
5.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Baut den Ausrüstungskatalog für den Charakterverwalter.
Quelle ist die kuratierbare Tabelle ``westreiche_website/data/item_catalog.csv``
(Spalten: name;kind;cost_sm;weight;availability;note). Daraus entstehen zwei
Artefakte im App-Verzeichnis:
* ``app/item_catalog_data.php`` – PHP-Array, aus dem ``item_catalog_sync()``
den Katalog in die Datenbank spiegelt (Upsert über den Namen).
* ``sql/seed_items.sql`` – INSERT-Statements für Neuinstallationen/CLI.
Preise: Die Werte sind **Silbertaler** (OSE-Goldmünzen 1:1 übernommen).
python3 tools/build_item_catalog.py
"""
from __future__ import annotations
import csv
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
APP = ROOT / "westreiche_website"
CSV_PATH = APP / "data" / "item_catalog.csv"
PHP_OUT = APP / "app" / "item_catalog_data.php"
SQL_OUT = APP / "sql" / "seed_items.sql"
KINDS = ["Waffe", "Rüstung", "Schild", "Ausrüstung", "Verbrauch", "Schatz", "Sonstiges"]
AVAILABILITY = ["methaven", "garana", "selten"]
def read_rows() -> list[dict[str, str]]:
"""CSV lesen, validieren und in Bogen-Reihenfolge sortieren."""
rows: list[dict[str, str]] = []
seen: set[str] = set()
with CSV_PATH.open(encoding="utf-8", newline="") as handle:
for number, raw in enumerate(csv.DictReader(handle, delimiter=";"), start=2):
name = (raw.get("name") or "").strip()
if not name or name.startswith("#"):
continue
kind = (raw.get("kind") or "").strip()
availability = (raw.get("availability") or "").strip()
if kind not in KINDS:
raise SystemExit(f"Zeile {number}: unbekannte Art „{kind}“ ({name})")
if availability not in AVAILABILITY:
raise SystemExit(f"Zeile {number}: unbekannte Verfügbarkeit „{availability}“ ({name})")
if name.lower() in seen:
raise SystemExit(f"Zeile {number}: doppelter Name „{name}“")
seen.add(name.lower())
try:
cost = float((raw.get("cost_sm") or "0").replace(",", ".") or 0)
except ValueError as error:
raise SystemExit(f"Zeile {number}: Preis unlesbar ({name})") from error
rows.append(
{
"name": name,
"kind": kind,
"cost": cost,
"weight": (raw.get("weight") or "").strip(),
"availability": availability,
"note": (raw.get("note") or "").strip(),
}
)
rows.sort(key=lambda row: (KINDS.index(row["kind"]), row["cost"], row["name"].lower()))
return rows
def php_string(value: str) -> str:
return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
def write_php(rows: list[dict[str, object]]) -> None:
lines = [
"<?php",
"declare(strict_types=1);",
"",
"/**",
" * Westreiche – Ausrüstungskatalog (generiert).",
" *",
" * Quelle: westreiche_website/data/item_catalog.csv – dort kuratieren und",
" * anschließend „python3 tools/build_item_catalog.py“ laufen lassen.",
" * Preise in Silbertalern (OSE-Goldmünzen 1:1).",
" *",
" * @return list<array{name:string,kind:string,cost:float,weight:string,availability:string,note:string}>",
" */",
"function item_catalog_data(): array",
"{",
" return [",
]
for row in rows:
lines.append(
" ["
f"'name' => {php_string(row['name'])}, "
f"'kind' => {php_string(row['kind'])}, "
f"'cost' => {row['cost']:.2f}, "
f"'weight' => {php_string(row['weight'])}, "
f"'availability' => {php_string(row['availability'])}, "
f"'note' => {php_string(row['note'])}],"
)
lines += [" ];", "}", ""]
PHP_OUT.write_text("\n".join(lines), encoding="utf-8")
def sql_string(value: str) -> str:
return "'" + value.replace("\\", "\\\\").replace("'", "''") + "'"
def write_sql(rows: list[dict[str, object]]) -> None:
header = [
"-- Westreiche – Ausrüstungskatalog (generiert von tools/build_item_catalog.py).",
"-- Quelle: westreiche_website/data/item_catalog.csv. Preise in Silbertalern.",
"-- INSERT ... ON DUPLICATE KEY UPDATE, damit ein erneuter Lauf nichts doppelt anlegt.",
"",
]
statements: list[str] = []
for order, row in enumerate(rows, start=1):
statements.append(
"INSERT INTO item_catalog (name, kind, cost, weight, availability, note, sort_order) VALUES ("
f"{sql_string(str(row['name']))}, {sql_string(str(row['kind']))}, {row['cost']:.2f}, "
f"{sql_string(str(row['weight']))}, {sql_string(str(row['availability']))}, "
f"{sql_string(str(row['note']))}, {order * 10}) "
"ON DUPLICATE KEY UPDATE kind = VALUES(kind), cost = VALUES(cost), weight = VALUES(weight), "
"availability = VALUES(availability), note = VALUES(note), sort_order = VALUES(sort_order);"
)
SQL_OUT.write_text("\n".join(header + statements) + "\n", encoding="utf-8")
def main() -> int:
if not CSV_PATH.is_file():
print(f"Katalogdatei fehlt: {CSV_PATH}", file=sys.stderr)
return 1
rows = read_rows()
write_php(rows)
write_sql(rows)
print(f"{len(rows)} Gegenstände geschrieben: {PHP_OUT.name}, {SQL_OUT.name}")
return 0
if __name__ == "__main__":
raise SystemExit(main())