Ejemplo n.º 1
0
 def test_normal_flow(self):
     u"""
     Tests that ``translation(lang)`` changes the selected language within the ``with``
     statement and restores it afterwards.
     """
     original = get_language()
     with translation(u'de'):
         self.assertEqual(get_language(), u'de')
         with translation(u'sk'):
             self.assertEqual(get_language(), u'sk')
         self.assertEqual(get_language(), u'de')
     self.assertEqual(get_language(), original)
Ejemplo n.º 2
0
 def test_normal_flow(self):
     u"""
     Tests that ``translation(lang)`` changes the selected language within the ``with``
     statement and restores it afterwards.
     """
     original = get_language()
     with translation(u'de'):
         self.assertEqual(get_language(), u'de')
         with translation(u'sk'):
             self.assertEqual(get_language(), u'sk')
         self.assertEqual(get_language(), u'de')
     self.assertEqual(get_language(), original)
Ejemplo n.º 3
0
 def test_datetime_input_formats(self):
     with translation(u'en'):
         self.assertFieldOutput(forms.DateTimeField,
                 valid={
                     u'10/25/2006 14:30:59':        local_datetime_from_local(u'2006-10-25 14:30:59'),
                     u'10/25/2006 14:30:59.000200': local_datetime_from_local(u'2006-10-25 14:30:59.000200'),
                     u'10/25/2006 14:30':           local_datetime_from_local(u'2006-10-25 14:30:00'),
                     u'10/25/2006':                 local_datetime_from_local(u'2006-10-25 00:00:00'),
                     u'10/25/06 14:30:59':          local_datetime_from_local(u'2006-10-25 14:30:59'),
                     u'10/25/06 14:30:59.000200':   local_datetime_from_local(u'2006-10-25 14:30:59.000200'),
                     u'10/25/06 14:30':             local_datetime_from_local(u'2006-10-25 14:30:00'),
                     u'10/25/06':                   local_datetime_from_local(u'2006-10-25 00:00:00'),
                     u'2006-10-25 14:30:59':        local_datetime_from_local(u'2006-10-25 14:30:59'),
                     u'2006-10-25 14:30:59.000200': local_datetime_from_local(u'2006-10-25 14:30:59.000200'),
                     u'2006-10-25 14:30':           local_datetime_from_local(u'2006-10-25 14:30:00'),
                     u'2006-10-25':                 local_datetime_from_local(u'2006-10-25 00:00:00'),
                     },
                 invalid={
                     u'25/10/2006 14:30': [u'Enter a valid date/time.'],
                     u'25/10/06 14:30':   [u'Enter a valid date/time.'],
                     u'25.10.2006 14:30': [u'Enter a valid date/time.'],
                     u'25.10.06 14:30':   [u'Enter a valid date/time.'],
                     u'10.25.2006 14:30': [u'Enter a valid date/time.'],
                     u'10.25.06 14:30':   [u'Enter a valid date/time.'],
                     u'2006-25-10 14:30': [u'Enter a valid date/time.'],
                     u'10/25/2006 14':    [u'Enter a valid date/time.'],
                     },
                 field_kwargs=dict(localize=True),
                 empty_value=None,
                 )
Ejemplo n.º 4
0
    def test_date_output_format(self):
        with translation(u'en'):
            class Form(forms.Form):
                field = forms.DateField(localize=True)

            form = Form(initial=dict(field=naive_date(u'2006-10-25')))
            self.assertHTMLEqual(str(form[u'field']), u'<input id="id_field" name="field" type="text" value="10/25/2006">')
Ejemplo n.º 5
0
 def test_exception(self):
     u"""
     Tests that ``translation(lang)`` restores the language even if an exception is raised
     within the ``with`` statement.
     """
     original = get_language()
     try:
         with translation(u'de'):
             self.assertEqual(get_language(), u'de')
             try:
                 with translation(u'sk'):
                     self.assertEqual(get_language(), u'sk')
                     raise ValueError
             finally:
                 self.assertEqual(get_language(), u'de') # pragma: no branch
     except ValueError:
         pass
     self.assertEqual(get_language(), original)
Ejemplo n.º 6
0
 def test_exception(self):
     u"""
     Tests that ``translation(lang)`` restores the language even if an exception is raised
     within the ``with`` statement.
     """
     original = get_language()
     try:
         with translation(u'de'):
             self.assertEqual(get_language(), u'de')
             try:
                 with translation(u'sk'):
                     self.assertEqual(get_language(), u'sk')
                     raise ValueError
             finally:
                 self.assertEqual(get_language(),
                                  u'de')  # pragma: no branch
     except ValueError:
         pass
     self.assertEqual(get_language(), original)
Ejemplo n.º 7
0
    def test_datetime_output_format(self):
        with translation(u'en'):
            class Form(forms.Form):
                field = forms.DateTimeField(localize=True)

            form = Form(initial=dict(field=local_datetime_from_local(u'2006-10-25 14:30:59.000200')))
            self.assertHTMLEqual(str(form[u'field']), u'<input id="id_field" name="field" type="text" value="10/25/2006 14:30:59">')

            form = Form(initial=dict(field=local_datetime_from_local(u'2006-10-25')))
            self.assertHTMLEqual(str(form[u'field']), u'<input id="id_field" name="field" type="text" value="10/25/2006 00:00:00">')
