Ejemplo n.º 1
0
def confirm_cart_to_user(profile, action):
    """send message by email"""

    from_email = getattr(settings, 'DEFAULT_FROM_EMAIL')
    subject = get_cart_confirmation_subject()


    data = {
        'profile': profile,
        'action': action,
        'subject': subject,
    }


    the_template = get_template('Store/cart_confirmation_email.html')
    html_text = the_template.render(Context(data))
    text = dehtml(html_text)

    email = EmailMultiAlternatives(
        subject,
        text,
        from_email,
        [profile.contact.email],
    )
    email.attach_alternative(html_text, "text/html")

    try:
        email.send()
    except Exception:
        logger.exception("confirm_cart_to_user")
Ejemplo n.º 2
0
def notify_cart_to_admin(contact, action):
    """send message by email"""
    notification_email = getattr(settings, 'BALAFON_NOTIFICATION_EMAIL', '')
    if notification_email:
        from_email = getattr(settings, 'DEFAULT_FROM_EMAIL')
        subject = _("New cart purchased on store")
        data = {
            'contact': contact,
            'action': action,
            'subject': subject,
        }
        the_template = get_template('Store/cart_notification_email.html')
        html_text = the_template.render(data)
        text = dehtml(html_text)

        email = EmailMultiAlternatives(subject,
                                       text,
                                       from_email, [notification_email],
                                       headers={'Reply-To': contact.email})
        email.attach_alternative(html_text, "text/html")

        try:
            email.send()
        except Exception:
            logger.exception("notify_cart_to_admin")
Ejemplo n.º 3
0
def confirm_cart_to_user(contact, action, custom_template=None):
    """send message by email"""

    from_email = getattr(settings, 'DEFAULT_FROM_EMAIL')
    subject = get_cart_confirmation_subject(contact, action)

    data = {
        'contact': contact,
        'action': action,
        'subject': subject,
    }

    if custom_template:
        template_name = custom_template
    else:
        template_name = 'Store/cart_confirmation_email.html'
    the_template = get_template(template_name)
    html_text = the_template.render(data)
    text = dehtml(html_text)

    email = EmailMultiAlternatives(
        subject,
        text,
        from_email,
        [contact.email],
    )
    email.attach_alternative(html_text, "text/html")

    try:
        email.send()
    except Exception:
        logger.exception("confirm_cart_to_user")
Ejemplo n.º 4
0
    def __init__(self, user, *args, **kwargs):
        article = kwargs['instance']

        try:
            initials = kwargs['initial']
        except KeyError:
            initials = {}
        summary = article.summary
        if not summary:
            summary = dehtml(article.content)[:400]
        initials.update({'summary': summary})
        initials.update({
            'publication_date':
            article.publication_date.strftime("%Y-%m-%d %H:%M:%S")
        })

        kwargs['initial'] = initials
        super(ArticleSettingsForm, self).__init__(*args, **kwargs)  # pylint: disable=E1002

        self.fields['category'].queryset = self.fields[
            'category'].queryset.filter(sites=settings.SITE_ID)

        choices = get_article_templates(article, user)
        if choices:
            self.fields["template"] = forms.ChoiceField(choices=choices)
        else:
            self.fields["template"] = forms.CharField()

        if 'sites' in self.fields and not is_multi_site():
            self.fields['sites'].widget = forms.MultipleHiddenInput()
Ejemplo n.º 5
0
    def __init__(self, user, *args, **kwargs):
        article = kwargs['instance']

        try:
            initials = kwargs['initial']
        except KeyError:
            initials = {}
        summary = article.summary
        if not summary:
            summary = dehtml(article.content)[:400]
        initials.update({'summary': summary})
        initials.update({'publication_date': article.publication_date.strftime("%Y-%m-%d %H:%M:%S")})
        
        kwargs['initial'] = initials
        super(ArticleSettingsForm, self).__init__(*args, **kwargs)  # pylint: disable=E1002

        self.fields['category'].queryset = self.fields['category'].queryset.filter(sites=settings.SITE_ID)

        choices = get_article_templates(article, user)
        if choices:
            self.fields["template"] = forms.ChoiceField(choices=choices)
        else:
            self.fields["template"] = forms.CharField()

        if 'sites' in self.fields and not is_multi_site():
            self.fields['sites'].widget = forms.MultipleHiddenInput()
