Add custom grid filter for phone number fields

and use it in various grid views
This commit is contained in:
Lance Edgar 2019-04-10 14:20:36 -05:00
parent 2bdcc4fe47
commit ec70d85638
6 changed files with 63 additions and 13 deletions

View file

@ -26,6 +26,7 @@ Grid Filters
from __future__ import unicode_literals, absolute_import
import re
import datetime
import logging
@ -765,6 +766,45 @@ class AlchemyGPCFilter(AlchemyGridFilter):
return query
class AlchemyPhoneNumberFilter(AlchemyStringFilter):
"""
Special string filter, with logic to deal with phone numbers.
"""
def parse_value(self, value):
newvalue = None
# first we try to split according to typical 7- or 10-digit number
digits = re.sub(r'\D', '', value or '')
if len(digits) == 7:
newvalue = "{} {}".format(digits[:3], digits[3:])
elif len(digits) == 10:
newvalue = "{} {} {}".format(digits[:3], digits[3:6], digits[6:])
# if that didn't work, we can also try to split by grouped digits
if not newvalue and value:
parts = re.split(r'\D+', value)
newvalue = ' '.join(parts)
return newvalue or value
def filter_contains(self, query, value):
"""
Try to parse the value into "parts" of a phone number, then do a normal
'ILIKE' query with those parts.
"""
value = self.parse_value(value)
return super(AlchemyPhoneNumberFilter, self).filter_contains(query, value)
def filter_does_not_contain(self, query, value):
"""
Try to parse the value into "parts" of a phone number, then do a normal
'NOT ILIKE' query with those parts.
"""
value = self.parse_value(value)
return super(AlchemyPhoneNumberFilter, self).filter_does_not_contain(query, value)
class GridFilterSet(OrderedDict):
"""
Collection class for :class:`GridFilter` instances.