Ejemplo n.º 8
0
def obligee_deadline_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects.not_closed().
                        without_undecided_email().prefetch_related(
                            Inforequest.prefetch_branches()).prefetch_related(
                                Branch.prefetch_last_action(u'branches')))

        filtered = []
        for inforequest in inforequests:
            for branch in inforequest.branches:
                try:
                    if not branch.last_action.has_obligee_deadline:
                        continue
                    if not branch.last_action.deadline_missed:
                        continue
                    # The last reminder was sent after the deadline was extended for the last time iff
                    # the extended deadline was missed before the reminder was sent. We don't want to
                    # send any more reminders if the last reminder was sent after the deadline was
                    # extended for the last time.
                    last = branch.last_action.last_deadline_reminder
                    last_date = local_date(last) if last else None
                    if last and branch.last_action.deadline_missed_at(
                            last_date):
                        continue
                    nop()  # To let tests raise testing exception here.
                    filtered.append(branch)
                except Exception:
                    cron_logger.error(
                        u'Checking if obligee deadline reminder should be sent failed: %s\n%s'
                        % (repr(branch.last_action), traceback.format_exc()))

        if not filtered:
            return

        filtered = (Branch.objects.select_related(u'inforequest__applicant').
                    select_related(u'historicalobligee').prefetch_related(
                        Branch.prefetch_last_action()).filter(
                            pk__in=(o.pk for o in filtered)))
        for branch in filtered:
            try:
                with transaction.atomic():
                    branch.inforequest.send_obligee_deadline_reminder(
                        branch.last_action)
                    nop()  # To let tests raise testing exception here.
                    cron_logger.info(
                        u'Sent obligee deadline reminder: %s' %
                        repr(branch.last_action))  # pragma: no branch
            except Exception:
                cron_logger.error(
                    u'Sending obligee deadline reminder failed: %s\n%s' %
                    (repr(branch.last_action), traceback.format_exc()))
Ejemplo n.º 9
0
def applicant_deadline_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects.not_closed().
                        without_undecided_email().prefetch_related(
                            Inforequest.prefetch_branches()).prefetch_related(
                                Branch.prefetch_last_action(u'branches')))

        filtered = []
        for inforequest in inforequests:
            for branch in inforequest.branches:
                try:
                    if not branch.last_action.has_applicant_deadline:
                        continue
                    # Although Advancement has an applicant deadline, we don't send reminders for it.
                    if branch.last_action.type == Action.TYPES.ADVANCEMENT:
                        continue
                    # The reminder is sent 2 WDs before the deadline is missed.
                    if branch.last_action.deadline_remaining > 2:
                        continue
                    # Applicant deadlines may not be extended, so we send at most one applicant
                    # deadline reminder for the action.
                    if branch.last_action.last_deadline_reminder:
                        continue
                    nop()  # To let tests raise testing exception here.
                    filtered.append(branch)
                except Exception:
                    cron_logger.error(
                        u'Checking if applicant deadline reminder should be sent failed: %s\n%s'
                        % (repr(branch.last_action), traceback.format_exc()))

        if not filtered:
            return

        filtered = (Branch.objects.select_related(
            u'inforequest__applicant').prefetch_related(
                Branch.prefetch_last_action()).filter(
                    pk__in=(o.pk for o in filtered)))
        for branch in filtered:
            try:
                with transaction.atomic():
                    branch.inforequest.send_applicant_deadline_reminder(
                        branch.last_action)
                    nop()  # To let tests raise testing exception here.
                    cron_logger.info(
                        u'Sent applicant deadline reminder: %s' %
                        repr(branch.last_action))  # pragma: no branch
            except Exception:
                cron_logger.error(
                    u'Sending applicant deadline reminder failed: %s\n%s' %
                    (repr(branch.last_action), traceback.format_exc()))
Ejemplo n.º 10
0
def obligee_deadline_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects
                .not_closed()
                .without_undecided_email()
                .prefetch_related(Inforequest.prefetch_branches())
                .prefetch_related(Branch.prefetch_last_action(u'branches'))
                )

        filtered = []
        for inforequest in inforequests:
            for branch in inforequest.branches:
                action = branch.last_action
                try:
                    if not action.has_obligee_deadline_snooze_missed:
                        continue
                    # The last reminder was sent after the applicant snoozed for the last time iff
                    # the snooze was missed before the reminder was sent. We don't want to send any
                    # more reminders if the last reminder was sent after the last snooze.
                    last = action.last_deadline_reminder
                    last_date = local_date(last) if last else None
                    if last and action.deadline.is_snooze_missed_at(last_date):
                        continue
                    filtered.append(branch)
                except Exception:
                    msg = u'Checking if obligee deadline reminder should be sent failed: {}\n{}'
                    trace = unicode(traceback.format_exc(), u'utf-8')
                    cron_logger.error(msg.format(action, trace))

        if not filtered:
            return

        filtered = (Branch.objects
                .select_related(u'inforequest__applicant')
                .select_related(u'historicalobligee')
                .prefetch_related(Branch.prefetch_last_action())
                .filter(pk__in=(o.pk for o in filtered))
                )
        for branch in filtered:
            try:
                with transaction.atomic():
                    branch.inforequest.send_obligee_deadline_reminder(branch.last_action)
                    msg = u'Sent obligee deadline reminder: {}'
                    cron_logger.info(msg.format(branch.last_action))
            except Exception:
                msg = u'Sending obligee deadline reminder failed: {}\n{}'
                trace = unicode(traceback.format_exc(), u'utf-8')
                cron_logger.error(msg.format(branch.last_action, trace))
