Пример #1
0
    def _decorator(self, *args, **kwargs):
        if self._in_fallback:
            pass_seconds = (datetime_now() - self._in_fallback_date).total_seconds()
            if pass_seconds > self._options.get("FAILOVER_TIME", 30):
                print("Go to default connection")
                self._client = self._old_client

                self._in_fallback = False
                self._in_fallback_date = None
                del self.fallback_client
            else:
                print("Mantain fallback connection")

        try:
            print("Executing {0}".format(method.__name__))
            return method(self, *args, **kwargs)
        except ConnectionInterrumped:
            if self._fallback and not self._in_fallback:
                print("raised ConnectionInterrumped")
                print("Switching to fallback conection")
                self._old_client = self._client
                self._client = self.fallback_client

                self._in_fallback = True
                self._in_fallback_date = datetime_now()

            return method(self, *args, **kwargs)
Пример #2
0
    def _decorator(self, *args, **kwargs):
        if self._in_fallback:
            pass_seconds = (datetime_now() -
                            self._in_fallback_date).total_seconds()
            if pass_seconds > self._options.get("FAILOVER_TIME", 30):
                print("Go to default connection")
                self._client = self._old_client

                self._in_fallback = False
                self._in_fallback_date = None
                del self.fallback_client
            else:
                print("Mantain fallback connection")

        try:
            print("Executing {0}".format(method.__name__))
            return method(self, *args, **kwargs)
        except ConnectionInterrumped:
            if self._fallback and not self._in_fallback:
                print("raised ConnectionInterrumped")
                print("Switching to fallback conection")
                self._old_client = self._client
                self._client = self.fallback_client

                self._in_fallback = True
                self._in_fallback_date = datetime_now()

            return method(self, *args, **kwargs)
Пример #3
0
 def check_immediate_reminders_emit(self):
     """Checks if the next reminder is in the timeframe and schedule its task if needed"""
     if self.next_reminder and self.next_reminder.at.date() == datetime_now().date():
         countdown = (self.next_reminder.at - datetime_now()).total_seconds()
         if countdown > 0:
             # Security check, avoiding potential infinite loop
             # Using countdown is also safer than eta because of timezones handling
             emit_reminders.apply_async(countdown=countdown, kwargs={'vosae_event_id': unicode(self.id)})
Пример #4
0
 def finish(self, status, successful=True, description=None):
     if successful:
         self.successful = datetime_now()
         self.failed = None
     else:
         self.failed = datetime_now()
         self.successful = None
     if description:
         self.status_description = smart_unicode(description)[:255]
     else:
         self.status_description =\
         smart_unicode(QiwiPaymentStatus.status_msg_by_code(status))[:255]
     self.qiwi_status = status
     self.save()
Пример #5
0
    def test_purge_old_entries(self):
        def send_mail(success):
            backend = ("django.core.mail.backends.locmem.EmailBackend"
                       if success else "tests.FailingMailerEmailBackend")
            with self.settings(MAILER_EMAIL_BACKEND=backend):
                mailer.send_mail("Subject", "Body", "*****@*****.**",
                                 ["*****@*****.**"])
                engine.send_all()
                if not success:
                    Message.objects.retry_deferred()
                    engine.send_all()

        # 1 success, 1 failure, and purge only success
        send_mail(True)
        send_mail(False)

        with patch.object(mailer.models, 'datetime_now') as datetime_now_patch:
            datetime_now_patch.return_value = datetime_now(
            ) + datetime.timedelta(days=2)
            call_command('purge_mail_log', '1')

        self.assertNotEqual(
            MessageLog.objects.filter(result=RESULT_FAILURE).count(), 0)
        self.assertEqual(
            MessageLog.objects.filter(result=RESULT_SUCCESS).count(), 0)

        # 1 success, 1 failure, and purge only failures
        send_mail(True)

        with patch.object(mailer.models, 'datetime_now') as datetime_now_patch:
            datetime_now_patch.return_value = datetime_now(
            ) + datetime.timedelta(days=2)
            call_command('purge_mail_log', '1', '-r', 'failure')

        self.assertEqual(
            MessageLog.objects.filter(result=RESULT_FAILURE).count(), 0)
        self.assertNotEqual(
            MessageLog.objects.filter(result=RESULT_SUCCESS).count(), 0)

        # 1 success, 1 failure, and purge everything
        send_mail(False)

        with patch.object(mailer.models, 'datetime_now') as datetime_now_patch:
            datetime_now_patch.return_value = datetime_now(
            ) + datetime.timedelta(days=2)
            call_command('purge_mail_log', '1', '-r', 'all')

        self.assertEqual(MessageLog.objects.count(), 0)
Пример #6
0
    def activation_key_expired(self):
        expiration_date = datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS)


        return self.activation_key == self.ACTIVATED or \
        (self.date_joined + expiration_date <= datetime_now())
Пример #7
0
 def reset(self):
     self.expire_date = datetime_now() + datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
     salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
     username = self.user.username
     if isinstance(username, unicode):
         username = username.encode('utf-8')
     self.activation_key = hashlib.sha1(salt+username).hexdigest()
