-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathparty.py
99 lines (82 loc) · 2.99 KB
/
party.py
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
# -*- coding: utf-8 -*-
import os
import logging
from wtforms import TextField, validators
from trytond.pool import PoolMeta, Pool
from trytond.modules.nereid.party import AddressForm
from trytond.config import config
from nereid import request, current_app, current_user
from trytond.modules.nereid_checkout.i18n import _
__metaclass__ = PoolMeta
__all__ = ['Address']
geoip = None
try:
from pygeoip import GeoIP
except ImportError:
logging.error("pygeoip is not installed")
else:
path = os.environ.get(
'GEOIP_DATA_PATH', config.get('nereid_webshop', 'geoip_data_path')
)
if path:
geoip = GeoIP(path)
class WebshopAddressForm(AddressForm):
"""Custom address form for webshop
"""
phone = TextField(_('Phone'), [validators.DataRequired(), ])
def get_default_country(self):
"""Get the default country based on geoip data.
"""
if not geoip or not request.remote_addr:
return None
Country = Pool().get('country.country')
try:
current_app.logger.debug(
"GeoIP lookup for remote address: %s" % request.remote_addr
)
country, = Country.search([
('code', '=', geoip.country_code_by_addr(request.remote_addr))
])
except ValueError:
return None
return country
def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
# While choices can be assigned after the form is constructed, default
# cannot be. The form's data is picked from the first available of
# formdata, obj data, and kwargs.
# Once the data has been resolved, changing the default won't do
# anything.
default_country = self.get_default_country()
if default_country:
kwargs.setdefault('country', default_country.id)
super(WebshopAddressForm, self).__init__(
formdata, obj, prefix, **kwargs
)
class Address:
__name__ = 'party.address'
@classmethod
def get_address_form(cls, address=None):
"""
Return an initialised Address form that can be validated and used to
create/update addresses
:param address: If an active record is provided it is used to autofill
the form.
"""
if address:
form = WebshopAddressForm(
request.form,
name=address.name,
street=address.street,
streetbis=address.streetbis,
zip=address.zip,
city=address.city,
country=address.country and address.country.id,
subdivision=address.subdivision and address.subdivision.id,
email=address.party.email,
phone=address.phone
)
else:
address_name = "" if current_user.is_anonymous else \
current_user.display_name
form = WebshopAddressForm(request.form, name=address_name)
return form