Ejemplo n.º 11
0
def obligee_deadline_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects
                .not_closed()
                .without_undecided_email()
                .prefetch_related(Inforequest.prefetch_branches())
                .prefetch_related(Branch.prefetch_last_action(u'branches'))
                )

        filtered = []
        for inforequest in inforequests:
            for branch in inforequest.branches:
                try:
                    if not branch.last_action.has_obligee_deadline:
                        continue
                    if not branch.last_action.deadline_missed:
                        continue
                    # The last reminder was sent after the deadline was extended for the last time iff
                    # the extended deadline was missed before the reminder was sent. We don't want to
                    # send any more reminders if the last reminder was sent after the deadline was
                    # extended for the last time.
                    last = branch.last_action.last_deadline_reminder
                    last_date = local_date(last) if last else None
                    if last and branch.last_action.deadline_missed_at(last_date):
                        continue
                    nop() # To let tests raise testing exception here.
                    filtered.append(branch)
                except Exception:
                    cron_logger.error(u'Checking if obligee deadline reminder should be sent failed: %s\n%s' % (repr(branch.last_action), traceback.format_exc()))

        if not filtered:
            return

        filtered = (Branch.objects
                .select_related(u'inforequest__applicant')
                .select_related(u'historicalobligee')
                .prefetch_related(Branch.prefetch_last_action())
                .filter(pk__in=(o.pk for o in filtered))
                )
        for branch in filtered:
            try:
                with transaction.atomic():
                    branch.inforequest.send_obligee_deadline_reminder(branch.last_action)
                    nop() # To let tests raise testing exception here.
                    cron_logger.info(u'Sent obligee deadline reminder: %s' % repr(branch.last_action)) # pragma: no branch
            except Exception:
                cron_logger.error(u'Sending obligee deadline reminder failed: %s\n%s' % (repr(branch.last_action), traceback.format_exc()))
Ejemplo n.º 12
0
def applicant_deadline_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects
                .not_closed()
                .without_undecided_email()
                .prefetch_related(Inforequest.prefetch_branches())
                .prefetch_related(Branch.prefetch_last_action(u'branches'))
                )

        filtered = []
        for inforequest in inforequests:
            for branch in inforequest.branches:
                action = branch.last_action
                try:
                    if not action.has_applicant_deadline:
                        continue
                    # The reminder is sent 2 CD before the deadline is missed.
                    if action.deadline.calendar_days_remaining > 2:
                        continue
                    # Applicant may not snooze his deadlines, so we send at most one applicant
                    # deadline reminder for the action.
                    if action.last_deadline_reminder:
                        continue
                    filtered.append(branch)
                except Exception:
                    msg = u'Checking if applicant deadline reminder should be sent failed: {}\n{}'
                    trace = unicode(traceback.format_exc(), u'utf-8')
                    cron_logger.error(msg.format(action, trace))

        if not filtered:
            return

        filtered = (Branch.objects
                .select_related(u'inforequest__applicant')
                .prefetch_related(Branch.prefetch_last_action())
                .filter(pk__in=(o.pk for o in filtered))
                )
        for branch in filtered:
            try:
                with transaction.atomic():
                    branch.inforequest.send_applicant_deadline_reminder(branch.last_action)
                    msg = u'Sent applicant deadline reminder: {}'
                    cron_logger.info(msg.format(branch.last_action))
            except Exception:
                msg = u'Sending applicant deadline reminder failed: {}\n{}'
                trace = unicode(traceback.format_exc(), u'utf-8')
                cron_logger.error(msg.format(branch.last_action, trace))
Ejemplo n.º 13
0
def applicant_deadline_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects.not_closed().
                        without_undecided_email().prefetch_related(
                            Inforequest.prefetch_branches()).prefetch_related(
                                Branch.prefetch_last_action(u'branches')))

        filtered = []
        for inforequest in inforequests:
            for branch in inforequest.branches:
                action = branch.last_action
                try:
                    if not action.has_applicant_deadline:
                        continue
                    # The reminder is sent 2 CD before the deadline is missed.
                    if action.deadline.calendar_days_remaining > 2:
                        continue
                    # Applicant may not snooze his deadlines, so we send at most one applicant
                    # deadline reminder for the action.
                    if action.last_deadline_reminder:
                        continue
                    filtered.append(branch)
                except Exception:
                    msg = u'Checking if applicant deadline reminder should be sent failed: {}\n{}'
                    trace = unicode(traceback.format_exc(), u'utf-8')
                    cron_logger.error(msg.format(action, trace))

        if not filtered:
            return

        filtered = (Branch.objects.select_related(
            u'inforequest__applicant').prefetch_related(
                Branch.prefetch_last_action()).filter(
                    pk__in=(o.pk for o in filtered)))
        for branch in filtered:
            try:
                with transaction.atomic():
                    branch.inforequest.send_applicant_deadline_reminder(
                        branch.last_action)
                    msg = u'Sent applicant deadline reminder: {}'
                    cron_logger.info(msg.format(branch.last_action))
            except Exception:
                msg = u'Sending applicant deadline reminder failed: {}\n{}'
                trace = unicode(traceback.format_exc(), u'utf-8')
                cron_logger.error(msg.format(branch.last_action, trace))
