Version 0.5.5.94: field type conversion, exclusion filters and value lists
- Change the data type of custom fields with stored values via a preview: values that cannot be converted need an explicit decision, the conversion runs in one transaction with row locks and a stale-preview check, old values are saved to data/backups and recorded in history. - Table filters: "!value" excludes rows, "=value" compares exactly; Excel-like value list (▾) per column in all tables. The software job list computes its value list on the server over the full job history. - Bulk edit offers custom fields with type-specific input and validation. - MeshCentral mappings: optional "value if empty" with a guard path; fallbacks are skipped when only basic data was delivered. - Deleting a field removes its translations (same name can be reused); one confirmation with the value count replaces the checkbox. - Job list filters recognize the "reinstall" action and the "software deployment" job type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
261b4f2029
commit
40cd88871f
20 files changed
+1382
-169
No files matched your search
@@ -1,4 +1,4 @@
|
||||
# AssetManager 0.5.5.93
|
||||
# AssetManager 0.5.5.94
|
||||
|
||||
AssetManager is a self-hosted web application for managing IT equipment and other organizational assets. It provides asset inventory, software inventory, remote job execution, reporting, privacy/retention documentation, and optional integration with MeshCentral.
|
||||
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
"""Safe data type conversion for custom field values.
|
||||
|
||||
A conversion is always planned first (preview) and then applied in one
|
||||
transaction. Values that cannot be converted are never dropped silently:
|
||||
the administrator has to decide explicitly (replace or clear) for each one.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, time
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from .models import AssetFieldValue, FieldDefinition
|
||||
|
||||
TEXT_TYPES = {"short_text", "long_text"}
|
||||
VALIDATED_TEXT_TYPES = {"url", "email", "ip"}
|
||||
CONVERTIBLE_TYPES = TEXT_TYPES | VALIDATED_TEXT_TYPES | {"integer", "decimal", "boolean", "date", "datetime"}
|
||||
|
||||
TRUE_WORDS = {"ja", "yes", "true", "1", "on", "an", "y", "j"}
|
||||
FALSE_WORDS = {"nein", "no", "false", "0", "off", "aus", "n"}
|
||||
|
||||
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||||
|
||||
|
||||
class ConversionError(ValueError):
|
||||
"""A single value cannot be represented in the target type."""
|
||||
|
||||
|
||||
def is_supported(from_type: str, to_type: str) -> bool:
|
||||
return from_type in CONVERTIBLE_TYPES and to_type in CONVERTIBLE_TYPES
|
||||
|
||||
|
||||
def read_value(row: AssetFieldValue, data_type: str) -> Any:
|
||||
"""Return the stored value from the column that belongs to ``data_type``."""
|
||||
if data_type == "boolean":
|
||||
return row.value_boolean
|
||||
if data_type in {"integer", "decimal"}:
|
||||
return row.value_number
|
||||
if data_type == "date":
|
||||
return row.value_date
|
||||
if data_type == "datetime":
|
||||
return row.value_datetime
|
||||
if data_type == "json":
|
||||
return row.value_json
|
||||
return row.value_text
|
||||
|
||||
|
||||
def is_empty(value: Any) -> bool:
|
||||
return value is None or (isinstance(value, str) and value.strip() == "")
|
||||
|
||||
|
||||
def write_value(row: AssetFieldValue, data_type: str, value: Any) -> None:
|
||||
"""Store an already converted value; every other value column is cleared."""
|
||||
row.value_text = row.value_number = row.value_date = None
|
||||
row.value_boolean = None
|
||||
row.value_datetime = None
|
||||
row.value_json = None
|
||||
if value is None:
|
||||
return
|
||||
if data_type == "boolean":
|
||||
row.value_boolean = bool(value)
|
||||
elif data_type in {"integer", "decimal"}:
|
||||
row.value_number = str(value)
|
||||
elif data_type == "date":
|
||||
row.value_date = str(value)
|
||||
elif data_type == "datetime":
|
||||
row.value_datetime = value
|
||||
else:
|
||||
row.value_text = str(value)
|
||||
|
||||
|
||||
def _as_text(value: Any, from_type: str, yes_no: tuple[str, str]) -> str:
|
||||
if from_type == "boolean":
|
||||
return yes_no[0] if value else yes_no[1]
|
||||
if from_type == "datetime" and isinstance(value, datetime):
|
||||
return value.isoformat(sep=" ", timespec="minutes" if value.second == 0 and value.microsecond == 0 else "seconds")
|
||||
return str(value).strip() if from_type not in TEXT_TYPES else str(value)
|
||||
|
||||
|
||||
def _parse_decimal(text: str) -> Decimal:
|
||||
cleaned = text.strip().replace(" ", "")
|
||||
if "," in cleaned and "." in cleaned:
|
||||
# 1.234,56 (German) or 1,234.56 (English): the last separator is the decimal mark.
|
||||
if cleaned.rfind(",") > cleaned.rfind("."):
|
||||
cleaned = cleaned.replace(".", "").replace(",", ".")
|
||||
else:
|
||||
cleaned = cleaned.replace(",", "")
|
||||
else:
|
||||
cleaned = cleaned.replace(",", ".")
|
||||
try:
|
||||
number = Decimal(cleaned)
|
||||
except InvalidOperation as exc:
|
||||
raise ConversionError("not_a_number") from exc
|
||||
if not number.is_finite():
|
||||
raise ConversionError("not_a_number")
|
||||
return number
|
||||
|
||||
|
||||
def _decimal_text(number: Decimal) -> str:
|
||||
text = format(number, "f")
|
||||
if "." in text:
|
||||
text = text.rstrip("0").rstrip(".")
|
||||
return text or "0"
|
||||
|
||||
|
||||
def _parse_date(text: str) -> date:
|
||||
text = text.strip()
|
||||
for fmt in ("%Y-%m-%d", "%d.%m.%Y"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date()
|
||||
except ValueError:
|
||||
pass
|
||||
raise ConversionError("not_a_date")
|
||||
|
||||
|
||||
def _parse_datetime(text: str) -> datetime:
|
||||
text = text.strip()
|
||||
try:
|
||||
return datetime.fromisoformat(text.replace("T", " "))
|
||||
except ValueError:
|
||||
pass
|
||||
for fmt in ("%d.%m.%Y %H:%M:%S", "%d.%m.%Y %H:%M", "%d.%m.%Y"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt)
|
||||
except ValueError:
|
||||
pass
|
||||
raise ConversionError("not_a_datetime")
|
||||
|
||||
|
||||
def convert_value(value: Any, from_type: str, to_type: str, yes_no: tuple[str, str] = ("Ja", "Nein")) -> Any:
|
||||
"""Convert one stored value. Returns ``None`` for empty values.
|
||||
|
||||
Raises ``ConversionError`` with a short reason code when the value cannot
|
||||
be represented in ``to_type`` without losing information.
|
||||
"""
|
||||
if is_empty(value):
|
||||
return None
|
||||
if from_type == to_type:
|
||||
return value
|
||||
|
||||
# Typed source values with a direct, lossless mapping.
|
||||
if from_type == "boolean" and to_type in {"integer", "decimal"}:
|
||||
return "1" if value else "0"
|
||||
if from_type == "date" and to_type == "datetime":
|
||||
return datetime.combine(_parse_date(str(value)), time(0, 0))
|
||||
if from_type == "datetime" and to_type == "date":
|
||||
if not isinstance(value, datetime):
|
||||
value = _parse_datetime(str(value))
|
||||
if value.time() != time(0, 0):
|
||||
raise ConversionError("time_would_be_lost")
|
||||
return value.date().isoformat()
|
||||
|
||||
text = _as_text(value, from_type, yes_no)
|
||||
|
||||
if to_type in TEXT_TYPES:
|
||||
return text
|
||||
if to_type == "boolean":
|
||||
word = text.strip().lower()
|
||||
if from_type in {"integer", "decimal"}:
|
||||
number = _parse_decimal(word)
|
||||
if number == 1:
|
||||
return True
|
||||
if number == 0:
|
||||
return False
|
||||
raise ConversionError("not_a_boolean")
|
||||
if word in TRUE_WORDS:
|
||||
return True
|
||||
if word in FALSE_WORDS:
|
||||
return False
|
||||
raise ConversionError("not_a_boolean")
|
||||
if to_type == "integer":
|
||||
number = _parse_decimal(text)
|
||||
if number != number.to_integral_value():
|
||||
raise ConversionError("decimals_would_be_lost")
|
||||
return str(int(number))
|
||||
if to_type == "decimal":
|
||||
return _decimal_text(_parse_decimal(text))
|
||||
if to_type == "date":
|
||||
if from_type in {"integer", "decimal"}:
|
||||
raise ConversionError("not_a_date")
|
||||
return _parse_date(text).isoformat()
|
||||
if to_type == "datetime":
|
||||
if from_type in {"integer", "decimal"}:
|
||||
raise ConversionError("not_a_datetime")
|
||||
return _parse_datetime(text)
|
||||
if to_type == "email":
|
||||
if not _EMAIL_RE.match(text.strip()):
|
||||
raise ConversionError("not_an_email")
|
||||
return text.strip()
|
||||
if to_type == "url":
|
||||
parsed = urlparse(text.strip())
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise ConversionError("not_a_url")
|
||||
return text.strip()
|
||||
if to_type == "ip":
|
||||
try:
|
||||
return str(ipaddress.ip_address(text.strip()))
|
||||
except ValueError as exc:
|
||||
raise ConversionError("not_an_ip") from exc
|
||||
raise ConversionError("unsupported")
|
||||
|
||||
|
||||
def display(value: Any, data_type: str, yes_no: tuple[str, str]) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if data_type == "boolean":
|
||||
return yes_no[0] if value else yes_no[1]
|
||||
if isinstance(value, datetime):
|
||||
return value.isoformat(sep=" ", timespec="minutes")
|
||||
if isinstance(value, (dict, list)):
|
||||
return json.dumps(value, ensure_ascii=False)
|
||||
return str(value)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PlannedValue:
|
||||
row_id: int
|
||||
asset_id: int
|
||||
old_value: Any
|
||||
old_display: str
|
||||
new_value: Any = None
|
||||
new_display: str = ""
|
||||
error: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConversionPlan:
|
||||
definition_id: int
|
||||
from_type: str
|
||||
to_type: str
|
||||
converted: list[PlannedValue] = field(default_factory=list)
|
||||
failed: list[PlannedValue] = field(default_factory=list)
|
||||
empty_count: int = 0
|
||||
fingerprint: str = ""
|
||||
|
||||
@property
|
||||
def total(self) -> int:
|
||||
return len(self.converted) + len(self.failed) + self.empty_count
|
||||
|
||||
|
||||
def _fingerprint(definition: FieldDefinition, rows: list[AssetFieldValue]) -> str:
|
||||
digest = hashlib.sha256(f"{definition.id}:{definition.data_type}".encode())
|
||||
for row in sorted(rows, key=lambda item: item.id):
|
||||
digest.update(json.dumps([
|
||||
row.id, row.asset_id, row.value_text, row.value_number, row.value_boolean,
|
||||
row.value_date, row.value_datetime.isoformat() if row.value_datetime else None,
|
||||
row.value_json,
|
||||
], ensure_ascii=False, sort_keys=True, default=str).encode())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def plan_conversion(rows: list[AssetFieldValue], definition: FieldDefinition, to_type: str, yes_no: tuple[str, str]) -> ConversionPlan:
|
||||
from_type = definition.data_type
|
||||
plan = ConversionPlan(definition_id=definition.id, from_type=from_type, to_type=to_type)
|
||||
for row in rows:
|
||||
old_value = read_value(row, from_type)
|
||||
if is_empty(old_value):
|
||||
plan.empty_count += 1
|
||||
continue
|
||||
item = PlannedValue(row_id=row.id, asset_id=row.asset_id, old_value=old_value, old_display=display(old_value, from_type, yes_no))
|
||||
try:
|
||||
item.new_value = convert_value(old_value, from_type, to_type, yes_no)
|
||||
item.new_display = display(item.new_value, to_type, yes_no)
|
||||
plan.converted.append(item)
|
||||
except ConversionError as exc:
|
||||
item.error = str(exc) or "unsupported"
|
||||
plan.failed.append(item)
|
||||
plan.fingerprint = _fingerprint(definition, rows)
|
||||
return plan
|
||||
+57
-3
@@ -27,6 +27,8 @@ BASE_TRANSLATIONS = {
|
||||
"fields.stored_values": ("Stored values", "Gespeicherte Werte"),
|
||||
"fields.delete_confirm": ("Delete this field and all values?", "Dieses Feld und alle gespeicherten Werte löschen?"),
|
||||
"fields.confirm_values": ("Confirm values", "Werte bestätigen"),
|
||||
"fields.delete_confirm_empty": ("Delete field {field}?", "Feld {field} löschen?"),
|
||||
"fields.delete_confirm_values": ("Field {field} contains values for {count} assets. Permanently delete the field and all values?", "Feld {field} enthält Werte für {count} Assets. Feld und alle Werte endgültig löschen?"),
|
||||
"fields.technical_name": ("Technical field name", "Technischer Feldname"),
|
||||
"fields.technical_name_help": ("Letters, numbers and underscores only.", "Nur Buchstaben, Zahlen und Unterstriche."),
|
||||
"fields.automatic": ("automatic", "automatisch"),
|
||||
@@ -212,8 +214,15 @@ BASE_TRANSLATIONS = {
|
||||
"lists.row_number": ("Row number", "Zeilennummer"),
|
||||
"lists.row_number_resize": ("Drag to change the row-number column width", "Ziehen, um die Breite der Nummernspalte zu ändern"),
|
||||
"lists.column_resize": ("Drag to change the column width", "Ziehen, um die Spaltenbreite zu ändern"),
|
||||
"lists.multi_value_filter_hint": ("Paste multiple search values one per line. Values within one column are OR-linked. Numeric and date values also support >x, <x, >=x, <=x and ranges such as 'from x to y'.", "Mehrere Suchwerte können zeilenweise eingefügt werden. Innerhalb einer Spalte gilt ODER. Zahlen- und Datumswerte unterstützen zusätzlich >x, <x, >=x, <=x sowie Bereiche wie ‚von x bis y‘."),
|
||||
"lists.multi_value_filter_hint": ("One search value per line; lines within a column are OR-linked. !value excludes rows, =value compares the whole value exactly. Numbers and dates also support >x, <x, >=x, <=x and ranges such as 'from x to y'. The ▾ button opens a value list with checkboxes.", "Ein Suchwert pro Zeile; Zeilen einer Spalte sind ODER-verknüpft. !Wert schließt Zeilen aus, =Wert vergleicht den ganzen Wert exakt. Zahlen und Datumswerte unterstützen zusätzlich >x, <x, >=x, <=x sowie Bereiche wie ‚von x bis y‘. Der Knopf ▾ öffnet eine Werteliste mit Häkchen."),
|
||||
"lists.advanced_filter.title": ("Advanced filter", "Erweiterter Filter"),
|
||||
"lists.value_list.open": ("Select values", "Werte auswählen"),
|
||||
"lists.value_list.search": ("Search values", "Werte durchsuchen"),
|
||||
"lists.value_list.select_all": ("(Select all)", "(Alle auswählen)"),
|
||||
"lists.value_list.empty": ("(Empty)", "(Leer)"),
|
||||
"lists.value_list.error": ("The value list could not be loaded.", "Die Werteliste konnte nicht geladen werden."),
|
||||
"lists.value_list.scan_limited": ("Only the newest {count} jobs were evaluated.", "Es wurden nur die neuesten {count} Jobs ausgewertet."),
|
||||
"lists.value_list.limited": ("Showing {shown} of {total} values, narrow them with the search field.", "Es werden {shown} von {total} Werten angezeigt, grenze sie mit dem Suchfeld ein."),
|
||||
"lists.advanced_filter.operator": ("Condition", "Bedingung"),
|
||||
"lists.advanced_filter.value": ("Value", "Wert"),
|
||||
"lists.advanced_filter.value_from": ("From", "Von"),
|
||||
@@ -694,7 +703,7 @@ BASE_TRANSLATIONS.update({
|
||||
"mesh.store_source_json": ("Store source JSON on asset", "Quell-JSON am Asset speichern"), "mesh.save_connection": ("Save connection and behavior", "Verbindung und Verhalten speichern"),
|
||||
"mesh.field_mappings": ("Field mappings", "Feld-Mappings"), "mesh.mappings_help": ("Synchronization uses only the enabled rules in this table, including system and custom fields. A debug line is written for each applied mapping when a value changes. Dot notation reads nested JSON values; [] traverses lists and | separates alternative paths.", "Die Synchronisierung verwendet ausschließlich die aktivierten Regeln dieser Tabelle – auch für System- und eigene Felder. Im Live-Protokoll erscheint bei einer Änderung für jedes angewendete Mapping eine Debug-Zeile. Punktnotation liest verschachtelte JSON-Werte. [] durchläuft Listen; | trennt alternative Pfade."),
|
||||
"mesh.mappings_examples": ("Examples", "Beispiele"), "mesh.priority": ("Priority", "Prio"), "mesh.target_field": ("Target field", "Zielfeld"),
|
||||
"mesh.transformation": ("Transformation", "Transformation"), "mesh.multi_values": ("Multiple values", "Mehrfachwerte"), "mesh.separator": ("Separator", "Trenner"), "mesh.update_rule": ("Update rule", "Update-Regel"),
|
||||
"mesh.transformation": ("Transformation", "Transformation"), "mesh.multi_values": ("Multiple values", "Mehrfachwerte"), "mesh.separator": ("Separator", "Trenner"), "mesh.update_rule": ("Update rule", "Update-Regel"), "mesh.empty_value": ("Value if empty", "Wert, wenn leer"), "mesh.empty_value_help": ("Optional. Written when the MeshCentral source is missing or empty, converted like a normal value (e.g. 'false' for a boolean field). Leave empty to keep the field untouched. Combine with 'MeshCentral wins' so later changes are applied.", "Optional. Wird geschrieben, wenn der Wert in MeshCentral fehlt oder leer ist, und wie ein normaler Wert umgewandelt (z. B. 'false' für ein Ja/Nein-Feld). Leer lassen, um das Feld unverändert zu lassen. Mit der Regel 'MeshCentral gewinnt' kombinieren, damit spätere Änderungen übernommen werden."),
|
||||
"mesh.system_mapping": ("System mapping", "System-Mapping"), "mesh.custom_mapping": ("Custom rule", "Eigene Regel"),
|
||||
"mesh.rule_fill_empty": ("Empty fields only", "Nur leere Felder"), "mesh.rule_mesh_wins": ("MeshCentral wins", "MeshCentral gewinnt"), "mesh.rule_local_wins": ("Local value wins", "Lokaler Wert gewinnt"),
|
||||
"mesh.save_mappings": ("Save mapping rules", "Mapping-Regeln speichern"), "mesh.new_mapping": ("New mapping rule", "Neue Mapping-Regel"),
|
||||
@@ -1810,6 +1819,51 @@ BASE_TRANSLATIONS.update({
|
||||
"errors.asset_or_category_not_found": ("Asset or category not found.", "Asset oder Kategorie nicht gefunden."),
|
||||
"errors.asset_save_unique": ("The asset could not be saved. The asset tag, serial number or MeshCentral node ID may already be in use.", "Asset konnte nicht gespeichert werden. Inventarnummer, Seriennummer oder MeshCentral Node-ID ist möglicherweise bereits vergeben."),
|
||||
"errors.asset_tag_in_use": ("The asset tag {asset_tag} is already in use.", "Die Inventarnummer {asset_tag} ist bereits vergeben."),
|
||||
'fields.conversion.title': ('Change data type', 'Datentyp ändern'),
|
||||
'fields.conversion.subtitle': ('Field {field}: {from_type} → {to_type}. Nothing has been changed yet.', 'Feld {field}: {from_type} → {to_type}. Es wurde noch nichts geändert.'),
|
||||
'fields.conversion.summary': ('Preview', 'Vorschau'),
|
||||
'fields.conversion.count_converted': ('{count} values can be converted', '{count} Werte lassen sich umwandeln'),
|
||||
'fields.conversion.count_empty': ('{count} empty values (stay empty)', '{count} leere Werte (bleiben leer)'),
|
||||
'fields.conversion.count_failed': ('{count} values cannot be converted and need a decision', '{count} Werte lassen sich nicht umwandeln und brauchen eine Entscheidung'),
|
||||
'fields.conversion.safety_help': ('The conversion runs in one transaction: either every value is converted or nothing changes. A safety copy of all old values is written to the backup directory, and every change is recorded in the asset history.', 'Die Umwandlung läuft in einer Transaktion: Entweder werden alle Werte umgewandelt oder nichts ändert sich. Vorher wird eine Sicherungskopie aller alten Werte im Backup-Verzeichnis abgelegt, und jede Änderung wird in der Asset-Historie eingetragen.'),
|
||||
'fields.conversion.failed_title': ('Values that cannot be converted', 'Nicht umwandelbare Werte'),
|
||||
'fields.conversion.failed_help': ('Nothing is deleted without your decision. Replace each value with a valid value or clear it explicitly. Alternatively cancel and correct the values in the assets first.', 'Ohne deine Entscheidung wird nichts gelöscht. Ersetze jeden Wert durch einen gültigen Wert oder leere ihn ausdrücklich. Alternativ abbrechen und die Werte zuerst in den Assets korrigieren.'),
|
||||
'fields.conversion.apply_all': ('For all values below', 'Für alle Werte unten'),
|
||||
'fields.conversion.apply_all_button': ('Apply to all', 'Für alle übernehmen'),
|
||||
'fields.conversion.replace_with': ('Replace with', 'Ersetzen durch'),
|
||||
'fields.conversion.clear': ('Clear value', 'Wert leeren'),
|
||||
'fields.conversion.replacement': ('Replacement value', 'Ersatzwert'),
|
||||
'fields.conversion.asset': ('Asset', 'Asset'),
|
||||
'fields.conversion.current_value': ('Current value', 'Aktueller Wert'),
|
||||
'fields.conversion.new_value': ('New value', 'Neuer Wert'),
|
||||
'fields.conversion.reason': ('Reason', 'Grund'),
|
||||
'fields.conversion.decision': ('Decision', 'Entscheidung'),
|
||||
'fields.conversion.converted_title': ('{count} values that will be converted', '{count} Werte, die umgewandelt werden'),
|
||||
'fields.conversion.mappings_title': ('MeshCentral mappings', 'MeshCentral-Mappings'),
|
||||
'fields.conversion.mappings_help': ('These mappings write into this field, but their transformation does not fit the new data type.', 'Diese Mappings schreiben in dieses Feld, ihre Transformation passt aber nicht zum neuen Datentyp.'),
|
||||
'fields.conversion.adjust_mappings': ('Adjust the transformation of these mappings', 'Transformation dieser Mappings anpassen'),
|
||||
'fields.conversion.execute': ('Convert and save', 'Umwandeln und speichern'),
|
||||
'fields.conversion.confirm': ('Convert all values of {field} to {to_type} now?', 'Alle Werte von {field} jetzt in {to_type} umwandeln?'),
|
||||
'fields.conversion.changed': ('The stored values have changed since the preview. Please check the conversion again.', 'Die gespeicherten Werte haben sich seit der Vorschau geändert. Bitte prüfe die Umwandlung erneut.'),
|
||||
'fields.conversion.decisions_missing': ('Please decide for every value that cannot be converted.', 'Bitte entscheide für jeden nicht umwandelbaren Wert.'),
|
||||
'fields.conversion.done': ('Data type changed: {count} values converted. Safety copy: {file}', 'Datentyp geändert: {count} Werte umgewandelt. Sicherungskopie: {file}'),
|
||||
'fields.conversion.reason.not_a_boolean': ('Not a yes/no value', 'Kein Ja/Nein-Wert'),
|
||||
'fields.conversion.reason.not_a_number': ('Not a number', 'Keine Zahl'),
|
||||
'fields.conversion.reason.decimals_would_be_lost': ('Decimal places would be lost', 'Nachkommastellen würden verloren gehen'),
|
||||
'fields.conversion.reason.not_a_date': ('Not a date (YYYY-MM-DD or DD.MM.YYYY)', 'Kein Datum (JJJJ-MM-TT oder TT.MM.JJJJ)'),
|
||||
'fields.conversion.reason.not_a_datetime': ('Not a date and time', 'Kein Datum mit Uhrzeit'),
|
||||
'fields.conversion.reason.time_would_be_lost': ('The time would be lost', 'Die Uhrzeit würde verloren gehen'),
|
||||
'fields.conversion.reason.not_an_email': ('Not an e-mail address', 'Keine E-Mail-Adresse'),
|
||||
'fields.conversion.reason.not_a_url': ('Not a URL', 'Keine URL'),
|
||||
'fields.conversion.reason.not_an_ip': ('Not an IP address', 'Keine IP-Adresse'),
|
||||
'fields.conversion.reason.unsupported': ('Not convertible', 'Nicht umwandelbar'),
|
||||
'fields.conversion.reason.undecided': ('Decision missing', 'Entscheidung fehlt'),
|
||||
'fields.conversion.reason.empty_replacement': ('Replacement value missing', 'Ersatzwert fehlt'),
|
||||
'errors.data_type_conversion_unsupported': ('Stored values of type {from_type} cannot be converted to {to_type}. Supported are text, number, yes/no, date, date and time, URL, e-mail and IP address.', 'Gespeicherte Werte vom Typ {from_type} lassen sich nicht in {to_type} umwandeln. Unterstützt werden Text, Zahl, Ja/Nein, Datum, Datum mit Uhrzeit, URL, E-Mail und IP-Adresse.'),
|
||||
'errors.conversion_backup_failed': ('The safety copy of the old values could not be written. Nothing was changed.', 'Die Sicherungskopie der alten Werte konnte nicht geschrieben werden. Es wurde nichts geändert.'),
|
||||
'mesh.empty_value_guard': ('Only if present', 'Nur wenn vorhanden'),
|
||||
'mesh.empty_value_guard_help': ('Optional path in the device JSON. The value for empty sources is only written if this path exists for the device. Empty = parent path of the source path.', 'Optionaler Pfad im Geräte-JSON. Der Wert für leere Quellen wird nur geschrieben, wenn dieser Pfad beim Gerät vorhanden ist. Leer = übergeordneter Pfad des Quellpfads.'),
|
||||
"errors.bulk_value_invalid": ("The value is not valid for the field type {data_type}.", "Der Wert ist für den Feldtyp {data_type} nicht gültig."),
|
||||
"errors.bulk_field_not_allowed":("The selected field is not allowed in all selected asset categories.", "Das gewählte Feld ist nicht in allen ausgewählten Gerätekategorien zugelassen."),
|
||||
"errors.bulk_save_failed": ("The data could not be saved for all assets.", "Die Daten konnten nicht für alle Assets gespeichert werden."),
|
||||
"errors.callback_part_too_large": ("{label} is too large.", "{label} ist zu groß."),
|
||||
@@ -1829,7 +1883,7 @@ BASE_TRANSLATIONS.update({
|
||||
"errors.data_type_locked": ("The data type can only be changed while the custom field has no stored values.", "Der Datentyp kann nur geändert werden, solange das eigene Feld keine gespeicherten Werte hat."),
|
||||
"errors.excel_invalid": ("The Excel file is invalid or damaged.", "Die Excel-Datei ist ungültig oder beschädigt."),
|
||||
"errors.excel_no_header": ("The Excel file has no header row.", "Die Excel-Datei enthält keine Kopfzeile."),
|
||||
"errors.field_has_values": ("This field contains values for {count} assets. Confirm deletion of all values.", "Dieses Feld enthält Werte für {count} Assets. Bitte das Löschen aller Werte bestätigen."),
|
||||
"errors.field_has_values": ("This field now contains values for {count} assets. Please reload the page and confirm the deletion again.", "Dieses Feld enthält inzwischen Werte für {count} Assets. Bitte die Seite neu laden und das Löschen erneut bestätigen."),
|
||||
"errors.field_name_exists": ("A field with this name already exists.", "Ein Feld mit diesem Namen existiert bereits."),
|
||||
"errors.field_name_invalid": ("The field name is invalid or already reserved.", "Der Feldname ist ungültig oder bereits reserviert."),
|
||||
"errors.field_not_found": ("Field not found.", "Feld nicht gefunden."),
|
||||
|
||||
+469
-127
@@ -39,7 +39,7 @@ from starlette.middleware.sessions import SessionMiddleware
|
||||
from starlette.requests import ClientDisconnect
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy import and_, case, func, or_, false, distinct, cast, String
|
||||
from sqlalchemy import and_, case, func, or_, not_, false, distinct, cast, String
|
||||
from sqlalchemy.orm import Session, aliased, joinedload, selectinload, load_only, contains_eager
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from jinja2 import pass_context
|
||||
@@ -51,6 +51,7 @@ from .models import Asset, AssetHistory, Category, CategoryField, StatusOption,
|
||||
from .config import load_config, public_config, save_config
|
||||
from .meshcentral import synchronize, fetch_device_summaries_for_linking
|
||||
from .migrations import apply_lightweight_migrations
|
||||
from . import field_conversion
|
||||
from .i18n import seed_i18n, translate, dictionary as translation_dictionary, languages as i18n_languages, clear_translation_cache
|
||||
from .software_control import token_hash, detect_platform, execute_job, build_registry_user_script, cleanup_stale_remote_job_directories
|
||||
from .job_state import backfill_asset_job_states, filter_state_key, sync_asset_job_state
|
||||
@@ -1686,6 +1687,8 @@ def _seed_mesh_field_mappings(db: Session) -> None:
|
||||
priority=int(item.get("priority") or (1000 + index)),
|
||||
description=item.get("description"),
|
||||
update_rule=str(item.get("update_rule") or "fill_empty"),
|
||||
empty_value=(str(item.get("empty_value")).strip()[:255] or None) if item.get("empty_value") not in (None, "") else None,
|
||||
empty_value_guard=(str(item.get("empty_value_guard")).strip()[:255] or None) if item.get("empty_value_guard") not in (None, "") else None,
|
||||
is_system=False,
|
||||
)
|
||||
db.add(row)
|
||||
@@ -2699,22 +2702,69 @@ def dashboard(request: Request, db: Session = Depends(get_db)):
|
||||
|
||||
BULK_EDIT_EXCLUDED_FIELDS = {"asset_tag", "serial_number", "mesh_node_id"}
|
||||
|
||||
def _is_custom_category_field(field: CategoryField) -> bool:
|
||||
return bool(field.definition and not field.definition.is_system)
|
||||
|
||||
|
||||
def _bulk_edit_fields_for_assets(assets: list[Asset]) -> list[dict]:
|
||||
"""Return active fields shared by all selected asset categories."""
|
||||
"""Return active fields shared by all selected asset categories.
|
||||
|
||||
Custom (non-system) fields are not Asset attributes; they are included via
|
||||
their field definition and stored in AssetFieldValue.
|
||||
"""
|
||||
if not assets:
|
||||
return []
|
||||
category_maps = []
|
||||
for asset in assets:
|
||||
fields = {
|
||||
field.field_name: _definition_label(field)
|
||||
field.field_name: field
|
||||
for field in asset.category.visible_fields
|
||||
if field.active and hasattr(asset, field.field_name) and field.field_name not in BULK_EDIT_EXCLUDED_FIELDS and not _definition_readonly(field) and (not field.definition or field.definition.bulk_edit)
|
||||
if field.active
|
||||
and (hasattr(asset, field.field_name) or _is_custom_category_field(field))
|
||||
and field.field_name not in BULK_EDIT_EXCLUDED_FIELDS
|
||||
and not _definition_readonly(field)
|
||||
and (not field.definition or field.definition.bulk_edit)
|
||||
}
|
||||
category_maps.append(fields)
|
||||
common = set(category_maps[0])
|
||||
for item in category_maps[1:]:
|
||||
common &= set(item)
|
||||
return [{"field_name": name, "label": category_maps[0][name]} for name in sorted(common, key=lambda n: category_maps[0][n].casefold())]
|
||||
result = []
|
||||
for name in common:
|
||||
field = category_maps[0][name]
|
||||
custom = _is_custom_category_field(field)
|
||||
result.append({
|
||||
"field_name": name,
|
||||
"label": _definition_label(field),
|
||||
"custom": custom,
|
||||
"definition": field.definition if custom else None,
|
||||
"data_type": field.definition.data_type if field.definition else "short_text",
|
||||
})
|
||||
return sorted(result, key=lambda item: item["label"].casefold())
|
||||
|
||||
|
||||
def _bulk_custom_value(definition: FieldDefinition, value: str | None):
|
||||
"""Validate a bulk-edit value for a custom field; raise a translated 400 on bad input."""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if definition.data_type == "integer":
|
||||
int(value)
|
||||
elif definition.data_type == "decimal":
|
||||
float(value.replace(",", "."))
|
||||
value = value.replace(",", ".")
|
||||
elif definition.data_type == "boolean":
|
||||
if value.lower() not in {"true", "false", "1", "0", "on", "yes", "no"}:
|
||||
raise ValueError(value)
|
||||
elif definition.data_type == "date":
|
||||
date.fromisoformat(value)
|
||||
elif definition.data_type == "datetime":
|
||||
datetime.fromisoformat(value)
|
||||
elif definition.data_type == "json":
|
||||
json.loads(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise TranslatedHTTPException(400, "errors.bulk_value_invalid", "The value is not valid for the field type {data_type}.", data_type=definition.data_type) from exc
|
||||
return value
|
||||
|
||||
|
||||
def _selected_asset_ids(values: list[str]) -> list[int]:
|
||||
@@ -4808,10 +4858,33 @@ def assets_bulk_edit_apply(request: Request, asset_ids: list[str] = Form([]), fi
|
||||
assets = (db.query(Asset).options(joinedload(Asset.category).joinedload(Category.visible_fields)).filter(Asset.id.in_(ids)).all())
|
||||
if not ids or len(assets) != len(ids):
|
||||
raise TranslatedHTTPException(400, "errors.selection_empty_or_incomplete", "The selection is empty or no longer complete.")
|
||||
allowed = {"category_id": "Kategorie", **{item["field_name"]: item["label"] for item in _bulk_edit_fields_for_assets(assets)}}
|
||||
bulk_fields = _bulk_edit_fields_for_assets(assets)
|
||||
allowed = {"category_id": "Kategorie", **{item["field_name"]: item["label"] for item in bulk_fields}}
|
||||
if field_name not in allowed:
|
||||
raise TranslatedHTTPException(400, "errors.bulk_field_not_allowed", "The selected field is not allowed in all selected asset categories.")
|
||||
value = _normalize_optional_text(new_value)
|
||||
custom_definition = next((item["definition"] for item in bulk_fields if item["field_name"] == field_name and item["custom"]), None)
|
||||
if custom_definition is not None:
|
||||
value = _bulk_custom_value(custom_definition, value)
|
||||
changed = 0
|
||||
for asset in assets:
|
||||
old_value = _custom_value_get(asset, custom_definition, db)
|
||||
if _display_value(old_value) == _display_value(value):
|
||||
continue
|
||||
_custom_value_set(asset, custom_definition, value, db)
|
||||
db.flush()
|
||||
new_stored = _custom_value_get(asset, custom_definition, db)
|
||||
if _display_value(old_value) == _display_value(new_stored):
|
||||
continue
|
||||
_record_asset_history(db, asset, {allowed[field_name]: {"old": _display_value(old_value), "new": _display_value(new_stored)}}, source="bulk-update", changed_by=_changed_by(request))
|
||||
changed += 1
|
||||
try:
|
||||
db.commit()
|
||||
except (IntegrityError, ValueError) as exc:
|
||||
db.rollback()
|
||||
raise TranslatedHTTPException(400, "errors.bulk_save_failed", "The data could not be saved for all assets.") from exc
|
||||
target = f"/assets?category_id={category_id}" if category_id else "/assets"
|
||||
return RedirectResponse(f"{target}{'&' if '?' in target else '?'}toast_success={quote(_translate_request(request, 'assets.toast.bulk_updated', '{count} assets updated.', count=changed))}", status_code=303)
|
||||
parent_asset = None
|
||||
target_category = None
|
||||
if field_name == "category_id":
|
||||
@@ -5665,6 +5738,13 @@ def _software_installation_rows(db: Session):
|
||||
|
||||
|
||||
|
||||
SOFTWARE_JOB_TYPE_CODES = ("software_inventory", "software_deployment", "job_definition")
|
||||
SOFTWARE_JOB_ACTION_CODES = ("run", "install", "uninstall", "reinstall", "update")
|
||||
SOFTWARE_JOB_STATUS_CODES = ("created", "sending", "sent", "running", "success", "partial", "failed", "timeout", "cancelled")
|
||||
# Columns of the recent-job table that offer the server-side value list.
|
||||
# Job ID and time are (nearly) unique per job; they keep the range helper.
|
||||
SOFTWARE_JOB_VALUE_LIST_COLUMNS = ("asset", "job_type", "package", "action", "priority", "platform", "status")
|
||||
|
||||
_SOFTWARE_JOB_FILTER_KEYS = (
|
||||
"job_id",
|
||||
"created_at",
|
||||
@@ -5755,6 +5835,7 @@ def _translated_filter_codes(
|
||||
prefix: str,
|
||||
codes: tuple[str, ...],
|
||||
search_value: str,
|
||||
exact: bool = False,
|
||||
) -> list[str]:
|
||||
"""Map translated, partially entered labels back to their internal codes.
|
||||
|
||||
@@ -5787,7 +5868,10 @@ def _translated_filter_codes(
|
||||
for code in codes:
|
||||
key = f"{prefix}.{code}"
|
||||
label = cache["own"].get(key) or cache["en"].get(key) or code
|
||||
if needle in _normalize_filter_text(code) or needle in _normalize_filter_text(label):
|
||||
if exact:
|
||||
if needle in (_normalize_filter_text(code), _normalize_filter_text(label)):
|
||||
matches.append(code)
|
||||
elif needle in _normalize_filter_text(code) or needle in _normalize_filter_text(label):
|
||||
matches.append(code)
|
||||
return matches
|
||||
|
||||
@@ -5952,149 +6036,236 @@ def _multi_filter_terms(value: Any, *, max_terms: int = 200) -> list[str]:
|
||||
return terms
|
||||
|
||||
|
||||
def _filter_term_parts(value: str) -> tuple[bool, str]:
|
||||
"""Split a filter term into (exact, text): '=abc' compares the whole value."""
|
||||
text = str(value or "").strip()
|
||||
if text.startswith("=") and not text.startswith("=="):
|
||||
return True, text[1:].strip()
|
||||
return False, text
|
||||
|
||||
|
||||
def _sql_text_matches(column: Any, value: str):
|
||||
"""'=value' is an exact (normalized) comparison, everything else a substring search."""
|
||||
exact, text = _filter_term_parts(value)
|
||||
if text.lower() == "@empty":
|
||||
return func.coalesce(cast(column, String), "") == ""
|
||||
if text.lower() == "@notempty":
|
||||
return func.coalesce(cast(column, String), "") != ""
|
||||
if exact:
|
||||
return _sql_normalized_filter_text(column) == _normalize_filter_text(text)
|
||||
return _sql_text_contains(column, text)
|
||||
|
||||
|
||||
def _combine_filter_terms(terms: list[str], condition_for):
|
||||
"""Combine the line-based terms of one column.
|
||||
|
||||
Lines are OR-linked includes; lines starting with '!' are excludes. A row
|
||||
passes when it matches at least one include (if there are any) and none of
|
||||
the excludes. NULL results of an exclude count as "not matched".
|
||||
"""
|
||||
includes = [term for term in terms if not term.startswith("!")]
|
||||
excludes = [term[1:].strip() for term in terms if term.startswith("!") and term[1:].strip()]
|
||||
parts = []
|
||||
if includes:
|
||||
parts.append(or_(*[condition_for(term) for term in includes]))
|
||||
if excludes:
|
||||
parts.append(not_(func.coalesce(or_(*[condition_for(term) for term in excludes]), false())))
|
||||
return and_(*parts) if parts else None
|
||||
|
||||
|
||||
def _apply_software_job_filters(query: Any, request: Request, filters: dict[str, str]):
|
||||
"""Apply all recent-job filters before LIMIT is evaluated.
|
||||
|
||||
Multiple lines within one column are OR-linked. Different columns remain
|
||||
Multiple lines within one column are OR-linked, lines starting with '!'
|
||||
exclude matching rows, '=value' compares exactly. Different columns remain
|
||||
AND-linked. This allows users to paste a column copied from Excel directly
|
||||
into a table filter without changing the normal single-value behavior.
|
||||
"""
|
||||
parameters_text = cast(SoftwareJob.parameters, String)
|
||||
|
||||
terms = _multi_filter_terms(filters["job_id"])
|
||||
if terms:
|
||||
conditions = []
|
||||
for value in terms:
|
||||
def job_id_condition(value: str):
|
||||
advanced = _software_job_numeric_filter(SoftwareJob.id, value)
|
||||
if advanced is not None:
|
||||
conditions.append(advanced)
|
||||
elif value.isdigit():
|
||||
conditions.append(SoftwareJob.id == int(value))
|
||||
else:
|
||||
conditions.append(_sql_text_contains(SoftwareJob.id, value))
|
||||
query = query.filter(or_(*conditions))
|
||||
return advanced
|
||||
if value.isdigit():
|
||||
return SoftwareJob.id == int(value)
|
||||
return _sql_text_matches(SoftwareJob.id, value)
|
||||
|
||||
terms = _multi_filter_terms(filters["created_at"])
|
||||
if terms:
|
||||
query = query.filter(or_(*[
|
||||
_software_job_date_filter(SoftwareJob.created_at, value)
|
||||
for value in terms
|
||||
]))
|
||||
def created_condition(value: str):
|
||||
return _software_job_date_filter(SoftwareJob.created_at, value)
|
||||
|
||||
terms = _multi_filter_terms(filters["asset"])
|
||||
if terms:
|
||||
query = query.filter(or_(*[
|
||||
_sql_text_contains(Asset.name, value)
|
||||
for value in terms
|
||||
]))
|
||||
def asset_condition(value: str):
|
||||
return _sql_text_matches(Asset.name, value)
|
||||
|
||||
terms = _multi_filter_terms(filters["job_type"])
|
||||
if terms:
|
||||
term_conditions = []
|
||||
for value in terms:
|
||||
conditions = [
|
||||
_sql_text_contains(SoftwareJob.job_type, value),
|
||||
_sql_text_contains(parameters_text, value),
|
||||
]
|
||||
job_type_codes = _translated_filter_codes(
|
||||
request,
|
||||
"jobs.type",
|
||||
("software_inventory", "job_definition"),
|
||||
value,
|
||||
)
|
||||
def job_type_condition(value: str):
|
||||
exact, text = _filter_term_parts(value)
|
||||
conditions = [_sql_text_matches(SoftwareJob.job_type, value)]
|
||||
if not exact:
|
||||
conditions.append(_sql_text_contains(parameters_text, text))
|
||||
job_type_codes = _translated_filter_codes(request, "jobs.type", SOFTWARE_JOB_TYPE_CODES, text, exact=exact)
|
||||
if job_type_codes:
|
||||
conditions.append(SoftwareJob.job_type.in_(job_type_codes))
|
||||
job_kind_codes = _translated_filter_codes(
|
||||
request,
|
||||
"jobdefs.kind",
|
||||
("script", "registry"),
|
||||
value,
|
||||
)
|
||||
for kind in job_kind_codes:
|
||||
conditions.append(
|
||||
and_(
|
||||
SoftwareJob.job_type == "job_definition",
|
||||
_sql_text_contains(parameters_text, kind),
|
||||
)
|
||||
)
|
||||
term_conditions.append(or_(*conditions))
|
||||
query = query.filter(or_(*term_conditions))
|
||||
for kind in _translated_filter_codes(request, "jobdefs.kind", ("script", "registry"), text, exact=exact):
|
||||
if exact:
|
||||
# Same rule as the table display: missing kind = script.
|
||||
stored_kind = parameters_text.contains(f'"definition_job_kind": "{kind}"')
|
||||
if kind == "script":
|
||||
stored_kind = or_(stored_kind, ~parameters_text.contains('"definition_job_kind"'))
|
||||
conditions.append(and_(SoftwareJob.job_type == "job_definition", stored_kind))
|
||||
else:
|
||||
conditions.append(and_(SoftwareJob.job_type == "job_definition", _sql_text_contains(parameters_text, kind)))
|
||||
return or_(*conditions)
|
||||
|
||||
terms = _multi_filter_terms(filters["package"])
|
||||
if terms:
|
||||
query = query.filter(or_(*[
|
||||
or_(
|
||||
_sql_text_contains(SoftwarePackage.name, value),
|
||||
_sql_text_contains(parameters_text, value),
|
||||
def package_condition(value: str):
|
||||
exact, text = _filter_term_parts(value)
|
||||
if exact:
|
||||
# The table shows the job-definition name for job definitions, otherwise the package name.
|
||||
# JSON may store non-ASCII characters escaped (json) or plain (jsonb).
|
||||
definition_name = or_(
|
||||
parameters_text.contains(json.dumps({"definition_name": text})[1:-1]),
|
||||
parameters_text.contains(json.dumps({"definition_name": text}, ensure_ascii=False)[1:-1]),
|
||||
)
|
||||
for value in terms
|
||||
]))
|
||||
return or_(
|
||||
and_(SoftwareJob.job_type != "job_definition", _sql_text_matches(SoftwarePackage.name, value)),
|
||||
and_(SoftwareJob.job_type == "job_definition", or_(definition_name, _sql_text_matches(SoftwarePackage.name, value))),
|
||||
)
|
||||
return or_(_sql_text_contains(SoftwarePackage.name, text), _sql_text_contains(parameters_text, text))
|
||||
|
||||
terms = _multi_filter_terms(filters["action"])
|
||||
if terms:
|
||||
term_conditions = []
|
||||
for value in terms:
|
||||
conditions = [_sql_text_contains(SoftwareJob.action, value)]
|
||||
action_codes = _translated_filter_codes(
|
||||
request,
|
||||
"jobs.action",
|
||||
("run", "install", "uninstall", "update"),
|
||||
value,
|
||||
)
|
||||
def action_condition(value: str):
|
||||
exact, text = _filter_term_parts(value)
|
||||
conditions = [_sql_text_matches(SoftwareJob.action, value)]
|
||||
action_codes = _translated_filter_codes(request, "jobs.action", SOFTWARE_JOB_ACTION_CODES, text, exact=exact)
|
||||
if action_codes:
|
||||
conditions.append(SoftwareJob.action.in_(action_codes))
|
||||
term_conditions.append(or_(*conditions))
|
||||
query = query.filter(or_(*term_conditions))
|
||||
return or_(*conditions)
|
||||
|
||||
terms = _multi_filter_terms(filters["priority"])
|
||||
if terms:
|
||||
conditions = []
|
||||
for value in terms:
|
||||
def priority_condition(value: str):
|
||||
advanced = _software_job_numeric_filter(SoftwareJob.priority, value)
|
||||
if advanced is not None:
|
||||
conditions.append(advanced)
|
||||
elif re.fullmatch(r"[-+]?\d+", value):
|
||||
conditions.append(SoftwareJob.priority == int(value))
|
||||
else:
|
||||
conditions.append(_sql_text_contains(SoftwareJob.priority, value))
|
||||
query = query.filter(or_(*conditions))
|
||||
return advanced
|
||||
if re.fullmatch(r"[-+]?\d+", value):
|
||||
return SoftwareJob.priority == int(value)
|
||||
return _sql_text_matches(SoftwareJob.priority, value)
|
||||
|
||||
terms = _multi_filter_terms(filters["platform"])
|
||||
if terms:
|
||||
query = query.filter(or_(*[
|
||||
_sql_text_contains(SoftwareJob.platform, value)
|
||||
for value in terms
|
||||
]))
|
||||
def platform_condition(value: str):
|
||||
return _sql_text_matches(SoftwareJob.platform, value)
|
||||
|
||||
terms = _multi_filter_terms(filters["status"])
|
||||
if terms:
|
||||
term_conditions = []
|
||||
for value in terms:
|
||||
conditions = [_sql_text_contains(SoftwareJob.status, value)]
|
||||
def status_condition(value: str):
|
||||
exact, text = _filter_term_parts(value)
|
||||
conditions = [_sql_text_matches(SoftwareJob.status, value)]
|
||||
status_codes = _translated_filter_codes(
|
||||
request,
|
||||
"software.status",
|
||||
(
|
||||
"created",
|
||||
"sending",
|
||||
"sent",
|
||||
"running",
|
||||
"success",
|
||||
"partial",
|
||||
"failed",
|
||||
"timeout",
|
||||
"cancelled",
|
||||
),
|
||||
value,
|
||||
SOFTWARE_JOB_STATUS_CODES,
|
||||
text,
|
||||
exact=exact,
|
||||
)
|
||||
if status_codes:
|
||||
conditions.append(SoftwareJob.status.in_(status_codes))
|
||||
term_conditions.append(or_(*conditions))
|
||||
query = query.filter(or_(*term_conditions))
|
||||
return or_(*conditions)
|
||||
|
||||
for key, condition_for in (
|
||||
("job_id", job_id_condition),
|
||||
("created_at", created_condition),
|
||||
("asset", asset_condition),
|
||||
("job_type", job_type_condition),
|
||||
("package", package_condition),
|
||||
("action", action_condition),
|
||||
("priority", priority_condition),
|
||||
("platform", platform_condition),
|
||||
("status", status_condition),
|
||||
):
|
||||
condition = _combine_filter_terms(_multi_filter_terms(filters[key]), condition_for)
|
||||
if condition is not None:
|
||||
query = query.filter(condition)
|
||||
return query
|
||||
|
||||
|
||||
def _software_job_display_value(request: Request, job: SoftwareJob, column: str) -> str:
|
||||
"""The value a recent-job table cell shows (see software.html)."""
|
||||
if column == "asset":
|
||||
return job.asset.name if job.asset else ""
|
||||
if column == "job_type":
|
||||
return _translate_request(request, job.display_job_type_key, job.display_job_type_fallback)
|
||||
if column == "package":
|
||||
return str(job.display_package_name or "")
|
||||
if column == "action":
|
||||
return _translate_request(request, f"jobs.action.{job.action}", job.action)
|
||||
if column == "priority":
|
||||
return "" if job.priority is None else str(job.priority)
|
||||
if column == "platform":
|
||||
return str(job.platform or "")
|
||||
if column == "status":
|
||||
return _translate_request(request, f"software.status.{job.status}", job.status)
|
||||
return ""
|
||||
|
||||
|
||||
SOFTWARE_JOB_VALUE_LIST_SCAN_LIMIT = 20000
|
||||
|
||||
|
||||
@app.get("/software/job-filter-values")
|
||||
def software_job_filter_values(request: Request, column: str, db: Session = Depends(get_db)):
|
||||
"""Distinct values of one recent-job column for the Excel-like value list.
|
||||
|
||||
Considers the jobs that pass the filters of all OTHER columns; ``checked``
|
||||
tells whether jobs with this value also pass the column's own filter.
|
||||
"""
|
||||
_require_admin(request)
|
||||
if column not in SOFTWARE_JOB_VALUE_LIST_COLUMNS:
|
||||
raise TranslatedHTTPException(400, "errors.invalid_filter_column", "This column has no value list.")
|
||||
filters = _software_job_filter_values(request)
|
||||
own_filter = filters.get(column, "")
|
||||
other_filters = {**filters, column: ""}
|
||||
|
||||
def base_query():
|
||||
return (
|
||||
db.query(SoftwareJob)
|
||||
.join(Asset, Asset.id == SoftwareJob.asset_id)
|
||||
.outerjoin(SoftwarePackage, SoftwarePackage.id == SoftwareJob.package_id)
|
||||
)
|
||||
|
||||
jobs = (
|
||||
_apply_software_job_filters(base_query(), request, other_filters)
|
||||
.options(
|
||||
load_only(
|
||||
SoftwareJob.id, SoftwareJob.asset_id, SoftwareJob.package_id, SoftwareJob.status,
|
||||
SoftwareJob.job_type, SoftwareJob.action, SoftwareJob.priority, SoftwareJob.platform,
|
||||
SoftwareJob.parameters,
|
||||
),
|
||||
contains_eager(SoftwareJob.asset).load_only(Asset.id, Asset.name),
|
||||
contains_eager(SoftwareJob.package).load_only(SoftwarePackage.id, SoftwarePackage.name),
|
||||
)
|
||||
.order_by(SoftwareJob.created_at.desc(), SoftwareJob.id.desc())
|
||||
.limit(SOFTWARE_JOB_VALUE_LIST_SCAN_LIMIT + 1)
|
||||
.all()
|
||||
)
|
||||
truncated = len(jobs) > SOFTWARE_JOB_VALUE_LIST_SCAN_LIMIT
|
||||
jobs = jobs[:SOFTWARE_JOB_VALUE_LIST_SCAN_LIMIT]
|
||||
passing_ids = None
|
||||
if own_filter.strip() and jobs:
|
||||
scanned_ids = [job.id for job in jobs]
|
||||
passing_ids = set()
|
||||
for start in range(0, len(scanned_ids), 1000):
|
||||
passing_ids.update(
|
||||
job_id for (job_id,) in _apply_software_job_filters(base_query(), request, filters)
|
||||
.filter(SoftwareJob.id.in_(scanned_ids[start:start + 1000]))
|
||||
.with_entities(SoftwareJob.id)
|
||||
.all()
|
||||
)
|
||||
_decorate_jobs_for_display(db, jobs)
|
||||
values: dict[str, dict[str, Any]] = {}
|
||||
for job in jobs:
|
||||
label = " ".join(_software_job_display_value(request, job, column).split())
|
||||
entry = values.setdefault(label, {"label": label, "count": 0, "checked": passing_ids is None})
|
||||
entry["count"] += 1
|
||||
if passing_ids is not None and job.id in passing_ids:
|
||||
entry["checked"] = True
|
||||
return JSONResponse(
|
||||
{"values": list(values.values()), "truncated": truncated, "scan_limit": SOFTWARE_JOB_VALUE_LIST_SCAN_LIMIT},
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/software")
|
||||
def software_overview(request: Request, db: Session = Depends(get_db)):
|
||||
_require_admin(request)
|
||||
@@ -9696,6 +9867,11 @@ def field_definition_create(request: Request, field_name: str = Form(...), label
|
||||
for category in db.query(Category).all():
|
||||
db.add(CategoryField(category_id=category.id, field_name=name, label=definition.label, field_definition_id=definition.id, active=False, required=False, show_in_list=False, readonly=definition.readonly, sort_order=definition.sort_order))
|
||||
# Add English fallback translation; German can be maintained in translation editor.
|
||||
existing_translation = db.query(Translation).filter(Translation.translation_key == definition.translation_key, Translation.language_code == 'en').first()
|
||||
if existing_translation:
|
||||
# Left over from an earlier field with the same name (deleted before 0.5.5.94).
|
||||
existing_translation.text_value = definition.label
|
||||
else:
|
||||
db.add(Translation(translation_key=definition.translation_key, language_code='en', text_value=definition.label))
|
||||
db.commit(); clear_translation_cache()
|
||||
except IntegrityError as exc:
|
||||
@@ -9709,24 +9885,181 @@ def field_definition_edit(definition_id: int, request: Request, db: Session = De
|
||||
if not definition: raise TranslatedHTTPException(404, "errors.field_not_found", "Field not found.")
|
||||
return templates.TemplateResponse('field_definition_form.html', {'request': request, 'definition': definition, 'data_types': FIELD_DATA_TYPES})
|
||||
|
||||
FIELD_DEFINITION_FLAG_FIELDS = ("readonly", "is_active", "searchable", "filterable", "chart_enabled", "excel_import", "excel_export", "bulk_edit", "is_default")
|
||||
|
||||
|
||||
def _apply_field_definition_attributes(definition: FieldDefinition, values: dict[str, Any]) -> None:
|
||||
"""Apply every editable attribute except the data type (shared by save and type conversion)."""
|
||||
definition.label = str(values.get("label") or "").strip() or definition.label
|
||||
definition.description = str(values.get("description") or "").strip() or None
|
||||
def flag(key: str) -> bool:
|
||||
return values.get(key) == "on"
|
||||
definition.readonly = True if definition.field_name in SYSTEM_READONLY_FIELDS else flag("readonly")
|
||||
definition.is_active = True if definition.is_system else flag("is_active")
|
||||
definition.searchable = flag("searchable"); definition.filterable = flag("filterable"); definition.chart_enabled = flag("chart_enabled")
|
||||
definition.excel_import = False if definition.readonly else flag("excel_import")
|
||||
definition.excel_export = flag("excel_export")
|
||||
definition.bulk_edit = False if definition.readonly else flag("bulk_edit")
|
||||
definition.is_default = flag("is_default")
|
||||
definition.list_width = _optional_form_int(values.get("list_width"), field_name="list_width", minimum=40, maximum=800)
|
||||
for link in definition.category_links:
|
||||
link.label = definition.label; link.readonly = definition.readonly
|
||||
|
||||
|
||||
def _yes_no_default_language(db: Session) -> tuple[str, str]:
|
||||
language_code = str(load_config().get("general", {}).get("default_language", "de") or "de")
|
||||
return (translate(db, language_code, "common.yes", "Yes"), translate(db, language_code, "common.no", "No"))
|
||||
|
||||
|
||||
MAPPING_TRANSFORM_FOR_TYPE = {"boolean": "boolean", "integer": "integer", "decimal": "decimal"}
|
||||
MAPPING_TRANSFORMS_COMPATIBLE = {
|
||||
"boolean": {"boolean"},
|
||||
"integer": {"integer"},
|
||||
"decimal": {"decimal", "integer", "sum_memory_gb", "sum_storage_gb"},
|
||||
}
|
||||
|
||||
|
||||
def _mapping_adjustments(db: Session, definition: FieldDefinition, to_type: str) -> list[dict[str, Any]]:
|
||||
"""MeshCentral mappings whose transformation does not fit the new data type."""
|
||||
result = []
|
||||
mappings = db.query(MeshFieldMapping).filter(MeshFieldMapping.target_field_name == definition.field_name).order_by(MeshFieldMapping.priority, MeshFieldMapping.id).all()
|
||||
for mapping in mappings:
|
||||
transform = mapping.transform or "raw"
|
||||
if to_type in MAPPING_TRANSFORMS_COMPATIBLE:
|
||||
suggestion = None if transform in MAPPING_TRANSFORMS_COMPATIBLE[to_type] else MAPPING_TRANSFORM_FOR_TYPE[to_type]
|
||||
else:
|
||||
suggestion = "string" if transform in {"boolean", "integer", "decimal"} else None
|
||||
if suggestion:
|
||||
result.append({"mapping": mapping, "current": transform, "suggestion": suggestion})
|
||||
return result
|
||||
|
||||
|
||||
def _field_conversion_page(request: Request, db: Session, definition: FieldDefinition, to_type: str, values: dict[str, Any], plan, *, errors: dict[int, str] | None = None, notice: str | None = None, status_code: int = 200):
|
||||
asset_ids = [item.asset_id for item in plan.converted + plan.failed] or [0]
|
||||
asset_names = {asset_id: name for asset_id, name in db.query(Asset.id, Asset.name).filter(Asset.id.in_(asset_ids)).all()}
|
||||
hidden = {key: values.get(key) for key in ("label", "description", "list_width", *FIELD_DEFINITION_FLAG_FIELDS) if values.get(key) not in (None, "")}
|
||||
return templates.TemplateResponse("field_type_conversion.html", {
|
||||
"request": request, "definition": definition, "to_type": to_type, "plan": plan, "hidden": hidden,
|
||||
"asset_names": asset_names, "data_types": FIELD_DATA_TYPES, "errors": errors or {}, "notice": notice,
|
||||
"form": values, "mapping_adjustments": _mapping_adjustments(db, definition, to_type),
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
CONVERSION_UNSUPPORTED_DEFAULT = "Stored values of type {from_type} cannot be converted to {to_type}. Supported are text, number, yes/no, date, date and time, URL, e-mail and IP address."
|
||||
|
||||
|
||||
@app.post('/settings/fields/{definition_id}/edit')
|
||||
def field_definition_update(definition_id: int, request: Request, label: str = Form(...), description: str = Form(''), data_type: str = Form('short_text'), readonly: str | None = Form(None), is_active: str | None = Form(None), searchable: str | None = Form(None), filterable: str | None = Form(None), chart_enabled: str | None = Form(None), excel_import: str | None = Form(None), excel_export: str | None = Form(None), bulk_edit: str | None = Form(None), is_default: str | None = Form(None), list_width: str | None = Form(None), db: Session = Depends(get_db)):
|
||||
async def field_definition_update(definition_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
_require_admin(request)
|
||||
form = await request.form()
|
||||
values = {key: form.get(key) for key in form.keys()}
|
||||
data_type = str(values.get("data_type") or "short_text")
|
||||
definition = db.get(FieldDefinition, definition_id)
|
||||
if not definition: raise TranslatedHTTPException(404, "errors.field_not_found", "Field not found.")
|
||||
if data_type not in FIELD_DATA_TYPES: raise TranslatedHTTPException(400, "errors.invalid_data_type", "Invalid data type.")
|
||||
if not definition.is_system and definition.data_type != data_type and db.query(AssetFieldValue).filter(AssetFieldValue.field_definition_id == definition.id).count():
|
||||
raise TranslatedHTTPException(400, "errors.data_type_locked", "The data type can only be changed while the custom field has no stored values.")
|
||||
definition.label=label.strip(); definition.description=description.strip() or None; definition.data_type=data_type
|
||||
definition.readonly=True if definition.field_name in SYSTEM_READONLY_FIELDS else readonly == 'on'
|
||||
definition.is_active=True if definition.is_system else is_active == 'on'
|
||||
definition.searchable=searchable == 'on'; definition.filterable=filterable == 'on'; definition.chart_enabled=chart_enabled == 'on'
|
||||
definition.excel_import=False if definition.readonly else excel_import == 'on'; definition.excel_export=excel_export == 'on'; definition.bulk_edit=False if definition.readonly else bulk_edit == 'on'; definition.is_default=is_default == 'on'; definition.list_width=_optional_form_int(list_width, field_name="list_width", minimum=40, maximum=800)
|
||||
for link in definition.category_links:
|
||||
link.label=definition.label; link.readonly=definition.readonly
|
||||
if not definition.is_system and definition.data_type != data_type:
|
||||
rows = db.query(AssetFieldValue).filter(AssetFieldValue.field_definition_id == definition.id).all()
|
||||
if any(not field_conversion.is_empty(field_conversion.read_value(row, definition.data_type)) for row in rows):
|
||||
if not field_conversion.is_supported(definition.data_type, data_type):
|
||||
raise TranslatedHTTPException(400, "errors.data_type_conversion_unsupported", CONVERSION_UNSUPPORTED_DEFAULT, from_type=definition.data_type, to_type=data_type)
|
||||
# Nothing is saved yet: show the conversion preview first.
|
||||
plan = field_conversion.plan_conversion(rows, definition, data_type, _yes_no_default_language(db))
|
||||
return _field_conversion_page(request, db, definition, data_type, values, plan)
|
||||
# Only empty rows: clear them so the new type starts consistently.
|
||||
for row in rows:
|
||||
field_conversion.write_value(row, data_type, None)
|
||||
definition.data_type = data_type
|
||||
_apply_field_definition_attributes(definition, values)
|
||||
db.commit(); clear_translation_cache()
|
||||
return RedirectResponse('/settings/fields?toast_success=' + quote(_translate_request(request, "fields.toast.saved", "Field saved.")), status_code=303)
|
||||
|
||||
|
||||
@app.post('/settings/fields/{definition_id}/convert-type')
|
||||
async def field_definition_convert_type(definition_id: int, request: Request, db: Session = Depends(get_db)):
|
||||
_require_admin(request)
|
||||
form = await request.form()
|
||||
values = {key: form.get(key) for key in form.keys()}
|
||||
to_type = str(values.get("to_type") or "")
|
||||
definition = db.get(FieldDefinition, definition_id)
|
||||
if not definition: raise TranslatedHTTPException(404, "errors.field_not_found", "Field not found.")
|
||||
if definition.is_system or to_type not in FIELD_DATA_TYPES or not field_conversion.is_supported(definition.data_type, to_type):
|
||||
raise TranslatedHTTPException(400, "errors.data_type_conversion_unsupported", CONVERSION_UNSUPPORTED_DEFAULT, from_type=definition.data_type, to_type=to_type)
|
||||
yes_no = _yes_no_default_language(db)
|
||||
# Lock the value rows (PostgreSQL) so nothing changes between check and commit.
|
||||
rows = db.query(AssetFieldValue).filter(AssetFieldValue.field_definition_id == definition.id).order_by(AssetFieldValue.id).with_for_update().all()
|
||||
plan = field_conversion.plan_conversion(rows, definition, to_type, yes_no)
|
||||
if plan.fingerprint != values.get("fingerprint"):
|
||||
db.rollback()
|
||||
plan = field_conversion.plan_conversion(db.query(AssetFieldValue).filter(AssetFieldValue.field_definition_id == definition.id).order_by(AssetFieldValue.id).all(), definition, to_type, yes_no)
|
||||
return _field_conversion_page(request, db, definition, to_type, values, plan, notice=_translate_request(request, "fields.conversion.changed", "The stored values have changed since the preview. Please check the conversion again."), status_code=409)
|
||||
|
||||
errors: dict[int, str] = {}
|
||||
for item in plan.failed:
|
||||
decision = values.get(f"decision_{item.row_id}")
|
||||
if decision == "clear":
|
||||
item.new_value = None
|
||||
item.new_display = ""
|
||||
elif decision == "replace":
|
||||
replacement = str(values.get(f"replacement_{item.row_id}") or "").strip()
|
||||
try:
|
||||
if not replacement:
|
||||
raise field_conversion.ConversionError("empty_replacement")
|
||||
item.new_value = field_conversion.convert_value(replacement, "short_text", to_type, yes_no)
|
||||
item.new_display = field_conversion.display(item.new_value, to_type, yes_no)
|
||||
except field_conversion.ConversionError as exc:
|
||||
errors[item.row_id] = str(exc) or "unsupported"
|
||||
else:
|
||||
errors[item.row_id] = "undecided"
|
||||
if errors:
|
||||
db.rollback()
|
||||
return _field_conversion_page(request, db, definition, to_type, values, plan, errors=errors, notice=_translate_request(request, "fields.conversion.decisions_missing", "Please decide for every value that cannot be converted."), status_code=400)
|
||||
|
||||
from_type = definition.data_type
|
||||
rows_by_id = {row.id: row for row in rows}
|
||||
planned = plan.converted + plan.failed
|
||||
planned_ids = {item.row_id for item in planned}
|
||||
# Safety copy of every old value before anything is changed.
|
||||
backup_file = BACKUP_DIR / f"field-conversion-{definition.field_name}-{datetime.utcnow().strftime('%Y%m%d-%H%M%S-%f')}.json"
|
||||
try:
|
||||
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with backup_file.open("x", encoding="utf-8") as handle: # never overwrite an existing copy
|
||||
handle.write(json.dumps({
|
||||
"field_name": definition.field_name, "field_definition_id": definition.id,
|
||||
"from_type": from_type, "to_type": to_type, "created_at": datetime.utcnow().isoformat() + "Z",
|
||||
"changed_by": _changed_by(request),
|
||||
"values": [{
|
||||
"row_id": row.id, "asset_id": row.asset_id, "value_text": row.value_text, "value_number": row.value_number,
|
||||
"value_boolean": row.value_boolean, "value_date": row.value_date,
|
||||
"value_datetime": row.value_datetime.isoformat() if row.value_datetime else None, "value_json": row.value_json,
|
||||
} for row in rows],
|
||||
}, ensure_ascii=False, indent=2, default=str))
|
||||
except OSError as exc:
|
||||
db.rollback()
|
||||
raise TranslatedHTTPException(500, "errors.conversion_backup_failed", "The safety copy of the old values could not be written. Nothing was changed.") from exc
|
||||
|
||||
try:
|
||||
assets = {asset.id: asset for asset in db.query(Asset).filter(Asset.id.in_([row.asset_id for row in rows] or [0])).all()}
|
||||
label = definition.label
|
||||
for item in planned:
|
||||
field_conversion.write_value(rows_by_id[item.row_id], to_type, item.new_value)
|
||||
if item.old_display != item.new_display and item.asset_id in assets:
|
||||
_record_asset_history(db, assets[item.asset_id], {label: {"old": item.old_display, "new": item.new_display}}, source="type-conversion", changed_by=_changed_by(request))
|
||||
for row in rows:
|
||||
if row.id not in planned_ids:
|
||||
field_conversion.write_value(row, to_type, None)
|
||||
if values.get("adjust_mappings") == "on":
|
||||
for adjustment in _mapping_adjustments(db, definition, to_type):
|
||||
adjustment["mapping"].transform = adjustment["suggestion"]
|
||||
definition.data_type = to_type
|
||||
_apply_field_definition_attributes(definition, values)
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
clear_translation_cache()
|
||||
message = _translate_request(request, "fields.conversion.done", "Data type changed: {count} values converted. Safety copy: {file}", count=len(planned), file=backup_file.name)
|
||||
return RedirectResponse('/settings/fields?toast_success=' + quote(message), status_code=303)
|
||||
|
||||
@app.post('/settings/fields/{definition_id}/delete')
|
||||
def field_definition_delete(definition_id: int, request: Request, confirm_values: str | None = Form(None), db: Session = Depends(get_db)):
|
||||
_require_admin(request)
|
||||
@@ -9734,8 +10067,13 @@ def field_definition_delete(definition_id: int, request: Request, confirm_values
|
||||
if not definition: raise TranslatedHTTPException(404, "errors.field_not_found", "Field not found.")
|
||||
if definition.is_system: raise TranslatedHTTPException(400, "errors.system_field_not_deletable", "System fields cannot be deleted.")
|
||||
count = db.query(AssetFieldValue).filter(AssetFieldValue.field_definition_id == definition.id).count()
|
||||
if count and confirm_values != 'on': raise TranslatedHTTPException(400, "errors.field_has_values", "This field contains values for {count} assets. Confirm deletion of all values.", count=count)
|
||||
db.delete(definition); db.commit()
|
||||
# The list page sends the value count it showed in the confirmation; if values
|
||||
# were added meanwhile, the user has to confirm again with the current count.
|
||||
if count and confirm_values != str(count): raise TranslatedHTTPException(400, "errors.field_has_values", "This field now contains values for {count} assets. Please reload the page and confirm the deletion again.", count=count)
|
||||
if definition.translation_key:
|
||||
# Remove the field's own translations, otherwise a new field with the same name is rejected.
|
||||
db.query(Translation).filter(Translation.translation_key == definition.translation_key).delete(synchronize_session=False)
|
||||
db.delete(definition); db.commit(); clear_translation_cache()
|
||||
return RedirectResponse('/settings/fields?toast_success=' + quote(_translate_request(request, "fields.toast.deleted", "Field deleted.")), status_code=303)
|
||||
|
||||
@app.post('/sync/meshcentral/settings')
|
||||
@@ -9867,6 +10205,8 @@ async def meshcentral_mappings_save(request: Request, db: Session = Depends(get_
|
||||
rule = str(form.get(prefix + 'update_rule') or 'fill_empty')
|
||||
row.update_rule = rule if rule in allowed_rules else 'fill_empty'
|
||||
row.description = str(form.get(prefix + 'description') or '').strip() or None
|
||||
row.empty_value = str(form.get(prefix + 'empty_value') or '').strip()[:255] or None
|
||||
row.empty_value_guard = str(form.get(prefix + 'empty_value_guard') or '').strip()[:255] or None
|
||||
db.commit()
|
||||
return RedirectResponse('/sync/meshcentral?toast_success=' + quote(_translate_request(request, "mesh.toast.mappings_saved", "Mapping rules saved.")), status_code=303)
|
||||
|
||||
@@ -9893,6 +10233,8 @@ async def meshcentral_mapping_new(request: Request, db: Session = Depends(get_db
|
||||
priority=(max_priority.priority + 10) if max_priority else 10,
|
||||
description=str(form.get('description') or '').strip() or None,
|
||||
update_rule=str(form.get('update_rule') or 'fill_empty'),
|
||||
empty_value=str(form.get('empty_value') or '').strip()[:255] or None,
|
||||
empty_value_guard=str(form.get('empty_value_guard') or '').strip()[:255] or None,
|
||||
is_system=False,
|
||||
)
|
||||
db.add(row)
|
||||
|
||||
+46
-1
@@ -392,7 +392,13 @@ def fetch_device_summaries_for_linking() -> list[dict[str, str]]:
|
||||
raise RuntimeError("MeshCentral-Geräteliste konnte nicht geladen werden: " + detail)
|
||||
|
||||
|
||||
# False when the last fetch_devices() fell back to basic data although details were requested.
|
||||
LAST_FETCH_DETAILS_COMPLETE = True
|
||||
|
||||
|
||||
def fetch_devices(log: Callable[[str, str], None] | None = None) -> list[dict[str, Any]]:
|
||||
global LAST_FETCH_DETAILS_COMPLETE
|
||||
LAST_FETCH_DETAILS_COMPLETE = True
|
||||
log = log or (lambda level, message: None)
|
||||
cfg = load_config()["meshcentral"]
|
||||
if not cfg.get("enabled"):
|
||||
@@ -422,6 +428,8 @@ def fetch_devices(log: Callable[[str, str], None] | None = None) -> list[dict[st
|
||||
else:
|
||||
devices = _extract_devices(_parse_json_output(result.stdout))
|
||||
log("success", f"{len(devices)} Gerät(e) aus MeshCentral gelesen.")
|
||||
if use_details and not include_details:
|
||||
LAST_FETCH_DETAILS_COMPLETE = False
|
||||
return devices
|
||||
except (ValueError, json.JSONDecodeError, RuntimeError) as exc:
|
||||
attempts.append(("mit Details: " if include_details else "ohne Details: ") + str(exc))
|
||||
@@ -649,6 +657,29 @@ def _convert_mapping_value(values: list[Any], transform: str, separator: str) ->
|
||||
return None
|
||||
|
||||
|
||||
def _parent_path(path: str) -> str:
|
||||
"""Parent of every alternative of a source path: 'a.b.c|x.y' -> 'a.b|x'."""
|
||||
parents = []
|
||||
for alternative in [item.strip() for item in str(path or '').split('|') if item.strip()]:
|
||||
if '.' in alternative:
|
||||
parents.append(alternative.rsplit('.', 1)[0])
|
||||
else:
|
||||
return '' # top-level key: the device itself is the parent
|
||||
return '|'.join(parents)
|
||||
|
||||
|
||||
def _empty_value_allowed(raw: dict[str, Any], mapping: dict[str, Any]) -> bool:
|
||||
"""Only use the fallback when the device really delivered the surrounding data.
|
||||
|
||||
Otherwise a device without detail data (new agent, failed detail query)
|
||||
would be reported as e.g. 'BitLocker off'.
|
||||
"""
|
||||
guard = str(mapping.get('empty_value_guard') or '').strip() or _parent_path(str(mapping.get('source_path') or ''))
|
||||
if not guard:
|
||||
return True
|
||||
return bool(_path_values(raw, guard))
|
||||
|
||||
|
||||
def _mapped_value(raw: dict[str, Any], mapping: dict[str, Any]) -> Any:
|
||||
values = _path_values(raw, str(mapping.get('source_path') or ''))
|
||||
mode = str(mapping.get('multi_value_mode') or 'first')
|
||||
@@ -661,7 +692,10 @@ def _mapped_value(raw: dict[str, Any], mapping: dict[str, Any]) -> Any:
|
||||
'gpu_names', 'active_antivirus'
|
||||
}
|
||||
if transform in special:
|
||||
return _convert_mapping_value(values, transform, separator)
|
||||
result = _convert_mapping_value(values, transform, separator)
|
||||
if result in (None, '', [], {}) and mapping.get('empty_value') not in (None, '') and _empty_value_allowed(raw, mapping):
|
||||
return str(mapping.get('empty_value'))
|
||||
return result
|
||||
|
||||
def convert(value: Any) -> Any:
|
||||
if transform == 'integer':
|
||||
@@ -680,7 +714,12 @@ def _mapped_value(raw: dict[str, Any], mapping: dict[str, Any]) -> Any:
|
||||
converted = [convert(value) for value in values if value not in (None, '', [], {})]
|
||||
converted = [value for value in converted if value is not None]
|
||||
if not converted:
|
||||
# Optional fallback, e.g. BitLocker: the key only exists when enabled,
|
||||
# so an empty source means "off" instead of "leave the field untouched".
|
||||
empty_value = mapping.get('empty_value')
|
||||
if empty_value in (None, '') or not _empty_value_allowed(raw, mapping):
|
||||
return None
|
||||
return convert(str(empty_value))
|
||||
if mode == 'json': return converted if len(converted) > 1 else converted[0]
|
||||
if mode == 'count': return len(converted)
|
||||
if mode == 'join':
|
||||
@@ -1068,6 +1107,7 @@ def synchronize(db: Session, log: Callable[[str, str], None] | None = None, *, d
|
||||
"source_path": row.source_path, "target_field": row.target_field_name,
|
||||
"transform": row.transform, "multi_value_mode": row.multi_value_mode,
|
||||
"separator": row.separator, "enabled": row.enabled, "update_rule": row.update_rule,
|
||||
"empty_value": row.empty_value, "empty_value_guard": row.empty_value_guard,
|
||||
} for row in mapping_rows]
|
||||
mapping_rules = {row.target_field_name: row.update_rule for row in mapping_rows}
|
||||
field_definitions = {
|
||||
@@ -1112,6 +1152,11 @@ def synchronize(db: Session, log: Callable[[str, str], None] | None = None, *, d
|
||||
log("info", f"Dummy-Seriennummernfilter aktiv: {invalid_global_count} globale Werte, {invalid_manufacturer_count} Herstellerregel(n). Node-ID bleibt die stabile Geräteidentität.")
|
||||
devices = fetch_devices(log)
|
||||
run.devices_found = len(devices)
|
||||
if not LAST_FETCH_DETAILS_COMPLETE and any(item.get("empty_value") not in (None, "") for item in field_mappings):
|
||||
# Without detail data every device would look like 'value missing'.
|
||||
for item in field_mappings:
|
||||
item["empty_value"] = None
|
||||
log("warning", "MeshCentral hat nur Basisdaten geliefert: 'Wert, wenn leer' wird in diesem Lauf nicht angewendet, bestehende Werte bleiben unverändert.")
|
||||
log("info", f"Verarbeite {len(devices)} Gerät(e).")
|
||||
|
||||
# Determine serial numbers that are already ambiguous within the current
|
||||
|
||||
@@ -43,6 +43,8 @@ STATUS_COLUMNS = {
|
||||
MESH_MAPPING_COLUMNS = {
|
||||
"update_rule": "VARCHAR(30) NOT NULL DEFAULT 'fill_empty'",
|
||||
"is_system": "BOOLEAN NOT NULL DEFAULT FALSE",
|
||||
"empty_value": "VARCHAR(255)",
|
||||
"empty_value_guard": "VARCHAR(255)",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -170,6 +170,10 @@ class MeshFieldMapping(Base):
|
||||
priority: Mapped[int] = mapped_column(Integer, default=0)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
update_rule: Mapped[str] = mapped_column(String(30), default="fill_empty")
|
||||
# Value written when the MeshCentral source is missing or empty (None = skip the field).
|
||||
empty_value: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
# Path that must exist in the device JSON before empty_value is used (None = parent of source_path).
|
||||
empty_value_guard: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
is_system: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
|
||||
@@ -3430,3 +3430,30 @@ html[data-theme="dark"] .standard-data-table-scroll > .data-table > thead > .col
|
||||
html[data-theme="dark"] .localized-file-picker-name{
|
||||
color:#edf3f8;
|
||||
}
|
||||
|
||||
/* 0.5.5.94: field data type conversion preview, mapping fallback guard */
|
||||
.mesh-mapping-table .mapping-empty-value-guard{display:block;margin-top:4px;font-family:monospace}
|
||||
.data-table tr.row-error td{background:rgba(180,35,24,.08)}
|
||||
.text-danger{color:var(--am-danger,#b42318)}
|
||||
|
||||
/* 0.5.5.94: Excel-like value list in table filters */
|
||||
.column-filter-row th.value-list-filter-cell{position:relative}
|
||||
.column-filter-row th.value-list-filter-cell textarea{padding-right:24px}
|
||||
.value-list-button{position:absolute;top:8px;right:8px;width:20px;height:28px;margin:0;padding:0;border:0;border-radius:3px;background:transparent;color:inherit;font-size:13px;line-height:28px;cursor:pointer;opacity:.65}
|
||||
.value-list-button:hover,.value-list-button:focus-visible{opacity:1;background:rgba(0,0,0,.08)}
|
||||
.value-list-popup{width:min(340px,calc(100vw - 12px));max-width:calc(100vw - 12px)}
|
||||
.value-list-popup .value-list-search{width:100%;box-sizing:border-box;margin:0 0 6px}
|
||||
.value-list-items{max-height:300px;overflow:auto;border:1px solid var(--border-color,#d8dde2);border-radius:4px;padding:4px 0}
|
||||
.value-list-popup label.value-list-item{display:flex;align-items:center;gap:6px;margin:0;padding:3px 8px;font-weight:400;cursor:pointer}
|
||||
.value-list-popup label.value-list-item:hover{background:rgba(0,0,0,.05)}
|
||||
.value-list-popup label.value-list-all{font-weight:600;border-bottom:1px solid var(--border-color,#e7edf3)}
|
||||
.value-list-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.value-list-count{color:#6b7785;font-size:12px}
|
||||
.value-list-info{margin:6px 0 0;font-size:12px}
|
||||
html[data-theme="dark"] .value-list-button:hover{background:rgba(255,255,255,.12)}
|
||||
html[data-theme="dark"] .value-list-items{border-color:#53606d}
|
||||
html[data-theme="dark"] .value-list-popup label.value-list-item:hover{background:rgba(255,255,255,.07)}
|
||||
html[data-theme="dark"] .value-list-count{color:#9aa7b4}
|
||||
.value-list-popup label.value-list-item input[type="checkbox"]{flex:0 0 auto;width:16px;min-width:16px;height:16px;margin:0;padding:0}
|
||||
.value-list-popup label.value-list-all{white-space:nowrap}
|
||||
.value-list-button.is-loading{opacity:.35;cursor:progress}
|
||||
+335
-20
@@ -117,6 +117,51 @@
|
||||
return `${explicitFilterValue} ${cell.textContent || ''}`.trim();
|
||||
}
|
||||
|
||||
// The value a user sees in a cell (selected option text, input value or
|
||||
// plain text). Used by the value list and by exact "=value" filters.
|
||||
function listValue(cell) {
|
||||
if (!cell) return '';
|
||||
const controls = [...cell.querySelectorAll('input, select, textarea')]
|
||||
.filter(control => control.type !== 'hidden');
|
||||
let text;
|
||||
if (controls.length) {
|
||||
const yes = document.body.dataset.valueListYes || 'Yes';
|
||||
const no = document.body.dataset.valueListNo || 'No';
|
||||
const parts = controls.map(control => {
|
||||
if (control.tagName === 'SELECT') return control.options?.[control.selectedIndex]?.textContent || '';
|
||||
if (control.type === 'checkbox' || control.type === 'radio') return control.checked ? yes : no;
|
||||
return control.value || '';
|
||||
});
|
||||
text = [...parts, textOutsideControls(cell)].join(' ');
|
||||
} else {
|
||||
text = cell.textContent || '';
|
||||
}
|
||||
return text.replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
function exactValueKey(value) {
|
||||
return normalizeSearchText(value, { collapseWhitespace: true });
|
||||
}
|
||||
|
||||
// "!term" excludes, everything else includes (OR). "==x" keeps a literal "=x" search.
|
||||
function splitFilterTerms(text) {
|
||||
const includes = [];
|
||||
const excludes = [];
|
||||
String(text || '')
|
||||
.split(/\r?\n/)
|
||||
.map(term => term.trim())
|
||||
.filter(Boolean)
|
||||
.forEach(term => {
|
||||
if (term.startsWith('!')) {
|
||||
const excluded = term.slice(1).trim();
|
||||
if (excluded) excludes.push(excluded);
|
||||
} else {
|
||||
includes.push(term);
|
||||
}
|
||||
});
|
||||
return { includes, excludes };
|
||||
}
|
||||
|
||||
function parsedValue(value) {
|
||||
const text = value.trim();
|
||||
if (!text) return { type: 'empty', value: '' };
|
||||
@@ -793,6 +838,21 @@
|
||||
if (neutralTerm === '@empty') return !String(comparable || '').trim();
|
||||
if (neutralTerm === '@notempty') return !!String(comparable || '').trim();
|
||||
|
||||
// "=value": the whole visible cell value must match (value list, exact search).
|
||||
// Numeric/date columns additionally keep their "=5" / "=18.11.2026" comparison.
|
||||
const trimmedTerm = String(term || '').trim();
|
||||
const exact = trimmedTerm.startsWith('=') && !trimmedTerm.startsWith('==');
|
||||
if (exact) {
|
||||
const expected = exactValueKey(trimmedTerm.slice(1));
|
||||
if (exactValueKey(listValue(cell)) === expected) return true;
|
||||
const numericExact = numericFilterMatches(comparable, trimmedTerm, false);
|
||||
if (numericExact !== null) return numericExact;
|
||||
const dateExact = dateFilterMatches(comparable, trimmedTerm);
|
||||
if (dateExact !== null) return dateExact;
|
||||
return false;
|
||||
}
|
||||
if (trimmedTerm.startsWith('==')) term = trimmedTerm.slice(1);
|
||||
|
||||
// Preserve the pre-existing software-summary numeric behavior exactly:
|
||||
// plain numeric input is an exact match in columns explicitly marked as numeric.
|
||||
if (definition.numericFilter) {
|
||||
@@ -1009,6 +1069,255 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Excel-like value list: every distinct value of the column among the rows
|
||||
// that pass the filters of all OTHER columns, with checkboxes. The result is
|
||||
// written into the normal filter field ("=a" lines or "!=b" lines), so saved
|
||||
// filters, the filter status and "reset filters" keep working unchanged.
|
||||
function createValueListButton(filterCell, definition) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'value-list-button';
|
||||
button.textContent = '▾';
|
||||
button.title = document.body.dataset.valueListOpen || 'Select values';
|
||||
button.setAttribute('aria-label', `${button.title}: ${definition.title}`);
|
||||
button.setAttribute('aria-haspopup', 'dialog');
|
||||
filterCell.classList.add('value-list-filter-cell');
|
||||
filterCell.appendChild(button);
|
||||
button.addEventListener('click', event => {
|
||||
event.stopPropagation();
|
||||
const open = document.querySelector('.value-list-popup');
|
||||
if (open && open._anchor === button) { open._close(); return; }
|
||||
openValueList(definition, button);
|
||||
});
|
||||
}
|
||||
|
||||
function collectColumnValues(definition) {
|
||||
const others = activeFilterItems().filter(item => item.definition !== definition);
|
||||
const own = activeFilterItems().find(item => item.definition === definition) || null;
|
||||
const values = new Map();
|
||||
[...tbody.rows].forEach(row => {
|
||||
if (row.querySelector('.empty-state')) return;
|
||||
if (others.some(item => !rowPassesFilter(row, item))) return;
|
||||
const cell = cellForDefinition(row, definition);
|
||||
let label = listValue(cell);
|
||||
if (!label) label = comparableCellValue(cell);
|
||||
const key = label ? exactValueKey(label) : '@empty';
|
||||
let entry = values.get(key);
|
||||
if (!entry) {
|
||||
entry = { key, label, count: 0, checked: own ? rowPassesFilter(row, own) : true };
|
||||
values.set(key, entry);
|
||||
}
|
||||
entry.count += 1;
|
||||
});
|
||||
const entries = [...values.values()];
|
||||
entries.sort((a, b) => {
|
||||
if (a.key === '@empty') return -1;
|
||||
if (b.key === '@empty') return 1;
|
||||
return compareValues(a.label, b.label);
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
// Server tables (software jobs) only contain the current page of rows, so
|
||||
// their value list is computed on the server with the other column filters.
|
||||
async function serverColumnValues(definition) {
|
||||
const target = new URL(table.dataset.valueListUrl, window.location.origin);
|
||||
target.searchParams.set('column', definition.serverName);
|
||||
filterDefinitions.forEach(item => {
|
||||
const value = item.input.value.trim();
|
||||
if (item.serverName && value) target.searchParams.set(`job_filter_${item.serverName}`, value);
|
||||
});
|
||||
const response = await fetch(target.toString(), { cache: 'no-store', headers: { 'X-Requested-With': 'AssetManagerValueList' } });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const data = await response.json();
|
||||
const entries = (data.values || []).map(item => ({
|
||||
key: item.label ? exactValueKey(item.label) : '@empty',
|
||||
label: item.label,
|
||||
count: item.count,
|
||||
checked: Boolean(item.checked)
|
||||
}));
|
||||
entries.sort((a, b) => {
|
||||
if (a.key === '@empty') return -1;
|
||||
if (b.key === '@empty') return 1;
|
||||
return compareValues(a.label, b.label);
|
||||
});
|
||||
entries.truncated = Boolean(data.truncated);
|
||||
entries.scanLimit = data.scan_limit;
|
||||
return entries;
|
||||
}
|
||||
|
||||
async function openValueList(definition, anchor) {
|
||||
document.querySelectorAll('.value-list-popup').forEach(popup => popup._close?.());
|
||||
let entries;
|
||||
if (usesServerFilters) {
|
||||
anchor.classList.add('is-loading');
|
||||
try {
|
||||
entries = await serverColumnValues(definition);
|
||||
} catch (error) {
|
||||
console.error('[AssetManager] value list failed', error);
|
||||
window.AssetManagerToast?.error?.(document.body.dataset.valueListError || 'The value list could not be loaded.');
|
||||
return;
|
||||
} finally {
|
||||
anchor.classList.remove('is-loading');
|
||||
}
|
||||
} else {
|
||||
entries = collectColumnValues(definition);
|
||||
}
|
||||
const maxRendered = 500;
|
||||
const popup = document.createElement('div');
|
||||
popup.className = 'advanced-filter-popup advanced-filter-popup-portal value-list-popup';
|
||||
popup.setAttribute('role', 'dialog');
|
||||
popup.setAttribute('aria-label', definition.title);
|
||||
|
||||
const title = document.createElement('strong');
|
||||
title.className = 'advanced-filter-title';
|
||||
title.textContent = definition.title;
|
||||
const search = document.createElement('input');
|
||||
search.type = 'search';
|
||||
search.className = 'value-list-search';
|
||||
search.placeholder = document.body.dataset.valueListSearch || 'Search';
|
||||
search.autocomplete = 'off';
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'value-list-items';
|
||||
const info = document.createElement('p');
|
||||
info.className = 'value-list-info muted';
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'advanced-filter-actions';
|
||||
const apply = document.createElement('button');
|
||||
apply.type = 'button';
|
||||
apply.className = 'button button-primary';
|
||||
apply.textContent = document.body.dataset.advancedFilterApply || 'Apply';
|
||||
const cancel = document.createElement('button');
|
||||
cancel.type = 'button';
|
||||
cancel.className = 'button button-secondary';
|
||||
cancel.textContent = document.body.dataset.valueListCancel || 'Cancel';
|
||||
actions.append(apply, cancel);
|
||||
popup.append(title, search, list, info, actions);
|
||||
document.body.appendChild(popup);
|
||||
|
||||
const emptyLabel = document.body.dataset.valueListEmpty || '(Empty)';
|
||||
const visibleEntries = () => {
|
||||
const term = search.value.trim();
|
||||
return term ? entries.filter(entry => searchTextMatches(entry.key === '@empty' ? emptyLabel : entry.label, term)) : entries;
|
||||
};
|
||||
|
||||
const render = () => {
|
||||
const shown = visibleEntries();
|
||||
list.replaceChildren();
|
||||
const allLabel = document.createElement('label');
|
||||
allLabel.className = 'value-list-item value-list-all';
|
||||
const all = document.createElement('input');
|
||||
all.type = 'checkbox';
|
||||
const checkedShown = shown.filter(entry => entry.checked).length;
|
||||
all.checked = shown.length > 0 && checkedShown === shown.length;
|
||||
all.indeterminate = checkedShown > 0 && checkedShown < shown.length;
|
||||
all.addEventListener('change', () => {
|
||||
shown.forEach(entry => { entry.checked = all.checked; });
|
||||
render();
|
||||
});
|
||||
allLabel.append(all, document.createTextNode(` ${document.body.dataset.valueListSelectAll || '(Select all)'}`));
|
||||
list.appendChild(allLabel);
|
||||
|
||||
shown.slice(0, maxRendered).forEach(entry => {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'value-list-item';
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.checked = entry.checked;
|
||||
checkbox.addEventListener('change', () => {
|
||||
entry.checked = checkbox.checked;
|
||||
const checkedNow = shown.filter(item => item.checked).length;
|
||||
all.checked = checkedNow === shown.length;
|
||||
all.indeterminate = checkedNow > 0 && checkedNow < shown.length;
|
||||
updateApply();
|
||||
});
|
||||
const text = document.createElement('span');
|
||||
text.className = 'value-list-label';
|
||||
text.textContent = entry.key === '@empty' ? emptyLabel : entry.label;
|
||||
text.title = text.textContent;
|
||||
const count = document.createElement('span');
|
||||
count.className = 'value-list-count';
|
||||
count.textContent = String(entry.count);
|
||||
label.append(checkbox, text, count);
|
||||
list.appendChild(label);
|
||||
});
|
||||
const notes = [];
|
||||
if (shown.length > maxRendered) {
|
||||
notes.push((document.body.dataset.valueListLimited || 'Showing {shown} of {total} values, use the search field.')
|
||||
.replace('{shown}', String(maxRendered)).replace('{total}', String(shown.length)));
|
||||
}
|
||||
if (entries.truncated) {
|
||||
notes.push((document.body.dataset.valueListScanLimited || 'Only the newest {count} jobs were evaluated.')
|
||||
.replace('{count}', String(entries.scanLimit)));
|
||||
}
|
||||
info.textContent = notes.join(' ');
|
||||
info.hidden = !info.textContent;
|
||||
updateApply();
|
||||
};
|
||||
const updateApply = () => {
|
||||
apply.disabled = !entries.some(entry => entry.checked);
|
||||
};
|
||||
|
||||
const position = () => {
|
||||
const rect = anchor.closest('th').getBoundingClientRect();
|
||||
const margin = 6;
|
||||
const popupRect = popup.getBoundingClientRect();
|
||||
let left = Math.min(rect.left, window.innerWidth - popupRect.width - margin);
|
||||
left = Math.max(margin, left);
|
||||
let top = rect.bottom + 4;
|
||||
if (top + popupRect.height > window.innerHeight - margin && rect.top > popupRect.height + margin) {
|
||||
top = rect.top - popupRect.height - 4;
|
||||
}
|
||||
popup.style.left = `${Math.round(left)}px`;
|
||||
popup.style.top = `${Math.round(Math.max(margin, top))}px`;
|
||||
};
|
||||
|
||||
const onDocumentClick = event => {
|
||||
if (!popup.contains(event.target) && event.target !== anchor) close();
|
||||
};
|
||||
const onKey = event => {
|
||||
if (event.key === 'Escape') { close(); anchor.focus(); }
|
||||
};
|
||||
function close() {
|
||||
popup.remove();
|
||||
document.removeEventListener('click', onDocumentClick, true);
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
window.removeEventListener('resize', position);
|
||||
window.removeEventListener('scroll', position, true);
|
||||
}
|
||||
popup._close = close;
|
||||
popup._anchor = anchor;
|
||||
|
||||
apply.addEventListener('click', () => {
|
||||
const checked = entries.filter(entry => entry.checked);
|
||||
const unchecked = entries.filter(entry => !entry.checked);
|
||||
const term = entry => (entry.key === '@empty' ? '@empty' : `=${entry.label}`);
|
||||
let lines = [];
|
||||
if (!unchecked.length) lines = [];
|
||||
else if (checked.length <= unchecked.length) lines = checked.map(term);
|
||||
else lines = unchecked.map(entry => `!${term(entry)}`);
|
||||
definition.input.value = lines.join('\n');
|
||||
definition.input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
if (usesServerFilters) submitServerFilters(true);
|
||||
close();
|
||||
});
|
||||
cancel.addEventListener('click', close);
|
||||
search.addEventListener('input', render);
|
||||
search.addEventListener('keydown', event => {
|
||||
if (event.key === 'Enter') { event.preventDefault(); if (!apply.disabled) apply.click(); }
|
||||
});
|
||||
|
||||
render();
|
||||
position();
|
||||
document.addEventListener('click', onDocumentClick, true);
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
window.addEventListener('resize', position);
|
||||
window.addEventListener('scroll', position, true);
|
||||
search.focus();
|
||||
}
|
||||
|
||||
function submitServerFilters(immediate = false) {
|
||||
if (!usesServerFilters) return;
|
||||
if (serverFilterTimer) window.clearTimeout(serverFilterTimer);
|
||||
@@ -1090,18 +1399,26 @@
|
||||
});
|
||||
}
|
||||
|
||||
function activeFilterItems() {
|
||||
return filterDefinitions
|
||||
.map(definition => ({ definition, ...splitFilterTerms(definition.input?.value) }))
|
||||
.filter(item => item.includes.length || item.excludes.length);
|
||||
}
|
||||
|
||||
// A row passes one column filter when it matches at least one include line
|
||||
// (if there are any) and none of the "!" exclude lines.
|
||||
function rowPassesFilter(row, item) {
|
||||
const cell = cellForDefinition(row, item.definition);
|
||||
const value = textValue(cell);
|
||||
const matches = term => advancedFilterMatches(cell, value, term, item.definition);
|
||||
if (item.includes.length && !item.includes.some(matches)) return false;
|
||||
return !item.excludes.some(matches);
|
||||
}
|
||||
|
||||
function applyFilters() {
|
||||
rebuildMissingCellKeys();
|
||||
|
||||
const active = filterDefinitions
|
||||
.map(definition => ({
|
||||
definition,
|
||||
terms: String(definition.input?.value || '')
|
||||
.split(/\r?\n/)
|
||||
.map(term => term.trim())
|
||||
.filter(Boolean)
|
||||
}))
|
||||
.filter(item => item.terms.length);
|
||||
const active = activeFilterItems();
|
||||
|
||||
if (usesServerFilters) {
|
||||
const serverTotal = Number.parseInt(table.dataset.serverFilterTotal || '', 10);
|
||||
@@ -1122,14 +1439,7 @@
|
||||
let visibleRows = 0;
|
||||
|
||||
[...tbody.rows].forEach(row => {
|
||||
const hidden = active.some(({ definition, terms }) => {
|
||||
const cell = cellForDefinition(row, definition);
|
||||
const value = textValue(cell);
|
||||
const matchesAnyTerm = terms.some(term =>
|
||||
advancedFilterMatches(cell, value, term, definition)
|
||||
);
|
||||
return !matchesAnyTerm;
|
||||
});
|
||||
const hidden = active.some(item => !rowPassesFilter(row, item));
|
||||
|
||||
row.hidden = hidden;
|
||||
if (!hidden) visibleRows += 1;
|
||||
@@ -1230,14 +1540,19 @@
|
||||
filterCell.appendChild(input);
|
||||
const advancedFilterType = inferredAdvancedFilterType(header, columnIndex, serverName);
|
||||
createAdvancedFilterHelper(filterCell, input, advancedFilterType);
|
||||
filterDefinitions.push({
|
||||
const definition = {
|
||||
field,
|
||||
columnIndex,
|
||||
input,
|
||||
serverName,
|
||||
numericFilter: header.dataset.numericFilter === '1',
|
||||
advancedFilterType
|
||||
});
|
||||
advancedFilterType,
|
||||
title: textValue(header)
|
||||
};
|
||||
filterDefinitions.push(definition);
|
||||
if (!header.dataset.noValueList && (!usesServerFilters || header.dataset.valueList === 'server')) {
|
||||
createValueListButton(filterCell, definition);
|
||||
}
|
||||
}
|
||||
|
||||
filterRow.appendChild(filterCell);
|
||||
|
||||
@@ -36,6 +36,13 @@
|
||||
}, seconds * 1000);
|
||||
}
|
||||
|
||||
// Small API for scripts that need to report an error without a page reload.
|
||||
window.AssetManagerToast = {
|
||||
error: message => showToast(message, 'error'),
|
||||
warning: message => showToast(message, 'warning'),
|
||||
success: message => showToast(message, 'success')
|
||||
};
|
||||
|
||||
let changed = false;
|
||||
entries.forEach(([key, level]) => {
|
||||
const values = params.getAll(key);
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<label>{{ t('common.field') }}
|
||||
<select name="field_name" id="bulk-field" required>
|
||||
<option value="">{{ t('common.please_select') }}</option>
|
||||
{% for field in fields %}<option value="{{ field.field_name }}">{{ field.label }}</option>{% endfor %}
|
||||
{% for field in fields %}<option value="{{ field.field_name }}" data-type="{{ field.data_type or '' }}" data-custom="{{ '1' if field.custom else '0' }}">{{ field.label }}</option>{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label>{{ t('history.new_value') }}
|
||||
@@ -22,6 +22,11 @@
|
||||
<option value="">{{ t('assets.bulk_edit.no_parent') }}</option>
|
||||
{% for parent in parent_candidates %}<option value="{{ parent.id }}">{{ parent.name }}{% if parent.asset_tag %} – {{ parent.asset_tag }}{% endif %} ({{ parent.category.name }})</option>{% endfor %}
|
||||
</select>
|
||||
<select id="bulk-boolean-value" class="hidden-control">
|
||||
<option value="">{{ t('assets.bulk_edit.empty_value') }}</option>
|
||||
<option value="true">{{ t('common.yes') }}</option>
|
||||
<option value="false">{{ t('common.no') }}</option>
|
||||
</select>
|
||||
<select id="bulk-category-value" class="hidden-control">
|
||||
<option value="">{{ t('assets.bulk_edit.select_category') }}</option>
|
||||
{% for category in categories %}<option value="{{ category.id }}">{{ category.name }}</option>{% endfor %}
|
||||
@@ -40,16 +45,27 @@
|
||||
const status = document.getElementById('bulk-status-value');
|
||||
const parent = document.getElementById('bulk-parent-value');
|
||||
const category = document.getElementById('bulk-category-value');
|
||||
const controls = [input, status, parent, category];
|
||||
const bool = document.getElementById('bulk-boolean-value');
|
||||
const controls = [input, status, parent, category, bool];
|
||||
field.addEventListener('change', () => {
|
||||
const selected = field.value;
|
||||
const active = selected === 'status' ? status : selected === 'parent_asset_id' ? parent : selected === 'category_id' ? category : input;
|
||||
const option = field.selectedOptions[0];
|
||||
const isCustom = option && option.dataset.custom === '1';
|
||||
const dataType = option ? option.dataset.type : '';
|
||||
const active = selected === 'status' ? status : selected === 'parent_asset_id' ? parent : selected === 'category_id' ? category : (isCustom && dataType === 'boolean') ? bool : input;
|
||||
controls.forEach(control => {
|
||||
control.classList.toggle('hidden-control', control !== active);
|
||||
if (control === active) control.name = 'new_value'; else control.removeAttribute('name');
|
||||
});
|
||||
const dateFields = ['assigned_on','purchase_date','warranty_until'];
|
||||
input.type = dateFields.includes(selected) ? 'date' : 'text';
|
||||
input.removeAttribute('step');
|
||||
if (dateFields.includes(selected) || (isCustom && dataType === 'date')) input.type = 'date';
|
||||
else if (isCustom && dataType === 'datetime') input.type = 'datetime-local';
|
||||
else if (isCustom && dataType === 'integer') { input.type = 'number'; input.step = '1'; }
|
||||
else if (isCustom && dataType === 'decimal') { input.type = 'number'; input.step = 'any'; }
|
||||
else if (isCustom && dataType === 'email') input.type = 'email';
|
||||
else if (isCustom && dataType === 'url') input.type = 'url';
|
||||
else input.type = 'text';
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
--am-warning:{{ colors.get('warning_color', '#d97706') }};
|
||||
--am-danger:{{ colors.get('danger_color', '#b42318') }};
|
||||
}
|
||||
</style><script>(()=>{try{if(localStorage.getItem('assetmanager.sidebar.collapsed')==='true')document.documentElement.classList.add('sidebar-collapsed-preset')}catch(_){}})();</script><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ title or general.get('title', 'AssetManager') }}</title>{% set favicon_path = general.get('favicon') or general.get('logo') %}{% if favicon_path %}<link rel="icon" href="{{ favicon_path }}">{% endif %}<link rel="stylesheet" href="/static/css/app.css?v={{ application_version() }}"><link rel="stylesheet" href="/custom.css"></head><body{% if request and request.url.path == '/assets' %} class="asset-list-scroll-page"{% endif %} data-record-count-template="{{ t('lists.record_count', 'Angezeigt: {visible} von {total} Datensätzen')|e }}" data-record-count-title="{{ t('lists.record_count_hint', 'Die Anzeige berücksichtigt die aktuell gesetzten Tabellenfilter.')|e }}" data-filter-active-label="{{ t('lists.filter_active', 'Filter aktiv')|e }}" data-filters-active-template="{{ t('lists.filters_active', '{count} Filter aktiv')|e }}" data-filter-status-template="{{ t('lists.filter_status', 'Gefiltert: {visible} von {total} Datensätzen')|e }}" data-clear-filters-label="{{ t('lists.clear_filters', 'Filter zurücksetzen')|e }}" data-row-number-label="{{ t('lists.row_number', 'Zeilennummer')|e }}" data-row-number-resize-label="{{ t('lists.row_number_resize', 'Ziehen, um die Breite der Nummernspalte zu ändern')|e }}" data-column-resize-label="{{ t('lists.column_resize', 'Ziehen, um die Spaltenbreite zu ändern')|e }}" data-multi-value-filter-hint="{{ t('lists.multi_value_filter_hint', 'Mehrere Suchwerte können zeilenweise eingefügt werden. Innerhalb einer Spalte gilt ODER.')|e }}" data-advanced-filter-title="{{ t('lists.advanced_filter.title')|e }}" data-advanced-filter-operator="{{ t('lists.advanced_filter.operator')|e }}" data-advanced-filter-value="{{ t('lists.advanced_filter.value')|e }}" data-advanced-filter-value-from="{{ t('lists.advanced_filter.value_from')|e }}" data-advanced-filter-value-to="{{ t('lists.advanced_filter.value_to')|e }}" data-advanced-filter-equal="{{ t('lists.advanced_filter.equal')|e }}" data-advanced-filter-gt="{{ t('lists.advanced_filter.gt')|e }}" data-advanced-filter-gte="{{ t('lists.advanced_filter.gte')|e }}" data-advanced-filter-lt="{{ t('lists.advanced_filter.lt')|e }}" data-advanced-filter-lte="{{ t('lists.advanced_filter.lte')|e }}" data-advanced-filter-range="{{ t('lists.advanced_filter.range')|e }}" data-advanced-filter-apply="{{ t('lists.advanced_filter.apply')|e }}" data-advanced-filter-clear="{{ t('lists.advanced_filter.clear')|e }}" data-advanced-filter-empty="{{ t('lists.advanced_filter.empty')|e }}" data-advanced-filter-not-empty="{{ t('lists.advanced_filter.not_empty')|e }}" data-persist-browser-state="{{ 'true' if session_user and session_user.persist_browser_state else 'false' }}" data-toast-position="{{ session_user.toast_position if session_user else 'top-right' }}" data-toast-duration="{{ session_user.toast_duration_seconds if session_user else 6 }}" data-toast-close-label="{{ t('common.close')|e }}">
|
||||
</style><script>(()=>{try{if(localStorage.getItem('assetmanager.sidebar.collapsed')==='true')document.documentElement.classList.add('sidebar-collapsed-preset')}catch(_){}})();</script><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{ title or general.get('title', 'AssetManager') }}</title>{% set favicon_path = general.get('favicon') or general.get('logo') %}{% if favicon_path %}<link rel="icon" href="{{ favicon_path }}">{% endif %}<link rel="stylesheet" href="/static/css/app.css?v={{ application_version() }}"><link rel="stylesheet" href="/custom.css"></head><body{% if request and request.url.path == '/assets' %} class="asset-list-scroll-page"{% endif %} data-record-count-template="{{ t('lists.record_count', 'Angezeigt: {visible} von {total} Datensätzen')|e }}" data-record-count-title="{{ t('lists.record_count_hint', 'Die Anzeige berücksichtigt die aktuell gesetzten Tabellenfilter.')|e }}" data-filter-active-label="{{ t('lists.filter_active', 'Filter aktiv')|e }}" data-filters-active-template="{{ t('lists.filters_active', '{count} Filter aktiv')|e }}" data-filter-status-template="{{ t('lists.filter_status', 'Gefiltert: {visible} von {total} Datensätzen')|e }}" data-clear-filters-label="{{ t('lists.clear_filters', 'Filter zurücksetzen')|e }}" data-row-number-label="{{ t('lists.row_number', 'Zeilennummer')|e }}" data-row-number-resize-label="{{ t('lists.row_number_resize', 'Ziehen, um die Breite der Nummernspalte zu ändern')|e }}" data-column-resize-label="{{ t('lists.column_resize', 'Ziehen, um die Spaltenbreite zu ändern')|e }}" data-multi-value-filter-hint="{{ t('lists.multi_value_filter_hint', 'Mehrere Suchwerte können zeilenweise eingefügt werden. Innerhalb einer Spalte gilt ODER.')|e }}" data-advanced-filter-title="{{ t('lists.advanced_filter.title')|e }}" data-value-list-open="{{ t('lists.value_list.open')|e }}" data-value-list-search="{{ t('lists.value_list.search')|e }}" data-value-list-select-all="{{ t('lists.value_list.select_all')|e }}" data-value-list-empty="{{ t('lists.value_list.empty')|e }}" data-value-list-cancel="{{ t('common.cancel')|e }}" data-value-list-limited="{{ t('lists.value_list.limited')|e }}" data-value-list-yes="{{ t('common.yes')|e }}" data-value-list-no="{{ t('common.no')|e }}" data-value-list-error="{{ t('lists.value_list.error')|e }}" data-value-list-scan-limited="{{ t('lists.value_list.scan_limited')|e }}" data-advanced-filter-operator="{{ t('lists.advanced_filter.operator')|e }}" data-advanced-filter-value="{{ t('lists.advanced_filter.value')|e }}" data-advanced-filter-value-from="{{ t('lists.advanced_filter.value_from')|e }}" data-advanced-filter-value-to="{{ t('lists.advanced_filter.value_to')|e }}" data-advanced-filter-equal="{{ t('lists.advanced_filter.equal')|e }}" data-advanced-filter-gt="{{ t('lists.advanced_filter.gt')|e }}" data-advanced-filter-gte="{{ t('lists.advanced_filter.gte')|e }}" data-advanced-filter-lt="{{ t('lists.advanced_filter.lt')|e }}" data-advanced-filter-lte="{{ t('lists.advanced_filter.lte')|e }}" data-advanced-filter-range="{{ t('lists.advanced_filter.range')|e }}" data-advanced-filter-apply="{{ t('lists.advanced_filter.apply')|e }}" data-advanced-filter-clear="{{ t('lists.advanced_filter.clear')|e }}" data-advanced-filter-empty="{{ t('lists.advanced_filter.empty')|e }}" data-advanced-filter-not-empty="{{ t('lists.advanced_filter.not_empty')|e }}" data-persist-browser-state="{{ 'true' if session_user and session_user.persist_browser_state else 'false' }}" data-toast-position="{{ session_user.toast_position if session_user else 'top-right' }}" data-toast-duration="{{ session_user.toast_duration_seconds if session_user else 6 }}" data-toast-close-label="{{ t('common.close')|e }}">
|
||||
<header class="main-header">
|
||||
<a class="brand" href="/">{% if general.get('logo') %}<img src="{{ general.get('logo') }}" alt="Logo">{% endif %}<span>{{ general.get('title', 'AssetManager') }}</span>{% if general.get('company_name') %}<span class="brand-company">– {{ general.get('company_name') }}</span>{% endif %}</a>
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
<div class="toolbar"><h1>{{ t('fields.title') }}</h1><div class="toolbar-actions"><a class="button" href="/settings/fields/new">➕ {{ t('fields.add') }}</a><a class="button button-secondary" href="/settings">{{ t('common.back') }}</a></div></div>
|
||||
<p class="muted">{{ t('fields.catalog_help') }}</p>
|
||||
<div class="sticky-table management-table-scroll"><table class="data-table"><thead><tr><th>{{ t('fields.field') }}</th><th>{{ t('fields.label') }}</th><th>{{ t('common.description') }}</th><th>{{ t('fields.data_type') }}</th><th>{{ t('fields.read_only') }}</th><th>{{ t('fields.system') }}</th><th>{{ t('fields.stored_values') }}</th><th>{{ t('common.actions') }}</th></tr></thead><tbody>
|
||||
{% for d in definitions %}<tr><td><code>{{d.field_name}}</code></td><td>{{d.label}}</td><td>{{d.description or ''}}</td><td>{{ t('fields.data_type_' ~ d.data_type, data_types.get(d.data_type,d.data_type)) }}</td><td>{{t('common.yes') if d.readonly else t('common.no')}}</td><td>{{t('common.yes') if d.is_system else t('common.no')}}</td><td>{{value_counts.get(d.id,0)}}</td><td><a class="button button-secondary" href="/settings/fields/{{d.id}}/edit">{{t('common.edit')}}</a>{% if not d.is_system %}<form class="inline-form" method="post" action="/settings/fields/{{d.id}}/delete" onsubmit="return confirm({{ t('fields.delete_confirm')|tojson }});"><label class="checkbox-label"><input class="checkbox" type="checkbox" name="confirm_values">{{ t('fields.confirm_values') }}</label><button class="button button-danger">{{t('common.delete')}}</button></form>{% endif %}</td></tr>{% endfor %}
|
||||
{% for d in definitions %}<tr><td><code>{{d.field_name}}</code></td><td>{{d.label}}</td><td>{{d.description or ''}}</td><td>{{ t('fields.data_type_' ~ d.data_type, data_types.get(d.data_type,d.data_type)) }}</td><td>{{t('common.yes') if d.readonly else t('common.no')}}</td><td>{{t('common.yes') if d.is_system else t('common.no')}}</td><td>{{value_counts.get(d.id,0)}}</td><td><a class="button button-secondary" href="/settings/fields/{{d.id}}/edit">{{t('common.edit')}}</a>{% if not d.is_system %}{% set stored = value_counts.get(d.id, 0) %}<form class="inline-form" method="post" action="/settings/fields/{{d.id}}/delete" onsubmit='return confirm({{ (t("fields.delete_confirm_values", field=d.label, count=stored) if stored else t("fields.delete_confirm_empty", field=d.label))|tojson }});'>{% if stored %}<input type="hidden" name="confirm_values" value="{{ stored }}">{% endif %}<button class="button button-danger">{{t('common.delete')}}</button></form>{% endif %}</td></tr>{% endfor %}
|
||||
</tbody></table></div>{% endblock %}
|
||||
@@ -0,0 +1,95 @@
|
||||
{% extends 'base.html' %}
|
||||
{% block content %}
|
||||
{% set from_label = t('fields.data_type_' ~ definition.data_type, data_types.get(definition.data_type, definition.data_type)) %}
|
||||
{% set to_label = t('fields.data_type_' ~ to_type, data_types.get(to_type, to_type)) %}
|
||||
<div class="toolbar"><div><h1>{{ t('fields.conversion.title') }}</h1>
|
||||
<p class="muted">{{ t('fields.conversion.subtitle', field=definition.label, from_type=from_label, to_type=to_label) }}</p></div>
|
||||
<a class="button button-secondary" href="/settings/fields/{{ definition.id }}/edit">{{ t('common.cancel') }}</a></div>
|
||||
|
||||
{% if notice %}<p class="notice warning">{{ notice }}</p>{% endif %}
|
||||
|
||||
<form method="post" action="/settings/fields/{{ definition.id }}/convert-type" id="field-conversion-form">
|
||||
{% for key, value in hidden.items() %}<input type="hidden" name="{{ key }}" value="{{ value }}">{% endfor %}
|
||||
<input type="hidden" name="to_type" value="{{ to_type }}">
|
||||
<input type="hidden" name="fingerprint" value="{{ plan.fingerprint }}">
|
||||
|
||||
<section class="panel">
|
||||
<h2>{{ t('fields.conversion.summary') }}</h2>
|
||||
<ul class="compact-list">
|
||||
<li>{{ t('fields.conversion.count_converted', count=plan.converted|length) }}</li>
|
||||
<li>{{ t('fields.conversion.count_empty', count=plan.empty_count) }}</li>
|
||||
<li><strong>{{ t('fields.conversion.count_failed', count=plan.failed|length) }}</strong></li>
|
||||
</ul>
|
||||
<p class="muted">{{ t('fields.conversion.safety_help') }}</p>
|
||||
</section>
|
||||
|
||||
{% if plan.failed %}
|
||||
<section class="panel">
|
||||
<h2>{{ t('fields.conversion.failed_title') }}</h2>
|
||||
<p class="muted">{{ t('fields.conversion.failed_help') }}</p>
|
||||
<div class="form-grid">
|
||||
<label>{{ t('fields.conversion.apply_all') }}
|
||||
<select id="conversion-all-decision"><option value="">{{ t('common.please_select') }}</option><option value="replace">{{ t('fields.conversion.replace_with') }}</option><option value="clear">{{ t('fields.conversion.clear') }}</option></select>
|
||||
</label>
|
||||
<label>{{ t('fields.conversion.replacement') }}<input id="conversion-all-replacement" autocomplete="off"></label>
|
||||
<div><button type="button" class="button button-secondary" id="conversion-all-apply">{{ t('fields.conversion.apply_all_button') }}</button></div>
|
||||
</div>
|
||||
<div class="table-scroll"><table class="data-table">
|
||||
<thead><tr><th>{{ t('fields.conversion.asset') }}</th><th>{{ t('fields.conversion.current_value') }}</th><th>{{ t('fields.conversion.reason') }}</th><th>{{ t('fields.conversion.decision') }}</th><th>{{ t('fields.conversion.replacement') }}</th></tr></thead>
|
||||
<tbody>
|
||||
{% for item in plan.failed %}
|
||||
{% set error = errors.get(item.row_id) %}
|
||||
<tr{% if error %} class="row-error"{% endif %}>
|
||||
<td><a href="/assets/{{ item.asset_id }}" target="_blank" rel="noopener">{{ asset_names.get(item.asset_id, '#' ~ item.asset_id) }}</a></td>
|
||||
<td><code>{{ item.old_display }}</code></td>
|
||||
<td>{{ t('fields.conversion.reason.' ~ item.error, item.error) }}{% if error %}<br><strong class="text-danger">{{ t('fields.conversion.reason.' ~ error, error) }}</strong>{% endif %}</td>
|
||||
<td><select name="decision_{{ item.row_id }}" class="conversion-decision">
|
||||
<option value="">{{ t('common.please_select') }}</option>
|
||||
<option value="replace" {% if form.get('decision_' ~ item.row_id) == 'replace' %}selected{% endif %}>{{ t('fields.conversion.replace_with') }}</option>
|
||||
<option value="clear" {% if form.get('decision_' ~ item.row_id) == 'clear' %}selected{% endif %}>{{ t('fields.conversion.clear') }}</option>
|
||||
</select></td>
|
||||
<td><input name="replacement_{{ item.row_id }}" class="conversion-replacement" value="{{ form.get('replacement_' ~ item.row_id) or '' }}" autocomplete="off"></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if mapping_adjustments %}
|
||||
<section class="panel">
|
||||
<h2>{{ t('fields.conversion.mappings_title') }}</h2>
|
||||
<p class="muted">{{ t('fields.conversion.mappings_help') }}</p>
|
||||
<ul class="compact-list">{% for item in mapping_adjustments %}<li><code>{{ item.mapping.source_path }}</code>: {{ item.current }} → <strong>{{ item.suggestion }}</strong></li>{% endfor %}</ul>
|
||||
<label class="checkbox-label"><input class="checkbox" type="checkbox" name="adjust_mappings" {% if not form or form.get('adjust_mappings', 'on') == 'on' %}checked{% endif %}> {{ t('fields.conversion.adjust_mappings') }}</label>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if plan.converted %}
|
||||
<section class="panel">
|
||||
<details{% if plan.converted|length <= 20 %} open{% endif %}><summary>{{ t('fields.conversion.converted_title', count=plan.converted|length) }}</summary>
|
||||
<div class="table-scroll"><table class="data-table">
|
||||
<thead><tr><th>{{ t('fields.conversion.asset') }}</th><th>{{ t('fields.conversion.current_value') }}</th><th>{{ t('fields.conversion.new_value') }}</th></tr></thead>
|
||||
<tbody>{% for item in plan.converted %}<tr><td>{{ asset_names.get(item.asset_id, '#' ~ item.asset_id) }}</td><td><code>{{ item.old_display }}</code></td><td><code>{{ item.new_display }}</code></td></tr>{% endfor %}</tbody>
|
||||
</table></div></details>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
<div class="form-actions">
|
||||
<a class="button button-secondary" href="/settings/fields/{{ definition.id }}/edit">{{ t('common.cancel') }}</a>
|
||||
<button type="submit" class="button-save" onclick="return confirm({{ t('fields.conversion.confirm', field=definition.label, to_type=to_label)|tojson }})">💾 {{ t('fields.conversion.execute') }}</button>
|
||||
</div>
|
||||
</form>
|
||||
<script>
|
||||
(() => {
|
||||
const apply = document.getElementById('conversion-all-apply');
|
||||
if (!apply) return;
|
||||
apply.addEventListener('click', () => {
|
||||
const decision = document.getElementById('conversion-all-decision').value;
|
||||
const replacement = document.getElementById('conversion-all-replacement').value;
|
||||
document.querySelectorAll('.conversion-decision').forEach(select => { select.value = decision; });
|
||||
if (decision === 'replace') document.querySelectorAll('.conversion-replacement').forEach(input => { input.value = replacement; });
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -91,7 +91,7 @@
|
||||
<h2>3. {{ t('mesh.field_mappings') }}</h2>
|
||||
<p class="muted">{{ t('mesh.mappings_help') }} {{ t('mesh.mappings_examples') }}: <code>node.osdesc</code>, <code>sys.hardware.windows.cpu[].Name</code>, <code>node.name|name</code>.</p>
|
||||
<form method="post" action="/sync/meshcentral/mappings/save">
|
||||
<div class="table-scroll management-table-scroll"><table class="data-table mesh-mapping-table"><thead><tr><th>{{ t('common.active') }}</th><th>{{ t('mesh.priority') }}</th><th>{{ t('mesh.target_field') }}</th><th>{{ t('mesh.source_path') }}</th><th>{{ t('mesh.transformation') }}</th><th>{{ t('mesh.multi_values') }}</th><th>{{ t('mesh.separator') }}</th><th>{{ t('mesh.update_rule') }}</th><th>{{ t('common.description') }}</th><th></th></tr></thead><tbody>
|
||||
<div class="table-scroll management-table-scroll"><table class="data-table mesh-mapping-table"><thead><tr><th>{{ t('common.active') }}</th><th>{{ t('mesh.priority') }}</th><th>{{ t('mesh.target_field') }}</th><th>{{ t('mesh.source_path') }}</th><th>{{ t('mesh.transformation') }}</th><th>{{ t('mesh.multi_values') }}</th><th>{{ t('mesh.separator') }}</th><th>{{ t('mesh.update_rule') }}</th><th title="{{ t('mesh.empty_value_help') }}">{{ t('mesh.empty_value') }}</th><th>{{ t('common.description') }}</th><th></th></tr></thead><tbody>
|
||||
{% for m in mappings %}
|
||||
<tr>
|
||||
<td><input type="checkbox" name="mapping_{{m.id}}_enabled" {% if m.enabled %}checked{% endif %}></td>
|
||||
@@ -102,6 +102,7 @@
|
||||
<td><select name="mapping_{{m.id}}_multi_value_mode">{% for v in ['first','join','json','count'] %}<option value="{{v}}" {% if m.multi_value_mode==v %}selected{% endif %}>{{v}}</option>{% endfor %}</select></td>
|
||||
<td><input class="mapping-separator" name="mapping_{{m.id}}_separator" value="{{m.separator|replace('\n','\\n')|replace('\t','\\t')}}"></td>
|
||||
<td><select name="mapping_{{m.id}}_update_rule"><option value="fill_empty" {% if m.update_rule=='fill_empty' %}selected{% endif %}>{{ t('mesh.rule_fill_empty') }}</option><option value="meshcentral_wins" {% if m.update_rule=='meshcentral_wins' %}selected{% endif %}>{{ t('mesh.rule_mesh_wins') }}</option><option value="local_wins" {% if m.update_rule=='local_wins' %}selected{% endif %}>{{ t('mesh.rule_local_wins') }}</option></select></td>
|
||||
<td><input class="mapping-empty-value" name="mapping_{{m.id}}_empty_value" value="{{m.empty_value or ''}}" title="{{ t('mesh.empty_value_help') }}" maxlength="255"><input class="mapping-empty-value-guard" name="mapping_{{m.id}}_empty_value_guard" value="{{m.empty_value_guard or ''}}" placeholder="{{ t('mesh.empty_value_guard') }}" title="{{ t('mesh.empty_value_guard_help') }}" maxlength="255"></td>
|
||||
<td><input name="mapping_{{m.id}}_description" value="{{m.description or ''}}"></td>
|
||||
<td>{% if not m.is_system %}<button class="button danger" type="submit" formaction="/sync/meshcentral/mappings/{{m.id}}/delete" formmethod="post" onclick="return confirm({{ t('mesh.delete_mapping_confirm')|tojson }})">{{ t('common.delete') }}</button>{% endif %}</td>
|
||||
</tr>
|
||||
@@ -122,6 +123,8 @@
|
||||
<label>{{ t('mesh.multi_values') }}<select name="multi_value_mode"><option value="first">first</option><option value="join">join</option><option value="json">json</option><option value="count">count</option></select></label>
|
||||
<label>{{ t('mesh.separator') }}<input name="separator" value="\n"></label>
|
||||
<label>{{ t('mesh.update_rule') }}<select name="update_rule"><option value="fill_empty">{{ t('mesh.rule_fill_empty') }}</option><option value="meshcentral_wins">{{ t('mesh.rule_mesh_wins') }}</option><option value="local_wins">{{ t('mesh.rule_local_wins') }}</option></select></label>
|
||||
<label>{{ t('mesh.empty_value') }}<input name="empty_value" maxlength="255" title="{{ t('mesh.empty_value_help') }}"><small class="muted">{{ t('mesh.empty_value_help') }}</small></label>
|
||||
<label>{{ t('mesh.empty_value_guard') }}<input name="empty_value_guard" maxlength="255" placeholder="sys.hardware.windows"><small class="muted">{{ t('mesh.empty_value_guard_help') }}</small></label>
|
||||
<label>{{ t('common.description') }}<input name="description"></label>
|
||||
<label class="checkbox-label"><input class="checkbox" type="checkbox" name="enabled" checked> {{ t('common.active') }}</label>
|
||||
</div><button class="button button-save">+ {{ t('mesh.create_mapping') }}</button>
|
||||
|
||||
@@ -91,6 +91,7 @@
|
||||
data-storage-key="software-jobs"
|
||||
data-server-filters="1"
|
||||
data-server-filter-url="/software"
|
||||
data-value-list-url="/software/job-filter-values"
|
||||
data-server-filter-total="{{ jobs_filtered_total if jobs_filters_active else jobs|length }}"
|
||||
data-restart-label="↻ {{ t('jobs.restart')|e }}"
|
||||
data-restart-confirm="{{ t('jobs.restart.confirm')|e }}"
|
||||
@@ -99,13 +100,13 @@
|
||||
<th class="selection-column" data-no-sort="1" data-no-filter="1"><input type="checkbox" id="select-all-restartable-jobs" aria-label="{{ t('jobs.select_all_restartable')|e }}"></th>
|
||||
<th data-server-filter-name="job_id" data-filter-type="integer" data-server-filter-value="{{ job_filters.job_id|e }}">{{ t('software.job_id') }}</th>
|
||||
<th data-server-filter-name="created_at" data-filter-type="datetime" data-server-filter-value="{{ job_filters.created_at|e }}">{{ t('software.time') }}</th>
|
||||
<th data-server-filter-name="asset" data-server-filter-value="{{ job_filters.asset|e }}">{{ t('common.assets') }}</th>
|
||||
<th data-server-filter-name="job_type" data-server-filter-value="{{ job_filters.job_type|e }}">{{ t('jobs.type') }}</th>
|
||||
<th data-server-filter-name="package" data-server-filter-value="{{ job_filters.package|e }}">{{ t('software.package') }}</th>
|
||||
<th data-server-filter-name="action" data-server-filter-value="{{ job_filters.action|e }}">{{ t('jobs.action') }}</th>
|
||||
<th data-server-filter-name="priority" data-filter-type="integer" data-server-filter-value="{{ job_filters.priority|e }}">{{ t('jobs.priority') }}</th>
|
||||
<th data-server-filter-name="platform" data-server-filter-value="{{ job_filters.platform|e }}">{{ t('software.platform') }}</th>
|
||||
<th data-server-filter-name="status" data-server-filter-value="{{ job_filters.status|e }}">{{ t('software.status') }}</th>
|
||||
<th data-server-filter-name="asset" data-value-list="server" data-server-filter-value="{{ job_filters.asset|e }}">{{ t('common.assets') }}</th>
|
||||
<th data-server-filter-name="job_type" data-value-list="server" data-server-filter-value="{{ job_filters.job_type|e }}">{{ t('jobs.type') }}</th>
|
||||
<th data-server-filter-name="package" data-value-list="server" data-server-filter-value="{{ job_filters.package|e }}">{{ t('software.package') }}</th>
|
||||
<th data-server-filter-name="action" data-value-list="server" data-server-filter-value="{{ job_filters.action|e }}">{{ t('jobs.action') }}</th>
|
||||
<th data-server-filter-name="priority" data-value-list="server" data-filter-type="integer" data-server-filter-value="{{ job_filters.priority|e }}">{{ t('jobs.priority') }}</th>
|
||||
<th data-server-filter-name="platform" data-value-list="server" data-server-filter-value="{{ job_filters.platform|e }}">{{ t('software.platform') }}</th>
|
||||
<th data-server-filter-name="status" data-value-list="server" data-server-filter-value="{{ job_filters.status|e }}">{{ t('software.status') }}</th>
|
||||
<th>{{ t('software.details') }}</th>
|
||||
<th>{{ t('jobs.actions') }}</th>
|
||||
</tr></thead>
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
APP_VERSION = "0.5.5.93"
|
||||
APP_VERSION = "0.5.5.94"
|
||||
__version__ = APP_VERSION
|
||||
@@ -1,3 +1,4 @@
|
||||
- [0.5.5.94](UPDATE-0.5.5.94.md) - data type conversion for custom fields with preview, exclusion filters and Excel-like value lists in tables, bulk edit for custom fields, MeshCentral fallback values for empty sources.
|
||||
- [0.5.5.93](UPDATE-0.5.5.93.md) - custom fields in asset lists, MeshCentral sync flag for statuses, enforced session secret and translated UI texts.
|
||||
- [0.5.5.92](UPDATE-0.5.5.92.md) - startup diagnostics with runtime, database and callback endpoint information.
|
||||
- [0.5.5.91](UPDATE-0.5.5.91.md) - smoother table scrolling and consolidated current development changes.
|
||||
@@ -29,7 +30,7 @@
|
||||
|
||||
Release notes are stored outside the project root to keep the repository overview compact.
|
||||
|
||||
The current release is **0.5.5.93**.
|
||||
The current release is **0.5.5.94**.
|
||||
|
||||
Older notes are concise English summaries migrated from the original release documents. Git history remains authoritative for exact implementation details.
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Update 0.5.5.94
|
||||
|
||||
Version 0.5.5.94 makes custom fields fully usable in bulk edit, allows changing the data type of custom fields that already contain values, and lets MeshCentral mappings write a value when the source is missing.
|
||||
|
||||
## Changes
|
||||
|
||||
- **Bulk edit for custom fields:** custom fields with the "Bulk edit" flag are now offered in asset bulk edit (previously only fields stored directly on the asset were listed). Yes/no fields get a Yes/No/Empty selection, date, number, e-mail and URL fields get a matching input. Values are validated against the field type, changes are recorded in the asset history.
|
||||
- **Data type conversion with preview:** changing the data type of a custom field with stored values no longer fails. Saving opens a preview that shows convertible values, empty values and values that cannot be converted, together with MeshCentral mappings whose transformation does not fit the new type.
|
||||
- Values that cannot be converted are never dropped silently; for each one the administrator chooses *replace with* (validated) or *clear*.
|
||||
- The conversion runs in one database transaction with row locks. If the values changed after the preview, the conversion is rejected and a new preview is shown.
|
||||
- Before converting, all old values are written to `data/backups/field-conversion-<field>-<timestamp>.json`; every changed value is recorded in the asset history (source `type-conversion`).
|
||||
- Supported types: short/long text, integer, decimal, yes/no, date, date and time, URL, e-mail, IP address. Text → yes/no recognizes `ja, yes, true, 1, on, an` and `nein, no, false, 0, off, aus`. Yes/no → text uses the default language (e.g. "Ja"/"Nein"). JSON, references and status fields are excluded.
|
||||
- **MeshCentral "Value if empty":** each field mapping has an optional fallback value that is written when the MeshCentral source is missing or empty (e.g. `false` for BitLocker, whose key only exists while it is enabled). Combine it with the rule "MeshCentral wins" so later changes are applied.
|
||||
- The fallback is only used if the surrounding data exists for the device: by default the parent path of the source path, or an explicit path in **Only if present**. Devices without detail data keep their values.
|
||||
- If MeshCentral only delivers basic data (fallback after a failed detail query), no fallback values are applied in that run and a warning is logged.
|
||||
- **Exclusion filters in all tables:** a filter line starting with `!` excludes matching rows (`!Dell`, `!@empty`), `=value` compares the whole cell value exactly (`=Windows 10` does not match "Windows 10 Pro"). Include lines stay OR-linked; a row must match one include (if any) and no exclude. `==x` searches for a literal "=x". The software job list supports the same syntax on the server.
|
||||
- **Value list per column (Excel-like):** the ▾ button in a filter cell opens a list of all values of the column, with counts, search and "(Select all)". Only rows that pass the filters of the other columns are considered. Applying writes the selection into the normal filter field (`=a` lines or, if shorter, `!=b` lines), so saved filters, the filter status and "Reset filters" keep working.
|
||||
- The software job list computes its value list on the server (`/software/job-filter-values`) over the complete job history, not only the displayed page, considering the filters of the other columns (at most the newest 20,000 jobs). Job ID and time have no value list; they keep the range helper.
|
||||
- **Fix:** the job list text filters now also recognize the translated action "reinstall" and the job type "software deployment".
|
||||
- **Deleting fields:** the "Confirm values" checkbox next to the delete button was removed. A single confirmation now names the field and the number of stored values; the server additionally checks that this number is still current.
|
||||
- **Fix:** deleting a custom field now also removes its translations, so a field with the same technical name can be created again. Translations left over from earlier deletions are reused.
|
||||
- Version updated to 0.5.5.94.
|
||||
|
||||
## Upgrade notes
|
||||
|
||||
- The database columns `mesh_field_mappings.empty_value` and `mesh_field_mappings.empty_value_guard` are added automatically at startup.
|
||||
Reference in new issue
Block a user