loko/streetup/common/hooks.py

106 lines
3.4 KiB
Python

from django.db.models import Q
class ExtensionHooks:
def __init__(self):
self._form_cleaners = []
self._search_annotators = []
self._search_filters = []
self._pdf_fields_extractors = []
self._export_headers = []
self._export_row_extractors = []
self._custom_allowed_fields = []
self._custom_export_fields = []
self._inline_validators = []
self._custom_source_ref_value_extractor = None
def register_custom_source_ref_value_extractor(self, func):
self._custom_source_ref_value_extractor = func
return func
def get_custom_source_ref_value(self, intervention):
if self._custom_source_ref_value_extractor:
return self._custom_source_ref_value_extractor(intervention)
return None
def register_custom_export_field(self, label, extractor):
self._custom_export_fields.append((label, extractor))
return (label, extractor)
def get_custom_export_fields(self):
return self._custom_export_fields
def register_inline_validator(self, func):
self._inline_validators.append(func)
return func
def run_inline_edit_validator(self, field, new_value, intervention):
for validator in self._inline_validators:
res = validator(field, new_value, intervention)
if res[0] is not None:
return res
return (None, None)
def register_form_cleaner(self, func):
self._form_cleaners.append(func)
return func
def register_search_annotator(self, func):
self._search_annotators.append(func)
return func
def register_search_filter(self, func):
self._search_filters.append(func)
return func
def register_pdf_fields_extractor(self, func):
self._pdf_fields_extractors.append(func)
return func
def register_export_headers(self, headers_list):
self._export_headers.extend(headers_list)
def register_export_row_extractor(self, func):
self._export_row_extractors.append(func)
return func
def register_custom_allowed_field(self, field_name_or_list):
if isinstance(field_name_or_list, list):
self._custom_allowed_fields.extend(field_name_or_list)
else:
self._custom_allowed_fields.append(field_name_or_list)
def run_form_cleaners(self, form, cleaned_data):
for cleaner in self._form_cleaners:
cleaned_data = cleaner(form, cleaned_data)
return cleaned_data
def apply_search_annotations(self, queryset):
for annotator in self._search_annotators:
queryset = annotator(queryset)
return queryset
def get_search_filters(self, word):
q_obj = Q()
for filter_func in self._search_filters:
q_obj |= filter_func(word)
return q_obj
def extract_pdf_fields(self, intervention):
fields = []
for extractor in self._pdf_fields_extractors:
fields.extend(extractor(intervention))
return fields
def get_export_headers(self):
return self._export_headers
def extract_export_row(self, intervention):
row_data = []
for extractor in self._export_row_extractors:
row_data.extend(extractor(intervention))
return row_data
def get_custom_allowed_fields(self):
return self._custom_allowed_fields
hooks = ExtensionHooks()