Ejemplo n.º 6
0
def notify_cart_to_admin(profile, action):
    """send message by email"""
    notification_email = getattr(settings, 'BALAFON_NOTIFICATION_EMAIL', '')
    if notification_email:
        from_email = getattr(settings, 'DEFAULT_FROM_EMAIL')
        subject = _(u"New cart purchased on store")
        data = {
            'profile': profile,
            'action': action,
            'subject': subject,
        }
        the_template = get_template('Store/cart_notification_email.html')
        html_text = the_template.render(Context(data))
        text = dehtml(html_text)

        email = EmailMultiAlternatives(
            subject,
            text,
            from_email,
            [notification_email],
            headers={'Reply-To': profile.contact.email}
        )
        email.attach_alternative(html_text, "text/html")

        try:
            email.send()
        except Exception:
            logger.exception("notify_cart_to_admin")
Ejemplo n.º 7
0
 def __init__(self, *args, **kwargs):
     article = kwargs['instance']
     try:
         initials = kwargs['initial']
     except:
         initials = {}
     summary = article.summary
     if not summary:
         summary = dehtml(article.content)[:250]
     initials.update({'summary': summary})
     kwargs['initial'] = initials
     super(PublishArticleForm, self).__init__(*args, **kwargs)
Ejemplo n.º 8
0
def get_emailing_context(emailing, contact):
    """get context for emailing: user,...."""
    data = dict(contact.__dict__)
    for field in ('gender_name', 'gender_dear', 'city_name', 'entity_name',
                  'full_address', 'fullname'):
        data[field] = getattr(contact, field)

    # clone the object: Avoid overwriting {tags} for ever
    newsletter = Newsletter()
    newsletter.__dict__ = dict(emailing.newsletter.__dict__)
    newsletter.subject = format_context(newsletter.subject, data)

    html_content = format_context(newsletter.content, data)

    unregister_url = newsletter.get_site_prefix() + reverse(
        'emailing_unregister', args=[emailing.id, contact.uuid])

    newsletter.content = html_content

    context_dict = {
        'title':
        dehtml(newsletter.subject).replace('\n\n', '\n').replace('\n', ' '),
        'newsletter':
        newsletter,
        'by_email':
        True,
        'MEDIA_URL':
        settings.MEDIA_URL,
        'STATIC_URL':
        settings.STATIC_URL,
        'SITE_PREFIX':
        emailing.get_domain_url_prefix(),
        'my_company':
        emailing.subscription_type.name,
        'unregister_url':
        unregister_url,
        'contact':
        contact,
        'emailing':
        emailing,
    }

    for callback in get_newsletter_context_callbacks():
        dictionary = callback(newsletter)
        if dictionary:
            context_dict.update(dictionary)

    return context_dict
Ejemplo n.º 9
0
    def __init__(self, user, *args, **kwargs):
        article = kwargs['instance']

        try:
            initials = kwargs['initial']
        except:
            initials = {}
        summary = article.summary
        if not summary:
            summary = dehtml(article.content)[:250]
        initials.update({'summary': summary})
        kwargs['initial'] = initials
        super(ArticleSettingsForm, self).__init__(*args, **kwargs)

        choices = get_article_templates(article, user)
        if choices:
            self.fields["template"] = forms.ChoiceField(choices=choices)
        else:
            self.fields["template"] = forms.CharField()
Ejemplo n.º 10
0
def send_email(subject,
               template_name,
               context,
               recipients,
               sender=None,
               cc_list=None):
    """Send an HTML email"""
    emails = []
    connection = get_connection()
    from_email = sender if sender else settings.DEFAULT_FROM_EMAIL
    for address in recipients:
        context['email_address'] = address
        context['subject'] = subject
        the_template = get_template(template_name)
        html_text = the_template.render(context)
        text = dehtml(html_text)
        email = EmailMultiAlternatives(subject,
                                       text,
                                       from_email, [address],
                                       cc=cc_list if cc_list else [])
        email.attach_alternative(html_text, "text/html")
        emails.append(email)
    return connection.send_messages(emails)
