Files
Assetmanager/app/field_conversion.py
RolandandClaude Opus 5.5 40cd88871f 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>
2026-11-18 21:14:21 +01:00

276 lines
9.5 KiB
Python

"""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