Add selector nomenclature for conditional field visibility

A selector is a nomenclature whose value decides which other nomenclatures
appear beneath it: picking "Ship" reveals the ship fields, "Warehouse"
reveals the warehouse ones. Previously every vehicle nomenclature rendered
at once, so the operator had to know which were relevant and a vehicle
could silently carry both a ship and a warehouse.

Visibility is one rule - a nomenclature is hidden if some selector option
reveals it and that selector's value is not the revealing option - kept in
nomenclatures/visibility.py and mirrored in services/nomenclatureVisibility.js.
A nomenclature no selector references always shows, so installations without
selectors are unchanged.

The serializer, not the UI, enforces the invariant: a value for a hidden
nomenclature is rejected, as is a selector value that matches no option.
The frontend clearing values on switch and pruning hidden keys before save
is convenience on top of that.

Selector values join lookups in the quick-fill combination projection, so
applying a saved combination sets the source and its revealed fields in one
click rather than collapsing "Ship + cargo" and "Warehouse + cargo" into
one indistinguishable row.

Configuration rejects nesting (a selector revealing another selector) and
double-reveal (one nomenclature revealed by two selectors, leaving its
visibility ambiguous). The admin UI filters both out of the reveal list as
well, so an invalid configuration cannot be built in the first place.

