You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

abstract_models.py 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. import re
  2. import zlib
  3. import string
  4. from django.db import models
  5. from django.utils.translation import ugettext_lazy as _, pgettext_lazy
  6. from django.core import exceptions
  7. from oscar.core.compat import AUTH_USER_MODEL
  8. from oscar.models.fields import UppercaseCharField
  9. class AbstractAddress(models.Model):
  10. """
  11. Superclass address object
  12. This is subclassed and extended to provide models for
  13. user, shipping and billing addresses.
  14. """
  15. MR, MISS, MRS, MS, DR = ('Mr', 'Miss', 'Mrs', 'Ms', 'Dr')
  16. TITLE_CHOICES = (
  17. (MR, _("Mr")),
  18. (MISS, _("Miss")),
  19. (MRS, _("Mrs")),
  20. (MS, _("Ms")),
  21. (DR, _("Dr")),
  22. )
  23. # Regex for each country. Not listed countries don't use postcodes
  24. # Based on http://en.wikipedia.org/wiki/List_of_postal_codes
  25. POSTCODES_REGEX = {
  26. 'AC': r'^[A-Z]{4}[0-9][A-Z]$',
  27. 'AD': r'^AD[0-9]{3}$',
  28. 'AF': r'^[0-9]{4}$',
  29. 'AI': r'^AI-2640$',
  30. 'AL': r'^[0-9]{4}$',
  31. 'AM': r'^[0-9]{4}$',
  32. 'AR': r'^([0-9]{4}|[A-Z][0-9]{4}[A-Z]{3}$',
  33. 'AS': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$',
  34. 'AT': r'^[0-9]{4}$',
  35. 'AU': r'^[0-9]{4}$',
  36. 'AX': r'^[0-9]{5}$',
  37. 'AZ': r'^AZ[0-9]{4}$',
  38. 'BA': r'^[0-9]{5}$',
  39. 'BB': r'^BB[0-9]{5}$',
  40. 'BD': r'^[0-9]{4}$',
  41. 'BE': r'^[0-9]{4}$',
  42. 'BG': r'^[0-9]{4}$',
  43. 'BH': r'^[0-9]{3,4}$',
  44. 'BL': r'^[0-9]{5}$',
  45. 'BM': r'^[A-Z]{2}([0-9]{2}|[A-Z]{2})',
  46. 'BN': r'^[A-Z}{2}[0-9]]{4}$',
  47. 'BO': r'^[0-9]{4}$',
  48. 'BR': r'^[0-9]{5}(-[0-9]{3})?$',
  49. 'BT': r'^[0-9]{3}$',
  50. 'BY': r'^[0-9]{6}$',
  51. 'CA': r'^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$',
  52. 'CC': r'^[0-9]{4}$',
  53. 'CH': r'^[0-9]{4}$',
  54. 'CL': r'^([0-9]{7}|[0-9]{3}-[0-9]{4})$',
  55. 'CN': r'^[0-9]{6}$',
  56. 'CO': r'^[0-9]{6}$',
  57. 'CR': r'^[0-9]{4,5}$',
  58. 'CU': r'^[0-9]{5}$',
  59. 'CV': r'^[0-9]{4}$',
  60. 'CX': r'^[0-9]{4}$',
  61. 'CY': r'^[0-9]{4}$',
  62. 'CZ': r'^[0-9]{5}$',
  63. 'DE': r'^[0-9]{5}$',
  64. 'DK': r'^[0-9]{4}$',
  65. 'DO': r'^[0-9]{5}$',
  66. 'DZ': r'^[0-9]{5}$',
  67. 'EC': r'^EC[0-9]{6}$',
  68. 'EE': r'^[0-9]{5}$',
  69. 'EG': r'^[0-9]{5}$',
  70. 'ES': r'^[0-9]{5}$',
  71. 'ET': r'^[0-9]{4}$',
  72. 'FI': r'^[0-9]{5}$',
  73. 'FK': r'^[A-Z]{4}[0-9][A-Z]{2}$',
  74. 'FM': r'^[0-9]{5}(-[0-9]{4})?$',
  75. 'FO': r'^[0-9]{3}$',
  76. 'FR': r'^[0-9]{5}$',
  77. 'GA': r'^[0-9]{2}.*[0-9]{2}$',
  78. 'GB': r'^[A-Z][A-Z0-9]{1,3}[0-9][A-Z]{2}$',
  79. 'GE': r'^[0-9]{4}$',
  80. 'GF': r'^[0-9]{5}$',
  81. 'GG': r'^([A-Z]{2}[0-9]{2,3}[A-Z]{2}$',
  82. 'GI': r'^GX111AA$',
  83. 'GL': r'^[0-9]{4}$',
  84. 'GP': r'^[0-9]{5}$',
  85. 'GR': r'^[0-9]{5}$',
  86. 'GS': r'^SIQQ1ZZ$',
  87. 'GT': r'^[0-9]{5}$',
  88. 'GU': r'^[0-9]{5}$',
  89. 'GW': r'^[0-9]{4}$',
  90. 'HM': r'^[0-9]{4}$',
  91. 'HN': r'^[0-9]{5}$',
  92. 'HR': r'^[0-9]{5}$',
  93. 'HT': r'^[0-9]{4}$',
  94. 'HU': r'^[0-9]{4}$',
  95. 'ID': r'^[0-9]{5}$',
  96. 'IL': r'^[0-9]{7}$',
  97. 'IM': r'^IM[0-9]{2,3}[A-Z]{2}$$',
  98. 'IN': r'^[0-9]{6}$',
  99. 'IO': r'^[A-Z]{4}[0-9][A-Z]{2}$',
  100. 'IQ': r'^[0-9]{5}$',
  101. 'IR': r'^[0-9]{5}-[0-9]{5}$',
  102. 'IS': r'^[0-9]{3}$',
  103. 'IT': r'^[0-9]{5}$',
  104. 'JE': r'^JE[0-9]{2}[A-Z]{2}$',
  105. 'JM': r'^JM[A-Z]{3}[0-9]{2}$',
  106. 'JO': r'^[0-9]{5}$',
  107. 'JP': r'^[0-9]{3}-?[0-9]{4}$',
  108. 'KE': r'^[0-9]{5}$',
  109. 'KG': r'^[0-9]{6}$',
  110. 'KH': r'^[0-9]{5}$',
  111. 'KR': r'^[0-9]{3}-?[0-9]{3}$',
  112. 'KY': r'^KY[0-9]-[0-9]{4}$',
  113. 'KZ': r'^[0-9]{6}$',
  114. 'LA': r'^[0-9]{5}$',
  115. 'LB': r'^[0-9]{8}$',
  116. 'LI': r'^[0-9]{4}$',
  117. 'LK': r'^[0-9]{5}$',
  118. 'LR': r'^[0-9]{4}$',
  119. 'LS': r'^[0-9]{3}$',
  120. 'LT': r'^[0-9]{5}$',
  121. 'LU': r'^[0-9]{4}$',
  122. 'LV': r'^LV-[0-9]{4}$',
  123. 'LY': r'^[0-9]{5}$',
  124. 'MA': r'^[0-9]{5}$',
  125. 'MC': r'^980[0-9]{2}$',
  126. 'MD': r'^MD-?[0-9]{4}$',
  127. 'ME': r'^[0-9]{5}$',
  128. 'MF': r'^[0-9]{5}$',
  129. 'MG': r'^[0-9]{3}$',
  130. 'MH': r'^[0-9]{5}$',
  131. 'MK': r'^[0-9]{4}$',
  132. 'MM': r'^[0-9]{5}$',
  133. 'MN': r'^[0-9]{5}$',
  134. 'MP': r'^[0-9]{5}$',
  135. 'MQ': r'^[0-9]{5}$',
  136. 'MT': r'^[A-Z]{3}[0-9]{4}$',
  137. 'MV': r'^[0-9]{4,5}$',
  138. 'MX': r'^[0-9]{5}$',
  139. 'MY': r'^[0-9]{5}$',
  140. 'MZ': r'^[0-9]{4}$',
  141. 'NA': r'^[0-9]{5}$',
  142. 'NC': r'^[0-9]{5}$',
  143. 'NE': r'^[0-9]{4}$',
  144. 'NF': r'^[0-9]{4}$',
  145. 'NG': r'^[0-9]{6}$',
  146. 'NI': r'^[0-9]{3}-[0-9]{3}-[0-9]$',
  147. 'NL': r'^[0-9]{4}[A-Z]{2}$',
  148. 'NO': r'^[0-9]{4}$',
  149. 'NP': r'^[0-9]{5}$',
  150. 'NZ': r'^[0-9]{4}$',
  151. 'OM': r'^[0-9]{3}$',
  152. 'PA': r'^[0-9]{6}$',
  153. 'PE': r'^[0-9]{5}$',
  154. 'PF': r'^[0-9]{5}$',
  155. 'PG': r'^[0-9]{3}$',
  156. 'PH': r'^[0-9]{4}$',
  157. 'PK': r'^[0-9]{5}$',
  158. 'PL': r'^[0-9]{2}-?[0-9]{3}$',
  159. 'PM': r'^[0-9]{5}$',
  160. 'PN': r'^[A-Z]{4}[0-9][A-Z]{2}$',
  161. 'PR': r'^[0-9]{5}$',
  162. 'PT': r'^[0-9]{4}(-?[0-9]{3})?$',
  163. 'PW': r'^[0-9]{5}$',
  164. 'PY': r'^[0-9]{4}$',
  165. 'RE': r'^[0-9]{5}$',
  166. 'RO': r'^[0-9]{6}$',
  167. 'RS': r'^[0-9]{5}$',
  168. 'RU': r'^[0-9]{6}$',
  169. 'SA': r'^[0-9]{5}$',
  170. 'SD': r'^[0-9]{5}$',
  171. 'SE': r'^[0-9]{5}$',
  172. 'SG': r'^([0-9]{2}|[0-9]{4}|[0-9]{6})$',
  173. 'SH': r'^(STHL1ZZ|TDCU1ZZ)$',
  174. 'SI': r'^(SI-)?[0-9]{4}$',
  175. 'SK': r'^[0-9]{5}$',
  176. 'SM': r'^[0-9]{5}$',
  177. 'SN': r'^[0-9]{5}$',
  178. 'SV': r'^01101$',
  179. 'SZ': r'^[A-Z][0-9]{3}$',
  180. 'TC': r'^TKCA1ZZ$',
  181. 'TD': r'^[0-9]{5}$',
  182. 'TH': r'^[0-9]{5}$',
  183. 'TJ': r'^[0-9]{6}$',
  184. 'TM': r'^[0-9]{6}$',
  185. 'TN': r'^[0-9]{4}$',
  186. 'TR': r'^[0-9]{5}$',
  187. 'TT': r'^[0-9]{6}$',
  188. 'TW': r'^[0-9]{5}$',
  189. 'UA': r'^[0-9]{5}$',
  190. 'US': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$',
  191. 'UY': r'^[0-9]{5}$',
  192. 'UZ': r'^[0-9]{6}$',
  193. 'VA': r'^00120$',
  194. 'VC': r'^VC[0-9]{4}',
  195. 'VE': r'^[0-9]{4}[A-Z]?$',
  196. 'VG': r'^VG[0-9]{4}$',
  197. 'VI': r'^[0-9]{5}$',
  198. 'VN': r'^[0-9]{6}$',
  199. 'WF': r'^[0-9]{5}$',
  200. 'XK': r'^[0-9]{5}$',
  201. 'YT': r'^[0-9]{5}$',
  202. 'ZA': r'^[0-9]{4}$',
  203. 'ZM': r'^[0-9]{5}$',
  204. }
  205. title = models.CharField(
  206. pgettext_lazy(u"Treatment Pronouns for the customer", u"Title"),
  207. max_length=64, choices=TITLE_CHOICES, blank=True, null=True)
  208. first_name = models.CharField(
  209. _("First name"), max_length=255, blank=True, null=True)
  210. last_name = models.CharField(_("Last name"), max_length=255, blank=True)
  211. # We use quite a few lines of an address as they are often quite long and
  212. # it's easier to just hide the unnecessary ones than add extra ones.
  213. line1 = models.CharField(_("First line of address"), max_length=255)
  214. line2 = models.CharField(
  215. _("Second line of address"), max_length=255, blank=True, null=True)
  216. line3 = models.CharField(
  217. _("Third line of address"), max_length=255, blank=True, null=True)
  218. line4 = models.CharField(_("City"), max_length=255, blank=True, null=True)
  219. state = models.CharField(
  220. _("State/County"), max_length=255, blank=True, null=True)
  221. postcode = UppercaseCharField(
  222. _("Post/Zip-code"), max_length=64, blank=True, null=True)
  223. country = models.ForeignKey('address.Country', verbose_name=_("Country"))
  224. #: A field only used for searching addresses - this contains all the
  225. #: relevant fields. This is effectively a poor man's Solr text field.
  226. search_text = models.CharField(
  227. _("Search text - used only for searching addresses"),
  228. max_length=1000, editable=False)
  229. def __unicode__(self):
  230. return self.summary
  231. class Meta:
  232. abstract = True
  233. verbose_name = _('Address')
  234. verbose_name_plural = _('Addresses')
  235. # Saving
  236. def save(self, *args, **kwargs):
  237. self._update_search_text()
  238. super(AbstractAddress, self).save(*args, **kwargs)
  239. def clean(self):
  240. # Strip all whitespace
  241. for field in ['first_name', 'last_name', 'line1', 'line2', 'line3',
  242. 'line4', 'state', 'postcode']:
  243. if self.__dict__[field]:
  244. self.__dict__[field] = self.__dict__[field].strip()
  245. # Ensure postcodes are valid for country
  246. self.ensure_postcode_is_valid_for_country()
  247. def ensure_postcode_is_valid_for_country(self):
  248. """
  249. Validate postcode given the country
  250. """
  251. if not self.postcode and self.country_id:
  252. country_code = self.country.iso_3166_1_a2
  253. regex = self.POSTCODES_REGEX.get(country_code, None)
  254. if regex:
  255. msg = ("Addresses in %(country)s require a postcode") % {
  256. 'country': self.country}
  257. raise exceptions.ValidationError(msg)
  258. if self.postcode and self.country_id:
  259. # Ensure postcodes are always uppercase
  260. postcode = self.postcode.upper().replace(' ', '')
  261. country_code = self.country.iso_3166_1_a2
  262. regex = self.POSTCODES_REGEX.get(country_code, None)
  263. # Validate postcode against regext for the country if available
  264. if regex and not re.match(regex, postcode):
  265. msg = _("The postcode '%(postcode)s' is not valid "
  266. "for the %(country)s") % {
  267. 'postcode': self.postcode,
  268. 'country': self.country}
  269. raise exceptions.ValidationError(msg)
  270. def _update_search_text(self):
  271. search_fields = filter(
  272. bool, [self.first_name, self.last_name,
  273. self.line1, self.line2, self.line3, self.line4,
  274. self.state, self.postcode, self.country.name])
  275. self.search_text = ' '.join(search_fields)
  276. # Properties
  277. @property
  278. def city(self):
  279. # Common alias
  280. return self.line4
  281. @property
  282. def summary(self):
  283. """
  284. Returns a single string summary of the address,
  285. separating fields using commas.
  286. """
  287. return u", ".join(self.active_address_fields())
  288. @property
  289. def salutation(self):
  290. """
  291. Name (including title)
  292. """
  293. return self.join_fields(
  294. ('title', 'first_name', 'last_name'),
  295. separator=u" ")
  296. @property
  297. def name(self):
  298. return self.join_fields(('first_name', 'last_name'), separator=u" ")
  299. # Helpers
  300. def generate_hash(self):
  301. """
  302. Returns a hash of the address summary
  303. """
  304. # We use an upper-case version of the summary
  305. return zlib.crc32(self.summary.strip().upper().encode('UTF8'))
  306. def join_fields(self, fields, separator=u", "):
  307. """
  308. Join a sequence of fields using the specified separator
  309. """
  310. field_values = []
  311. for field in fields:
  312. # Title is special case
  313. if field == 'title':
  314. value = self.get_title_display()
  315. else:
  316. value = getattr(self, field)
  317. field_values.append(value)
  318. return separator.join(filter(bool, field_values))
  319. def populate_alternative_model(self, address_model):
  320. """
  321. For populating an address model using the matching fields
  322. from this one.
  323. This is used to convert a user address to a shipping address
  324. as part of the checkout process.
  325. """
  326. destination_field_names = [
  327. field.name for field in address_model._meta.fields]
  328. for field_name in [field.name for field in self._meta.fields]:
  329. if field_name in destination_field_names and field_name != 'id':
  330. setattr(address_model, field_name, getattr(self, field_name))
  331. def active_address_fields(self):
  332. """
  333. Return the non-empty components of the address, but merging the
  334. title, first_name and last_name into a single line.
  335. """
  336. fields = [self.salutation, self.line1, self.line2,
  337. self.line3, self.line4, self.state, self.postcode]
  338. fields = map(string.strip, filter(bool, fields))
  339. try:
  340. fields.append(self.country.name)
  341. except exceptions.ObjectDoesNotExist:
  342. pass
  343. return fields
  344. class AbstractCountry(models.Model):
  345. """
  346. International Organization for Standardization (ISO) 3166-1 Country list.
  347. """
  348. iso_3166_1_a2 = models.CharField(_('ISO 3166-1 alpha-2'), max_length=2,
  349. primary_key=True)
  350. iso_3166_1_a3 = models.CharField(_('ISO 3166-1 alpha-3'), max_length=3,
  351. null=True, db_index=True)
  352. # This should have been a CharField as it needs to be padded with zeros to
  353. # be 3 digits. Access via the numeric_code instead.
  354. iso_3166_1_numeric = models.PositiveSmallIntegerField(
  355. _('ISO 3166-1 numeric'), null=True, db_index=True)
  356. name = models.CharField(_('Official name (CAPS)'), max_length=128)
  357. printable_name = models.CharField(_('Country name'), max_length=128)
  358. display_order = models.PositiveSmallIntegerField(
  359. _("Display order"), default=0, db_index=True,
  360. help_text=_('Higher the number, higher the country in the list.'))
  361. is_shipping_country = models.BooleanField(_("Is Shipping Country"),
  362. default=False, db_index=True)
  363. class Meta:
  364. abstract = True
  365. verbose_name = _('Country')
  366. verbose_name_plural = _('Countries')
  367. ordering = ('-display_order', 'name',)
  368. def __unicode__(self):
  369. return self.printable_name or self.name
  370. @property
  371. def numeric_code(self):
  372. return u"%.03d" % self.iso_3166_1_numeric
  373. class AbstractShippingAddress(AbstractAddress):
  374. """
  375. A shipping address.
  376. A shipping address should not be edited once the order has been placed -
  377. it should be read-only after that.
  378. """
  379. phone_number = models.CharField(
  380. _("Phone number"), max_length=32, blank=True, null=True,
  381. help_text=_("In case we need to call you about your order"))
  382. notes = models.TextField(
  383. blank=True, null=True,
  384. verbose_name=_('Instructions'),
  385. help_text=_("Tell us anything we should know when delivering "
  386. "your order."))
  387. class Meta:
  388. abstract = True
  389. verbose_name = _("Shipping address")
  390. verbose_name_plural = _("Shipping addresses")
  391. @property
  392. def order(self):
  393. """
  394. Return the order linked to this shipping address
  395. """
  396. orders = self.order_set.all()
  397. if not orders:
  398. return None
  399. return orders[0]
  400. class AbstractUserAddress(AbstractShippingAddress):
  401. """
  402. A user's address. A user can have many of these and together they form an
  403. 'address book' of sorts for the user.
  404. We use a separate model for shipping and billing (even though there will be
  405. some data duplication) because we don't want shipping/billing addresses
  406. changed or deleted once an order has been placed. By having a separate
  407. model, we allow users the ability to add/edit/delete from their address
  408. book without affecting orders already placed.
  409. """
  410. user = models.ForeignKey(
  411. AUTH_USER_MODEL, related_name='addresses', verbose_name=_("User"))
  412. #: Whether this address is the default for shipping
  413. is_default_for_shipping = models.BooleanField(
  414. _("Default shipping address?"), default=False)
  415. #: Whether this address should be the default for billing.
  416. is_default_for_billing = models.BooleanField(
  417. _("Default billing address?"), default=False)
  418. #: We keep track of the number of times an address has been used
  419. #: as a shipping address so we can show the most popular ones
  420. #: first at the checkout.
  421. num_orders = models.PositiveIntegerField(_("Number of Orders"), default=0)
  422. #: A hash is kept to try and avoid duplicate addresses being added
  423. #: to the address book.
  424. hash = models.CharField(_("Address Hash"), max_length=255, db_index=True,
  425. editable=False)
  426. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  427. def save(self, *args, **kwargs):
  428. """
  429. Save a hash of the address fields
  430. """
  431. # Save a hash of the address fields so we can check whether two
  432. # addresses are the same to avoid saving duplicates
  433. self.hash = self.generate_hash()
  434. # Ensure that each user only has one default shipping address
  435. # and billing address
  436. self._ensure_defaults_integrity()
  437. super(AbstractUserAddress, self).save(*args, **kwargs)
  438. def _ensure_defaults_integrity(self):
  439. if self.is_default_for_shipping:
  440. self.__class__._default_manager.filter(
  441. user=self.user,
  442. is_default_for_shipping=True).update(
  443. is_default_for_shipping=False)
  444. if self.is_default_for_billing:
  445. self.__class__._default_manager.filter(
  446. user=self.user,
  447. is_default_for_billing=True).update(
  448. is_default_for_billing=False)
  449. class Meta:
  450. abstract = True
  451. verbose_name = _("User address")
  452. verbose_name_plural = _("User addresses")
  453. ordering = ['-num_orders']
  454. unique_together = ('user', 'hash')
  455. def validate_unique(self, exclude=None):
  456. super(AbstractAddress, self).validate_unique(exclude)
  457. qs = self.__class__.objects.filter(
  458. user=self.user,
  459. hash=self.generate_hash())
  460. if self.id:
  461. qs = qs.exclude(id=self.id)
  462. if qs.count() > 0:
  463. raise exceptions.ValidationError({
  464. '__all__': [_("This address is already in your address book")]})
  465. class AbstractBillingAddress(AbstractAddress):
  466. class Meta:
  467. abstract = True
  468. verbose_name = _("Billing address")
  469. verbose_name_plural = _("Billing addresses")
  470. @property
  471. def order(self):
  472. """
  473. Return the order linked to this shipping address
  474. """
  475. orders = self.order_set.all()
  476. if not orders:
  477. return None
  478. return orders[0]
  479. class AbstractPartnerAddress(AbstractAddress):
  480. """
  481. A partner can have one or more addresses. This can be useful e.g. when
  482. determining US tax which depends on the origin of the shipment.
  483. """
  484. partner = models.ForeignKey('partner.Partner', related_name='addresses',
  485. verbose_name=_('Partner'))
  486. class Meta:
  487. abstract = True
  488. verbose_name = _("Partner address")
  489. verbose_name_plural = _("Partner addresses")