1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
|
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from itertools import chain
try:
import phonenumbers
from phonenumbers import NumberParseException, PhoneNumberFormat
except ImportError:
phonenumbers = None
from trytond.i18n import gettext
from trytond.model import (
DeactivableMixin, Index, ModelSQL, ModelView, MultiValueMixin, ValueMixin,
fields, sequence_ordered)
from trytond.model.exceptions import AccessError
from trytond.pyson import Eval
from trytond.tools.email_ import (
EmailNotValidError, normalize_email, validate_email)
from trytond.transaction import Transaction
from .exceptions import InvalidEMail, InvalidPhoneNumber
_TYPES = [
('phone', 'Phone'),
('mobile', 'Mobile'),
('fax', 'Fax'),
('email', 'E-Mail'),
('website', 'Website'),
('skype', 'Skype'),
('sip', 'SIP'),
('irc', 'IRC'),
('jabber', 'Jabber'),
('other', 'Other'),
]
_PHONE_TYPES = {
'phone',
'mobile',
'fax',
}
class _ContactMechanismMixin:
__slots__ = ()
def contact_mechanism_get(self, types=None, usage=None):
"""
Try to find a contact mechanism for the given types and usage, if no
usage matches the first mechanism of the given types is returned.
"""
default_mechanism = None
if types:
if isinstance(types, str):
types = {types}
mechanisms = [m for m in self.contact_mechanisms
if m.type in types]
else:
mechanisms = self.contact_mechanisms
if mechanisms:
default_mechanism = mechanisms[0]
if usage:
for mechanism in mechanisms:
if getattr(mechanism, usage):
return mechanism
return default_mechanism
class ContactMechanism(
DeactivableMixin, sequence_ordered(), ModelSQL, ModelView,
MultiValueMixin):
"Contact Mechanism"
__name__ = 'party.contact_mechanism'
_rec_name = 'value'
type = fields.Selection(_TYPES, "Type", required=True, sort=False)
value = fields.Char(
"Value",
# Add all function fields to ensure to always fill them via on_change
depends={
'email', 'website', 'skype', 'sip', 'other_value',
'value_compact'})
value_compact = fields.Char('Value Compact', readonly=True)
name = fields.Char("Name")
comment = fields.Text("Comment")
party = fields.Many2One(
'party.party', "Party", required=True, ondelete='CASCADE')
address = fields.Many2One(
'party.address', "Address", ondelete='CASCADE',
domain=[
('party', '=', Eval('party', -1)),
])
language = fields.MultiValue(
fields.Many2One('ir.lang', "Language",
help="Used to translate communication made "
"using the contact mechanism.\n"
"Leave empty for the party language."))
languages = fields.One2Many(
'party.contact_mechanism.language', 'contact_mechanism', "Languages")
email = fields.Function(fields.Char('E-Mail', states={
'invisible': Eval('type') != 'email',
'required': Eval('type') == 'email',
}, depends={'value'}),
'get_value', setter='set_value')
website = fields.Function(fields.Char('Website', states={
'invisible': Eval('type') != 'website',
'required': Eval('type') == 'website',
}, depends={'value'}),
'get_value', setter='set_value')
skype = fields.Function(fields.Char('Skype', states={
'invisible': Eval('type') != 'skype',
'required': Eval('type') == 'skype',
}, depends={'value'}),
'get_value', setter='set_value')
sip = fields.Function(fields.Char('SIP', states={
'invisible': Eval('type') != 'sip',
'required': Eval('type') == 'sip',
}, depends={'value'}),
'get_value', setter='set_value')
other_value = fields.Function(fields.Char('Value', states={
'invisible': Eval('type').in_(['email', 'website', 'skype', 'sip']),
'required': ~Eval('type').in_(['email', 'website']),
}, depends={'value'}),
'get_value', setter='set_value')
url = fields.Function(fields.Char('URL', states={
'invisible': ~Eval('url'),
}),
'on_change_with_url')
@classmethod
def __setup__(cls):
cls.value.search_unaccented = False
cls.value_compact.search_unaccented = False
super(ContactMechanism, cls).__setup__()
t = cls.__table__()
cls._sql_indexes.add(
Index(t, (Index.Unaccent(t.value_compact), Index.Similarity())))
cls._order.insert(0, ('party.distance', 'ASC NULLS LAST'))
cls._order.insert(1, ('party', 'ASC'))
@staticmethod
def default_type():
return 'phone'
@classmethod
def default_party(cls):
return Transaction().context.get('related_party')
@fields.depends('address', '_parent_address.party')
def on_change_address(self):
if self.address:
self.party = self.address.party
@classmethod
def get_value(cls, mechanisms, names):
return dict((name, dict((m.id, m.value) for m in mechanisms))
for name in names)
@fields.depends('type', 'value')
def on_change_with_url(self, name=None, value=None):
if value is None:
value = self.value
if self.type == 'email':
return 'mailto:%s' % value
elif self.type == 'website':
return value
elif self.type == 'skype':
return 'callto:%s' % value
elif self.type == 'sip':
return 'sip:%s' % value
elif self.type in {'phone', 'mobile'}:
return 'tel:%s' % value
elif self.type == 'fax':
return 'fax:%s' % value
return None
@fields.depends('party', '_parent_party.addresses')
def _phone_country_codes(self):
if self.party:
for address in self.party.addresses:
if address.country:
yield address.country.code
@fields.depends(methods=['_phone_country_codes'])
def _parse_phonenumber(self, value):
for country_code in chain(self._phone_country_codes(), [None]):
try:
# Country code is ignored if value has an international prefix
phonenumber = phonenumbers.parse(value, country_code)
except NumberParseException:
pass
else:
if phonenumbers.is_valid_number(phonenumber):
return phonenumber
return None
@fields.depends(methods=['_parse_phonenumber'])
def format_value(self, value=None, type_=None):
if phonenumbers and type_ in _PHONE_TYPES:
phonenumber = self._parse_phonenumber(value)
if phonenumber:
value = phonenumbers.format_number(
phonenumber, PhoneNumberFormat.INTERNATIONAL)
if type_ == 'email' and value:
value = normalize_email(value)
return value
@fields.depends(methods=['_parse_phonenumber'])
def format_value_compact(self, value=None, type_=None):
if phonenumbers and type_ in _PHONE_TYPES:
phonenumber = self._parse_phonenumber(value)
if phonenumber:
value = phonenumbers.format_number(
phonenumber, PhoneNumberFormat.E164)
return value
@classmethod
def set_value(cls, mechanisms, name, value):
# Setting value is done by on_changes
pass
@fields.depends(
methods=['on_change_with_url', 'format_value', 'format_value_compact'])
def _change_value(self, value, type_):
self.value = self.format_value(value=value, type_=type_)
self.value_compact = self.format_value_compact(
value=value, type_=type_)
self.website = value
self.email = value
self.skype = value
self.sip = value
self.other_value = value
self.url = self.on_change_with_url(value=value)
@fields.depends('value', 'type', methods=['_change_value'])
def on_change_value(self):
return self._change_value(self.value, self.type)
@fields.depends('website', 'type', methods=['_change_value'])
def on_change_website(self):
return self._change_value(self.website, self.type)
@fields.depends('email', 'type', methods=['_change_value'])
def on_change_email(self):
return self._change_value(self.email, self.type)
@fields.depends('skype', 'type', methods=['_change_value'])
def on_change_skype(self):
return self._change_value(self.skype, self.type)
@fields.depends('sip', 'type', methods=['_change_value'])
def on_change_sip(self):
return self._change_value(self.sip, self.type)
@fields.depends('other_value', 'type', methods=['_change_value'])
def on_change_other_value(self):
return self._change_value(self.other_value, self.type)
def get_rec_name(self, name):
name = self.name or self.party.rec_name
return '%s <%s>' % (name, self.value_compact or self.value)
@classmethod
def search_rec_name(cls, name, clause):
if clause[1].startswith('!') or clause[1].startswith('not '):
bool_op = 'AND'
else:
bool_op = 'OR'
return [bool_op,
('value',) + tuple(clause[1:]),
('value_compact',) + tuple(clause[1:]),
]
@classmethod
def _format_values(cls, mechanisms):
for mechanism in mechanisms:
value = mechanism.format_value(
value=mechanism.value, type_=mechanism.type)
if value != mechanism.value:
mechanism.value = value
value_compact = mechanism.format_value_compact(
value=mechanism.value, type_=mechanism.type)
if value_compact != mechanism.value_compact:
mechanism.value_compact = value_compact
cls.save(mechanisms)
@classmethod
def create(cls, vlist):
mechanisms = super(ContactMechanism, cls).create(vlist)
cls._format_values(mechanisms)
return mechanisms
@classmethod
def write(cls, *args):
actions = iter(args)
all_mechanisms = []
for mechanisms, values in zip(actions, actions):
all_mechanisms.extend(mechanisms)
if 'party' in values:
for mechanism in mechanisms:
if mechanism.party.id != values['party']:
raise AccessError(
gettext('party'
'.msg_contact_mechanism_change_party') % {
'contact': mechanism.rec_name,
})
super(ContactMechanism, cls).write(*args)
cls._format_values(all_mechanisms)
@classmethod
def validate_fields(cls, mechanisms, field_names):
super().validate_fields(mechanisms, field_names)
cls.check_valid_phonenumber(mechanisms, field_names)
cls.check_valid_email(mechanisms, field_names)
@classmethod
def check_valid_phonenumber(cls, mechanisms, field_names=None):
if field_names and not (field_names & {'type', 'value'}):
return
if not phonenumbers:
return
for mechanism in mechanisms:
if mechanism.type not in _PHONE_TYPES:
continue
if not mechanism._parse_phonenumber(mechanism.value):
raise InvalidPhoneNumber(
gettext('party.msg_invalid_phone_number',
phone=mechanism.value, party=mechanism.party.rec_name))
@classmethod
def check_valid_email(cls, mechanisms, field_names=None):
if field_names and not (field_names & {'type', 'value'}):
return
for mechanism in mechanisms:
if mechanism.type == 'email' and mechanism.value:
try:
validate_email(mechanism.value)
except EmailNotValidError as e:
raise InvalidEMail(gettext(
'party.msg_email_invalid',
email=mechanism.value,
party=mechanism.party.rec_name),
str(e)) from e
@classmethod
def usages(cls, _fields=None):
"Returns the selection list of usage"
usages = [(None, "")]
if _fields:
for name, desc in cls.fields_get(_fields).items():
usages.append((name, desc['string']))
return usages
class ContactMechanismLanguage(ModelSQL, ValueMixin):
"Contact Mechanism Language"
__name__ = 'party.contact_mechanism.language'
contact_mechanism = fields.Many2One(
'party.contact_mechanism', "Contact Mechanism",
ondelete='CASCADE')
language = fields.Many2One('ir.lang', "Language")
|