Пример #8
0
class Attachment(models.Model):
    upload_to = lambda inst, fn: 'attach/%s/%s/%s' % (datetime_now().year, inst
                                                      .article.slug, fn)

    article = models.ForeignKey(Article, related_name='attachments')
    attachment = models.FileField(max_length=255, upload_to=upload_to)
    caption = models.CharField(max_length=255, blank=True)
    is_featured = models.BooleanField(_('Is Featured'),
                                      blank=True,
                                      default=False,
                                      null=False)

    class Meta:
        ordering = ('-article', 'id')

    def __unicode__(self):
        return u'%s: %s' % (self.article, self.caption)

    @property
    def filename(self):
        return self.attachment.name.split('/')[-1]

    @property
    def content_type_class(self):
        mt = mimetypes.guess_type(self.attachment.path)[0]
        if mt:
            content_type = mt.replace('/', '_')
        else:
            # assume everything else is text/plain
            content_type = 'text_plain'

        return content_type
    def activation_key_expired(self):
        """
        Determine whether this ``RegistrationProfile``'s activation
        key has expired, returning a boolean -- ``True`` if the key
        has expired.
        Key expiration is determined by a two-step process:
        1. If the user has already activated, the key will have been
        reset to the string constant ``ACTIVATED``. Re-activating
        is not permitted, and so this method returns ``True`` in
        this case.

        2. Otherwise, the date the user signed up is incremented by
        the number of days specified in the setting
        ``REGISTRATION_API_ACCOUNT_ACTIVATION_DAYS`` (which should be
        the number of days after signup during which a user is allowed
        to activate their account); if the result is less than or
        equal to the current date, the key has expired and this method
        returns ``True``.

        """

        # utils imported here to avoid circular import
        from . import utils

        expiration_date = datetime.timedelta(days=utils.get_settings(
            'REGISTRATION_API_ACCOUNT_ACTIVATION_DAYS'))
        return self.activation_key == self.ACTIVATED or (getattr(
            self.user,
            utils.get_settings('REGISTRATION_API_USER_REGISTER_DATE_FIELD')) +
                                                         expiration_date <=
                                                         datetime_now())
Пример #10
0
 def purge_old_entries(self, days):
     limit = datetime_now() - datetime.timedelta(days=days)
     # query = self.filter(when_attempted__lt=limit, result=RESULT_SUCCESS)
     query = self.filter(when_attempted__lt=limit)
     count = query.count()
     query.delete()
     return count
Пример #11
0
 def reset_activation(self):
     """
     Used to reset activation key when user is disabled.
     """
     self.activation_key = self.generate_key()
     self.sent = datetime_now()
     self.save()
Пример #12
0
    def daily_occurrences(self, location, dt=None, event=None):
        '''
        Returns a queryset of for instances that have any overlap with a
        particular day.

        * ``dt`` may be either a datetime.datetime, datetime.date object, or
          ``None``. If ``None``, default to the current day.

        * ``event`` can be an ``Event`` instance for further filtering.
        '''
        dt = dt or datetime_now()
        start = datetime(dt.year, dt.month, dt.day, tzinfo=dt.tzinfo)
        end = start.replace(hour=23, minute=59, second=59)
        qs = self.filter(
            models.Q(
                start_time__gte=start,
                start_time__lte=end,
            ) | models.Q(
                end_time__gte=start,
                end_time__lte=end,
            ) | models.Q(start_time__lt=start, end_time__gt=end),
            event__location=location,
        )

        return qs.filter(event=event) if event else qs
