Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. from datetime import date
  2. from calendar import monthrange
  3. import re
  4. from django import forms
  5. from django.db.models import get_model
  6. from django.utils.translation import ugettext_lazy as _
  7. from oscar.apps.address.forms import AbstractAddressForm
  8. from . import bankcards
  9. Country = get_model('address', 'Country')
  10. BillingAddress = get_model('order', 'BillingAddress')
  11. Bankcard = get_model('payment', 'Bankcard')
  12. class BankcardNumberField(forms.CharField):
  13. def __init__(self, *args, **kwargs):
  14. _kwargs = {
  15. 'max_length': 20,
  16. 'widget': forms.TextInput(attrs={'autocomplete': 'off'}),
  17. 'label': _("Card number")
  18. }
  19. _kwargs.update(kwargs)
  20. super(BankcardNumberField, self).__init__(*args, **_kwargs)
  21. def clean(self, value):
  22. """
  23. Check if given CC number is valid and one of the
  24. card types we accept
  25. """
  26. non_decimal = re.compile(r'\D+')
  27. value = non_decimal.sub('', value.strip())
  28. if value and not bankcards.luhn(value):
  29. raise forms.ValidationError(
  30. _("Please enter a valid credit card number."))
  31. return super(BankcardNumberField, self).clean(value)
  32. class BankcardMonthWidget(forms.MultiWidget):
  33. """
  34. Widget containing two select boxes for selecting the month and year
  35. """
  36. def decompress(self, value):
  37. return [value.month, value.year] if value else [None, None]
  38. def format_output(self, rendered_widgets):
  39. html = u' '.join(rendered_widgets)
  40. return u'<span style="white-space: nowrap">%s</span>' % html
  41. class BankcardMonthField(forms.MultiValueField):
  42. """
  43. A modified version of the snippet: http://djangosnippets.org/snippets/907/
  44. """
  45. default_error_messages = {
  46. 'invalid_month': _('Enter a valid month.'),
  47. 'invalid_year': _('Enter a valid year.'),
  48. }
  49. num_years = 5
  50. def __init__(self, *args, **kwargs):
  51. # Allow the number of years to be specified
  52. if 'num_years' in kwargs:
  53. self.num_years = kwargs.pop('num_years')
  54. errors = self.default_error_messages.copy()
  55. if 'error_messages' in kwargs:
  56. errors.update(kwargs['error_messages'])
  57. fields = (
  58. forms.ChoiceField(
  59. choices=self.month_choices(),
  60. error_messages={'invalid': errors['invalid_month']}),
  61. forms.ChoiceField(
  62. choices=self.year_choices(),
  63. error_messages={'invalid': errors['invalid_year']}),
  64. )
  65. if 'widget' not in kwargs:
  66. kwargs['widget'] = BankcardMonthWidget(
  67. widgets=[fields[0].widget, fields[1].widget])
  68. super(BankcardMonthField, self).__init__(fields, *args, **kwargs)
  69. def month_choices(self):
  70. return []
  71. def year_choices(self):
  72. return []
  73. class BankcardExpiryMonthField(BankcardMonthField):
  74. num_years = 10
  75. def __init__(self, *args, **kwargs):
  76. today = date.today()
  77. _kwargs = {
  78. 'required': True,
  79. 'label': _("Valid to"),
  80. 'initial': ["%.2d" % today.month, today.year]
  81. }
  82. _kwargs.update(kwargs)
  83. super(BankcardExpiryMonthField, self).__init__(*args, **_kwargs)
  84. def month_choices(self):
  85. return [("%.2d" % x, "%.2d" % x) for x in xrange(1, 13)]
  86. def year_choices(self):
  87. return [(x, x) for x in xrange(date.today().year,
  88. date.today().year + self.num_years)]
  89. def clean(self, value):
  90. expiry_date = super(BankcardExpiryMonthField, self).clean(value)
  91. if date.today() > expiry_date:
  92. raise forms.ValidationError(
  93. _("The expiration date you entered is in the past."))
  94. return expiry_date
  95. def compress(self, data_list):
  96. if data_list:
  97. if data_list[1] in forms.fields.EMPTY_VALUES:
  98. error = self.error_messages['invalid_year']
  99. raise forms.ValidationError(error)
  100. if data_list[0] in forms.fields.EMPTY_VALUES:
  101. error = self.error_messages['invalid_month']
  102. raise forms.ValidationError(error)
  103. year = int(data_list[1])
  104. month = int(data_list[0])
  105. # find last day of the month
  106. day = monthrange(year, month)[1]
  107. return date(year, month, day)
  108. return None
  109. class BankcardStartingMonthField(BankcardMonthField):
  110. def __init__(self, *args, **kwargs):
  111. _kwargs = {
  112. 'required': False,
  113. 'label': _("Valid from"),
  114. }
  115. _kwargs.update(kwargs)
  116. super(BankcardStartingMonthField, self).__init__(*args, **_kwargs)
  117. def month_choices(self):
  118. months = [("%.2d" % x, "%.2d" % x) for x in xrange(1, 13)]
  119. months.insert(0, ("", "--"))
  120. return months
  121. def year_choices(self):
  122. today = date.today()
  123. years = [(x, x) for x in xrange(today.year - self.num_years,
  124. today.year + 1)]
  125. years.insert(0, ("", "--"))
  126. return years
  127. def clean(self, value):
  128. starting_date = super(BankcardMonthField, self).clean(value)
  129. if starting_date and date.today() < starting_date:
  130. raise forms.ValidationError(
  131. _("The starting date you entered is in the future."))
  132. return starting_date
  133. def compress(self, data_list):
  134. if data_list:
  135. if data_list[1] in forms.fields.EMPTY_VALUES:
  136. error = self.error_messages['invalid_year']
  137. raise forms.ValidationError(error)
  138. if data_list[0] in forms.fields.EMPTY_VALUES:
  139. error = self.error_messages['invalid_month']
  140. raise forms.ValidationError(error)
  141. year = int(data_list[1])
  142. month = int(data_list[0])
  143. return date(year, month, 1)
  144. return None
  145. class BankcardCCVField(forms.RegexField):
  146. def __init__(self, *args, **kwargs):
  147. _kwargs = {
  148. 'required': True,
  149. 'label': _("CCV number"),
  150. 'widget': forms.TextInput(attrs={'size': '5'}),
  151. 'error_message': _("Please enter a 3 or 4 digit number"),
  152. 'help_text': _("This is the 3 or 4 digit security number "
  153. "on the back of your bankcard")
  154. }
  155. _kwargs.update(kwargs)
  156. super(BankcardCCVField, self).__init__(
  157. r'^\d{3,4}$', *args, **_kwargs)
  158. def clean(self, value):
  159. if value is not None:
  160. value = value.strip()
  161. return super(BankcardCCVField, self).clean(value)
  162. class BankcardForm(forms.ModelForm):
  163. number = BankcardNumberField()
  164. ccv = BankcardCCVField()
  165. start_month = BankcardStartingMonthField()
  166. expiry_month = BankcardExpiryMonthField()
  167. class Meta:
  168. model = Bankcard
  169. fields = ('number', 'start_month', 'expiry_month', 'ccv')
  170. def save(self, *args, **kwargs):
  171. # It doesn't really make sense to save directly from the form as saving
  172. # will obfuscate some of the card details which you normally need to
  173. # pass to a payment gateway. Better to use the bankcard property below
  174. # to get the cleaned up data, then once you've used the sensitive
  175. # details, you can save.
  176. raise RuntimeError("Don't save bankcards directly from form")
  177. @property
  178. def bankcard(self):
  179. """
  180. Return an instance of the Bankcard model (unsaved)
  181. """
  182. return Bankcard(number=self.cleaned_data['number'],
  183. expiry_date=self.cleaned_data['expiry_month'],
  184. start_date=self.cleaned_data['start_month'],
  185. ccv=self.cleaned_data['ccv'])
  186. class BillingAddressForm(AbstractAddressForm):
  187. def __init__(self, *args, **kwargs):
  188. super(BillingAddressForm, self).__init__(*args, **kwargs)
  189. self.set_country_queryset()
  190. def set_country_queryset(self):
  191. self.fields['country'].queryset = Country._default_manager.all()
  192. class Meta:
  193. model = BillingAddress
  194. exclude = ('search_text',)