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:
+107
-6
@@ -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)
|
||||
|
||||
@@ -188,12 +188,19 @@ def _assign_weighing(vehicle, value, user, manual=False, note=None):
|
||||
|
||||
|
||||
def _record_extra_combination(extra_data):
|
||||
"""Record the lookup-only projection of a vehicle's extra data as a reusable combination."""
|
||||
"""Record the lookup/selector projection of a vehicle's extra data as a reusable combination.
|
||||
|
||||
The selector value is part of the combination: without it, "Ship + Varna Star"
|
||||
and "Warehouse + WH-3" would collapse into indistinguishable rows.
|
||||
"""
|
||||
if not extra_data:
|
||||
return
|
||||
|
||||
lookup_codes = set(
|
||||
Nomenclature.objects.filter(applies_to='vehicle', kind=Nomenclature.LOOKUP)
|
||||
Nomenclature.objects.filter(
|
||||
applies_to='vehicle',
|
||||
kind__in=[Nomenclature.LOOKUP, Nomenclature.SELECTOR],
|
||||
)
|
||||
.values_list('code', flat=True)
|
||||
)
|
||||
combo = {k: v for k, v in extra_data.items() if k in lookup_codes and v is not None}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from django.contrib import admin
|
||||
from .models import Nomenclature, NomenclatureField, NomenclatureEntry
|
||||
from .models import Nomenclature, NomenclatureField, NomenclatureEntry, SelectorOption
|
||||
|
||||
|
||||
class NomenclatureFieldInline(admin.TabularInline):
|
||||
@@ -7,12 +7,18 @@ class NomenclatureFieldInline(admin.TabularInline):
|
||||
extra = 1
|
||||
|
||||
|
||||
class SelectorOptionInline(admin.TabularInline):
|
||||
model = SelectorOption
|
||||
extra = 1
|
||||
filter_horizontal = ['reveals']
|
||||
|
||||
|
||||
@admin.register(Nomenclature)
|
||||
class NomenclatureAdmin(admin.ModelAdmin):
|
||||
list_display = ['code', 'name', 'applies_to', 'kind', 'sort_order']
|
||||
list_filter = ['applies_to', 'kind']
|
||||
search_fields = ['code', 'name']
|
||||
inlines = [NomenclatureFieldInline]
|
||||
inlines = [NomenclatureFieldInline, SelectorOptionInline]
|
||||
|
||||
|
||||
@admin.register(NomenclatureEntry)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Generated by Django 6.0.1 on 2026-09-18 16:26
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("nomenclatures", "0002_alter_nomenclature_options_and_more"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="nomenclature",
|
||||
name="kind",
|
||||
field=models.CharField(
|
||||
choices=[
|
||||
("lookup", "Lookup Table"),
|
||||
("field", "Custom Field"),
|
||||
("selector", "Selector"),
|
||||
],
|
||||
default="lookup",
|
||||
max_length=10,
|
||||
),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="SelectorOption",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("value", models.CharField(max_length=50)),
|
||||
("label", models.CharField(max_length=255)),
|
||||
("sort_order", models.IntegerField(default=0)),
|
||||
(
|
||||
"reveals",
|
||||
models.ManyToManyField(
|
||||
blank=True,
|
||||
related_name="revealed_by",
|
||||
to="nomenclatures.nomenclature",
|
||||
),
|
||||
),
|
||||
(
|
||||
"selector",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="selector_options",
|
||||
to="nomenclatures.nomenclature",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"ordering": ["sort_order", "id"],
|
||||
"unique_together": {("selector", "value")},
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -11,9 +11,11 @@ class Nomenclature(models.Model):
|
||||
|
||||
LOOKUP = "lookup"
|
||||
FIELD = "field"
|
||||
SELECTOR = "selector"
|
||||
KIND_CHOICES = [
|
||||
(LOOKUP, "Lookup Table"),
|
||||
(FIELD, "Custom Field"),
|
||||
(SELECTOR, "Selector"),
|
||||
]
|
||||
|
||||
code = models.CharField(max_length=50, unique=True)
|
||||
@@ -35,6 +37,31 @@ class Nomenclature(models.Model):
|
||||
return f"{self.name} ({self.code})"
|
||||
|
||||
|
||||
class SelectorOption(models.Model):
|
||||
"""One choice of a selector, and the nomenclatures it reveals."""
|
||||
|
||||
selector = models.ForeignKey(
|
||||
Nomenclature,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="selector_options",
|
||||
)
|
||||
value = models.CharField(max_length=50)
|
||||
label = models.CharField(max_length=255)
|
||||
reveals = models.ManyToManyField(
|
||||
Nomenclature,
|
||||
blank=True,
|
||||
related_name="revealed_by",
|
||||
)
|
||||
sort_order = models.IntegerField(default=0)
|
||||
|
||||
class Meta:
|
||||
ordering = ["sort_order", "id"]
|
||||
unique_together = [("selector", "value")]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.selector.code}={self.value}"
|
||||
|
||||
|
||||
class NomenclatureField(models.Model):
|
||||
TEXT = "text"
|
||||
NUMBER = "number"
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""The one rule deciding which nomenclatures are visible for a given extra_data.
|
||||
|
||||
A nomenclature is hidden if it is revealed by some selector option and that
|
||||
selector's current value is not the option revealing it. Anything no selector
|
||||
references is always visible, so installations without selectors are unchanged.
|
||||
|
||||
Mirrored in frontend/src/utils/nomenclatureVisibility.js - keep the two in step.
|
||||
"""
|
||||
|
||||
from .models import Nomenclature, SelectorOption
|
||||
|
||||
|
||||
def build_reveal_map(nomenclatures=None):
|
||||
"""{revealed_code: {selector_code: {value, ...}}} for the given nomenclatures."""
|
||||
options = (
|
||||
SelectorOption.objects
|
||||
.select_related('selector')
|
||||
.prefetch_related('reveals')
|
||||
)
|
||||
if nomenclatures is not None:
|
||||
codes = {n.code for n in nomenclatures}
|
||||
options = [o for o in options if o.selector.code in codes]
|
||||
|
||||
reveal_map = {}
|
||||
for option in options:
|
||||
for revealed in option.reveals.all():
|
||||
reveal_map.setdefault(revealed.code, {}).setdefault(
|
||||
option.selector.code, set()
|
||||
).add(option.value)
|
||||
return reveal_map
|
||||
|
||||
|
||||
def is_visible(code, extra_data, reveal_map):
|
||||
"""True if the nomenclature `code` should be shown/accepted for this data."""
|
||||
controllers = reveal_map.get(code)
|
||||
if not controllers:
|
||||
return True
|
||||
for selector_code, revealing_values in controllers.items():
|
||||
if extra_data.get(selector_code) in revealing_values:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def visible_codes(codes, extra_data, reveal_map=None):
|
||||
"""Filter `codes` down to those visible for `extra_data`."""
|
||||
if reveal_map is None:
|
||||
reveal_map = build_reveal_map()
|
||||
return [c for c in codes if is_visible(c, extra_data or {}, reveal_map)]
|
||||
Reference in New Issue
Block a user