Пример #13
0
    def create_inactive_user(self, site, new_user=None, send_email=True,
                             request=None, profile_info={}, **user_info):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.

        By default, an activation email will be sent to the new
        user. To disable this, pass ``send_email=False``.
        Additionally, if email is sent and ``request`` is supplied,
        it will be passed to the email template.

        """
        if new_user is None:
            password = user_info.pop('password')
            new_user = UserModel()(**user_info)
            new_user.set_password(password)
        new_user.is_active = False

        # Since we calculate the RegistrationProfile expiration from this date,
        # we want to ensure that it is current
        new_user.date_joined = datetime_now()

        with transaction.atomic():
            new_user.save()
            registration_profile = self.create_profile(new_user, **profile_info)

        if send_email:
            registration_profile.send_activation_email(site, request)

        return new_user
Пример #14
0
 def activation_key_expired(self):
     """ Checks to see if your activation key has expired. """
     expiration_date = datetime.timedelta(
         days=settings.ACTIVATION_EXPIRATION_DAYS
     )
     return self.is_activated() or \
         (self.activation_key_date + expiration_date <= datetime_now())
Пример #15
0
    def activation_key_expired(self):
        """
        Determine whether this ``RegistrationProfile``'s activation
        key has expired, returning a boolean -- ``True`` if the key
        has expired.
        
        Key expiration is determined by a two-step process:
        
        1. If the user has already activated, the key will have been
           reset to the string constant ``ACTIVATED``. Re-activating
           is not permitted, and so this method returns ``True`` in
           this case.

        2. Otherwise, the date the user signed up is incremented by
           the number of days specified in the setting
           ``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
           days after signup during which a user is allowed to
           activate their account); if the result is less than or
           equal to the current date, the key has expired and this
           method returns ``True``.
        
        """
        expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
        return self.activation_key == self.ACTIVATED or \
               (self.user.date_joined + expiration_date <= datetime_now())
Пример #16
0
    def activation_key_expired(self):
        """
        Determine whether this ``RegistrationProfile``'s activation
        key has expired, returning a boolean -- ``True`` if the key
        has expired.

        Key expiration is determined by a two-step process:

        1. If the user has already activated, ``self.activated`` and
        `self.user.is_active`` will be ``True``.  Re-activating is not
        permitted, and so this method returns ``True`` in this case.

        2. Otherwise, the date the user signed up is incremented by the number
        of days specified in the setting ``ACCOUNT_ACTIVATION_DAYS`` (which
        should be the number of days after signup during which a user is
        allowed to activate their account); if the result is less than or equal
        to the current date, the key has expired and this method returns
        ``True``.
        """
        expiration_date = datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS)
        # A user is only considered activated when the entire registration
        # process is completed (i.e. an admin has approved the account)
        is_activated = self.activated and self.user.is_active
        return (is_activated
                or self.user.date_joined + expiration_date <= datetime_now())
Пример #17
0
    def test_purge_old_entries(self):
        # Send one successfully
        with self.settings(MAILER_EMAIL_BACKEND=
                           "django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_mail("Subject", "Body", "*****@*****.**",
                             ["*****@*****.**"])
            engine.send_all()

        # And one failure
        with self.settings(
                MAILER_EMAIL_BACKEND="mailer.tests.FailingMailerEmailBackend"):
            mailer.send_mail("Subject", "Body", "*****@*****.**",
                             ["*****@*****.**"])

            engine.send_all()
            Message.objects.retry_deferred()
            engine.send_all()

        with patch.object(mailer.models, 'datetime_now') as datetime_now_patch:
            datetime_now_patch.return_value = datetime_now(
            ) + datetime.timedelta(days=2)
            call_command('purge_mail_log', '1')

        self.assertNotEqual(
            MessageLog.objects.filter(result=RESULT_FAILURE).count(), 0)
        self.assertEqual(
            MessageLog.objects.filter(result=RESULT_SUCCESS).count(), 0)
Пример #18
0
    def activation_key_expired(self):
        """
        Determine whether this ``RegistrationProfile``'s activation
        key has expired, returning a boolean -- ``True`` if the key
        has expired.

        Key expiration is determined by a two-step process:

        1. If the user has already activated, the key will have been
           reset to the string constant ``ACTIVATED``. Re-activating
           is not permitted, and so this method returns ``True`` in
           this case.

        2. Otherwise, the date the user signed up is incremented by
           the number of days specified in the setting
           ``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
           days after signup during which a user is allowed to
           activate their account); if the result is less than or
           equal to the current date, the key has expired and this
           method returns ``True``.

        """
        expiration_date = datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS)
        return (self.activation_key == self.ACTIVATED
                or (self.user.date_joined + expiration_date <= datetime_now()))
    def activation_key_expired(self):
        """
        Determine whether this ``RegistrationProfile``'s activation
        key has expired, returning a boolean -- ``True`` if the key
        has expired.
        Key expiration is determined by a two-step process:
        1. If the user has already activated, the key will have been
        reset to the string constant ``ACTIVATED``. Re-activating
        is not permitted, and so this method returns ``True`` in
        this case.

        2. Otherwise, the date the user signed up is incremented by
        the number of days specified in the setting
        ``REGISTRATION_API_ACCOUNT_ACTIVATION_DAYS`` (which should be
        the number of days after signup during which a user is allowed
        to activate their account); if the result is less than or
        equal to the current date, the key has expired and this method
        returns ``True``.

        """

        # utils imported here to avoid circular import
        from registration_api import utils

        expiration_date = datetime.timedelta(
            days=utils.get_settings('REGISTRATION_API_ACCOUNT_ACTIVATION_DAYS'))
        date_joined=datetime.datetime(*(self.user.date_joined.timetuple()[:6])).replace(tzinfo=datetime_now().tzinfo)
        return self.activation_key == self.ACTIVATED or \
               (date_joined + expiration_date <= datetime_now())
Пример #20
0
 def cancel(self, issuer):
     """
     Cancel the :class:`~invoicing.models.Invoice` with the creation of an
     associated :class:`~invoicing.models.CreditNote`
     """
     from invoicing.models.credit_note import CreditNote
     if not self.is_cancelable():
         raise NotCancelableInvoice("Invoice is not cancelable.")
     credit_note = CreditNote(full_init=False,
                              tenant=self.tenant,
                              account_type=self.account_type,
                              issuer=issuer,
                              organization=self.organization,
                              contact=self.contact,
                              related_to=self,
                              group=self.group)
     cn_data = credit_note.add_revision(revision=self.current_revision)
     cn_data.issuer = issuer
     cn_data.issue_date = datetime_now()
     cn_data.credit_note_emission_date = datetime.date.today()
     for item in cn_data.line_items:
         if not isinstance(item.reference, basestring):
             item.reference = unicode(item.reference)
         item.unit_price = -item.unit_price
     credit_note.save()
     self.set_state(Invoice.STATES.CANCELLED)
     return credit_note
Пример #21
0
 def make_invoice(self, issuer):
     """Creates an invoice based on the current quotation"""
     from invoicing.models.invoice import Invoice
     # Initialize the invoice
     invoice = Invoice(
         full_init=False,
         tenant=self.tenant,
         account_type=self.account_type,
         issuer=issuer,
         organization=self.organization,
         contact=self.contact,
         related_quotation=self,
         attachments=self.attachments
     )
     # Save the invoice, based on the quotation
     inv_data = invoice.add_revision(revision=self.current_revision)
     inv_data.state = invoice.state
     inv_data.issuer = issuer
     inv_data.issue_date = datetime_now()
     inv_data.invoicing_date = datetime.date.today()
     inv_data.due_date = get_due_date(inv_data.invoicing_date, self.tenant.tenant_settings.invoicing.payment_conditions)
     invoice.save()
     # Update quotation with related invoice
     self.state = Quotation.STATES.INVOICED
     self.related_invoice = invoice
     self.save()
     invoicing_signals.post_make_invoice.send(self.__class__, document=self, new_document=invoice)
     return invoice
Пример #22
0
    def make_invoice(self, issuer):
        """Creates an invoice based on the current quotation/purchase order"""
        from invoicing.models.invoice import Invoice
        # Initialize the invoice
        invoice = Invoice(full_init=False,
                          tenant=self.tenant,
                          account_type=self.account_type,
                          issuer=issuer,
                          organization=self.organization,
                          contact=self.contact,
                          related_to=self,
                          group=self.group,
                          attachments=self.attachments)

        # Save the invoice, based on the quotation/purchase order
        inv_data = invoice.add_revision(revision=self.current_revision)
        inv_data.state = invoice.state
        inv_data.issuer = issuer
        inv_data.issue_date = datetime_now()
        inv_data.invoicing_date = datetime.date.today()
        inv_data.due_date = get_due_date(
            inv_data.invoicing_date,
            self.tenant.tenant_settings.invoicing.payment_conditions)
        invoice.save()

        # Update state
        if self.is_quotation():
            self.state = QUOTATION_STATES.INVOICED
        elif self.is_purchase_order():
            self.state = PURCHASE_ORDER_STATES.INVOICED
        self.save()
        return invoice
Пример #23
0
    def test_retry_deferred(self):
        with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.FailingMailerEmailBackend"):
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            engine.send_all()
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 1)
            self.assertEqual(MessageLog.objects.count(), 1)
            with patch.object(mailer.models, 'datetime_now') as datetime_now_patch:
                datetime_now_patch.side_effect = lambda: datetime_now() + datetime.timedelta(days=2)
                self.assertEquals(MessageLog.objects.purge_old_entries(1), 0)
                call_command('purge_mail_log', '1')
            self.assertEqual(MessageLog.objects.count(), 1)

        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):

            engine.send_all()
            self.assertEqual(len(mail.outbox), 0)
            # Should not have sent the deferred ones
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 1)

            # Now mark them for retrying
            Message.objects.retry_deferred()
            engine.send_all()
            self.assertEqual(len(mail.outbox), 1)
            self.assertEqual(Message.objects.count(), 0)
Пример #24
0
    def load(self):
        try:
            s = MongoSession.objects(session_key=self.session_key,
                                     expire_date__gt=datetime_now)[0]

            """ Update expiration date by 5 minutes by default """
            if s:
                minute=None
                cluster = Cluster.objects.get()
                if cluster.system_settings:
                    if cluster.system_settings.global_settings:
                        minute=cluster.system_settings.global_settings.gui_timeout
                if minute is None:
                    minute=5

                now_plus_x = datetime_now() + datetime.timedelta(minutes=minute)
                s.expire_date=now_plus_x
                s.save()

            if MONGOENGINE_SESSION_DATA_ENCODE:
                return self.decode(force_unicode(s.session_data))
            else:
                return s.session_data
        except (IndexError, SuspiciousOperation):
            self.create()
            return {}
Пример #25
0
    def send(self):
        ap = ActivationProfile.objects.get_or_create(user=self.invitee,
                                                     email=self.invitee_email)[0]
        if ap.activation_key_expired():
            ap.reset_activation()
            ap = ActivationProfile.objects.get(pk=ap.pk)

        context = {'invitation': self,
                   'activation_key': ap.activation_key}

        if self.added_saved_search:
            initial_email = self.added_saved_search.initial_email(send=False)
            context['initial_search_email'] = initial_email

        body = render_to_string('registration/invitation_email.html',
                                context)
        body = Pynliner().from_string(body).run()

        if self.inviting_user:
            from_ = self.inviting_user.email
        else:
            from_ = self.inviting_company.name

        headers = {
            'X-SMTPAPI': '{"category": "Invitation Sent (%s)"}' % self.pk
        }

        self.invitee.email_user(body, email_type=settings.INVITATION,
                                inviter=from_, headers=headers)

        ap.sent = datetime_now()
        ap.save()
Пример #26
0
 def reset_activation(self):
     """
     Used to reset activation key when user is disabled.
     """
     self.activation_key = self.generate_key()
     self.sent = datetime_now()
     self.save()
    def activation_key_expired(self):
        """get whether the activation key of this profile has expired

        Determine whether this ``RegistrationProfiel``'s activation key has
        expired, returning a boolean -- ``True`` if the key has expired.

        Key expiration is determined by a two-step process:

        1.  If the inspection status is not ``'accepted'``, the key is set to
            ``None``. In this case, this method returns ``False`` because these
            profiles are not treated yet or rejected by inspector.

        2.  Otherwise, the date the user signed up (which automatically updated
            in registration acceptance) is incremented by the number of days 
            specified in the setting ``ACCOUNT_ACTIVATION_DAYS`` (which should
            be the number of days after acceptance during which a user is allowed
            to activate their account); if the result is less than or equal to
            the current date, the key has expired and this method return ``True``.

        """
        if self._status != 'accepted':
            return False
        expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
        expired = self.user.date_joined + expiration_date <= datetime_now()
        return expired
    def activation_key_expired(self):
        """get whether the activation key of this profile has expired

        Determine whether this ``RegistrationProfiel``'s activation key has
        expired, returning a boolean -- ``True`` if the key has expired.

        Key expiration is determined by a two-step process:

        1.  If the inspection status is not ``'accepted'``, the key is set to
            ``None``. In this case, this method returns ``False`` because these
            profiles are not treated yet or rejected by inspector.

        2.  Otherwise, the date the user signed up (which automatically updated
            in registration acceptance) is incremented by the number of days 
            specified in the setting ``ACCOUNT_ACTIVATION_DAYS`` (which should
            be the number of days after acceptance during which a user is allowed
            to activate their account); if the result is less than or equal to
            the current date, the key has expired and this method return ``True``.

        """
        if self._status != 'accepted':
            return False
        expiration_date = datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS)
        expired = self.user.date_joined + expiration_date <= datetime_now()
        return expired
Пример #29
0
    def test_blacklisted_emails(self):
        with self.settings(MAILER_EMAIL_BACKEND=
                           "django.core.mail.backends.locmem.EmailBackend"):
            now = datetime_now()
            obj = DontSendEntry.objects.create(to_address="*****@*****.**",
                                               when_added=now)
            self.assertTrue(obj.to_address, "*****@*****.**")

            mailer.send_mail("Subject", "GoBody", "*****@*****.**",
                             ["*****@*****.**"])
            mailer.send_mail("Subject", "NoGoBody", "*****@*****.**",
                             ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 2)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            # All messages are processed
            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)

            # but only one should get sent
            self.assertEqual(len(mail.outbox), 1)
            sent = mail.outbox[0]

            # Default "plain text"
            self.assertEqual(sent.body, "GoBody")
            self.assertEqual(sent.to, ["*****@*****.**"])
Пример #30
0
    def activation_key_expired(self):
        """
        Determine whether this ``RegistrationProfile``'s activation
        key has expired, returning a boolean -- ``True`` if the key
        has expired.

        Key expiration is determined by a two-step process:

        1. If the user has already activated, ``self.activated`` and
        `self.user.is_active`` will be ``True``.  Re-activating is not
        permitted, and so this method returns ``True`` in this case.

        2. Otherwise, the date the user signed up is incremented by the number
        of days specified in the setting ``ACCOUNT_ACTIVATION_DAYS`` (which
        should be the number of days after signup during which a user is
        allowed to activate their account); if the result is less than or equal
        to the current date, the key has expired and this method returns
        ``True``.
        """
        expiration_date = datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS)
        # A user is only considered activated when the entire registration
        # process is completed (i.e. an admin has approved the account)
        is_activated = self.activated and self.user.is_active
        return (is_activated or self.user.date_joined + expiration_date <= datetime_now())
Пример #31
0
 def cancel(self, issuer):
     """
     Cancel the :class:`~invoicing.models.Invoice` with the creation of an
     associated :class:`~invoicing.models.CreditNote`
     """
     from invoicing.models.credit_note import CreditNote
     if not self.is_cancelable():
         raise NotCancelableInvoice("Invoice is not cancelable.")
     credit_note = CreditNote(
         full_init=False,
         tenant=self.tenant,
         account_type=self.account_type,
         issuer=issuer,
         organization=self.organization,
         contact=self.contact,
         related_invoice=self
     )
     cn_data = credit_note.add_revision(revision=self.current_revision)
     cn_data.issuer = issuer
     cn_data.issue_date = datetime_now()
     cn_data.credit_note_emission_date = datetime.date.today()
     for item in cn_data.line_items:
         if not isinstance(item.reference, basestring):
             item.reference = unicode(item.reference)
         item.unit_price = -item.unit_price
     credit_note.save()
     self.update(set__related_credit_note=credit_note)
     self.set_state(Invoice.STATES.CANCELLED, True)
     invoicing_signals.post_cancel_invoice.send(self.__class__, document=self, credit_note=credit_note)
     return credit_note
Пример #32
0
 def cancel(self, issuer):
     """
     Cancel the :class:`~invoicing.models.Invoice` with the creation of an
     associated :class:`~invoicing.models.CreditNote`
     """
     from invoicing.models import CreditNote, CreditNoteRevision
     if not self.is_cancelable():
         raise NotCancelableInvoice("Invoice is not cancelable.")
     credit_note = CreditNote(full_init=False,
                              tenant=self.tenant,
                              account_type=self.account_type,
                              issuer=issuer,
                              organization=self.organization,
                              contact=self.contact,
                              related_to=self,
                              group=self.group)
     cn_data = credit_note.add_revision(revision=CreditNoteRevision(
         based_on=self.current_revision))
     cn_data.issuer = issuer
     cn_data.issue_date = datetime_now()
     cn_data.credit_note_emission_date = datetime.date.today()
     if self.is_down_payment_invoice():
         # XXX should be removed in favor of translatable line items
         cn_data.line_items = []
     credit_note.save()
     self.set_state(Invoice.STATES.CANCELLED)
     return credit_note
Пример #33
0
 def make_invoice(self, issuer):
     """Creates an invoice based on the current quotation/purchase order"""
     from invoicing.models.invoice import Invoice
     # Initialize the invoice
     invoice = Invoice(
         full_init=False,
         tenant=self.tenant,
         account_type=self.account_type,
         issuer=issuer,
         organization=self.organization,
         contact=self.contact,
         related_to=self,
         group=self.group,
         attachments=self.attachments
     )
     
     # Save the invoice, based on the quotation/purchase order
     inv_data = invoice.add_revision(revision=self.current_revision)
     inv_data.state = invoice.state
     inv_data.issuer = issuer
     inv_data.issue_date = datetime_now()
     inv_data.invoicing_date = datetime.date.today()
     inv_data.due_date = get_due_date(inv_data.invoicing_date, self.tenant.tenant_settings.invoicing.payment_conditions)
     invoice.save()
     
     # Update state
     if self.is_quotation():
         self.state = QUOTATION_STATES.INVOICED
     elif self.is_purchase_order():
         self.state = PURCHASE_ORDER_STATES.INVOICED
     self.save()
     return invoice
Пример #34
0
    def create_inactive_user(self,
                             site,
                             new_user=None,
                             send_email=True,
                             request=None,
                             profile_info={},
                             **user_info):
        """
        Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``.

        By default, an activation email will be sent to the new user.
        To disable this, pass ``send_email=False``.
        Additionally, if email is sent and ``request`` is supplied, it will be passed to the email template.
        """
        if new_user is None:
            password = user_info.pop('password')
            new_user = UserModel()(**user_info)
            new_user.set_password(password)
        new_user.is_active = False

        # Since we calculate the RegistrationProfile expiration from this date, we want to ensure that it is current
        new_user.date_joined = datetime_now()

        with transaction.atomic():
            new_user.save()
            registration_profile = self.create_profile(new_user,
                                                       **profile_info)

        if send_email:
            registration_profile.send_activation_email(site, request)

        return new_user
Пример #35
0
def profile(
    request,
    template_name,
    user_pk,
    tab='summary',
    sort='votes',
    page='1',
    pagesize=10,
    sort_dic={
        'newest': '-create_time',
        'active': '-edit_time',
        'votes': '-votes',
        'views': '-viewed',
    },
):
    page = int(page)
    header_type = 'users'
    anchor = 'tab-top'  #用于控制页码视图的锚
    pagination_kwargs = {
        'sort': sort,
        'tab': tab,
        'user_pk': user_pk,
    }
    profile_user = get_object_or_404(User, pk=user_pk)
    request_user = request.user
    display_username = '******' if profile_user == request_user else '该用户'
    member_age = datetime_now() - profile_user.date_joined
    if request_user != profile_user:
        profile_user.viewed += 1
        profile_user.save(update_fields=['viewed'])
    profile_answers = profile_user.questions_answer_creater.all()
    profile_questions = profile_user.question_set.all()
    viewname = 'users:profile_tab_sort_page'
    if tab == 'questions':
        if sort == 'votes':
            items = sorted(profile_questions,
                           key=lambda a: a.score,
                           reverse=True)
        else:
            items = profile_questions.order_by(sort_dic[sort])
        page_list, item_list = paginator(page=page,
                                         items=items,
                                         pagesize=pagesize,
                                         width=2)
    elif tab == 'answers':
        if sort == 'votes':
            items = sorted(profile_answers,
                           key=lambda a: a.score,
                           reverse=True)
        else:
            items = profile_answers.order_by(sort_dic[sort])
        page_list, item_list = paginator(page=page,
                                         items=items,
                                         pagesize=pagesize,
                                         width=2)
    return TemplateResponse(
        request,
        template_name,
        locals(),
    )
Пример #36
0
    def test_blacklisted_emails(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            now = datetime_now()
            obj = DontSendEntry.objects.create(to_address="*****@*****.**", when_added=now)
            self.assertTrue(obj.to_address, "*****@*****.**")

            mailer.send_mail("Subject", "GoBody", "*****@*****.**", ["*****@*****.**"])
            mailer.send_mail("Subject", "NoGoBody", "*****@*****.**", ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 2)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            # All messages are processed
            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)

            # but only one should get sent
            self.assertEqual(len(mail.outbox), 1)
            sent = mail.outbox[0]

            # Default "plain text"
            self.assertEqual(sent.body, "GoBody")
            self.assertEqual(sent.to, ["*****@*****.**"])
Пример #37
0
def add_event(request,
              calendar_slug,
              template='swingtime/add_event.html',
              event_form_class=forms.EventForm,
              recurrence_form_class=forms.MultipleOccurrenceForm):
    '''
    Add a new ``Event`` instance and 1 or more associated ``Occurrence``s.

    Context parameters:

    dtstart
        a datetime.datetime object representing the GET request value if present,
        otherwise None

    event_form
        a form object for updating the event

    recurrence_form
        a form object for adding occurrences

    '''
    location = get_location_or_404(calendar_slug)
    if not check_permission(request.user, 'swingtime.book_can_add', location):
        return forbidden_response(request,
                                  'You cannot add events for this location')

    location_list = get_location_list(request.user, 'swingtime.book_can_add')
    dtstart = None
    if request.method == 'POST':
        event_form = event_form_class(request.POST)
        event_form.fields['location'].queryset = location_list
        recurrence_form = recurrence_form_class(request.POST)
        if event_form.is_valid() and recurrence_form.is_valid():
            event = event_form.save()
            recurrence_form.save(event)
            return http.HttpResponseRedirect(event.get_absolute_url())

    else:
        if 'dtstart' in request.GET:
            try:
                dtstart = parser.parse(request.GET['dtstart'])
                print('GET dtstart', dtstart)
            except:
                # TODO A badly formatted date is passed to add_event
                print('Badly formatted!')
                dtstart = datetime_now()

        event_form = event_form_class(initial=dict(location=location.id))
        event_form.fields['location'].queryset = location_list
        recurrence_form = recurrence_form_class(initial=dict(dtstart=dtstart))

    return render(
        request,
        template,
        dict(dtstart=dtstart,
             event_form=event_form,
             recurrence_form=recurrence_form,
             location=location),
    )
Пример #38
0
    def current_state(self):

        # the no comunication from the server for quite a while
        delta = datetime_now() - self.last_heartbeat
        if delta.total_seconds() > 30:  # TODO: turn into setting
            return "disconnected"

        return "disconnected"
Пример #39
0
    def current_state(self):

        # the no comunication from the server for quite a while
        delta = datetime_now() - self.last_heartbeat
        if delta.total_seconds() > 30:  # TODO: turn into setting
            return 'disconnected'

        return "disconnected"
Пример #40
0
    def send(self, context_object=""):
        """
        Inputs:
            :context_object: An object used to determine the invitation
                             context. A string signifies a custom message
                             context. Other types can specify a context by
                             registering with
                             `universal.helpers.invitation_context`.

        Outputs:
            An invitation email is sent to the ```Invitation.invitee``` using
            the ```Invitation.email``` address. Tailored messages are sent if
            ```Invitation.added_saved_search``` or
            ```Invitation.added_permission are set. If neither are set and no
            ```context``` is set, a generic email is sent.

        """
        activation_profile, _ = ActivationProfile.objects.get_or_create(
            user=self.invitee, email=self.invitee.email)

        if activation_profile.activation_key_expired():
            activation_profile.reset_activation()
            activation_profile  = ActivationProfile.objects.get(
                pk=activation_profile.pk)

        context = {'invitation': self,
                   'activation_key': activation_profile.activation_key}
        context.update(invitation_context(context_object))

        body = Pynliner().from_string(render_to_string(
            'registration/invitation_email.html', context)).run()

        if self.inviting_user:
            from_ = self.inviting_user.email
        else:
            from_ = self.inviting_company.name

        headers = {
            'X-SMTPAPI': '{"category": "Invitation Sent (%s)"}' % self.pk
        }

        fail_message = None
        try:
            self.invitee.email_user(body, email_type=settings.INVITATION,
                                    inviter=from_, headers=headers,
                                    text_only=context.get('text_only', False))
        except Exception as e:
            fail_message = getattr(e, 'smtp_error', e.message)
        else:
            activation_profile.sent = datetime_now()
            activation_profile.save()
        finally:
            saved_search = context.get('saved_search')
            if saved_search and hasattr(saved_search, 'partnersavedsearch'):
                saved_search.partnersavedsearch.create_record(
                    "Automatic sending of initial partner saved search",
                    body=context['initial_search_email'],
                    failure_message=fail_message)
Пример #41
0
 def load_rss(self, body=None, filename=None):
     if body is not None:
         self.body = body
     elif filename is not None:
         with open(filename, "rb") as f:
             self.body = f.read()
     else:
         raise TypeError("Specify either `body` or `filename`.")
     self.fetched = datetime_now()
Пример #42
0
 def load_rss(self, body=None, filename=None):
     if body is not None:
         self.body = body
     elif filename is not None:
         with open(filename, 'rb') as f:
             self.body = f.read()
     else:
         raise TypeError('Specify either `body` or `filename`.')
     self.fetched = datetime_now()
Пример #43
0
 def save(self, *args, **kwargs):
     if self.phone and self.card:
         # 10 знаков номера без (8 или +7)
         src = "{}{}".format(self.phone[-10:], self.card)
         h = hashlib.sha256(src.encode())
         self.hash = h.hexdigest()
     if not self.created:
         self.created = datetime_now()
     return super().save(*args, **kwargs)
Пример #44
0
 def purge_old_entries(self, days, result_codes=None):
     if result_codes is None:
         # retro-compatibility with previous versions
         result_codes = [RESULT_SUCCESS]
     limit = datetime_now() - datetime.timedelta(days=days)
     query = self.filter(when_attempted__lt=limit, result__in=result_codes)
     count = query.count()
     query.delete()
     return count
Пример #45
0
 def delete_expired_users(self):
     User = get_user_model()
     for profile in self.filter(expire_date__lte=datetime_now()):
         try:
             user = profile.user
             if not user.is_active:
                 user.delete()
         except User.DoesNotExist:
             pass
         profile.delete()
Пример #46
0
 def active(self):
     """
     Retrieves all active articles which have been published and have not
     yet expired.
     """
     now = datetime_now()
     return self.get_query_set().filter(Q(expiration_date__isnull=True)
                                        | Q(expiration_date__gte=now),
                                        publish_date__lte=now,
                                        is_active=True)
    def is_valid(self, bundle, request=None):
        if not bundle.data:
            return {'__all__': 'Data should be present'}

        errors = {}
        for key, value in bundle.data.items():
            if 'purchase_date' in key and datetime_now() < from_current_timezone(get_date_from_string(value)):
                errors['purchase_date'] = ['Purchase date cannot be more than current date']

        return errors
Пример #48
0
    def set_activation_key(self):

        salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
        username = self.user.username
        if isinstance(username, unicode):
            username = username.encode('utf-8')

        self.user.date_joined = datetime_now()
        self.activation_key = hashlib.sha1(salt+username).hexdigest()
        self.save()
 def key_expired(self, user):
     activated = RegistrationProfile.objects.get(user=user)
     date_joined = user.date_joined
     expiration_date = datetime.timedelta(days=self.days)
     if date_joined + expiration_date <= datetime_now():
         activated.activation_key = self.ACTIVATED
         activated.save()
         return True
     else:
         return False
Пример #50
0
def today_view(request,
               calendar_slug,
               template='swingtime/daily_view.html',
               **params):
    '''
    See documentation for function``_datetime_view``.

    '''
    return _datetime_view(request, calendar_slug, template, datetime_now(),
                          **params)
Пример #51
0
def filter_list_by_day(vevent_seq, dt=None):
    """
    if dt is None, default to today.
    """
    dt = dt or datetime_now()
    if is_naive(dt):
        dt = make_aware(dt)
    start = datetime.datetime(dt.year, dt.month, dt.day, tzinfo=dt.tzinfo)
    end = start.replace(hour=23, minute=59, second=59)
    return (vevent for vevent in vevent_seq if has_overlap(vevent, start, end))
Пример #52
0
    def post(self, request):
        result = {'ok': False}

        card = request.POST.get('card')
        payments = request.POST.get('payments')
        use_sale = str(request.POST.get('use_sale') or 'true').lower() == 'true'

        try:
            payments = json.loads(payments)
        except Exception as err:
            card = None
            logger = logging.getLogger('system')
            logger.error('json format error: {} {}'.format(err, payments))

        now = datetime_now().date()
        variants = BonusPolicy.objects.filter(
            end__gte=now,
            begin__lte=now).order_by(
                # чем больше процент и чем меньше лимит
                '-percent', 'limit')

        try:
            policy = variants[:1].get()
        except BonusPolicy.DoesNotExist:
            policy = None

        if card and policy:
            try:
                client_pk = Client.objects.values_list(
                    'id', flat=True).get(card=card)
            except Client.DoesNotExist:
                result.update(msg=msg.NOT_FOUND)
            else:
                try:
                    result.update(
                        ok=True,
                        payment=create_payment(
                            client=client_pk,
                            use_sale=use_sale,
                            payments=payments,
                            limit=policy.limit,
                            percent=policy.percent))

                except Exception as err:
                    result.update(
                        msg='Ошибка выполнения: {}'.format(err))
        else:
            result.update(msg=msg.PARAMS_ERR)

        if not result['ok']:
            logger = logging.getLogger('system')
            logger.warning('Error: {} from {}'.format(
                result['msg'], get_client_ip(request)))

        return JsonResponse(result)
Пример #53
0
    def make_down_payment(self, issuer, percentage, tax, date):
        """Creates a down payment invoice based on the current quotation"""
        from invoicing.models.down_payment_invoice import DownPaymentInvoice
        if percentage <= 0 or percentage >= 1:
            raise InvalidDownPaymentPercentage("Percentage must be a decimal between 0 and 1.")
        inv_data = self.current_revision
        # Calculate the total amount from the base (excluding taxes) to avoid decimal differences.
        # Check with amount=97.72 and tax_rate=0.196.
        excl_tax_amount = ((self.amount * percentage).quantize(Decimal('1.00'), ROUND_HALF_UP) / (Decimal('1.00') + tax.rate)).quantize(Decimal('1.00'), ROUND_HALF_UP)
        down_payment_amount = (excl_tax_amount * (Decimal('1.00') + tax.rate)).quantize(Decimal('1.00'), ROUND_HALF_UP)
        current_percentage = Decimal('0.00')
        for down_payment in self.down_payments:
            current_percentage += down_payment.percentage
        if current_percentage + percentage > 1:
            raise InvalidDownPaymentPercentage("Total of down-payments percentages exceeds 1 (100%).")
        if date < datetime.date.today() or (date > inv_data.due_date if inv_data.due_date else False):
            raise InvalidDownPaymentDueDate("Invalid down-payment due date.")
        down_payment = DownPaymentInvoice(
            full_init=False,
            tenant=self.tenant,
            account_type=self.account_type,
            issuer=issuer,
            state="REGISTERED",
            organization=self.organization,
            contact=self.contact,
            related_quotation=self,
            percentage=percentage,
            tax_applied=tax,
            total=down_payment_amount,
            amount=down_payment_amount,
            balance=down_payment_amount
        )

        down_payment.add_revision(
            state=down_payment.state,
            issuer=issuer,
            issue_date=datetime_now(),
            sender=inv_data.sender,
            organization=inv_data.organization,
            contact=inv_data.contact,
            sender_address=inv_data.sender_address,
            billing_address=inv_data.billing_address,
            delivery_address=inv_data.delivery_address,
            customer_reference=inv_data.customer_reference,
            currency=inv_data.currency,
            invoicing_date=inv_data.invoicing_date or date.today(),
            due_date=date
        )
        # Save the down payment invoice
        down_payment.save()
        # Update quotation with related down-payment invoice
        self.down_payments.append(down_payment)
        self.save()
        invoicing_signals.post_make_down_payment_invoice.send(self.__class__, document=self, new_document=down_payment)
        return down_payment
Пример #54
0
def create_event(
        title,
        location,
        #    event_type,
        description='',
        start_time=None,
        end_time=None,
        note=None,
        **rrule_params):
    '''
    Convenience function to create an ``Event``, optionally create an
    ``EventType``, and associated ``Occurrence``s. ``Occurrence`` creation
    rules match those for ``Event.add_occurrences``.

    Returns the newly created ``Event`` instance.

    Parameters

    ``event_type``
        can be either an ``EventType`` object or 2-tuple of ``(abbreviation,label)``,
        from which an ``EventType`` is either created or retrieved.

    ``start_time``
        will default to the current hour if ``None``

    ``end_time``
        will default to ``start_time`` plus swingtime_settings.DEFAULT_OCCURRENCE_DURATION
        hour if ``None``

    ``freq``, ``count``, ``rrule_params``
        follow the ``dateutils`` API (see http://labix.org/python-dateutil)

    '''
    from swingtime.conf import settings as swingtime_settings

    #     if isinstance(event_type, tuple):
    #         event_type, created = EventType.objects.get_or_create(
    #             abbr=event_type[0],
    #             label=event_type[1]
    #         )

    event = Event.objects.create(title=title,
                                 description=description,
                                 location=location)

    if note is not None:
        event.notes.create(note=note)

    start_time = start_time or datetime_now().replace(
        minute=0, second=0, microsecond=0)

    end_time = end_time or start_time + swingtime_settings.DEFAULT_OCCURRENCE_DURATION
    event.add_occurrences(start_time, end_time, **rrule_params)
    return event
Пример #55
0
 def duplicate(self, issuer=None):
     """
     Return the duplicate of the current revision with generated revision
     unique parameters.
     """
     duplicate = copy.deepcopy(self)
     duplicate.revision = unicode(uuid.uuid4())
     duplicate.issue_date = datetime_now()
     if issuer:
         duplicate.issuer = issuer
     return duplicate
Пример #56
0
    def save(self, *args, **kwargs):

        with transaction.atomic():
            # This code executes inside a transaction.
            ch = stripe.Charge.retrieve(self.instance.stripe_token)
            ch.capture()

            self.instance.amount_due -= ch.amount
            self.instance.purchase_time = datetime_now()

            super(OrderForm,self).save(*args, **kwargs)
Пример #57
0
 def duplicate(self, issuer=None):
     """
     Return the duplicate of the current revision with generated revision
     unique parameters.
     """
     duplicate = copy.deepcopy(self)
     duplicate.revision = unicode(uuid.uuid4())
     duplicate.issue_date = datetime_now()
     if issuer:
         duplicate.issuer = issuer
     return duplicate
Пример #58
0
def check_fake(payment_id, qiwi_status):
    """
    Проверка есть ли поддельный ответ для qiwi
    """
    fake = get_object_or_None(FakeAnswer, id=payment_id,
                              completed__isnull=True)
    if fake:
        fake.completed = datetime_now()
        if isinstance(qiwi_status, int):
            fake.qiwi_status = qiwi_status
        fake.save()
        return fake.fake_status
Пример #59
0
    def test_unexpired_account_old_date_joined(self):
        """
        ``RegistrationProfile.activation_key_expired()`` is ``False`` within
        the activation window. Even if the user was created in the past.

        """
        self.user_info['date_joined'] = datetime_now(
        ) - timedelta(settings.ACCOUNT_ACTIVATION_DAYS + 1)
        new_user = self.registration_profile.objects.create_inactive_user(
            site=Site.objects.get_current(), **self.user_info)
        profile = self.registration_profile.objects.get(user=new_user)
        self.failIf(profile.activation_key_expired())