Ejemplo n.º 14
0
def obligee_deadline_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects.not_closed().
                        without_undecided_email().prefetch_related(
                            Inforequest.prefetch_branches()).prefetch_related(
                                Branch.prefetch_last_action(u'branches')))

        filtered = []
        for inforequest in inforequests:
            for branch in inforequest.branches:
                action = branch.last_action
                try:
                    if not action.has_obligee_deadline_snooze_missed:
                        continue
                    # The last reminder was sent after the applicant snoozed for the last time iff
                    # the snooze was missed before the reminder was sent. We don't want to send any
                    # more reminders if the last reminder was sent after the last snooze.
                    last = action.last_deadline_reminder
                    last_date = local_date(last) if last else None
                    if last and action.deadline.is_snooze_missed_at(last_date):
                        continue
                    filtered.append(branch)
                except Exception:
                    msg = u'Checking if obligee deadline reminder should be sent failed: {}\n{}'
                    trace = unicode(traceback.format_exc(), u'utf-8')
                    cron_logger.error(msg.format(action, trace))

        if not filtered:
            return

        filtered = (Branch.objects.select_related(u'inforequest__applicant').
                    select_related(u'historicalobligee').prefetch_related(
                        Branch.prefetch_last_action()).filter(
                            pk__in=(o.pk for o in filtered)))
        for branch in filtered:
            try:
                with transaction.atomic():
                    branch.inforequest.send_obligee_deadline_reminder(
                        branch.last_action)
                    msg = u'Sent obligee deadline reminder: {}'
                    cron_logger.info(msg.format(branch.last_action))
            except Exception:
                msg = u'Sending obligee deadline reminder failed: {}\n{}'
                trace = unicode(traceback.format_exc(), u'utf-8')
                cron_logger.error(msg.format(branch.last_action, trace))
Ejemplo n.º 15
0
def undecided_email_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects.not_closed().with_undecided_email(
        ).prefetch_related(Inforequest.prefetch_newest_undecided_email()))

        filtered = []
        for inforequest in inforequests:
            try:
                email = inforequest.newest_undecided_email
                last = inforequest.last_undecided_email_reminder
                if last and last > email.processed:
                    continue
                days = workdays.between(local_date(email.processed),
                                        local_today())
                if days < 5:
                    continue
                nop()  # To let tests raise testing exception here.
                filtered.append(inforequest)
            except Exception:
                cron_logger.error(
                    u'Checking if undecided email reminder should be sent failed: %s\n%s'
                    % (repr(inforequest), traceback.format_exc()))

        if not filtered:
            return

        filtered = (Inforequest.objects.select_related(
            u'applicant').select_undecided_emails_count().prefetch_related(
                Inforequest.prefetch_main_branch(
                    None, Branch.objects.select_related(u'historicalobligee'))
            ).prefetch_related(
                Inforequest.prefetch_newest_undecided_email()).filter(
                    pk__in=(o.pk for o in filtered)))
        for inforequest in filtered:
            try:
                with transaction.atomic():
                    inforequest.send_undecided_email_reminder()
                    nop()  # To let tests raise testing exception here.
                    cron_logger.info(u'Sent undecided email reminder: %s' %
                                     repr(inforequest))  # pragma: no branch
            except Exception:
                cron_logger.error(
                    u'Sending undecided email reminder failed: %s\n%s' %
                    (repr(inforequest), traceback.format_exc()))
Ejemplo n.º 16
0
def undecided_email_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects
                .not_closed()
                .with_undecided_email()
                .prefetch_related(Inforequest.prefetch_newest_undecided_email())
                )

        filtered = []
        for inforequest in inforequests:
            try:
                email = inforequest.newest_undecided_email
                last = inforequest.last_undecided_email_reminder
                if last and last > email.processed:
                    continue
                days = workdays.between(local_date(email.processed), local_today())
                if days < 5:
                    continue
                filtered.append(inforequest)
            except Exception:
                msg = u'Checking if undecided email reminder should be sent failed: {}\n{}'
                trace = unicode(traceback.format_exc(), u'utf-8')
                cron_logger.error(msg.format(inforequest, trace))

        if not filtered:
            return

        filtered = (Inforequest.objects
                .select_related(u'applicant')
                .select_undecided_emails_count()
                .prefetch_related(Inforequest.prefetch_main_branch(None,
                    Branch.objects.select_related(u'historicalobligee')))
                .prefetch_related(Inforequest.prefetch_newest_undecided_email())
                .filter(pk__in=(o.pk for o in filtered))
                )
        for inforequest in filtered:
            try:
                with transaction.atomic():
                    inforequest.send_undecided_email_reminder()
                    cron_logger.info(u'Sent undecided email reminder: {}'.format(inforequest))
            except Exception:
                msg = u'Sending undecided email reminder failed: {}\n{}'
                trace = unicode(traceback.format_exc(), u'utf-8')
                cron_logger.error(msg.format(inforequest, trace))