Ejemplo n.º 11
0
 def test_special_chars_two(self):
     text = "This \xf6is \xe4 simple text\xfc"
     html_text = "This öis ä simple textü"
     self.assertEqual(dehtml(html_text), text)
Ejemplo n.º 12
0
 def test_charset_chars_allowed(self):
     text = "à l'Opéra Grand Avignon"
     html_text = "<p>&agrave; l&#39;Op&eacute;ra Grand Avignon</p>"
     self.assertEqual(dehtml(html_text, allow_html_chars=True), text)
Ejemplo n.º 13
0
 def test_charset_chars(self):
     text = "à l'Opéra Grand Avignon"
     html_text = "<p>&agrave; l&#39;Op&eacute;ra Grand Avignon</p>"
     self.assertEqual(dehtml(html_text, allow_html_chars=False), text)
Ejemplo n.º 14
0
 def test_special_chars(self):
     text = "This &ouml;is &auml; simple text&uuml;"
     html_text = "This &ouml;is &auml; simple text&uuml;"
     self.assertEqual(dehtml(html_text, allow_html_chars=True), text)
Ejemplo n.º 15
0
 def test_charset_chars(self):
     text = "à l'Opéra Grand Avignon"
     html_text = "<p>&agrave; l&#39;Op&eacute;ra Grand Avignon</p>"
     self.assertEqual(dehtml(html_text, allow_html_chars=False), text)
Ejemplo n.º 16
0
 def test_paragraph_inside(self):
     text = "<h1>This is a title</h1><p>This is a paragraph</p><p>This is another paragraph</p>"
     self.assertEqual(
         dehtml(text),
         "This is a title\n\nThis is a paragraph\n\nThis is another paragraph"
     )
Ejemplo n.º 17
0
 def item_title(self, item):
     """title of an item"""
     return dehtml(item.title)
Ejemplo n.º 18
0
 def test_paragraph(self):
     text = "This is a simple text"
     html_text = '<p>{0}</p>'.format(text)
     self.assertEqual(dehtml(html_text), text)
Ejemplo n.º 19
0
 def test_simple_text(self):
     text = "This is a simple text"
     self.assertEqual(dehtml(text), text)
Ejemplo n.º 20
0
 def test_simple_text(self):
     text = "This is a simple text"
     self.assertEqual(dehtml(text), text)
Ejemplo n.º 21
0
 def test_special_chars_two(self):
     text = "This \xf6is \xe4 simple text\xfc"
     html_text = "This &ouml;is &auml; simple text&uuml;"
     self.assertEqual(dehtml(html_text), text)
Ejemplo n.º 22
0
 def test_charset_chars_allowed(self):
     text = "&agrave; l&#39;Op&eacute;ra Grand Avignon"
     html_text = "<p>&agrave; l&#39;Op&eacute;ra Grand Avignon</p>"
     self.assertEqual(dehtml(html_text, allow_html_chars=True), text)
