170 build - переименование Input и привязка

This commit is contained in:
2026-09-29 12:45:28 +03:00
parent cd1817e10f
commit bd0c86a85a
5 changed files with 352 additions and 99 deletions

3
app.py
View File

@@ -35,7 +35,7 @@ from khl_site.khl_data_center import APP as khl_site_app, configure_storage, syn
from hockey_data.khl_career import KhlCareerService
BASE_DIR = Path(__file__).resolve().parent
BUILD_VERSION = "2026.09.29.6"
BUILD_VERSION = "2026.09.29.7"
# compatibility: BUILD_VERSION = "2026.09.24.2"
# compatibility: BUILD_VERSION = "2026.09.23.8"
# compatibility: BUILD_VERSION = "2026.09.23.7"
@@ -180,6 +180,7 @@ async def hockey_mapping_auto_refresh_startup() -> None:
await run_db(sync_storage)
# BUILD151: isolated per-second schedule polling writes only to schedule_live.
await run_db(hockey_service.ensure_schedule_live_table)
await run_db(hockey_agent_hub.migrate_mapping_titles)
await run_db(hockey_agent_hub.mapping_data.ensure_defaults)
hockey_agent_hub.start_auto_refresh()
hockey_idle_matches.start()

View File

@@ -64,6 +64,24 @@ def _mapping_value_function(field_type: Any) -> str:
return "SetText"
def _mapping_inputs(value: Any) -> list[dict[str, Any]]:
try:
value = json.loads(value or "{}") if isinstance(value, str) else value
return [item for item in (value or {}).get("inputs", []) if isinstance(item, dict)]
except (ValueError, TypeError, AttributeError):
return []
def _mapping_title_error(title: str, inputs: list[dict[str, Any]]) -> str:
if not title.strip():
return "Не задано название Input"
if re.fullmatch(r"[+-]?\d+|\{?[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\}?", title):
return "Для привязки по имени название Input должно отличаться от номера и GUID"
if sum(str(item.get("title") or "") == title for item in inputs) > 1:
return f"Несколько Inputs с названием «{title}». Задайте уникальные названия в vMix"
return ""
def _mapping_rule_payload(value: Any) -> dict[str, Any]:
if isinstance(value, dict):
return dict(value)
@@ -612,7 +630,7 @@ class VmixAgentHub:
@staticmethod
def _inventory_target_pairs(value: Any) -> set[tuple[str, str]]:
"""Return stable ``(Input key, field name)`` pairs from an inventory."""
"""Return unique ``(Input title, field name)`` pairs from an inventory."""
try:
payload = json.loads(str(value or "{}")) if not isinstance(value, dict) else value
except Exception:
@@ -622,8 +640,8 @@ class VmixAgentHub:
for item in inputs:
if not isinstance(item, dict):
continue
input_key = str(item.get("key") or "").strip()
if not input_key:
input_key = str(item.get("title") or "")
if not input_key or sum(str(other.get("title") or "") == input_key for other in inputs if isinstance(other, dict)) != 1:
continue
fields = item.get("fields") if isinstance(item.get("fields"), list) else []
for field in fields:
@@ -638,7 +656,7 @@ class VmixAgentHub:
"""Recover a profile when the project changed only in unrelated Inputs.
A profile is considered compatible only when *all* enabled mapped targets
identified by stable vMix Input keys still exist in the current project. If
identified by exact vMix Input titles still exist in the current project. If
several profiles tie for the best coverage we deliberately do not guess.
"""
current_pairs = self._inventory_target_pairs(device.project_inventory_json)
@@ -657,11 +675,11 @@ class VmixAgentHub:
))
))
targets = {
(str(row.vmix_input_key or "").strip(), str(row.vmix_field or "").strip())
(str(row.vmix_input_title or "").strip(), str(row.vmix_field or "").strip())
for row in rows
if str(row.vmix_input_key or "").strip() and str(row.vmix_field or "").strip()
if str(row.vmix_input_title or "").strip() and str(row.vmix_field or "").strip()
}
if not targets or not targets.issubset(current_pairs):
if not targets or any(not row.vmix_input_title for row in rows) or not targets.issubset(current_pairs):
continue
candidates.append((len(targets), profile))
if not candidates:
@@ -1620,6 +1638,7 @@ class VmixAgentHub:
profile_id = profile.id
profile_name = profile.name
profile_version = profile.version
target_inputs = _mapping_inputs(device.project_inventory_json) or _mapping_inputs(profile.inventory_json)
user = HockeyUser(id=user_id, login=login or user_id, display_name=login or user_id)
supplied_context = {
@@ -1728,7 +1747,11 @@ class VmixAgentHub:
continue
raw_value = item.get("value", "")
value = "" if raw_value is None else str(raw_value)
input_ref = str(field.vmix_input_key or field.vmix_input_title or field.vmix_input_number or "").strip()
input_ref = str(field.vmix_input_title or "")
title_error = _mapping_title_error(input_ref, target_inputs)
if title_error:
result["errors"].append({"key": data_key, "reason": title_error})
continue
selected_name = str(field.vmix_field or "").strip()
if not input_ref or not selected_name:
result["errors"].append({"key": data_key, "reason": "missing_vmix_target"})
@@ -2309,7 +2332,7 @@ class VmixAgentHub:
switched games.
"""
device_id = self.normalise_device_id(device_id)
input_ref = str(input_ref or "").strip()
input_ref = str(input_ref or "")
selected_name = str(selected_name or "").strip()
value = str(value or "")
field_type = str(field_type or "text").strip().lower()
@@ -2325,6 +2348,9 @@ class VmixAgentHub:
device = session.scalar(select(VmixDevice).where(VmixDevice.device_uuid == device_id))
if device is None:
raise HTTPException(status_code=404, detail="Agent не найден")
title_error = _mapping_title_error(input_ref, _mapping_inputs(device.project_inventory_json))
if title_error:
raise HTTPException(422, title_error)
assignment_id = str(device.current_assignment_key or "")
match_id = str(device.current_match_external_id or "")
if not assignment_id or not match_id:
@@ -2376,8 +2402,8 @@ class VmixAgentHub:
raise HTTPException(status_code=409, detail="У этого Agent сейчас не назначен матч")
if not device.vmix_connected:
raise HTTPException(status_code=409, detail="vMix этого Agent сейчас не подключён")
return agent_version, assignment_id, match_id
agent_version, assignment_id, match_id = await run_db(load_assignment)
return agent_version, assignment_id, match_id, _mapping_inputs(device.project_inventory_json)
agent_version, assignment_id, match_id, target_inputs = await run_db(load_assignment)
result: dict[str, Any] = {
"ok": True, "device_id": device_id, "assignment_id": assignment_id,
@@ -2386,7 +2412,11 @@ class VmixAgentHub:
}
prepared: list[dict[str, Any]] = []
for index, item in enumerate(commands):
input_ref = str(getattr(item, "input", "") or "").strip()
input_ref = str(getattr(item, "input", "") or "")
title_error = _mapping_title_error(input_ref, target_inputs)
if title_error:
result["errors"].append({"index": index, "reason": title_error})
continue
selected_name = str(getattr(item, "selected_name", "") or "").strip()
value = str(getattr(item, "value", "") or "")
field_type = str(getattr(item, "field_type", "text") or "text").strip().lower()
@@ -3332,8 +3362,8 @@ class VmixAgentHub:
fields = [field for field in fields if str(field.data_key or "").startswith(prefix)]
grouped: dict[str, dict[str, Any]] = {}
for field in fields:
identity = str(field.vmix_input_key or field.vmix_input_title or field.vmix_input_number or "").strip()
if not identity:
identity = str(field.vmix_input_title or "")
if _mapping_title_error(identity, _mapping_inputs(inventory)):
continue
item = grouped.setdefault(identity, {
"key": str(field.vmix_input_key or ""),
@@ -3343,7 +3373,7 @@ class VmixAgentHub:
})
item["mapped_fields"] += 1
for item in grouped.values():
found = self._prepared_find_input(inventory, key=item["key"], number=item["number"], title=item["title"])
found = next((entry for entry in _mapping_inputs(inventory) if entry.get("title") == item["title"]), None)
if found is not None:
item.update({
"key": str(found.get("key") or item["key"]),
@@ -3371,10 +3401,13 @@ class VmixAgentHub:
profile, context, inventory = self._prepared_mapping_context(session, device, user)
if profile is None:
return {"device_id": device.device_uuid, "profile_id": 0, "fields": []}
source = self._prepared_find_input(inventory, key=input_key, number=input_number, title=input_title)
source_key = str(source.get("key") or input_key or "") if source else str(input_key or "")
source_number = str(source.get("number") or input_number or "") if source else str(input_number or "")
source_title = str(source.get("title") or input_title or "") if source else str(input_title or "")
source_title = str(input_title or "")
title_error = _mapping_title_error(source_title, _mapping_inputs(inventory))
if title_error:
raise HTTPException(422, title_error)
source = next((entry for entry in _mapping_inputs(inventory) if entry.get("title") == source_title), None)
source_key = str(source.get("key") or "") if source else ""
source_number = str(source.get("number") or "") if source else ""
fields = list(session.scalars(
select(VmixMappingField)
.where(and_(VmixMappingField.profile_id == profile.id, VmixMappingField.enabled.is_(True)))
@@ -3384,13 +3417,7 @@ class VmixAgentHub:
prefix = f"player_select.{panel_id}."
fields = [field for field in fields if str(field.data_key or "").startswith(prefix)]
def target_matches(field: VmixMappingField) -> bool:
if source_key and str(field.vmix_input_key or "") == source_key:
return True
if source_title and str(field.vmix_input_title or "") == source_title:
return True
if source_number and str(field.vmix_input_number or "") == source_number:
return True
return False
return str(field.vmix_input_title or "") == source_title
fields = [field for field in fields if target_matches(field)]
catalog = self.mapping_data.data_catalog(user, context)
by_key = {str(item.get("key") or ""): item for item in (catalog.get("items") or []) if item.get("key")}
@@ -3776,28 +3803,13 @@ class VmixAgentHub:
fields: list[dict[str, Any]],
inventory: dict[str, Any],
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Rebind saved Mapping targets to another vMix project inventory.
Resolution order is deliberately conservative: stable Input key first,
then a unique title, then a unique positional number as a legacy fallback.
The selected vMix field itself must also exist on the resolved Input.
"""
inputs = inventory.get("inputs") if isinstance(inventory, dict) and isinstance(inventory.get("inputs"), list) else []
by_key: dict[str, dict[str, Any]] = {}
"""Match exact Input titles; never guess by GUID or positional number."""
inputs = _mapping_inputs(inventory)
by_title: dict[str, list[dict[str, Any]]] = {}
by_number: dict[str, list[dict[str, Any]]] = {}
for item in inputs:
if not isinstance(item, dict):
continue
key = str(item.get("key") or "").strip()
title = cls._portable_text(item.get("title"))
number = str(item.get("number") or "").strip()
if key:
by_key[key] = item
title = str(item.get("title") or "")
if title:
by_title.setdefault(title, []).append(item)
if number:
by_number.setdefault(number, []).append(item)
rebound: list[dict[str, Any]] = []
skipped: list[dict[str, Any]] = []
@@ -3814,30 +3826,13 @@ class VmixAgentHub:
skipped.append({"index": index, "data_key": data_key, "vmix_field": vmix_field, "reason": "missing_mapping_key"})
continue
source_key = str(raw.get("vmix_input_key") or "").strip()
source_title = str(raw.get("vmix_input_title") or "").strip()
source_number = str(raw.get("vmix_input_number") or "").strip()
target = by_key.get(source_key) if source_key else None
resolution = "key" if target is not None else ""
if target is None and source_title:
title_matches = by_title.get(cls._portable_text(source_title), [])
if len(title_matches) == 1:
target = title_matches[0]
resolution = "title"
elif len(title_matches) > 1:
skipped.append({"index": index, "data_key": data_key, "input": source_title, "vmix_field": vmix_field, "reason": "ambiguous_input_title"})
continue
if target is None and source_number:
number_matches = by_number.get(source_number, [])
if len(number_matches) == 1:
target = number_matches[0]
resolution = "number"
elif len(number_matches) > 1:
skipped.append({"index": index, "data_key": data_key, "input": source_number, "vmix_field": vmix_field, "reason": "ambiguous_input_number"})
continue
if target is None:
skipped.append({"index": index, "data_key": data_key, "input": source_title or source_key or source_number, "vmix_field": vmix_field, "reason": "input_not_found"})
source_title = str(raw.get("vmix_input_title") or "")
title_matches = by_title.get(source_title, [])
if len(title_matches) != 1 or _mapping_title_error(source_title, inputs):
skipped.append({"index": index, "data_key": data_key, "input": source_title,
"vmix_field": vmix_field, "reason": "ambiguous_input_title" if len(title_matches) > 1 else "input_title_not_found"})
continue
target, resolution = title_matches[0], "title"
target_fields = target.get("fields") if isinstance(target.get("fields"), list) else []
exact = next((f for f in target_fields if isinstance(f, dict) and str(f.get("name") or "").strip() == vmix_field), None)
@@ -3857,7 +3852,7 @@ class VmixAgentHub:
continue
target_key = str(target.get("key") or "").strip()
target_title = str(target.get("title") or "").strip()
target_title = str(target.get("title") or "")
target_number = str(target.get("number") or "").strip()
dedupe = (data_key, target_key or target_title or target_number, selected_name)
if dedupe in seen:
@@ -3868,8 +3863,8 @@ class VmixAgentHub:
rebound.append({
"graphic": str(raw.get("graphic") or "")[:100],
"data_key": data_key[:200],
"vmix_input_key": target_key[:128],
"vmix_input_number": target_number[:32],
"vmix_input_key": target_key[:128], # inventory metadata, never a command address
"vmix_input_number": "",
"vmix_input_title": target_title[:300],
"vmix_field": selected_name[:300],
"field_type": str(raw.get("field_type") or "text")[:32],
@@ -3950,7 +3945,7 @@ class VmixAgentHub:
graphic=str(item.get("graphic") or "")[:100],
data_key=str(item.get("data_key") or "")[:200],
vmix_input_key=str(item.get("vmix_input_key") or "")[:128],
vmix_input_number=str(item.get("vmix_input_number") or "")[:32],
vmix_input_number="",
vmix_input_title=str(item.get("vmix_input_title") or "")[:300],
vmix_field=str(item.get("vmix_field") or "")[:300],
field_type=str(item.get("field_type") or "text")[:32],
@@ -4042,7 +4037,7 @@ class VmixAgentHub:
graphic=str(item.get("graphic") or "")[:100],
data_key=str(item.get("data_key") or "")[:200],
vmix_input_key=str(item.get("vmix_input_key") or "")[:128],
vmix_input_number=str(item.get("vmix_input_number") or "")[:32],
vmix_input_number="",
vmix_input_title=str(item.get("vmix_input_title") or "")[:300],
vmix_field=str(item.get("vmix_field") or "")[:300],
field_type=str(item.get("field_type") or "text")[:32],
@@ -4380,7 +4375,7 @@ class VmixAgentHub:
graphic=str(item.graphic or "")[:100],
data_key=str(item.data_key or "")[:200],
vmix_input_key=str(item.vmix_input_key or "")[:128],
vmix_input_number=str(item.vmix_input_number or "")[:32],
vmix_input_number="",
vmix_input_title=str(item.vmix_input_title or "")[:300],
vmix_field=str(item.vmix_field or "")[:300],
field_type=str(item.field_type or "text")[:32],
@@ -4590,6 +4585,87 @@ class VmixAgentHub:
await self._broadcast_mapping_for_fingerprint(result["project_fingerprint"])
return result
def migrate_mapping_titles(self) -> dict[str, int]:
changed = unresolved = 0
with self.database.session() as session:
for profile in session.scalars(select(VmixMappingProfile)):
inputs = _mapping_inputs(profile.inventory_json)
touched = False
for row in session.scalars(select(VmixMappingField).where(VmixMappingField.profile_id == profile.id)):
title = str(row.vmix_input_title or "")
if not title:
# A one-time recovery of the saved name, from this profile's
# own snapshot. These identifiers are never sent to vMix.
matches = [item for item in inputs if (
str(item.get("key") or "") == row.vmix_input_key if row.vmix_input_key else
bool(row.vmix_input_number) and str(item.get("number") or "") == row.vmix_input_number)]
if len(matches) == 1:
title = str(matches[0].get("title") or "")
if not title or _mapping_title_error(title, inputs):
unresolved += 1
continue
if row.vmix_input_title != title:
row.vmix_input_title = title
changed += 1; touched = True
if touched:
profile.version = int(profile.version or 0) + 1
return {"changed": changed, "unresolved": unresolved}
@refresh_plan_changed
async def rename_mapping_input(self, profile_id: int, payload: Any, user: HockeyUser) -> dict[str, Any]:
"""Rename the saved Input title and every Mapping link that addresses it."""
title = str(payload.title or "")
if not title.strip():
raise HTTPException(400, "Название титра не может быть пустым")
def persist():
with self.database.session() as session:
profile = session.get(VmixMappingProfile, profile_id, with_for_update=True)
if profile is None:
raise HTTPException(404, "Mapping-профиль не найден")
if int(profile.version or 0) != payload.expected_version:
raise HTTPException(409, "Конфиг уже изменён. Сохраните свои правки или обновите конфиг перед переименованием.")
try:
inventory = json.loads(profile.inventory_json or "{}")
inputs = inventory["inputs"]
if not isinstance(inputs, list):
raise ValueError()
except (ValueError, KeyError, TypeError):
raise HTTPException(409, "Сначала считайте структуру vMix для этого конфига")
old_title = str(payload.input_title or "")
candidates = [item for item in inputs if isinstance(item, dict)
and str(item.get("title") or "") == old_title]
if len(candidates) != 1:
raise HTTPException(409, "Не удалось однозначно найти титр. Обновите структуру vMix.")
target = candidates[0]
key = str(target.get("key") or "")
if any(item is not target and str(item.get("title") or "") == title for item in inputs):
raise HTTPException(409, "Это название уже занято другим Input. Задайте уникальное название.")
if _mapping_title_error(title, []):
raise HTTPException(400, _mapping_title_error(title, []))
if sum(str(item.get("title") or "") == old_title for item in inputs) != 1:
raise HTTPException(409, "Старое название неоднозначно. Сначала задайте уникальные названия в vMix и обновите структуру.")
updated = 0
for field in session.scalars(select(VmixMappingField).where(VmixMappingField.profile_id == profile_id)):
if str(field.vmix_input_title or "") != old_title:
continue
field.vmix_input_title = title
field.vmix_input_number = "" # Mapping commands address the exact title only.
if field.graphic == old_title:
field.graphic = title[:100]
updated += 1
target["title"] = title
profile.inventory_json = json.dumps(inventory, ensure_ascii=False, separators=(",", ":"))
profile.version = int(profile.version or 0) + 1
profile.updated_at = _utcnow()
profile.updated_by = user.login
session.flush()
return {"profile": self._mapping_profile_payload(session, profile), "updated_links": updated,
"input_key": key, "old_title": old_title, "title": title}
result = await run_db(persist)
await self._broadcast_mapping_for_fingerprint(result["profile"]["project_fingerprint"])
return result
@refresh_plan_changed
async def replace_mapping_fields(self, profile_id: int, payload: Any, user: HockeyUser) -> dict[str, Any]:
now = _utcnow()
@@ -4598,6 +4674,11 @@ class VmixAgentHub:
profile = session.get(VmixMappingProfile, profile_id)
if profile is None:
raise HTTPException(status_code=404, detail="Mapping-профиль не найден")
inputs = _mapping_inputs(profile.inventory_json)
for item in payload.fields:
error = _mapping_title_error(str(item.vmix_input_title or ""), inputs)
if error:
raise HTTPException(422, error)
for row in list(session.scalars(select(VmixMappingField).where(VmixMappingField.profile_id == profile_id))):
session.delete(row)
session.flush()
@@ -4610,8 +4691,8 @@ class VmixAgentHub:
profile_id=profile_id,
graphic=str(item.graphic or "")[:100],
data_key=data_key[:200],
vmix_input_key=str(item.vmix_input_key or "")[:128],
vmix_input_number=("" if (str(item.vmix_input_key or "").strip() or str(item.vmix_input_title or "").strip()) else str(item.vmix_input_number or "")[:32]),
vmix_input_key=next((str(target.get("key") or "") for target in inputs if target.get("title") == item.vmix_input_title), str(item.vmix_input_key or ""))[:128],
vmix_input_number="",
vmix_input_title=str(item.vmix_input_title or "")[:300],
vmix_field=vmix_field[:300],
field_type=str(item.field_type or "text")[:32],
@@ -4665,7 +4746,7 @@ class VmixAgentHub:
)
if profile is not None:
profile_payload = self._mapping_profile_payload(session, profile, include_inventory=False, include_fields=True)
# Include devices recovered by stable-key compatibility, not only
# Include devices recovered by title compatibility, not only
# devices whose whole-project fingerprint is byte-for-byte equal.
for row in session.scalars(select(VmixDevice).where(VmixDevice.project_fingerprint != "")):
resolved = self._active_mapping_profile_for_device(session, row)
@@ -4841,6 +4922,12 @@ class MappingFieldsReplacePayload(BaseModel):
fields: list[MappingFieldPayload] = Field(default_factory=list, max_length=2000)
class MappingInputRenamePayload(BaseModel):
input_title: str = Field(min_length=1, max_length=300)
title: str = Field(min_length=1, max_length=300)
expected_version: int = Field(ge=1)
class MappingProfileUsePayload(BaseModel):
device_id: str = Field(default="", max_length=128)
session_token: str = Field(default="", max_length=128)
@@ -5285,6 +5372,10 @@ def create_hockey_agent_router(
async def mapping_profile_fields(profile_id: int, payload: MappingFieldsReplacePayload, user: HockeyUser = Depends(auth_dependency)) -> dict[str, Any]:
return await hub.replace_mapping_fields(profile_id, payload, user)
@router.post("/api/hockey/admin/vmix-mapping/profiles/{profile_id}/inputs/rename", dependencies=admin)
async def mapping_input_rename(profile_id: int, payload: MappingInputRenamePayload, user: HockeyUser = Depends(auth_dependency)) -> dict[str, Any]:
return await hub.rename_mapping_input(profile_id, payload, user)
@router.delete("/api/hockey/admin/vmix-mapping/profiles/{profile_id}", dependencies=admin)
async def mapping_profile_delete(profile_id: int) -> dict[str, Any]:
return await hub.delete_mapping_profile(profile_id)

View File

@@ -2604,3 +2604,26 @@ body.hockey-admin-settings-open { overflow: hidden; }
.hockey-map-table-browser{grid-template-columns:1fr;grid-template-rows:minmax(90px,.55fr) minmax(130px,1.45fr)}
.hockey-map-table-fields-list{grid-template-columns:repeat(2,minmax(0,1fr))}
}
/* BUILD170: per-title Mapping actions and a reviewable copy dialog. */
.hockey-map-input-actions { display:flex; flex-wrap:wrap; gap:6px; margin-top:3px; }
.hockey-map-input-actions button { padding:6px 10px; font-size:11px; }
.hockey-map-input-error { color:#ff9aab!important; }
.hockey-map-input-dialog { width:min(650px,calc(100vw - 32px)); max-height:calc(100vh - 48px); overflow:auto; padding:24px; border:1px solid #38516b; border-radius:16px; color:#eaf4ff; background:#101d2d; box-shadow:0 24px 80px #0009; font:14px/1.5 system-ui,sans-serif; }
.hockey-map-input-dialog::backdrop { background:#02070cbf; }
.hockey-map-input-dialog form { display:grid; gap:16px; }
.hockey-map-input-dialog header, .hockey-map-input-dialog footer { display:flex; align-items:center; justify-content:space-between; gap:12px; }
.hockey-map-input-dialog h3, .hockey-map-input-dialog p { margin:0; }
.hockey-map-input-dialog p { color:#adbed1; }
.hockey-map-input-dialog label { display:grid; gap:7px; }
.hockey-map-input-dialog input:not([type=checkbox]), .hockey-map-input-dialog select { width:100%; min-width:0; box-sizing:border-box; height:40px; padding:8px 10px; color:#eaf4ff; background:#091421; border:1px solid #3d5874; border-radius:8px; font:inherit; }
.hockey-map-input-dialog .hockey-map-copy-overwrite { display:flex; align-items:center; gap:10px; }
.hockey-map-input-dialog input[type=checkbox] { width:17px; height:17px; accent-color:#45d9b5; }
.hockey-map-input-dialog input[type=checkbox]:checked { background:#45d9b5; border-color:#45d9b5; }
.hockey-map-input-dialog input[type=checkbox]:checked::before { color:#05271f; transform:scale(1); }
.hockey-map-input-dialog button { padding:8px 14px; border:1px solid #3d5874; border-radius:8px; background:#192e43; color:#eaf4ff; cursor:pointer; font:600 13px system-ui,sans-serif; }
.hockey-map-input-dialog button[type=submit] { background:#45d9b5; color:#05271f; border-color:#45d9b5; }
.hockey-map-input-dialog button:disabled { opacity:.45; cursor:default; }
.hockey-map-input-dialog footer { justify-content:flex-end; }
.hockey-map-input-dialog [data-input-report] { max-height:230px; overflow:auto; padding:12px; background:#091421; border:1px solid #29435d; border-radius:8px; }
.hockey-map-input-dialog ul { padding-left:20px; margin:10px 0 0; color:#adbed1; }

View File

@@ -1579,7 +1579,7 @@
function mappingInventoryInputs(profile) {
// Mapping picker is operator-facing: show Inputs in vMix numeric order so a
// title can be found by its familiar # quickly. Stable links still use key/title.
// title can be found by its familiar # quickly. Links address exact titles.
const inputs = Array.isArray(profile?.inventory?.inputs) ? [...profile.inventory.inputs] : [];
return inputs.sort((left, right) => {
const leftNumber = Number(left?.number);
@@ -1746,26 +1746,159 @@
let current = inputs.find((item) => mappingInputValue(item) === state.mappingSelectedInputKey);
if (!current) {
const linked = (profile?.fields || [])[0];
current = linked ? mappingInputByKey(profile, linked.vmix_input_key, linked.vmix_input_title) : null;
current = linked ? inputs.find(item => item.title === linked.vmix_input_title) : null;
}
current ||= inputs[0];
state.mappingSelectedInputKey = mappingInputValue(current);
return current;
}
function mappingRowMatchesInput(row, input) {
return Boolean(input?.title) && String(row?.vmix_input_title || "") === String(input.title);
}
function mappingInputTitleProblem(profile, input) {
const title = String(input?.title || "");
if (!title.trim()) return "У Input нет названия. Задайте его в vMix и обновите структуру.";
if (/^[+-]?\d+$/.test(title) || /^\{?[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\}?$/i.test(title)) return "Название Input должно отличаться от номера и GUID.";
if (mappingInventoryInputs(profile).filter(item => String(item.title || "") === title).length !== 1) return `Название «${title}» не уникально. Переименуйте Inputs в vMix и обновите структуру.`;
return "";
}
function mappingCopyInputPlan(profile, source, target, overwrite = false) {
const plan = { entries: [], skipped: [], error: "" };
plan.error = mappingInputTitleProblem(profile, source) || mappingInputTitleProblem(profile, target);
if (source === target || source?.title === target?.title) plan.error = "Выберите другой титр.";
if (plan.error) return plan;
const rows = (profile.fields || []).filter(row => mappingRowMatchesInput(row, source));
for (const row of rows) {
const matches = (target.fields || []).filter(field => field.name === row.vmix_field);
let reason = "";
if (rows.filter(other => other.vmix_field === row.vmix_field).length !== 1) reason = "Несколько исходных связей";
else if (!matches.length) reason = "Нет такого поля";
else if (matches.length > 1) reason = "Неоднозначное поле";
else if (mappingFieldKind(matches[0]) !== mappingFieldKind({ type: row.field_type })) reason = "Другой тип поля";
else if (!overwrite && (profile.fields || []).some(other => mappingRowMatchesInput(other, target) && other.vmix_field === row.vmix_field)) reason = "Уже связано";
if (reason) { plan.skipped.push({ field: row.vmix_field, reason }); continue; }
plan.entries.push({ ...JSON.parse(JSON.stringify(row)), id: undefined, graphic: String(target.title).slice(0,100),
vmix_input_key: String(target.key || ""), vmix_input_number: "", vmix_input_title: target.title, vmix_field: matches[0].name,
field_type: mappingFieldKind(matches[0]) });
}
const replaced = new Set(plan.entries.map(row => row.vmix_field));
const kept = (profile.fields || []).filter(row => !(mappingRowMatchesInput(row,target) && replaced.has(row.vmix_field)));
if (kept.length + plan.entries.length > 2000) plan.error = "В конфиге может быть не больше 2000 связей.";
return plan;
}
function mappingApplyInputCopy(profile, target, plan) {
if (plan.error || !plan.entries.length) return false;
const replaced = new Set(plan.entries.map(row => row.vmix_field));
profile.fields = (profile.fields || []).filter(row => !(mappingRowMatchesInput(row,target) && replaced.has(row.vmix_field))).concat(plan.entries);
return true;
}
function mappingInputDialog(title, body) {
const dialog = document.createElement("dialog");
dialog.className = "hockey-map-input-dialog";
dialog.setAttribute("aria-label", title);
dialog.innerHTML = `<form><header><h3>${escapeHtml(title)}</h3><button type="button" data-input-cancel aria-label="Закрыть">×</button></header>${body}</form>`;
dialog.querySelectorAll('[data-input-cancel]').forEach(button => button.addEventListener('click', () => dialog.close()));
dialog.addEventListener('keydown', event => { if (event.key === 'Escape') event.stopPropagation(); });
dialog.addEventListener('close', () => dialog.remove());
document.body.appendChild(dialog); dialog.showModal();
return dialog;
}
function openMappingInputRename() {
const profile = state.mappingActiveProfile, input = mappingCurrentInput(profile);
if (!profile || !input) return;
const problem = mappingInputTitleProblem(profile, input);
if (problem) { setStatus(problem, true); renderMapping(); return; }
const oldTitle = input.title;
const dialog = mappingInputDialog("Переименовать титр в Mapping", `
<p>Укажите новое название Input из vMix. Все связи и условия этого титра будут обращаться к новому названию.</p>
<label>Название Input<input data-input-title maxlength="300" required value="${escapeHtml(oldTitle)}"></label>
<p class="hockey-map-input-error" data-input-error role="status"></p>
<footer><button type="button" data-input-cancel>Отмена</button><button type="submit">Сохранить название</button></footer>`);
dialog.querySelector('[data-input-title]').select();
dialog.querySelector('form').addEventListener('submit', async event => {
event.preventDefault();
const title = dialog.querySelector('[data-input-title]').value;
if (title === oldTitle) { dialog.close(); return; }
const errorNode = dialog.querySelector('[data-input-error]'), submit = dialog.querySelector('[type=submit]');
const duplicate = mappingInventoryInputs(profile).some(item => item !== input && item.title === title);
if (!title.trim() || duplicate) { errorNode.textContent = duplicate ? 'Это название уже занято другим Input.' : 'Введите название.'; return; }
submit.disabled = true;
try {
const result = await request(`/api/hockey/admin/vmix-mapping/profiles/${profile.id}/inputs/rename`, {
method: 'POST', body: JSON.stringify({input_title: oldTitle, title, expected_version: profile.version})
});
// Keep every unsaved field/rule edit in this browser. The response is used
// for metadata only; its saved field list must not replace the draft.
for (const row of profile.fields || []) if (mappingRowMatchesInput(row,input)) {
row.vmix_input_title = result.title; row.vmix_input_number = '';
if (row.graphic === oldTitle) row.graphic = result.title.slice(0,100);
}
input.title = result.title;
profile.version = result.profile.version; profile.updated_at = result.profile.updated_at;
if (state.mappingActiveProfile === profile) {
state.mappingSelectedInputKey = mappingInputValue(input); state.mappingInputSearch = '';
setStatus(`Название «${result.title}» сохранено. Остальные правки связей сохраните кнопкой «Сохранить конфиг».`);
renderMapping();
}
dialog.close();
} catch(error) { errorNode.textContent = error.message || 'Не удалось сохранить название'; }
finally { submit.disabled = false; }
});
}
function openMappingInputCopy() {
const profile = state.mappingActiveProfile, source = mappingCurrentInput(profile);
if (!profile || !source) return;
const targets = mappingInventoryInputs(profile).filter(item => item !== source);
const dialog = mappingInputDialog("Копировать связи на другой титр", `
<p>Источник: <strong>${escapeHtml(source.title)}</strong></p>
<label>Титр назначения<select data-input-target>${targets.map((item,index) => `<option value="${index}">${escapeHtml(mappingInputLabel(item))}</option>`).join('')}</select></label>
<label class="hockey-map-copy-overwrite"><input type="checkbox" data-input-overwrite>Заменить существующие связи совпавших полей</label>
<p>Копируются источники данных, условия TRUE / ELSE и состояние связей. Поля сопоставляются по точному имени и типу. Исходный титр сохраняется.</p>
<div data-input-report role="status"></div>
<footer><button type="button" data-input-cancel>Отмена</button><button type="submit">Добавить в конфиг</button></footer>`);
const makePlan = () => {
const target = targets[Number(dialog.querySelector('[data-input-target]').value)];
const plan = mappingCopyInputPlan(profile, source, target, dialog.querySelector('[data-input-overwrite]').checked);
dialog.querySelector('[data-input-report]').innerHTML = plan.error ? `<p class="hockey-map-input-error">${escapeHtml(plan.error)}</p>` :
`<strong>Будет скопировано: ${plan.entries.length}. Пропущено: ${plan.skipped.length}.</strong>${plan.skipped.length ? `<ul>${plan.skipped.map(item => `<li>${escapeHtml(item.field)} — ${escapeHtml(item.reason)}</li>`).join('')}</ul>` : ''}`;
dialog.querySelector('[type=submit]').disabled = Boolean(plan.error) || !plan.entries.length;
return {target,plan};
};
dialog.querySelector('[data-input-target]').addEventListener('change',makePlan);
dialog.querySelector('[data-input-overwrite]').addEventListener('change',makePlan);
dialog.querySelector('form').addEventListener('submit', event => {
event.preventDefault();
if (state.mappingActiveProfile !== profile) { dialog.close(); return; }
const {target,plan} = makePlan();
if (!mappingApplyInputCopy(profile,target,plan)) return;
state.mappingSelectedInputKey = mappingInputValue(target); state.mappingInputSearch = ''; state.mappingVmixScrollTop = 0;
state.mappingTargetField = ''; state.mappingRuleField = '';
setStatus(`В «${target.title}» добавлено связей: ${plan.entries.length}. Пропущено: ${plan.skipped.length}. Нажмите «Сохранить конфиг».`);
dialog.close(); renderMapping();
});
makePlan();
}
function mappingRowForField(profile, input, fieldName) {
return (profile?.fields || []).find((row) => {
const sameInput = String(row.vmix_input_key || "") === String(input?.key || "")
|| (!row.vmix_input_key && String(row.vmix_input_title || "") === String(input?.title || ""));
const sameInput = mappingRowMatchesInput(row, input);
return sameInput && String(row.vmix_field || "") === String(fieldName || "");
}) || null;
}
function mappingSetLink(profile, input, field, source) {
const problem = mappingInputTitleProblem(profile, input);
if (problem) { setStatus(problem, true); return; }
const fields = [...(profile?.fields || [])];
const index = fields.findIndex((row) => {
const sameInput = String(row.vmix_input_key || "") === String(input?.key || "")
|| (!row.vmix_input_key && String(row.vmix_input_title || "") === String(input?.title || ""));
const sameInput = mappingRowMatchesInput(row, input);
return sameInput && String(row.vmix_field || "") === String(field?.name || "");
});
const previous = index >= 0 ? fields[index] : null;
@@ -1777,8 +1910,7 @@
graphic: String(input?.title || "graphic").trim().slice(0, 100),
data_key: source.key,
vmix_input_key: String(input?.key || ""),
// Input number is positional in vMix and changes after reordering.
// Persist key/title only; number remains display-only in inventory.
// Mapping addresses the exact Input title; number/key are inventory metadata only.
vmix_input_number: "",
vmix_input_title: String(input?.title || ""),
vmix_field: String(field?.name || ""),
@@ -1793,8 +1925,7 @@
function mappingRemoveLink(profile, input, fieldName) {
profile.fields = (profile?.fields || []).filter((row) => {
const sameInput = String(row.vmix_input_key || "") === String(input?.key || "")
|| (!row.vmix_input_key && String(row.vmix_input_title || "") === String(input?.title || ""));
const sameInput = mappingRowMatchesInput(row, input);
return !(sameInput && String(row.vmix_field || "") === String(fieldName || ""));
});
}
@@ -1876,7 +2007,7 @@
const raw = matched ? rule.true_value : rule.false_value;
const visible = !["0", "false", "off", "hide", "hidden", "no"].includes(String(raw).toLowerCase());
return {
input: row.vmix_input_key || row.vmix_input_title || row.vmix_input_number,
input: row.vmix_input_title,
selected_name: row.vmix_field,
value: "",
field_type: kind,
@@ -1891,7 +2022,7 @@
const colour = outputMode === "field" ? mappingSourceByKey(outputKey)?.value : (branch === "true" ? rule.true_value : rule.false_value);
if (!String(colour || "").trim()) return null;
return {
input: row.vmix_input_key || row.vmix_input_title || row.vmix_input_number,
input: row.vmix_input_title,
selected_name: row.vmix_field,
value: String(colour),
field_type: kind,
@@ -1964,7 +2095,7 @@
const rule = mappingNormaliseRule(row, mappingFieldKind(field));
if (rule.right_mode !== "field" || !rule.right_key) return { ok: false, reason: "Сначала выберите второе поле." };
const peer = (profile?.fields || []).find((item) => {
const sameInput = String(item.vmix_input_key || "") === String(input?.key || "") || (!item.vmix_input_key && String(item.vmix_input_title || "") === String(input?.title || ""));
const sameInput = mappingRowMatchesInput(item, input);
return sameInput && String(item.data_key || "") === rule.right_key;
});
if (!peer) return { ok: false, reason: "Второе поле данных ещё не связано с элементом vMix этого Input." };
@@ -2043,8 +2174,7 @@
let seedRows = [anchorRow];
if (mode === "row") {
seedRows = (profile?.fields || []).filter((row) => {
const sameInput = String(row.vmix_input_key || "") === String(input?.key || "")
|| (!row.vmix_input_key && String(row.vmix_input_title || "") === String(input?.title || ""));
const sameInput = mappingRowMatchesInput(row, input);
if (!sameInput) return false;
const cell = mappingParseTableCellKey(row.data_key);
return cell && cell.sourceCode === anchorCell.sourceCode && cell.rowIndex === anchorCell.rowIndex;
@@ -2126,8 +2256,7 @@
function mappingGridTemplateSeeds(profile, input, sourceCode, rowIndex) {
return (profile?.fields || []).filter((row) => {
const sameInput = String(row.vmix_input_key || "") === String(input?.key || "")
|| (!row.vmix_input_key && String(row.vmix_input_title || "") === String(input?.title || ""));
const sameInput = mappingRowMatchesInput(row, input);
if (!sameInput) return false;
const cell = mappingParseTableCellKey(row.data_key);
return cell && cell.sourceCode === sourceCode && Number(cell.rowIndex) === Number(rowIndex);
@@ -2507,6 +2636,9 @@
<label class="hockey-map-input-search"><span>⌕</span><input data-map-input-search value="${escapeHtml(state.mappingInputSearch)}" placeholder="Поиск по №, названию или key…"></label>
<select data-map-input-picker>${visibleInputs.map((item) => `<option value="${escapeHtml(mappingInputValue(item))}" ${mappingInputValue(item) === mappingInputValue(currentInput) ? "selected" : ""}>${escapeHtml(mappingInputLabel(item))}</option>`).join("")}</select>
<small>${visibleInputs.length === allInputs.length ? `${allInputs.length} Inputs` : `Найдено ${filteredInputs.length} из ${allInputs.length}`}</small>
<div class="hockey-map-input-actions"><button type="button" data-map-rename-input>✎ Переименовать</button><button type="button" data-map-copy-input>⧉ Копировать связи</button></div>
<small>Привязка по точному названию Input в vMix.</small>
${mappingInputTitleProblem(profile, currentInput) ? `<small class="hockey-map-input-error">${escapeHtml(mappingInputTitleProblem(profile, currentInput))}</small>` : ""}
<div class="hockey-map-field-toolbar">
<div class="hockey-map-field-tabs" role="group" aria-label="Тип поля vMix">
<button type="button" data-map-field-filter="text" class="${filter === "text" ? "is-active" : ""}">Text <b>${counts.text}</b></button>
@@ -2831,14 +2963,16 @@
function collectMappingFields() {
return [...(state.mappingActiveProfile?.fields || [])].map((row, index) => ({
...row,
// Never re-save a positional vMix Input number when a stable key/title is known.
vmix_input_number: (row.vmix_input_key || row.vmix_input_title) ? "" : String(row.vmix_input_number || ""),
// Input key is inventory metadata only; command addresses use the title.
vmix_input_number: "",
sort_order: index,
})).filter((row) => row.data_key && row.vmix_field);
}
function bindMapping() {
const modal = ensureModal();
modal.querySelector("[data-map-rename-input]")?.addEventListener("click", () => openMappingInputRename());
modal.querySelector("[data-map-copy-input]")?.addEventListener("click", () => openMappingInputCopy());
modal.querySelector("[data-map-refresh-device]")?.addEventListener("change", (event) => {
state.mappingRefreshDeviceId = event.currentTarget.value;
});
@@ -3611,8 +3745,10 @@
if (!deviceId) return setStatus("Выберите тестовый Agent.", true), renderMapping();
if (!row || !source) return setStatus("Сначала свяжите поле с данными.", true), renderMapping();
if (source.value === "" || source.value === null || source.value === undefined) return setStatus(`Для «${source.label}» в текущем матче нет значения.`, true), renderMapping();
const problem = mappingInputTitleProblem(profile, input);
if (problem) return setStatus(problem, true), renderMapping();
const commands = [{
input: row.vmix_input_key || row.vmix_input_title || row.vmix_input_number,
input: row.vmix_input_title,
selected_name: row.vmix_field, value: String(source.value),
field_type: row.field_type || mappingFieldKind(field), data_key: row.data_key,
}];
@@ -3631,6 +3767,8 @@
await loadMappingCatalog();
const profile = state.mappingActiveProfile;
const input = mappingCurrentInput(profile);
const problem = mappingInputTitleProblem(profile, input);
if (problem) return setStatus(problem, true), renderMapping();
const commands = [];
const missing = [];
for (const field of (input?.fields || [])) {
@@ -3639,7 +3777,7 @@
const source = mappingSourceByKey(row.data_key);
if (!source) { missing.push(row.data_key); continue; }
commands.push({
input: row.vmix_input_key || row.vmix_input_title || row.vmix_input_number,
input: row.vmix_input_title,
selected_name: row.vmix_field,
value: source.value == null ? "" : String(source.value),
field_type: row.field_type || mappingFieldKind(field),

View File

@@ -2055,7 +2055,7 @@
function enhanceStyledControls(root = document) {
const scope = root?.querySelectorAll ? root : document;
scope.querySelectorAll?.('select:not([data-css-enhanced])').forEach(select => {
if (!select.closest('.hockey-analytics')) enhanceSelect(select);
if (!select.closest('.hockey-analytics, .hockey-map-input-dialog')) enhanceSelect(select);
});
scope.querySelectorAll?.('input[type="date"]:not([data-css-enhanced]), input[type="time"]:not([data-css-enhanced]), input[type="datetime-local"]:not([data-css-enhanced])').forEach(enhanceDateTimeInput);
scope.querySelectorAll?.('input[type="color"]:not([data-css-enhanced])').forEach(enhanceColorInput);