Ejemplo n.º 17
0
def applicant_deadline_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects
                .not_closed()
                .without_undecided_email()
                .prefetch_related(Inforequest.prefetch_branches())
                .prefetch_related(Branch.prefetch_last_action(u'branches'))
                )

        filtered = []
        for inforequest in inforequests:
            for branch in inforequest.branches:
                try:
                    if not branch.last_action.has_applicant_deadline:
                        continue
                    # The reminder is sent 2 WDs before the deadline is missed.
                    if branch.last_action.deadline_remaining > 2:
                        continue
                    # Applicant deadlines may not be extended, so we send at most one applicant
                    # deadline reminder for the action.
                    if branch.last_action.last_deadline_reminder:
                        continue
                    nop() # To let tests raise testing exception here.
                    filtered.append(branch)
                except Exception:
                    cron_logger.error(u'Checking if applicant deadline reminder should be sent failed: %s\n%s' % (repr(branch.last_action), traceback.format_exc()))

        if not filtered:
            return

        filtered = (Branch.objects
                .select_related(u'inforequest__applicant')
                .prefetch_related(Branch.prefetch_last_action())
                .filter(pk__in=(o.pk for o in filtered))
                )
        for branch in filtered:
            try:
                with transaction.atomic():
                    branch.inforequest.send_applicant_deadline_reminder(branch.last_action)
                    nop() # To let tests raise testing exception here.
                    cron_logger.info(u'Sent applicant deadline reminder: %s' % repr(branch.last_action)) # pragma: no branch
            except Exception:
                cron_logger.error(u'Sending applicant deadline reminder failed: %s\n%s' % (repr(branch.last_action), traceback.format_exc()))
Ejemplo n.º 18
0
def undecided_email_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects.not_closed().with_undecided_email(
        ).prefetch_related(Inforequest.prefetch_newest_undecided_email()))

        filtered = []
        for inforequest in inforequests:
            try:
                email = inforequest.newest_undecided_email
                last = inforequest.last_undecided_email_reminder
                if last and last > email.processed:
                    continue
                days = workdays.between(local_date(email.processed),
                                        local_today())
                if days < 5:
                    continue
                filtered.append(inforequest)
            except Exception:
                msg = u'Checking if undecided email reminder should be sent failed: {}\n{}'
                trace = unicode(traceback.format_exc(), u'utf-8')
                cron_logger.error(msg.format(inforequest, trace))

        if not filtered:
            return

        filtered = (Inforequest.objects.select_related(
            u'applicant').select_undecided_emails_count().prefetch_related(
                Inforequest.prefetch_main_branch(
                    None, Branch.objects.select_related(u'historicalobligee'))
            ).prefetch_related(
                Inforequest.prefetch_newest_undecided_email()).filter(
                    pk__in=(o.pk for o in filtered)))
        for inforequest in filtered:
            try:
                with transaction.atomic():
                    inforequest.send_undecided_email_reminder()
                    cron_logger.info(
                        u'Sent undecided email reminder: {}'.format(
                            inforequest))
            except Exception:
                msg = u'Sending undecided email reminder failed: {}\n{}'
                trace = unicode(traceback.format_exc(), u'utf-8')
                cron_logger.error(msg.format(inforequest, trace))
Ejemplo n.º 19
0
 def test_date_input_formats(self):
     with translation(u'sk'):
         self.assertFieldOutput(forms.DateField,
                 valid={
                     u'25.10.2006': naive_date(u'2006-10-25'),
                     u'25.10.06': naive_date(u'2006-10-25'),
                     u'2006-10-25': naive_date(u'2006-10-25'),
                     },
                 invalid={
                     u'10.25.2006': [u'Zadajte platný dátum.'],
                     u'10.25.06':   [u'Zadajte platný dátum.'],
                     u'10/25/2006': [u'Zadajte platný dátum.'],
                     u'10/25/06':   [u'Zadajte platný dátum.'],
                     u'25/10/2006': [u'Zadajte platný dátum.'],
                     u'25/10/06':   [u'Zadajte platný dátum.'],
                     u'2006-25-10': [u'Zadajte platný dátum.'],
                     },
                 field_kwargs=dict(localize=True),
                 empty_value=None,
                 )
Ejemplo n.º 20
0
def undecided_email_reminder():
    with translation(settings.LANGUAGE_CODE):
        inforequests = (Inforequest.objects
                .not_closed()
                .with_undecided_email()
                .prefetch_related(Inforequest.prefetch_newest_undecided_email())
                )

        filtered = []
        for inforequest in inforequests:
            try:
                email = inforequest.newest_undecided_email
                last = inforequest.last_undecided_email_reminder
                if last and last > email.processed:
                    continue
                days = workdays.between(local_date(email.processed), local_today())
                if days < 5:
                    continue
                nop() # To let tests raise testing exception here.
                filtered.append(inforequest)
            except Exception:
                cron_logger.error(u'Checking if undecided email reminder should be sent failed: %s\n%s' % (repr(inforequest), traceback.format_exc()))

        if not filtered:
            return

        filtered = (Inforequest.objects
                .select_related(u'applicant')
                .select_undecided_emails_count()
                .prefetch_related(Inforequest.prefetch_main_branch(None, Branch.objects.select_related(u'historicalobligee')))
                .prefetch_related(Inforequest.prefetch_newest_undecided_email())
                .filter(pk__in=(o.pk for o in filtered))
                )
        for inforequest in filtered:
            try:
                with transaction.atomic():
                    inforequest.send_undecided_email_reminder()
                    nop() # To let tests raise testing exception here.
                    cron_logger.info(u'Sent undecided email reminder: %s' % repr(inforequest)) # pragma: no branch
            except Exception:
                cron_logger.error(u'Sending undecided email reminder failed: %s\n%s' % (repr(inforequest), traceback.format_exc()))