Ejemplo n.º 23
0
    def do_fill_workbook(self, workbook):
        """implement it in base class"""

        year = datetime.today().year
        participants_group = get_object_or_404(Group, name=u'Participation {0}'.format(year))
        groups = []
        for competition in Competition.objects.filter(is_archived=False):
            try:
                groups.append(Group.objects.get(name=competition.name))
            except Group.DoesNotExist:
                pass

        # group_18 = Group.objects.get(name=u'18 kilomètres')
        # group_12 = Group.objects.get(name=u'12 kilomètres')
        # group_6 = Group.objects.get(name=u'6 kilomètres')

        groupe_inscription_ok = Group.objects.get(name=u'Inscription Ok')
        groupe_paiement_ok = Group.objects.get(name=u'Paiement Ok')

        columns = [
            u'NUMERO', u'Nom', u'Prénom', u"Téléphone", u'Sexe', u'Naissance', u'License', u'Club', u'Email', u'Ville',
            u'Code postal', u'Inscription Ok', u'Paiement Ok', u'Notes', u'{0}'.format(year)
        ]

        for group in groups:

            sheet = workbook.add_sheet(group.name)
            sheet.protect = True

            warning_style = self.get_warning_style()

            for col, label in enumerate(columns):
                self.write_cell(sheet, 0, col, label, style=self.get_header_style())

            contacts = group.contacts.extra(
                select={'lower_name': 'lower(lastname)'}
            ).order_by('lower_name')
            for line, contact in enumerate(contacts):

                inscription_ok = contact in groupe_inscription_ok.contacts.all()
                paiement_ok = contact in groupe_paiement_ok.contacts.all()
                est_participant = contact in participants_group.contacts.all()

                try:
                    runner = Runner.objects.get(id=contact.id)
                    club = runner.club.strip()
                except Runner.DoesNotExist:
                    club = contact.get_custom_field('club').strip()

                #self.write_cell(sheet, line + 1, 0, contact.id, style=self.get_header_style())
                # self.write_cell(
                #     sheet, line + 1, 1, u'{0.lastname} {0.firstname}'.format(contact),
                #     style=None
                # )
                self.write_cell(
                    sheet, line + 1, 1, u'{0.lastname}'.format(contact),
                    style=warning_style if not (inscription_ok and paiement_ok) else None
                )
                self.write_cell(
                    sheet, line + 1, 2, u'{0.firstname}'.format(contact),
                    style=warning_style if not (inscription_ok and paiement_ok) else None
                )
                self.write_cell(sheet, line + 1, 3, contact.phone or contact.mobile)

                gender = ''
                if contact.gender == Contact.GENDER_MALE:
                    gender = u'H'
                elif contact.gender == Contact.GENDER_FEMALE:
                    gender = u'F'
                self.write_cell(sheet, line + 1, 4, gender)

                if contact.birth_date:
                    self.write_cell(sheet, line + 1, 5, contact.birth_date.year)
                else:
                    self.write_cell(sheet, line + 1, 5, u'??', style=warning_style)

                self.write_cell(sheet, line + 1, 6, contact.get_custom_field('license'))

                self.write_cell(sheet, line + 1, 7, club)

                self.write_cell(sheet, line + 1, 8, contact.email)

                self.write_cell(sheet, line + 1, 9, contact.city.name if contact.city else "?")

                self.write_cell(sheet, line + 1, 10, contact.zip_code)

                self.write_cell(
                    sheet, line + 1, 11, u'Oui' if inscription_ok else u'Non',
                    style=warning_style if not inscription_ok else None
                )

                self.write_cell(
                    sheet, line + 1, 12, u'Oui' if paiement_ok else u'Non',
                    style=warning_style if not paiement_ok else None
                )

                self.write_cell(sheet, line + 1, 13, dehtml(contact.notes))

                self.write_cell(sheet, line + 1, 14, u'X' if est_participant else u'')
Ejemplo n.º 24
0
 def test_gt_lt(self):
     text = "This is a simple text"
     html_text = '&gt;' + text + "&lt;"
     self.assertEqual(dehtml(html_text), ">" + text + "<")
Ejemplo n.º 25
0
 def test_nbsp(self):
     text = "This is a simple text"
     html_text = text.replace(' ', '&nbsp;')
     self.assertNotEqual(html_text, text)
     self.assertEqual(dehtml(html_text), text)
Ejemplo n.º 26
0
 def test_paragraph(self):
     text = "This is a simple text"
     html_text = '<p>{0}</p>'.format(text)
     self.assertEqual(dehtml(html_text), text)
