Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

abstract_models.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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.encoding import python_2_unicode_compatible
  12. from django.utils.translation import ugettext_lazy as _
  13. from oscar.apps.customer.managers import CommunicationTypeManager
  14. from oscar.core.compat import AUTH_USER_MODEL
  15. from oscar.models.fields import AutoSlugField
  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
  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. abstract = True
  66. verbose_name = _('User')
  67. verbose_name_plural = _('Users')
  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. @python_2_unicode_compatible
  90. class AbstractEmail(models.Model):
  91. """
  92. This is a record of all emails sent to a customer.
  93. Normally, we only record order-related emails.
  94. """
  95. user = models.ForeignKey(AUTH_USER_MODEL, related_name='emails',
  96. verbose_name=_("User"))
  97. subject = models.TextField(_('Subject'), max_length=255)
  98. body_text = models.TextField(_("Body Text"))
  99. body_html = models.TextField(_("Body HTML"), blank=True)
  100. date_sent = models.DateTimeField(_("Date Sent"), auto_now_add=True)
  101. class Meta:
  102. abstract = True
  103. app_label = 'customer'
  104. verbose_name = _('Email')
  105. verbose_name_plural = _('Emails')
  106. def __str__(self):
  107. return _(u"Email to %(user)s with subject '%(subject)s'") % {
  108. 'user': self.user.get_username(), 'subject': self.subject}
  109. @python_2_unicode_compatible
  110. class AbstractCommunicationEventType(models.Model):
  111. """
  112. A 'type' of communication. Like a order confirmation email.
  113. """
  114. #: Code used for looking up this event programmatically.
  115. # e.g. PASSWORD_RESET. AutoSlugField uppercases the code for us because
  116. # it's a useful convention that's been enforced in previous Oscar versions
  117. code = AutoSlugField(
  118. _('Code'), max_length=128, unique=True, populate_from='name',
  119. separator=six.u("_"), uppercase=True, editable=True,
  120. help_text=_("Code used for looking up this event programmatically"))
  121. #: Name is the friendly description of an event for use in the admin
  122. name = models.CharField(
  123. _('Name'), max_length=255,
  124. help_text=_("This is just used for organisational purposes"))
  125. # We allow communication types to be categorised
  126. ORDER_RELATED = _('Order related')
  127. USER_RELATED = _('User related')
  128. category = models.CharField(_('Category'), max_length=255,
  129. default=ORDER_RELATED)
  130. # Template content for emails
  131. # NOTE: There's an intentional distinction between None and ''. None
  132. # instructs Oscar to look for a file-based template, '' is just an empty
  133. # template.
  134. email_subject_template = models.CharField(
  135. _('Email Subject Template'), max_length=255, blank=True, null=True)
  136. email_body_template = models.TextField(
  137. _('Email Body Template'), blank=True, null=True)
  138. email_body_html_template = models.TextField(
  139. _('Email Body HTML Template'), blank=True, null=True,
  140. help_text=_("HTML template"))
  141. # Template content for SMS messages
  142. sms_template = models.CharField(_('SMS Template'), max_length=170,
  143. blank=True, null=True,
  144. help_text=_("SMS template"))
  145. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  146. date_updated = models.DateTimeField(_("Date Updated"), auto_now=True)
  147. objects = CommunicationTypeManager()
  148. # File templates
  149. email_subject_template_file = 'customer/emails/commtype_%s_subject.txt'
  150. email_body_template_file = 'customer/emails/commtype_%s_body.txt'
  151. email_body_html_template_file = 'customer/emails/commtype_%s_body.html'
  152. sms_template_file = 'customer/sms/commtype_%s_body.txt'
  153. class Meta:
  154. abstract = True
  155. app_label = 'customer'
  156. verbose_name = _("Communication event type")
  157. verbose_name_plural = _("Communication event types")
  158. def get_messages(self, ctx=None):
  159. """
  160. Return a dict of templates with the context merged in
  161. We look first at the field templates but fail over to
  162. a set of file templates that follow a conventional path.
  163. """
  164. code = self.code.lower()
  165. # Build a dict of message name to Template instances
  166. templates = {'subject': 'email_subject_template',
  167. 'body': 'email_body_template',
  168. 'html': 'email_body_html_template',
  169. 'sms': 'sms_template'}
  170. for name, attr_name in templates.items():
  171. field = getattr(self, attr_name, None)
  172. if field is not None:
  173. # Template content is in a model field
  174. templates[name] = Template(field)
  175. else:
  176. # Model field is empty - look for a file template
  177. template_name = getattr(self, "%s_file" % attr_name) % code
  178. try:
  179. templates[name] = get_template(template_name)
  180. except TemplateDoesNotExist:
  181. templates[name] = None
  182. # Pass base URL for serving images within HTML emails
  183. if ctx is None:
  184. ctx = {}
  185. ctx['static_base_url'] = getattr(
  186. settings, 'OSCAR_STATIC_BASE_URL', None)
  187. messages = {}
  188. for name, template in templates.items():
  189. messages[name] = template.render(Context(ctx)) if template else ''
  190. # Ensure the email subject doesn't contain any newlines
  191. messages['subject'] = messages['subject'].replace("\n", "")
  192. messages['subject'] = messages['subject'].replace("\r", "")
  193. return messages
  194. def __str__(self):
  195. return self.name
  196. def is_order_related(self):
  197. return self.category == self.ORDER_RELATED
  198. def is_user_related(self):
  199. return self.category == self.USER_RELATED
  200. @python_2_unicode_compatible
  201. class AbstractNotification(models.Model):
  202. recipient = models.ForeignKey(AUTH_USER_MODEL,
  203. related_name='notifications', db_index=True)
  204. # Not all notifications will have a sender.
  205. sender = models.ForeignKey(AUTH_USER_MODEL, null=True)
  206. # HTML is allowed in this field as it can contain links
  207. subject = models.CharField(max_length=255)
  208. body = models.TextField()
  209. # Some projects may want to categorise their notifications. You may want
  210. # to use this field to show a different icons next to the notification.
  211. category = models.CharField(max_length=255, blank=True)
  212. INBOX, ARCHIVE = 'Inbox', 'Archive'
  213. choices = (
  214. (INBOX, _('Inbox')),
  215. (ARCHIVE, _('Archive')))
  216. location = models.CharField(max_length=32, choices=choices,
  217. default=INBOX)
  218. date_sent = models.DateTimeField(auto_now_add=True)
  219. date_read = models.DateTimeField(blank=True, null=True)
  220. class Meta:
  221. abstract = True
  222. app_label = 'customer'
  223. ordering = ('-date_sent',)
  224. verbose_name = _('Notification')
  225. verbose_name_plural = _('Notifications')
  226. def __str__(self):
  227. return self.subject
  228. def archive(self):
  229. self.location = self.ARCHIVE
  230. self.save()
  231. archive.alters_data = True
  232. @property
  233. def is_read(self):
  234. return self.date_read is not None
  235. class AbstractProductAlert(models.Model):
  236. """
  237. An alert for when a product comes back in stock
  238. """
  239. product = models.ForeignKey('catalogue.Product')
  240. # A user is only required if the notification is created by a
  241. # registered user, anonymous users will only have an email address
  242. # attached to the notification
  243. user = models.ForeignKey(AUTH_USER_MODEL, db_index=True, blank=True,
  244. null=True, related_name="alerts",
  245. verbose_name=_('User'))
  246. email = models.EmailField(_("Email"), db_index=True, blank=True)
  247. # This key are used to confirm and cancel alerts for anon users
  248. key = models.CharField(_("Key"), max_length=128, blank=True, db_index=True)
  249. # An alert can have two different statuses for authenticated
  250. # users ``ACTIVE`` and ``INACTIVE`` and anonymous users have an
  251. # additional status ``UNCONFIRMED``. For anonymous users a confirmation
  252. # and unsubscription key are generated when an instance is saved for
  253. # the first time and can be used to confirm and unsubscribe the
  254. # notifications.
  255. UNCONFIRMED, ACTIVE, CANCELLED, CLOSED = (
  256. 'Unconfirmed', 'Active', 'Cancelled', 'Closed')
  257. STATUS_CHOICES = (
  258. (UNCONFIRMED, _('Not yet confirmed')),
  259. (ACTIVE, _('Active')),
  260. (CANCELLED, _('Cancelled')),
  261. (CLOSED, _('Closed')),
  262. )
  263. status = models.CharField(_("Status"), max_length=20,
  264. choices=STATUS_CHOICES, default=ACTIVE)
  265. date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
  266. date_confirmed = models.DateTimeField(_("Date confirmed"), blank=True,
  267. null=True)
  268. date_cancelled = models.DateTimeField(_("Date cancelled"), blank=True,
  269. null=True)
  270. date_closed = models.DateTimeField(_("Date closed"), blank=True, null=True)
  271. class Meta:
  272. abstract = True
  273. app_label = 'customer'
  274. verbose_name = _('Product alert')
  275. verbose_name_plural = _('Product alerts')
  276. @property
  277. def is_anonymous(self):
  278. return self.user is None
  279. @property
  280. def can_be_confirmed(self):
  281. return self.status == self.UNCONFIRMED
  282. @property
  283. def can_be_cancelled(self):
  284. return self.status == self.ACTIVE
  285. @property
  286. def is_cancelled(self):
  287. return self.status == self.CANCELLED
  288. @property
  289. def is_active(self):
  290. return self.status == self.ACTIVE
  291. def confirm(self):
  292. self.status = self.ACTIVE
  293. self.date_confirmed = timezone.now()
  294. self.save()
  295. confirm.alters_data = True
  296. def cancel(self):
  297. self.status = self.CANCELLED
  298. self.date_cancelled = timezone.now()
  299. self.save()
  300. cancel.alters_data = True
  301. def close(self):
  302. self.status = self.CLOSED
  303. self.date_closed = timezone.now()
  304. self.save()
  305. close.alters_data = True
  306. def get_email_address(self):
  307. if self.user:
  308. return self.user.email
  309. else:
  310. return self.email
  311. def save(self, *args, **kwargs):
  312. if not self.id and not self.user:
  313. self.key = self.get_random_key()
  314. self.status = self.UNCONFIRMED
  315. # Ensure date fields get updated when saving from modelform (which just
  316. # calls save, and doesn't call the methods cancel(), confirm() etc).
  317. if self.status == self.CANCELLED and self.date_cancelled is None:
  318. self.date_cancelled = timezone.now()
  319. if not self.user and self.status == self.ACTIVE \
  320. and self.date_confirmed is None:
  321. self.date_confirmed = timezone.now()
  322. if self.status == self.CLOSED and self.date_closed is None:
  323. self.date_closed = timezone.now()
  324. return super(AbstractProductAlert, self).save(*args, **kwargs)
  325. def get_random_key(self):
  326. """
  327. Get a random generated key based on SHA-1 and email address
  328. """
  329. salt = hashlib.sha1(str(random.random()).encode('utf8')).hexdigest()
  330. return hashlib.sha1((salt + self.email).encode('utf8')).hexdigest()
  331. def get_confirm_url(self):
  332. return reverse('customer:alerts-confirm', kwargs={'key': self.key})
  333. def get_cancel_url(self):
  334. return reverse('customer:alerts-cancel-by-key', kwargs={'key':
  335. self.key})