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
+1400
-187
No files matched your search
+485
-143
@@ -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:
|
||||
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))
|
||||
def job_id_condition(value: str):
|
||||
advanced = _software_job_numeric_filter(SoftwareJob.id, value)
|
||||
if advanced is not None:
|
||||
return advanced
|
||||
if value.isdigit():
|
||||
return SoftwareJob.id == int(value)
|
||||
return _sql_text_matches(SoftwareJob.id, value)
|
||||
|
||||
def created_condition(value: str):
|
||||
return _software_job_date_filter(SoftwareJob.created_at, value)
|
||||
|
||||
def asset_condition(value: str):
|
||||
return _sql_text_matches(Asset.name, 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))
|
||||
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(_sql_text_contains(SoftwareJob.id, value))
|
||||
query = query.filter(or_(*conditions))
|
||||
conditions.append(and_(SoftwareJob.job_type == "job_definition", _sql_text_contains(parameters_text, kind)))
|
||||
return or_(*conditions)
|
||||
|
||||
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
|
||||
]))
|
||||
|
||||
terms = _multi_filter_terms(filters["asset"])
|
||||
if terms:
|
||||
query = query.filter(or_(*[
|
||||
_sql_text_contains(Asset.name, value)
|
||||
for value in terms
|
||||
]))
|
||||
|
||||
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 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]),
|
||||
)
|
||||
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,
|
||||
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))),
|
||||
)
|
||||
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))
|
||||
return or_(_sql_text_contains(SoftwarePackage.name, text), _sql_text_contains(parameters_text, text))
|
||||
|
||||
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),
|
||||
)
|
||||
for value in terms
|
||||
]))
|
||||
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))
|
||||
return or_(*conditions)
|
||||
|
||||
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,
|
||||
)
|
||||
if action_codes:
|
||||
conditions.append(SoftwareJob.action.in_(action_codes))
|
||||
term_conditions.append(or_(*conditions))
|
||||
query = query.filter(or_(*term_conditions))
|
||||
def priority_condition(value: str):
|
||||
advanced = _software_job_numeric_filter(SoftwareJob.priority, value)
|
||||
if advanced is not None:
|
||||
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["priority"])
|
||||
if terms:
|
||||
conditions = []
|
||||
for value in terms:
|
||||
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))
|
||||
def platform_condition(value: str):
|
||||
return _sql_text_matches(SoftwareJob.platform, value)
|
||||
|
||||
terms = _multi_filter_terms(filters["platform"])
|
||||
if terms:
|
||||
query = query.filter(or_(*[
|
||||
_sql_text_contains(SoftwareJob.platform, value)
|
||||
for value in terms
|
||||
]))
|
||||
|
||||
terms = _multi_filter_terms(filters["status"])
|
||||
if terms:
|
||||
term_conditions = []
|
||||
for value in terms:
|
||||
conditions = [_sql_text_contains(SoftwareJob.status, value)]
|
||||
status_codes = _translated_filter_codes(
|
||||
request,
|
||||
"software.status",
|
||||
(
|
||||
"created",
|
||||
"sending",
|
||||
"sent",
|
||||
"running",
|
||||
"success",
|
||||
"partial",
|
||||
"failed",
|
||||
"timeout",
|
||||
"cancelled",
|
||||
),
|
||||
value,
|
||||
)
|
||||
if status_codes:
|
||||
conditions.append(SoftwareJob.status.in_(status_codes))
|
||||
term_conditions.append(or_(*conditions))
|
||||
query = query.filter(or_(*term_conditions))
|
||||
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",
|
||||
SOFTWARE_JOB_STATUS_CODES,
|
||||
text,
|
||||
exact=exact,
|
||||
)
|
||||
if status_codes:
|
||||
conditions.append(SoftwareJob.status.in_(status_codes))
|
||||
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,7 +9867,12 @@ 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.
|
||||
db.add(Translation(translation_key=definition.translation_key, language_code='en', text_value=definition.label))
|
||||
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:
|
||||
db.rollback(); raise TranslatedHTTPException(400, "errors.field_name_exists", "A field with this name already exists.") from 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)
|
||||
|
||||
Reference in new issue
Block a user