Ejemplo n.º 27
0
def send_newsletter(emailing, max_nb):
    """send newsletter"""

    # Create automatically an action type for logging one action by contact
    emailing_action_type = ActionType.objects.get_or_create(
        name=_('Emailing'))[0]

    # Clean the urls
    emailing.newsletter.content = make_links_absolute(
        emailing.newsletter.content,
        emailing.newsletter,
        site_prefix=emailing.get_domain_url_prefix())

    connection = get_connection()
    from_email = emailing.from_email or settings.COOP_CMS_FROM_EMAIL
    emails = []

    contacts = list(emailing.send_to.all()[:max_nb])
    for contact in contacts:

        if contact.get_email:
            lang = emailing.lang or contact.favorite_language or settings.LANGUAGE_CODE[:
                                                                                        2]
            translation.activate(lang)

            emailing_context = get_emailing_context(emailing, contact)
            emailing_context["LANGUAGE_CODE"] = lang
            context = emailing_context
            the_template = get_template(
                emailing.newsletter.get_template_name())

            html_text = the_template.render(context)

            html_text = patch_emailing_html(html_text, emailing, contact)

            html_text = make_links_absolute(
                html_text,
                emailing.newsletter,
                site_prefix=emailing.get_domain_url_prefix())

            text = dehtml(html_text)
            list_unsubscribe_url = emailing.get_domain_url_prefix() + reverse(
                "emailing_unregister", args=[emailing.id, contact.uuid])
            list_unsubscribe_email = getattr(settings, 'COOP_CMS_REPLY_TO',
                                             '') or from_email
            headers = {
                "List-Unsubscribe":
                "<{0}>, <mailto:{1}?subject=unsubscribe>".format(
                    list_unsubscribe_url, list_unsubscribe_email)
            }

            if getattr(settings, 'COOP_CMS_REPLY_TO', None):
                headers['Reply-To'] = settings.COOP_CMS_REPLY_TO

            email = EmailMultiAlternatives(context['title'],
                                           force_line_max_length(text),
                                           from_email,
                                           [contact.get_email_address()],
                                           headers=headers)
            html_text = force_line_max_length(html_text,
                                              max_length_per_line=400,
                                              dont_cut_in_quotes=True)
            email.attach_alternative(html_text, "text/html")
            emails.append(email)

            # create action
            action = Action.objects.create(subject=context['title'],
                                           planned_date=emailing.scheduling_dt,
                                           type=emailing_action_type,
                                           detail=text,
                                           done=True,
                                           display_on_board=False,
                                           done_date=datetime.now())
            action.contacts.add(contact)
            action.save()

        # print contact, "processed"
        emailing.send_to.remove(contact)
        emailing.sent_to.add(contact)

    emailing.save()
    nb_sent = connection.send_messages(emails)
    return nb_sent or 0
Ejemplo n.º 28
0
 def test_gt_lt(self):
     text = "This is a simple text"
     html_text = '&gt;' + text + "&lt;"
     self.assertEqual(dehtml(html_text), ">" + text + "<")
Ejemplo n.º 29
0
 def item_title(self, item):
     """title of an item"""
     return dehtml(item.title)
Ejemplo n.º 30
0
 def test_special_chars(self):
     text = "This &ouml;is &auml; simple text&uuml;"
     html_text = "This &ouml;is &auml; simple text&uuml;"
     self.assertEqual(dehtml(html_text, allow_html_chars=True), text)
Ejemplo n.º 31
0
 def test_nbsp(self):
     text = "This is a simple text"
     html_text = text.replace(' ', '&nbsp;')
     self.assertNotEqual(html_text, text)
     self.assertEqual(dehtml(html_text), text)
Ejemplo n.º 32
0
 def _dehtmled_field(self, fieldname, **kwargs):
     """html to text for a field content"""
     value = self.cleaned_data[fieldname]
     return dehtml(value, **kwargs)
Ejemplo n.º 33
0
 def test_paragraph_inside(self):
     text = "<h1>This is a title</h1><p>This is a paragraph</p><p>This is another paragraph</p>"
     self.assertEqual(dehtml(text), "This is a title\n\nThis is a paragraph\n\nThis is another paragraph")
Ejemplo n.º 34
0
 def _dehtmled_field(self, fieldname, **kwargs):
     """html to text for a field content"""
     value = self.cleaned_data[fieldname]
     return dehtml(value, **kwargs)