+
+class Chooser(APIView):
+ def get(self, request):
+ return Response([{
+ 'value': 'x',
+ 'name': 'name',
+ 'description': 'desc',
+ 'sub': [
+ {
+ 'value': 'y',
+ 'name': 'name y',
+ 'description': 'desc y',
+ }
+ ]
+ }])
+
+
+class ThemaChooser(Chooser):
+ queryset = models.Thema.objects.filter(usable=True, hidden=False)
+
+ def get(self, request):
+ tree = {}
+
+ def getitem(code):
+ if len(code) == 1:
+ parent = tree
+ else:
+ parent = getitem(code[:-1]).setdefault('sub', {})
+ return parent.setdefault(code, {})
+
+ def getmissing(t):
+ for k, v in t.items():
+ if 'name' not in v:
+ yield k
+ if 'sub' in v:
+ for c in getmissing(v['sub']):
+ yield c
+
+ def populate(thema):
+ item = getitem(thema.code)
+ item['usable'] = thema.usable
+ item['hidden'] = thema.hidden
+ item['name'] = thema.name
+ item['description'] = thema.description
+
+ def order(tree):
+ res = []
+ for k, v in tree.items():
+ v.update(value=k)
+ if 'sub' in v:
+ v['sub'] = order(v['sub'])
+ res.append(v)
+ while len(res) == 1 and 'name' not in res[0] and 'sub' in res[0]:
+ res = res[0]['sub']
+ return res
+
+ def apply_filter(filt):
+ if 'not' in filt:
+ return ~apply_filter(filt['not'])
+ if 'startswith' in filt:
+ q = None
+ for prefix in filt['startswith']:
+ q2 = Q(code__startswith=prefix)
+ if q:
+ q |= q2
+ else:
+ q = q2
+ return q
+ assert False
+
+ qs = self.queryset
+ try:
+ filt = json.loads(request.GET.get('filter'))
+ except:
+ pass
+ else:
+ qs = qs.filter(apply_filter(filt))
+
+ for thema in qs:
+ populate(thema)
+
+ missing = list(getmissing(tree))
+ for thema in models.Thema.objects.filter(code__in=missing):
+ populate(thema)
+
+ tree = order(tree)
+
+ return Response(tree)
+
+
+class MainThemaChooser(ThemaChooser):
+ queryset = models.Thema.objects.filter(usable=True, hidden=False, usable_as_main=True)[:1000]
+
+