Ejemplo n.º 21
0
def change_lang(context, lang=None):
    u"""
    Get active page's url with laguage changed to the specified language.

    Example:
        {% change_lang 'en' %}

    Source: https://djangosnippets.org/snippets/2875/
    """
    path = context[u'request'].path
    url_parts = resolve(path)
    view_name = url_parts.view_name
    kwargs = url_parts.kwargs

    # Ask the view what to show after changing language.
    if hasattr(url_parts.func, u'change_lang'):
        view_name, kwargs = url_parts.func.change_lang(lang, **kwargs)

    with translation(lang):
        url = reverse(view_name, kwargs=kwargs)

    return format(url)
Ejemplo n.º 22
0
def change_lang(context, lang=None):
    u"""
    Get active page's url with laguage changed to the specified language.

    Example:
        {% change_lang 'en' %}

    Source: https://djangosnippets.org/snippets/2875/
    """
    path = context[u'request'].path
    url_parts = resolve(path)
    view_name = url_parts.view_name
    kwargs = url_parts.kwargs

    # Ask the view what to show after changing language.
    if hasattr(url_parts.func, u'change_lang'):
        view_name, kwargs = url_parts.func.change_lang(lang, **kwargs)

    with translation(lang):
        url = reverse(view_name, kwargs=kwargs)

    return format(url)
Ejemplo n.º 23
0
def assign_email_on_message_received(sender, message, **kwargs):
    if message.received_for:
        q = Q(unique_email__iexact=message.received_for)
    elif message.recipients:
        q = (Q(unique_email__iexact=r.mail) for r in message.recipients)
        q = reduce(operator.or_, q)
    else:
        return

    try:
        inforequest = Inforequest.objects.get(q)
    except (Inforequest.DoesNotExist, Inforequest.MultipleObjectsReturned):
        return

    inforequestemail = InforequestEmail(
            inforequest=inforequest,
            email=message,
            type=InforequestEmail.TYPES.UNDECIDED,
            )
    inforequestemail.save()

    if not inforequest.closed:
        with translation(settings.LANGUAGE_CODE):
            inforequest.send_received_email_notification(message)
Ejemplo n.º 24
0
def assign_email_on_message_received(sender, message, **kwargs):
    if message.received_for:
        q = Q(unique_email__iexact=message.received_for)
    elif message.recipients:
        q = (Q(unique_email__iexact=r.mail) for r in message.recipients)
        q = reduce(operator.or_, q)
    else:
        return

    try:
        inforequest = Inforequest.objects.get(q)
    except (Inforequest.DoesNotExist, Inforequest.MultipleObjectsReturned):
        return

    inforequestemail = InforequestEmail(
        inforequest=inforequest,
        email=message,
        type=InforequestEmail.TYPES.UNDECIDED,
    )
    inforequestemail.save()

    if not inforequest.closed:
        with translation(settings.LANGUAGE_CODE):
            inforequest.send_received_email_notification(message)
Ejemplo n.º 25
0
 def url(self):
     with translation(self._page._lang):
         return reverse(u'pages:file', args=[self._page.lpath, self._name])
Ejemplo n.º 26
0
 def test_translated_template_has_priority(self):
     # Existing: first.html, first.en.html
     with translation(u'en'):
         rendered = squeeze(render_to_string(u'first.html'))
         self.assertEqual(rendered, u'(first.en.html)')
Ejemplo n.º 27
0
 def test_with_only_untranslated_template(self):
     # Existing: first.html
     # Missing: first.de.html
     with translation(u'de'):
         rendered = squeeze(render_to_string(u'first.html'))
         self.assertEqual(rendered, u'(first.html)')
