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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import hashlib
  2. import random
  3. from django.conf import settings
  4. from django.contrib.auth import models as auth_models
  5. from django.core.urlresolvers import reverse
  6. from django.db import models
  7. from django.template import Template, Context, TemplateDoesNotExist
  8. from django.template.loader import get_template
  9. from django.utils import timezone
  10. from django.utils.translation import ugettext_lazy as _
  11. from oscar.apps.customer.managers import CommunicationTypeManager
  12. from oscar.core.compat import AUTH_USER_MODEL
  13. from oscar.models.fields import AutoSlugField
  14. # Only define custom UserManager/UserModel when Django >= 1.5
  15. if hasattr(auth_models, 'BaseUserManager'):
  16. class UserManager(auth_models.BaseUserManager):
  17. def create_user(self, email, password=None, **extra_fields):
  18. """
  19. Creates and saves a User with the given username, email and
  20. password.
  21. """
  22. now = timezone.now()
  23. if not email:
  24. raise ValueError('The given email must be set')
  25. email = UserManager.normalize_email(email)
  26. user = self.model(
  27. email=email, is_staff=False, is_active=True,
  28. is_superuser=False,
  29. last_login=now, date_joined=now, **extra_fields)
  30. user.set_password(password)
  31. user.save(using=self._db)
  32. return user
  33. def create_superuser(self, email, password, **extra_fields):
  34. u = self.create_user(email, password, **extra_fields)
  35. u.is_staff = True
  36. u.is_active = True
  37. u.is_superuser = True
  38. u.save(using=self._db)
  39. return u
  40. class AbstractUser(auth_models.AbstractBaseUser,
  41. auth_models.PermissionsMixin):
  42. """
  43. An abstract base user suitable for use in Oscar projects.
  44. This is basically a copy of the core AbstractUser model but without a
  45. username field and with a unique index on the email field.
  46. """
  47. email = models.EmailField(_('email address'), unique=True)
  48. first_name = models.CharField(
  49. _('First name'), max_length=255, blank=True)
  50. last_name = models.CharField(
  51. _('Last name'), max_length=255, blank=True)
  52. is_staff = models.BooleanField(
  53. _('Staff status'), default=False,
  54. help_text=_('Designates whether the user can log into this admin '
  55. 'site.'))
  56. is_active = models.BooleanField(
  57. _('Active'), default=True,
  58. help_text=_('Designates whether this user should be treated as '
  59. 'active. Unselect this instead of deleting accounts.'))
  60. date_joined = models.DateTimeField(_('date joined'),
  61. default=timezone.now)
  62. objects = UserManager()
  63. USERNAME_FIELD = 'email'
  64. class Meta:
  65. verbose_name = _('User')
  66. verbose_name_plural = _('Users')
  67. abstract = True
  68. def get_full_name(self):
  69. full_name = '%s %s' % (self.first_name, self.last_name)
  70. return full_name.strip()
  71. def get_short_name(self):
  72. return self.first_name
  73. def _migrate_alerts_to_user(self):
  74. """
  75. Transfer any active alerts linked to a user's email address to the
  76. newly registered user.
  77. """
  78. ProductAlert = self.alerts.model
  79. alerts = ProductAlert.objects.filter(
  80. email=self.email, status=ProductAlert.ACTIVE)
  81. alerts.update(user=self, key=None, email=None)
  82. def save(self, *args, **kwargs):
  83. super(AbstractUser, self).save(*args, **kwargs)
  84. # Migrate any "anonymous" product alerts to the registered user
  85. # Ideally, this would be done via a post-save signal. But we can't
  86. # use get_user_model to wire up signals to custom user models
  87. # see Oscar ticket #1127, Django ticket #19218
  88. self._migrate_alerts_to_user()
  89. class AbstractEmail(models.Model):
  90. """
  91. This is a record of all emails sent to a customer.
  92. Normally, we only record order-related emails.
  93. """
  94. user = models.ForeignKey(AUTH_USER_MODEL, related_name='emails',
  95. verbose_name=_("User"))
  96. subject = models.TextField(_('Subject'), max_length=255)
  97. body_text = models.TextField(_("Body Text"))
  98. body_html = models.TextField(_("Body HTML"), blank=True, null=True)
  99. date_sent = models.DateTimeField(_("Date Sent"), auto_now_add=True)
  100. class Meta:
  101. abstract = True
  102. verbose_name = _('Email')
  103. verbose_name_plural = _('Emails')
  104. def __unicode__(self):
  105. return _("Email to %(user)s with subject '%(subject)s'") % {
  106. 'user': self.user.username, 'subject': self.subject}
  107. class AbstractCommunicationEventType(models.Model):
  108. """
  109. A 'type' of communication. Like a order confirmation email.
  110. """
  111. # Code used for looking up this event programmatically.
  112. # eg. PASSWORD_RESET
  113. code = AutoSlugField(_('Code'), max_length=128, unique=True,
  114. populate_from='name')
  115. #: Name is the friendly description of an event for use in the admin
  116. name = models.CharField(
  117. _('Name'), max_length=255,
  118. help_text=_("This is just used for organisational purposes"))
  119. # We allow communication types to be categorised
  120. ORDER_RELATED = _('Order related')
  121. USER_RELATED = _('User related')
  122. category = models.CharField(_('Category'), max_length=255,
  123. default=ORDER_RELATED)
  124. # Template content for emails
  125. email_subject_template = models.CharField(
  126. _('Email Subject Template'), max_length=255, blank=True, null=True)
  127. email_body_template = models.TextField(
  128. _('Email Body Template'), blank=True, null=True)
  129. email_body_html_template = models.TextField(
  130. _('Email Body HTML Template'), blank=True, null=True,
  131. help_text=_("HTML template"))
  132. # Template content for SMS messages
  133. sms_template = models.CharField(_('SMS Template'), max_length=170,
  134. blank=True, null=True,
  135. help_text=_("SMS template"))
  136. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  137. date_updated = models.DateTimeField(_("Date Updated"), auto_now=True)
  138. objects = CommunicationTypeManager()
  139. # File templates
  140. email_subject_template_file = 'customer/emails/commtype_%s_subject.txt'
  141. email_body_template_file = 'customer/emails/commtype_%s_body.txt'
  142. email_body_html_template_file = 'customer/emails/commtype_%s_body.html'
  143. sms_template_file = 'customer/sms/commtype_%s_body.txt'
  144. class Meta:
  145. abstract = True
  146. verbose_name = _("Communication event type")
  147. verbose_name_plural = _("Communication event types")
  148. def get_messages(self, ctx=None):
  149. """
  150. Return a dict of templates with the context merged in
  151. We look first at the field templates but fail over to
  152. a set of file templates that follow a conventional path.
  153. """
  154. code = self.code.lower()
  155. # Build a dict of message name to Template instances
  156. templates = {'subject': 'email_subject_template',
  157. 'body': 'email_body_template',
  158. 'html': 'email_body_html_template',
  159. 'sms': 'sms_template'}
  160. for name, attr_name in templates.items():
  161. field = getattr(self, attr_name, None)
  162. if field is not None:
  163. # Template content is in a model field
  164. templates[name] = Template(field)
  165. else:
  166. # Model field is empty - look for a file template
  167. template_name = getattr(self, "%s_file" % attr_name) % code
  168. try:
  169. templates[name] = get_template(template_name)
  170. except TemplateDoesNotExist:
  171. templates[name] = None
  172. # Pass base URL for serving images within HTML emails
  173. if ctx is None:
  174. ctx = {}
  175. ctx['static_base_url'] = getattr(
  176. settings, 'OSCAR_STATIC_BASE_URL', None)
  177. messages = {}
  178. for name, template in templates.items():
  179. messages[name] = template.render(Context(ctx)) if template else ''
  180. # Ensure the email subject doesn't contain any newlines
  181. messages['subject'] = messages['subject'].replace("\n", "")
  182. messages['subject'] = messages['subject'].replace("\r", "")
  183. return messages
  184. def __unicode__(self):
  185. return self.name
  186. def is_order_related(self):
  187. return self.category == self.ORDER_RELATED
  188. def is_user_related(self):
  189. return self.category == self.USER_RELATED
  190. class AbstractNotification(models.Model):
  191. recipient = models.ForeignKey(AUTH_USER_MODEL,
  192. related_name='notifications', db_index=True)
  193. # Not all notifications will have a sender.
  194. sender = models.ForeignKey(AUTH_USER_MODEL, null=True)
  195. # HTML is allowed in this field as it can contain links
  196. subject = models.CharField(max_length=255)
  197. body = models.TextField()
  198. # Some projects may want to categorise their notifications. You may want
  199. # to use this field to show a different icons next to the notification.
  200. category = models.CharField(max_length=255, null=True)
  201. INBOX, ARCHIVE = 'Inbox', 'Archive'
  202. choices = (
  203. (INBOX, _('Inbox')),
  204. (ARCHIVE, _('Archive')))
  205. location = models.CharField(max_length=32, choices=choices,
  206. default=INBOX)
  207. date_sent = models.DateTimeField(auto_now_add=True)
  208. date_read = models.DateTimeField(blank=True, null=True)
  209. class Meta:
  210. ordering = ('-date_sent',)
  211. abstract = True
  212. def __unicode__(self):
  213. return self.subject
  214. def archive(self):
  215. self.location = self.ARCHIVE
  216. self.save()
  217. archive.alters_data = True
  218. @property
  219. def is_read(self):
  220. return self.date_read is not None
  221. class AbstractProductAlert(models.Model):
  222. """
  223. An alert for when a product comes back in stock
  224. """
  225. product = models.ForeignKey('catalogue.Product')
  226. # A user is only required if the notification is created by a
  227. # registered user, anonymous users will only have an email address
  228. # attached to the notification
  229. user = models.ForeignKey(AUTH_USER_MODEL, db_index=True, blank=True,
  230. null=True, related_name="alerts",
  231. verbose_name=_('User'))
  232. email = models.EmailField(_("Email"), db_index=True, blank=True, null=True)
  233. # This key are used to confirm and cancel alerts for anon users
  234. key = models.CharField(_("Key"), max_length=128, null=True, db_index=True)
  235. # An alert can have two different statuses for authenticated
  236. # users ``ACTIVE`` and ``INACTIVE`` and anonymous users have an
  237. # additional status ``UNCONFIRMED``. For anonymous users a confirmation
  238. # and unsubscription key are generated when an instance is saved for
  239. # the first time and can be used to confirm and unsubscribe the
  240. # notifications.
  241. UNCONFIRMED, ACTIVE, CANCELLED, CLOSED = (
  242. 'Unconfirmed', 'Active', 'Cancelled', 'Closed')
  243. STATUS_CHOICES = (
  244. (UNCONFIRMED, _('Not yet confirmed')),
  245. (ACTIVE, _('Active')),
  246. (CANCELLED, _('Cancelled')),
  247. (CLOSED, _('Closed')),
  248. )
  249. status = models.CharField(_("Status"), max_length=20,
  250. choices=STATUS_CHOICES, default=ACTIVE)
  251. date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
  252. date_confirmed = models.DateTimeField(_("Date confirmed"), blank=True,
  253. null=True)
  254. date_cancelled = models.DateTimeField(_("Date cancelled"), blank=True,
  255. null=True)
  256. date_closed = models.DateTimeField(_("Date closed"), blank=True, null=True)
  257. class Meta:
  258. abstract = True
  259. @property
  260. def is_anonymous(self):
  261. return self.user is None
  262. @property
  263. def can_be_confirmed(self):
  264. return self.status == self.UNCONFIRMED
  265. @property
  266. def can_be_cancelled(self):
  267. return self.status == self.ACTIVE
  268. @property
  269. def is_cancelled(self):
  270. return self.status == self.CANCELLED
  271. @property
  272. def is_active(self):
  273. return self.status == self.ACTIVE
  274. def confirm(self):
  275. self.status = self.ACTIVE
  276. self.date_confirmed = timezone.now()
  277. self.save()
  278. confirm.alters_data = True
  279. def cancel(self):
  280. self.status = self.CANCELLED
  281. self.date_cancelled = timezone.now()
  282. self.save()
  283. cancel.alters_data = True
  284. def close(self):
  285. self.status = self.CLOSED
  286. self.date_closed = timezone.now()
  287. self.save()
  288. close.alters_data = True
  289. def get_email_address(self):
  290. if self.user:
  291. return self.user.email
  292. else:
  293. return self.email
  294. def save(self, *args, **kwargs):
  295. if not self.id and not self.user:
  296. self.key = self.get_random_key()
  297. self.status = self.UNCONFIRMED
  298. # Ensure date fields get updated when saving from modelform (which just
  299. # calls save, and doesn't call the methods cancel(), confirm() etc).
  300. if self.status == self.CANCELLED and self.date_cancelled is None:
  301. self.date_cancelled = timezone.now()
  302. if not self.user and self.status == self.ACTIVE \
  303. and self.date_confirmed is None:
  304. self.date_confirmed = timezone.now()
  305. if self.status == self.CLOSED and self.date_closed is None:
  306. self.date_closed = timezone.now()
  307. return super(AbstractProductAlert, self).save(*args, **kwargs)
  308. def get_random_key(self):
  309. """
  310. Get a random generated key based on SHA-1 and email address
  311. """
  312. salt = hashlib.sha1(str(random.random()).encode('utf8')).hexdigest()
  313. return hashlib.sha1((salt + self.email).encode('utf8')).hexdigest()
  314. def get_confirm_url(self):
  315. return reverse('customer:alerts-confirm', kwargs={'key': self.key})
  316. def get_cancel_url(self):
  317. return reverse('customer:alerts-cancel-by-key', kwargs={'key':
  318. self.key})