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

abstract_models.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. if hasattr(auth_models, 'BaseUserManager'):
  14. # Only define custom UserModel when Django >= 1.5
  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'), default=timezone.now)
  60. objects = UserManager()
  61. USERNAME_FIELD = 'email'
  62. class Meta:
  63. verbose_name = _('User')
  64. verbose_name_plural = _('Users')
  65. abstract = True
  66. def get_full_name(self):
  67. full_name = '%s %s' % (self.first_name, self.last_name)
  68. return full_name.strip()
  69. def get_short_name(self):
  70. return self.first_name
  71. class AbstractEmail(models.Model):
  72. """
  73. This is a record of all emails sent to a customer.
  74. Normally, we only record order-related emails.
  75. """
  76. user = models.ForeignKey(AUTH_USER_MODEL, related_name='emails', verbose_name=_("User"))
  77. subject = models.TextField(_('Subject'), max_length=255)
  78. body_text = models.TextField(_("Body Text"))
  79. body_html = models.TextField(_("Body HTML"), blank=True, null=True)
  80. date_sent = models.DateTimeField(_("Date Sent"), auto_now_add=True)
  81. class Meta:
  82. abstract = True
  83. verbose_name = _('Email')
  84. verbose_name_plural = _('Emails')
  85. def __unicode__(self):
  86. return _("Email to %(user)s with subject '%(subject)s'") % {
  87. 'user': self.user.username, 'subject': self.subject}
  88. class AbstractCommunicationEventType(models.Model):
  89. """
  90. A 'type' of communication. Like a order confirmation email.
  91. """
  92. # Code used for looking up this event programmatically.
  93. # eg. PASSWORD_RESET
  94. code = models.SlugField(_('Code'), max_length=128)
  95. #: Name is the friendly description of an event for use in the admin
  96. name = models.CharField(
  97. _('Name'), max_length=255,
  98. help_text=_("This is just used for organisational purposes"))
  99. # We allow communication types to be categorised
  100. ORDER_RELATED = _('Order related')
  101. USER_RELATED = _('User related')
  102. category = models.CharField(_('Category'), max_length=255,
  103. default=ORDER_RELATED)
  104. # Template content for emails
  105. email_subject_template = models.CharField(
  106. _('Email Subject Template'), max_length=255, blank=True, null=True)
  107. email_body_template = models.TextField(
  108. _('Email Body Template'), blank=True, null=True)
  109. email_body_html_template = models.TextField(
  110. _('Email Body HTML Template'), blank=True, null=True,
  111. help_text=_("HTML template"))
  112. # Template content for SMS messages
  113. sms_template = models.CharField(_('SMS Template'), max_length=170,
  114. blank=True, help_text=_("SMS template"))
  115. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  116. date_updated = models.DateTimeField(_("Date Updated"), auto_now=True)
  117. objects = CommunicationTypeManager()
  118. # File templates
  119. email_subject_template_file = 'customer/emails/commtype_%s_subject.txt'
  120. email_body_template_file = 'customer/emails/commtype_%s_body.txt'
  121. email_body_html_template_file = 'customer/emails/commtype_%s_body.html'
  122. sms_template_file = 'customer/sms/commtype_%s_body.txt'
  123. class Meta:
  124. abstract = True
  125. verbose_name = _("Communication event type")
  126. verbose_name_plural = _("Communication event types")
  127. def get_messages(self, ctx=None):
  128. """
  129. Return a dict of templates with the context merged in
  130. We look first at the field templates but fail over to
  131. a set of file templates that follow a conventional path.
  132. """
  133. code = self.code.lower()
  134. # Build a dict of message name to Template instances
  135. templates = {'subject': 'email_subject_template',
  136. 'body': 'email_body_template',
  137. 'html': 'email_body_html_template',
  138. 'sms': 'sms_template'}
  139. for name, attr_name in templates.items():
  140. field = getattr(self, attr_name, None)
  141. if field is not None:
  142. # Template content is in a model field
  143. templates[name] = Template(field)
  144. else:
  145. # Model field is empty - look for a file template
  146. template_name = getattr(self, "%s_file" % attr_name) % code
  147. try:
  148. templates[name] = get_template(template_name)
  149. except TemplateDoesNotExist:
  150. templates[name] = None
  151. # Pass base URL for serving images within HTML emails
  152. if ctx is None:
  153. ctx = {}
  154. ctx['static_base_url'] = getattr(settings,
  155. 'OSCAR_STATIC_BASE_URL', None)
  156. messages = {}
  157. for name, template in templates.items():
  158. messages[name] = template.render(Context(ctx)) if template else ''
  159. # Ensure the email subject doesn't contain any newlines
  160. messages['subject'] = messages['subject'].replace("\n", "").replace("\r", "")
  161. return messages
  162. def __unicode__(self):
  163. return self.name
  164. def is_order_related(self):
  165. return self.category == self.ORDER_RELATED
  166. def is_user_related(self):
  167. return self.category == self.USER_RELATED
  168. class AbstractNotification(models.Model):
  169. recipient = models.ForeignKey(AUTH_USER_MODEL, related_name='notifications',
  170. db_index=True)
  171. # Not all notifications will have a sender.
  172. sender = models.ForeignKey(AUTH_USER_MODEL, null=True)
  173. # HTML is allowed in this field as it can contain links
  174. subject = models.CharField(max_length=255)
  175. body = models.TextField()
  176. # Some projects may want to categorise their notifications. You may want
  177. # to use this field to show a different icons next to the notification.
  178. category = models.CharField(max_length=255, null=True)
  179. INBOX, ARCHIVE = 'Inbox', 'Archive'
  180. choices = (
  181. (INBOX, _(INBOX)),
  182. (ARCHIVE, _(ARCHIVE)))
  183. location = models.CharField(max_length=32, choices=choices,
  184. default=INBOX)
  185. date_sent = models.DateTimeField(auto_now_add=True)
  186. date_read = models.DateTimeField(blank=True, null=True)
  187. class Meta:
  188. ordering = ('-date_sent',)
  189. abstract = True
  190. def __unicode__(self):
  191. return self.subject
  192. def archive(self):
  193. self.location = self.ARCHIVE
  194. self.save()
  195. archive.alters_data = True
  196. @property
  197. def is_read(self):
  198. return self.date_read is not None
  199. class AbstractProductAlert(models.Model):
  200. """
  201. An alert for when a product comes back in stock
  202. """
  203. product = models.ForeignKey('catalogue.Product')
  204. # A user is only required if the notification is created by a
  205. # registered user, anonymous users will only have an email address
  206. # attached to the notification
  207. user = models.ForeignKey(AUTH_USER_MODEL, db_index=True, blank=True, null=True,
  208. related_name="alerts", verbose_name=_('User'))
  209. email = models.EmailField(_("Email"), db_index=True, blank=True, null=True)
  210. # This key are used to confirm and cancel alerts for anon users
  211. key = models.CharField(_("Key"), max_length=128, null=True, db_index=True)
  212. # An alert can have two different statuses for authenticated
  213. # users ``ACTIVE`` and ``INACTIVE`` and anonymous users have an
  214. # additional status ``UNCONFIRMED``. For anonymous users a confirmation
  215. # and unsubscription key are generated when an instance is saved for
  216. # the first time and can be used to confirm and unsubscribe the
  217. # notifications.
  218. UNCONFIRMED, ACTIVE, CANCELLED, CLOSED = (
  219. 'Unconfirmed', 'Active', 'Cancelled', 'Closed')
  220. STATUS_CHOICES = (
  221. (UNCONFIRMED, _('Not yet confirmed')),
  222. (ACTIVE, _('Active')),
  223. (CANCELLED, _('Cancelled')),
  224. (CLOSED, _('Closed')),
  225. )
  226. status = models.CharField(_("Status"), max_length=20,
  227. choices=STATUS_CHOICES, default=ACTIVE)
  228. date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
  229. date_confirmed = models.DateTimeField(_("Date confirmed"), blank=True,
  230. null=True)
  231. date_cancelled = models.DateTimeField(_("Date cancelled"), blank=True,
  232. null=True)
  233. date_closed = models.DateTimeField(_("Date closed"), blank=True, null=True)
  234. class Meta:
  235. abstract = True
  236. @property
  237. def is_anonymous(self):
  238. return self.user is None
  239. @property
  240. def can_be_confirmed(self):
  241. return self.status == self.UNCONFIRMED
  242. @property
  243. def can_be_cancelled(self):
  244. return self.status == self.ACTIVE
  245. @property
  246. def is_cancelled(self):
  247. return self.status == self.CANCELLED
  248. @property
  249. def is_active(self):
  250. return self.status == self.ACTIVE
  251. def confirm(self):
  252. self.status = self.ACTIVE
  253. self.date_confirmed = timezone.now()
  254. self.save()
  255. confirm.alters_data = True
  256. def cancel(self):
  257. self.status = self.CANCELLED
  258. self.date_cancelled = timezone.now()
  259. self.save()
  260. cancel.alters_data = True
  261. def close(self):
  262. self.status = self.CLOSED
  263. self.date_closed = timezone.now()
  264. self.save()
  265. close.alters_data = True
  266. def get_email_address(self):
  267. if self.user:
  268. return self.user.email
  269. else:
  270. return self.email
  271. def save(self, *args, **kwargs):
  272. if not self.id and not self.user:
  273. self.key = self.get_random_key()
  274. self.status = self.UNCONFIRMED
  275. # Ensure date fields get updated when saving from modelform (which just
  276. # calls save, and doesn't call the methods cancel(), confirm() etc).
  277. if self.status == self.CANCELLED and self.date_cancelled is None:
  278. self.date_cancelled = timezone.now()
  279. if not self.user and self.status == self.ACTIVE and self.date_confirmed is None:
  280. self.date_confirmed = timezone.now()
  281. if self.status == self.CLOSED and self.date_closed is None:
  282. self.date_closed = timezone.now()
  283. return super(AbstractProductAlert, self).save(*args, **kwargs)
  284. def get_random_key(self):
  285. """
  286. Get a random generated key based on SHA-1 and email address
  287. """
  288. salt = hashlib.sha1(str(random.random())).hexdigest()
  289. return hashlib.sha1(salt + self.email).hexdigest()
  290. def get_confirm_url(self):
  291. return reverse('customer:alerts-confirm', kwargs={'key': self.key})
  292. def get_cancel_url(self):
  293. return reverse('customer:alerts-cancel', kwargs={'key': self.key})