Ejemplo n.º 28
0
    def __init__(self, page, create, *args, **kwargs):
        super(PageEditForm, self).__init__(*args, **kwargs)
        self.page = page
        self.create = create

        edit_root = not create and page.is_root
        edit_redirect = not create and page.is_redirect
        edit_regular = not create and not page.is_root and not page.is_redirect
        assert bool(create) + bool(edit_root) + bool(edit_redirect) + bool(edit_regular) == 1

        self.fieldsets = [
                Bunch(label=None, collapse=False, fields=[]),
                Bunch(label=u'Raw Config', collapse=True, fields=[]),
                Bunch(label=u'Page Content', collapse=False, fields=[]),
                ]

        if edit_regular:
            self.fields[u'parent'] = forms.CharField(
                label=u'URL Path',
                validators=[
                    RegexValidator(pages.path_regex, u'Enter a valid path. It must be an absolute path with respect to the root page starting and ending with a slash.'),
                    ],
                widget=forms.TextInput(attrs={
                    u'class': u'popup-path',
                    u'style': u'width: 50em;',
                    u'data-popup-url': reverse(u'admin:pages_index', args=[page.lang]),
                    u'data-icon': staticfiles_storage.url(u'admin/img/selector-search.gif'),
                    }),
                )
            self.initial[u'parent'] = page.ppath
            self.fieldsets[0].fields.append(self[u'parent'])
            self.fieldsets[0].fields.append(LivePath(page.lang, self[u'parent']))
        else:
            self.fieldsets[0].fields.append(FakeField(u'URL Path', page.path))

        if create or edit_regular:
            self.fields[u'name'] = forms.CharField(
                label=u'URL Name',
                validators=[
                    RegexValidator(pages.slug_regex, u'Enter a valid slug. Only letters, numbers and dashes are allowed.'),
                    ],
                )
            if not create:
                self.initial[u'name'] = page.name
            self.fieldsets[0].fields.append(self[u'name'])

        if create or edit_root or edit_regular:
            self.fields[u'title'] = forms.CharField(
                label=u'Page Title',
                required=False,
                widget=forms.TextInput(attrs={
                    u'style': u'width: 50em;',
                    }),
                )
            if not create:
                self.initial[u'title'] = page._config.get(u'title')
            self.fieldsets[0].fields.append(self[u'title'])

        if create or edit_root or edit_regular:
            self.fields[u'label'] = forms.CharField(
                label=u'Menu Label',
                required=False,
                )
            if not create:
                self.initial[u'label'] = page._config.get(u'label')
            self.fieldsets[0].fields.append(self[u'label'])

        if create or edit_regular:
            self.fields[u'order'] = forms.CharField(
                label=u'Sort Key',
                required=False,
                )
            if not create:
                self.initial[u'order'] = page._config.get(u'order')
            self.fieldsets[0].fields.append(self[u'order'])

        if create or edit_regular:
            for lang, _ in settings.LANGUAGES:
                if lang != page.lang:
                    key = u'lang_%s' % lang
                    self.fields[key] = forms.CharField(
                        label=u'Translation %s' % lang.upper(),
                        required=False,
                        validators=[
                            RegexValidator(pages.path_regex, u'Enter a valid path. It must be an absolute path with respect to the root page starting and ending with a slash.'),
                            ],
                        widget=forms.TextInput(attrs={
                            u'class': u'popup-path',
                            u'style': u'width: 50em;',
                            u'data-popup-url': reverse(u'admin:pages_index', args=[lang]),
                            u'data-icon': staticfiles_storage.url(u'admin/img/selector-search.gif'),
                            }),
                        )
                    if not create:
                        self.initial[key] = page._config.get(key)
                    self.fieldsets[0].fields.append(self[key])
                    self.fieldsets[0].fields.append(LivePath(lang, self[key]))

        if edit_redirect:
            self.fields[u'redirect'] = forms.CharField(
                label=u'Redirect',
                validators=[
                    RegexValidator(pages.path_regex, u'Enter a valid path. It must be an absolute path with respect to the root page starting and ending with a slash.'),
                    ],
                widget=forms.TextInput(attrs={
                    u'class': u'popup-path',
                    u'style': u'width: 50em;',
                    u'data-popup-url': reverse(u'admin:pages_index', args=[page.lang]),
                    u'data-icon': staticfiles_storage.url(u'admin/img/selector-search.gif'),
                    }),
                )
            self.initial[u'redirect'] = page.redirect_path
            self.fieldsets[0].fields.append(self[u'redirect'])
            self.fieldsets[0].fields.append(LivePath(page.lang, self[u'redirect']))

        if create or edit_root or edit_regular:
            self.fields[u'disabled'] = forms.BooleanField(
                label=u'Disabled',
                required=False,
                )
            if not create:
                self.initial[u'disabled'] = bool(page._config.get(u'disabled'))
            self.fieldsets[0].fields.append(self[u'disabled'])

        if create or edit_root or edit_regular:
            self.fields[u'raw'] = forms.CharField(
                label=u'',
                required=False,
                widget=forms.Textarea(attrs={
                    u'style': u'width: 100%; height: 10em;',
                    }),
                )
            if not create:
                self.initial[u'raw'] = page.raw_config
            self.fieldsets[1].fields.append(self[u'raw'])

        if create or edit_root or edit_regular:
            with translation(page.lang):
                url = reverse(u'admin:pages_preview')
            self.fields[u'template'] = forms.CharField(
                label=u'',
                required=False,
                widget=forms.Textarea(attrs={
                    u'class': u'template-widget',
                    u'data-url': url,
                    }),
                )
            if not create:
                self.initial[u'template'] = page.template
            self.fieldsets[2].fields.append(self[u'template'])
Ejemplo n.º 29
0
 def test_with_only_untranslated_template(self):
     # Existing: first.html
     # Missing: first.de.html
     with translation(u'de'):
         rendered = squeeze(render_to_string(u'first.html'))
         self.assertEqual(rendered, u'(first.html)')
Ejemplo n.º 30
0
 def test_translated_template_has_priority(self):
     # Existing: first.html, first.en.html
     with translation(u'en'):
         rendered = squeeze(render_to_string(u'first.html'))
         self.assertEqual(rendered, u'(first.en.html)')
Ejemplo n.º 31
0
 def url(self):
     with translation(self._lang):
         return reverse(u'pages:view', args=[self.lpath])
