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

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