Note: introducing a selector over existing data hides values already
entered - vehicles predating the selector have no selector key, so anything
it reveals becomes invisible until a source is chosen. The values remain
stored. Worth a data check before configuring the first selector.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-09-18 19:43:13 +03:00
parent fe9fb71860
commit d10b1d263f
13 changed files with 856 additions and 34 deletions
+107 -6
View File
@@ -2,7 +2,10 @@ from rest_framework import serializers
from django.contrib.auth.password_validation import validate_password
from .models import ComPortReading, User, Report, ScaleProtocol
from vehicles.models import Vehicle, VehicleExtra, ExtraCombination
from nomenclatures.models import Nomenclature, NomenclatureField, NomenclatureEntry
from nomenclatures.models import (
Nomenclature, NomenclatureField, NomenclatureEntry, SelectorOption,
)
from nomenclatures.visibility import build_reveal_map, is_visible
class UserSerializer(serializers.ModelSerializer):
@@ -79,15 +82,19 @@ class ComPortReadingSerializer(serializers.ModelSerializer):
def validate_vehicle_extra_data(value, lookup_only=False):
"""Validate a {nomenclature_code: value} dict against vehicle nomenclatures.
lookup_only=True rejects any key whose nomenclature is not kind='lookup'.
lookup_only=True rejects any key whose nomenclature is not kind='lookup'
or kind='selector' (the projection stored as a reusable combination).
"""
if not value:
return value
nomenclatures = {
n.code: n for n in
Nomenclature.objects.filter(applies_to='vehicle').prefetch_related('fields', 'entries')
Nomenclature.objects.filter(applies_to='vehicle').prefetch_related(
'fields', 'entries', 'selector_options__reveals'
)
}
reveal_map = build_reveal_map()
errors = {}
for key, val in value.items():
@@ -97,7 +104,20 @@ def validate_vehicle_extra_data(value, lookup_only=False):
nom = nomenclatures[key]
if nom.kind == Nomenclature.LOOKUP:
# A value for a nomenclature the current selector state hides is a
# contradiction: this is what actually enforces the rule, not the UI.
if val is not None and not is_visible(key, value, reveal_map):
errors[key] = (
f"'{key}' is not applicable for the current selector value."
)
continue
if nom.kind == Nomenclature.SELECTOR:
allowed = {o.value for o in nom.selector_options.all()}
if val is not None and val not in allowed:
errors[key] = f"Must be one of {sorted(allowed)}."
elif nom.kind == Nomenclature.LOOKUP:
if not isinstance(val, int):
errors[key] = "Must be a nomenclature entry ID (integer)."
elif not nom.entries.filter(id=val, is_active=True).exists():
@@ -105,7 +125,7 @@ def validate_vehicle_extra_data(value, lookup_only=False):
elif nom.kind == Nomenclature.FIELD:
if lookup_only:
errors[key] = "Only lookup nomenclatures are allowed here."
errors[key] = "Only lookup and selector nomenclatures are allowed here."
continue
field_def = nom.fields.first()
if field_def:
@@ -317,27 +337,53 @@ class NomenclatureEntrySerializer(serializers.ModelSerializer):
return value
class SelectorOptionSerializer(serializers.ModelSerializer):
"""One selector choice; `reveals` is a list of nomenclature codes."""
reveals = serializers.SlugRelatedField(
many=True,
slug_field='code',
queryset=Nomenclature.objects.all(),
required=False,
)
class Meta:
model = SelectorOption
fields = ['id', 'value', 'label', 'reveals', 'sort_order']
read_only_fields = ['id']
def validate_value(self, value):
if not value or not value.strip():
raise serializers.ValidationError("Option value cannot be empty")
return value.strip()
class NomenclatureSerializer(serializers.ModelSerializer):
fields = NomenclatureFieldSerializer(many=True, required=False)
selector_options = SelectorOptionSerializer(many=True, required=False)
entry_count = serializers.IntegerField(source='entries.count', read_only=True)
class Meta:
model = Nomenclature
fields = ['id', 'code', 'name', 'applies_to', 'kind', 'display_field',
'sort_order', 'fields', 'entry_count']
'sort_order', 'fields', 'selector_options', 'entry_count']
read_only_fields = ['id']
def create(self, validated_data):
fields_data = validated_data.pop('fields', [])
options_data = validated_data.pop('selector_options', [])
nomenclature = Nomenclature.objects.create(**validated_data)
for field_data in fields_data:
NomenclatureField.objects.create(nomenclature=nomenclature, **field_data)
self._write_options(nomenclature, options_data)
return nomenclature
def update(self, instance, validated_data):
fields_data = validated_data.pop('fields', None)
options_data = validated_data.pop('selector_options', None)
for attr, value in validated_data.items():
setattr(instance, attr, value)
@@ -348,8 +394,20 @@ class NomenclatureSerializer(serializers.ModelSerializer):
for field_data in fields_data:
NomenclatureField.objects.create(nomenclature=instance, **field_data)
if options_data is not None:
instance.selector_options.all().delete()
self._write_options(instance, options_data)
return instance
@staticmethod
def _write_options(nomenclature, options_data):
"""Recreate the selector's options; `reveals` is m2m so it is set after save."""
for option_data in options_data:
reveals = option_data.pop('reveals', [])
option = SelectorOption.objects.create(selector=nomenclature, **option_data)
option.reveals.set(reveals)
def validate_code(self, value):
if not value or not value.strip():
raise serializers.ValidationError("Code cannot be empty")
@@ -366,6 +424,14 @@ class NomenclatureSerializer(serializers.ModelSerializer):
def validate(self, data):
kind = data.get('kind', getattr(self.instance, 'kind', Nomenclature.LOOKUP))
fields_data = data.get('fields', [])
options_data = data.get('selector_options')
if kind == Nomenclature.SELECTOR:
self._validate_selector_options(options_data or [])
elif options_data:
raise serializers.ValidationError({
'selector_options': "Only a 'selector' nomenclature can have options."
})
if kind == Nomenclature.FIELD and fields_data and len(fields_data) != 1:
raise serializers.ValidationError(
@@ -382,6 +448,41 @@ class NomenclatureSerializer(serializers.ModelSerializer):
return data
def _validate_selector_options(self, options_data):
"""No nesting, and no nomenclature revealed by two different selectors."""
errors = []
seen_values = set()
for option in options_data:
value = option.get('value')
if value in seen_values:
errors.append(f"Duplicate option value '{value}'.")
seen_values.add(value)
for revealed in option.get('reveals', []):
if revealed.kind == Nomenclature.SELECTOR:
errors.append(
f"'{revealed.code}' is a selector; selectors cannot reveal "
f"other selectors."
)
continue
other = (
SelectorOption.objects
.filter(reveals=revealed)
.exclude(selector=self.instance)
.select_related('selector')
.first()
)
if other:
errors.append(
f"'{revealed.code}' is already revealed by selector "
f"'{other.selector.code}'."
)
if errors:
raise serializers.ValidationError({'selector_options': errors})
class ReportSerializer(serializers.ModelSerializer):
created_by_name = serializers.CharField(source='created_by.username', read_only=True, default=None)