Ejemplo n.º 32
0
    def __init__(self, page, create, *args, **kwargs):
        super(PageEditForm, self).__init__(*args, **kwargs)
        self.page = page
        self.create = create

        edit_root = not create and page.is_root
        edit_redirect = not create and page.is_redirect
        edit_regular = not create and not page.is_root and not page.is_redirect
        assert bool(create) + bool(edit_root) + bool(edit_redirect) + bool(
            edit_regular) == 1

        self.fieldsets = [
            Bunch(label=None, collapse=False, fields=[]),
            Bunch(label=u'Raw Config', collapse=True, fields=[]),
            Bunch(label=u'Page Content', collapse=False, fields=[]),
        ]

        if edit_regular:
            self.fields[u'parent'] = forms.CharField(
                label=u'URL Path',
                validators=[
                    RegexValidator(
                        pages.path_regex,
                        squeeze(u"""
                        Enter a valid path. It must be an absolute path with respect to the root
                        page starting and ending with a slash.
                        """)),
                ],
                widget=forms.TextInput(
                    attrs={
                        u'class':
                        u'popup-path',
                        u'style':
                        u'width: 50em;',
                        u'data-popup-url':
                        reverse(u'admin:pages_index', args=[page.lang]),
                        u'data-icon':
                        staticfiles_storage.url(
                            u'admin/img/selector-search.gif'),
                    }),
            )
            self.initial[u'parent'] = page.ppath
            self.fieldsets[0].fields.append(self[u'parent'])
            self.fieldsets[0].fields.append(
                LivePath(page.lang, self[u'parent']))
        else:
            self.fieldsets[0].fields.append(FakeField(u'URL Path', page.path))

        if create or edit_regular:
            self.fields[u'name'] = forms.CharField(
                label=u'URL Name',
                validators=[
                    RegexValidator(
                        pages.slug_regex,
                        u'Enter a valid slug. Only letters, numbers and dashes are allowed.'
                    ),
                ],
            )
            if not create:
                self.initial[u'name'] = page.name
            self.fieldsets[0].fields.append(self[u'name'])

        if create or edit_root or edit_regular:
            self.fields[u'title'] = forms.CharField(
                label=u'Page Title',
                required=False,
                widget=forms.TextInput(attrs={
                    u'style': u'width: 50em;',
                }),
            )
            if not create:
                self.initial[u'title'] = page._config.get(u'title')
            self.fieldsets[0].fields.append(self[u'title'])

        if create or edit_root or edit_regular:
            self.fields[u'label'] = forms.CharField(
                label=u'Menu Label',
                required=False,
            )
            if not create:
                self.initial[u'label'] = page._config.get(u'label')
            self.fieldsets[0].fields.append(self[u'label'])

        if create or edit_regular:
            self.fields[u'order'] = forms.CharField(
                label=u'Sort Key',
                required=False,
            )
            if not create:
                self.initial[u'order'] = page._config.get(u'order')
            self.fieldsets[0].fields.append(self[u'order'])

        if create or edit_regular:
            for lang, _ in settings.LANGUAGES:
                if lang != page.lang:
                    key = u'lang_{}'.format(lang)
                    self.fields[key] = forms.CharField(
                        label=u'Translation {}'.format(lang.upper()),
                        required=False,
                        validators=[
                            RegexValidator(
                                pages.path_regex,
                                squeeze(u"""
                                Enter a valid path. It must be an absolute path with respect to the
                                root page starting and ending with a slash.
                                """)),
                        ],
                        widget=forms.TextInput(
                            attrs={
                                u'class':
                                u'popup-path',
                                u'style':
                                u'width: 50em;',
                                u'data-popup-url':
                                reverse(u'admin:pages_index', args=[lang]),
                                u'data-icon':
                                staticfiles_storage.url(
                                    u'admin/img/selector-search.gif'),
                            }),
                    )
                    if not create:
                        self.initial[key] = page._config.get(key)
                    self.fieldsets[0].fields.append(self[key])
                    self.fieldsets[0].fields.append(LivePath(lang, self[key]))

        if edit_redirect:
            self.fields[u'redirect'] = forms.CharField(
                label=u'Redirect',
                validators=[
                    RegexValidator(
                        pages.path_regex,
                        squeeze(u"""
                        Enter a valid path. It must be an absolute path with respect to the root
                        page starting and ending with a slash.
                        """)),
                ],
                widget=forms.TextInput(
                    attrs={
                        u'class':
                        u'popup-path',
                        u'style':
                        u'width: 50em;',
                        u'data-popup-url':
                        reverse(u'admin:pages_index', args=[page.lang]),
                        u'data-icon':
                        staticfiles_storage.url(
                            u'admin/img/selector-search.gif'),
                    }),
            )
            self.initial[u'redirect'] = page.redirect_path
            self.fieldsets[0].fields.append(self[u'redirect'])
            self.fieldsets[0].fields.append(
                LivePath(page.lang, self[u'redirect']))

        if create or edit_root or edit_regular:
            self.fields[u'disabled'] = forms.BooleanField(
                label=u'Disabled',
                required=False,
            )
            if not create:
                self.initial[u'disabled'] = bool(page._config.get(u'disabled'))
            self.fieldsets[0].fields.append(self[u'disabled'])

        if create or edit_root or edit_regular:
            self.fields[u'raw'] = forms.CharField(
                label=u'',
                required=False,
                widget=forms.Textarea(attrs={
                    u'style': u'width: 100%; height: 10em;',
                }),
            )
            if not create:
                self.initial[u'raw'] = page.raw_config
            self.fieldsets[1].fields.append(self[u'raw'])

        if create or edit_root or edit_regular:
            with translation(page.lang):
                url = reverse(u'admin:pages_preview')
            self.fields[u'template'] = forms.CharField(
                label=u'',
                required=False,
                widget=forms.Textarea(attrs={
                    u'class': u'template-widget',
                    u'data-url': url,
                }),
            )
            if not create:
                self.initial[u'template'] = page.template
            self.fieldsets[2].fields.append(self[u'template'])
Ejemplo n.º 33
0
 def url(self):
     with translation(self._lang):
         return reverse(u'pages:view', args=[self.lpath])
Ejemplo n.º 34
0
 def url(self):
     with translation(self._page._lang):
         return reverse(u'pages:file', args=[self._page.lpath, self._name])