Guest User

Untitled

a guest
Jun 22nd, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.37 KB | None | 0 0
  1. ~ tieredweightzone/forms.py ~
  2.  
  3.  
  4. from django import forms
  5. from django.contrib.auth.models import User
  6. from django.db.models import Q
  7. from django.utils.translation import ugettext_lazy as _, ugettext
  8. from satchmo.configuration import config_value, config_get_group, SettingNotSet, SHOP_GROUP
  9. from satchmo.contact.models import Contact, AddressBook, PhoneNumber, Organization
  10. from satchmo.l10n.models import Country
  11. from satchmo.shop.models import Config
  12. import datetime
  13. import logging
  14. import signals
  15.  
  16. log = logging.getLogger('satchmo.contact.forms')
  17.  
  18. selection = ''
  19.  
  20. class ContactInfoForm(forms.Form):
  21. email = forms.EmailField(max_length=75, label=_('Email'))
  22. title = forms.CharField(max_length=30, label=_('Title'), required=False)
  23. first_name = forms.CharField(max_length=30, label=_('First Name'))
  24. last_name = forms.CharField(max_length=30, label=_('Last Name'))
  25. phone = forms.CharField(max_length=30, label=_('Phone'))
  26. addressee = forms.CharField(max_length=61, required=False, label=_('Addressee'))
  27. company = forms.CharField(max_length=50, required=False, label=_('Company'))
  28. street1 = forms.CharField(max_length=30, label=_('Street'))
  29. street2 = forms.CharField(max_length=30, required=False)
  30. city = forms.CharField(max_length=30, label=_('City'))
  31. state = forms.CharField(max_length=30, required=False, label=_('State'))
  32. postal_code = forms.CharField(max_length=10, label=_('ZIP code/Postcode'))
  33. copy_address = forms.BooleanField(required=False, label=_('Shipping same as billing?'))
  34. ship_addressee = forms.CharField(max_length=61, required=False, label=_('Addressee'))
  35. ship_street1 = forms.CharField(max_length=30, required=False, label=_('Street'))
  36. ship_street2 = forms.CharField(max_length=30, required=False)
  37. ship_city = forms.CharField(max_length=30, required=False, label=_('City'))
  38. ship_state = forms.CharField(max_length=30, required=False, label=_('State'))
  39. ship_postal_code = forms.CharField(max_length=10, required=False, label=_('ZIP code/Postcode'))
  40. next = forms.CharField(max_length=40, required=False, widget=forms.HiddenInput())
  41.  
  42. def __init__(self, *args, **kwargs):
  43.  
  44. if kwargs:
  45. data = kwargs.copy()
  46. else:
  47. data = {}
  48.  
  49. shop = data.pop('shop', None)
  50. contact = data.pop('contact', None)
  51. self.shippable = data.pop('shippable', True)
  52.  
  53. if not shop:
  54. shop = Config.objects.get_current()
  55.  
  56. super(ContactInfoForm, self).__init__(*args, **data)
  57.  
  58. self._billing_data_optional = config_value(SHOP_GROUP, 'BILLING_DATA_OPTIONAL')
  59.  
  60. self._local_only = shop.in_country_only
  61. areas = shop.areas()
  62. if shop.in_country_only and areas and areas.count()>0:
  63. areas = [(area.abbrev or area.name, area.name) for area in areas]
  64. billing_state = (contact and getattr(contact.billing_address, 'state', None)) or selection
  65. shipping_state = (contact and getattr(contact.shipping_address, 'state', None)) or selection
  66. if config_value('SHOP','ENFORCE_STATE'):
  67. self.fields['state'] = forms.ChoiceField(choices=areas, initial=billing_state, label=_('State'))
  68. self.fields['ship_state'] = forms.ChoiceField(choices=areas, initial=shipping_state, required=False, label=_('State'))
  69.  
  70. self._default_country = shop.sales_country
  71. billing_country = (contact and getattr(contact.billing_address, 'country', None)) or self._default_country
  72. shipping_country = (contact and getattr(contact.shipping_address, 'country', None)) or self._default_country
  73. self.fields['country'] = forms.ModelChoiceField(shop.countries(), required=False, label=_('Country'), empty_label=None, initial=billing_country.pk)
  74. self.fields['ship_country'] = forms.ModelChoiceField(shop.countries(), required=False, label=_('Country'), empty_label=None, initial=shipping_country.pk)
  75.  
  76. self.contact = contact
  77. if self._billing_data_optional:
  78. for fname in ('phone', 'street1', 'street2', 'city', 'state', 'country', 'postal_code', 'title'):
  79. self.fields[fname].required = False
  80.  
  81. # slap a star on the required fields
  82. for f in self.fields:
  83. fld = self.fields[f]
  84. if fld.required:
  85. fld.label = (fld.label or f) + '*'
  86.  
  87. def _check_state(self, data, country):
  88. if country and config_value('SHOP','ENFORCE_STATE') and country.adminarea_set.filter(active=True).count() > 0:
  89. if not data or data == selection:
  90. raise forms.ValidationError(
  91. self._local_only and _('This field is required.') \
  92. or _('State is required for your country.'))
  93. if (country.adminarea_set
  94. .filter(active=True)
  95. .filter(Q(name=data)
  96. |Q(abbrev=data)
  97. |Q(name=data.capitalize())
  98. |Q(abbrev=data.upper())).count() != 1):
  99. raise forms.ValidationError(_('Invalid state or province.'))
  100.  
  101.  
  102. def clean_email(self):
  103. """Prevent account hijacking by disallowing duplicate emails."""
  104. email = self.cleaned_data.get('email', None)
  105. if self.contact:
  106. if self.contact.email and self.contact.email == email:
  107. return email
  108. users_with_email = Contact.objects.filter(email=email)
  109. if len(users_with_email) == 0:
  110. return email
  111. if len(users_with_email) > 1 or users_with_email[0].id != self.contact.id:
  112. raise forms.ValidationError(
  113. ugettext("That email address is already in use."))
  114. return email
  115.  
  116. def clean_postal_code(self):
  117. postcode = self.cleaned_data.get('postal_code')
  118. country = None
  119.  
  120. if self._local_only:
  121. shop_config = Config.objects.get_current()
  122. country = shop_config.sales_country
  123. else:
  124. country = self.fields['country'].clean(self.data.get('country'))
  125. if not country:
  126. # Either the store is misconfigured, or the country was
  127. # not supplied, so the country validation will fail and
  128. # we can defer the postcode validation until that's fixed.
  129. return postcode
  130.  
  131. return self.validate_postcode_by_country(postcode, country)
  132.  
  133. def clean_state(self):
  134. data = self.cleaned_data.get('state')
  135. if self._local_only:
  136. country = self._default_country
  137. else:
  138. country = self.fields['country'].clean(self.data.get('country'))
  139. if country == None:
  140. raise forms.ValidationError(_('This field is required.'))
  141. self._check_state(data, country)
  142. return data
  143.  
  144. def clean_addressee(self):
  145. if not self.cleaned_data.get('addressee'):
  146. first_and_last = u' '.join((self.cleaned_data.get('first_name', ''),
  147. self.cleaned_data.get('last_name', '')))
  148. return first_and_last
  149. else:
  150. return self.cleaned_data['addressee']
  151.  
  152. def clean_ship_addressee(self):
  153. if not self.cleaned_data.get('ship_addressee') and \
  154. not self.cleaned_data.get('copy_address'):
  155. first_and_last = u' '.join((self.cleaned_data.get('first_name', ''),
  156. self.cleaned_data.get('last_name', '')))
  157. return first_and_last
  158. else:
  159. return self.cleaned_data['ship_addressee']
  160.  
  161. def clean_country(self):
  162. if self._local_only:
  163. return self._default_country
  164. else:
  165. if not self.cleaned_data.get('country'):
  166. log.error("No country! Got '%s'" % self.cleaned_data.get('country'))
  167. raise forms.ValidationError(_('This field is required.'))
  168. return self.cleaned_data['country']
  169.  
  170. def clean_ship_country(self):
  171. copy_address = self.fields['copy_address'].clean(self.data.get('copy_address'))
  172. if copy_address:
  173. return self.cleaned_data.get('country')
  174. if self._local_only:
  175. return self._default_country
  176. if not self.shippable:
  177. return self.cleaned_data.get['country']
  178. shipcountry = self.cleaned_data.get('ship_country')
  179. if not shipcountry:
  180. raise forms.ValidationError(_('This field is required.'))
  181. if config_value('PAYMENT', 'COUNTRY_MATCH'):
  182. country = self.cleaned_data.get('country')
  183. if shipcountry != country:
  184. raise forms.ValidationError(_('Shipping and Billing countries must match'))
  185. return shipcountry
  186.  
  187. def ship_charfield_clean(self, field_name):
  188. if self.cleaned_data.get('copy_address'):
  189. self.cleaned_data['ship_' + field_name] = self.fields[field_name].clean(self.data.get(field_name))
  190. return self.cleaned_data['ship_' + field_name]
  191. return self.fields['ship_' + field_name].clean(self.data.get('ship_' + field_name))
  192.  
  193. def clean_ship_street1(self):
  194. return self.ship_charfield_clean('street1')
  195.  
  196. def clean_ship_street2(self):
  197. if self.cleaned_data.get('copy_address'):
  198. if 'street2' in self.cleaned_data:
  199. self.cleaned_data['ship_street2'] = self.cleaned_data.get('street2')
  200. return self.cleaned_data.get('ship_street2')
  201.  
  202. def clean_ship_city(self):
  203. return self.ship_charfield_clean('city')
  204.  
  205. def clean_ship_postal_code(self):
  206. code = self.ship_charfield_clean('postal_code')
  207.  
  208. country = None
  209.  
  210. if self._local_only:
  211. shop_config = Config.objects.get_current()
  212. country = shop_config.sales_country
  213. else:
  214. country = self.ship_charfield_clean('country')
  215.  
  216. if not country:
  217. # Either the store is misconfigured, or the country was
  218. # not supplied, so the country validation will fail and
  219. # we can defer the postcode validation until that's fixed.
  220. return code
  221.  
  222. return self.validate_postcode_by_country(code, country)
  223.  
  224. def clean_ship_state(self):
  225. data = self.cleaned_data.get('ship_state')
  226.  
  227. if self.cleaned_data.get('copy_address'):
  228. if 'state' in self.cleaned_data:
  229. self.cleaned_data['ship_state'] = self.cleaned_data['state']
  230. return self.cleaned_data['ship_state']
  231.  
  232. if self._local_only:
  233. country = self._default_country
  234. else:
  235. country = self.ship_charfield_clean('country')
  236.  
  237. self._check_state(data, country)
  238. return data
  239.  
  240. def save(self, contact=None, update_newsletter=True, **kwargs):
  241. return self.save_info(contact=contact, update_newsletter=update_newsletter, **kwargs)
  242.  
  243. def save_info(self, contact=None, update_newsletter=True, **kwargs):
  244. """Save the contact info into the database.
  245. Checks to see if contact exists. If not, creates a contact
  246. and copies in the address and phone number."""
  247. if not contact:
  248. customer = Contact()
  249. log.debug('creating new contact')
  250. else:
  251. customer = contact
  252. log.debug('Saving contact info for %s', contact)
  253.  
  254. data = self.cleaned_data.copy()
  255. country = data['country']
  256. print "country",country
  257. if not isinstance(country, Country):
  258. country = Country.objects.get(pk=country)
  259. data['country'] = country
  260. data['country_id'] = country.id
  261.  
  262. shipcountry = data['ship_country']
  263. if not isinstance(shipcountry, Country):
  264. shipcountry = Country.objects.get(pk=shipcountry)
  265. data['ship_country'] = shipcountry
  266.  
  267. data['ship_country_id'] = shipcountry.id
  268.  
  269. companyname = data.pop('company', None)
  270. if companyname:
  271. org = Organization.objects.by_name(companyname, create=True)
  272. customer.organization = org
  273.  
  274. for field in customer.__dict__.keys():
  275. try:
  276. setattr(customer, field, data[field])
  277. except KeyError:
  278. pass
  279.  
  280. if update_newsletter and config_get_group('NEWSLETTER'):
  281. from satchmo.newsletter import update_subscription
  282. if 'newsletter' not in data:
  283. subscribed = False
  284. else:
  285. subscribed = data['newsletter']
  286.  
  287. update_subscription(contact, subscribed)
  288.  
  289. if not customer.role:
  290. customer.role = "Customer"
  291.  
  292. customer.save()
  293.  
  294. # we need to make sure we don't blindly add new addresses
  295. # this isn't ideal, but until we have a way to manage addresses
  296. # this will force just the two addresses, shipping and billing
  297. # TODO: add address management like Amazon.
  298.  
  299. bill_address = customer.billing_address
  300. if not bill_address:
  301. bill_address = AddressBook(contact=customer)
  302.  
  303. changed_location = False
  304. address_keys = bill_address.__dict__.keys()
  305. for field in address_keys:
  306. if (not changed_location) and field in ('state', 'country', 'city'):
  307. if getattr(bill_address, field) != data[field]:
  308. changed_location = True
  309. try:
  310. setattr(bill_address, field, data[field])
  311. except KeyError:
  312. pass
  313.  
  314. bill_address.is_default_billing = True
  315.  
  316. copy_address = data['copy_address']
  317.  
  318. ship_address = customer.shipping_address
  319.  
  320. if copy_address:
  321. # make sure we don't have any other default shipping address
  322. if ship_address and ship_address.id != bill_address.id:
  323. ship_address.delete()
  324. bill_address.is_default_shipping = True
  325.  
  326. bill_address.save()
  327.  
  328. if not copy_address:
  329. if not ship_address or ship_address.id == bill_address.id:
  330. ship_address = AddressBook()
  331.  
  332. for field in address_keys:
  333. if (not changed_location) and field in ('state', 'country', 'city'):
  334. if getattr(ship_address, field) != data[field]:
  335. changed_location = True
  336. try:
  337. setattr(ship_address, field, data['ship_' + field])
  338. except KeyError:
  339. pass
  340. ship_address.is_default_shipping = True
  341. ship_address.is_default_billing = False
  342. ship_address.contact = customer
  343. ship_address.save()
  344.  
  345. if not customer.primary_phone:
  346. phone = PhoneNumber()
  347. phone.primary = True
  348. else:
  349. phone = customer.primary_phone
  350. phone.phone = data['phone']
  351. phone.contact = customer
  352. phone.save()
  353.  
  354. signals.form_save.send(ContactInfoForm, object=customer, formdata=data, form=self)
  355.  
  356. if changed_location:
  357. signals.satchmo_contact_location_changed.send(self, contact=customer)
  358.  
  359. return customer.id
  360.  
  361. def validate_postcode_by_country(self, postcode, country):
  362. responses = signals.validate_postcode.send(self, postcode=postcode, country=country)
  363. # allow responders to reformat the code, but if they don't return
  364. # anything, then just use the existing code
  365. for responder, response in responses:
  366. if response:
  367. return response
  368.  
  369. return postcode
  370.  
  371. class DateTextInput(forms.TextInput):
  372. def render(self, name, value, attrs=None):
  373. if isinstance(value, datetime.date):
  374. value = value.strftime("%m.%d.%Y")
  375. return super(DateTextInput, self).render(name, value, attrs)
  376.  
  377. class ExtendedContactInfoForm(ContactInfoForm):
  378. """Contact form which includes birthday and newsletter."""
  379. dob = forms.DateField(required=False)
  380. newsletter = forms.BooleanField(label=_('Newsletter'), widget=forms.CheckboxInput(), required=False)
Add Comment
Please, Sign In to add comment