Ejemplo n.º 1
0
    def save(self, *args, **kwargs):
        data = self.cleaned_data
        subject = ''
        subj = data.get('subject', '')
        inc_last_name = data.get('personalize_subject_last_name')
        inc_first_name = data.get('personalize_subject_first_name')

        if inc_first_name and not inc_last_name:
            subject = '[firstname] ' + subj
        elif inc_last_name and not inc_first_name:
            subject = '[lastname] ' + subj
        elif inc_first_name and inc_last_name:
            subject = '[firstname] [lastname] ' + subj
        else:
            subject = subj
        nl = super(OldGenerateForm, self).save(*args, **kwargs)
        nl.subject = subject
        nl.actionname = subject
        nl.date_created = datetime.datetime.now()
        nl.send_status = 'draft'
        if nl.default_template:
            template = render_to_string(nl.default_template,
                                        context_instance=RequestContext(
                                            self.request))
            email_content = nl.generate_newsletter(self.request, template)

            email = Email()
            email.subject = subject
            email.body = email_content
            email.sender = self.request.user.email
            email.sender_display = self.request.user.profile.get_name()
            email.reply_to = self.request.user.email
            email.creator = self.request.user
            email.creator_username = self.request.user.username
            email.owner = self.request.user
            email.owner_username = self.request.user.username
            email.save()
            nl.email = email

        nl.save()

        return nl
Ejemplo n.º 2
0
    def save(self, *args, **kwargs):
        data = self.cleaned_data
        subject = ''
        subj = data.get('subject', '')
        inc_last_name = data.get('personalize_subject_last_name')
        inc_first_name = data.get('personalize_subject_first_name')

        if inc_first_name and not inc_last_name:
            subject = '[firstname] ' + subj
        elif inc_last_name and not inc_first_name:
            subject = '[lastname] ' + subj
        elif inc_first_name and inc_last_name:
            subject = '[firstname] [lastname] ' + subj
        else:
            subject = subj
        nl = super(OldGenerateForm, self).save(*args, **kwargs)
        nl.subject = subject
        nl.actionname = subject
        nl.date_created = datetime.datetime.now()
        nl.send_status = 'draft'
        if nl.default_template:
            template = render_to_string(nl.default_template, context_instance=RequestContext(self.request))
            email_content = nl.generate_newsletter(self.request, template)

            email = Email()
            email.subject = subject
            email.body = email_content
            email.sender = self.request.user.email
            email.sender_display = self.request.user.profile.get_name()
            email.reply_to = self.request.user.email
            email.creator = self.request.user
            email.creator_username = self.request.user.username
            email.owner = self.request.user
            email.owner_username = self.request.user.username
            email.save()
            nl.email = email

        nl.save()

        return nl
Ejemplo n.º 3
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user,'forms.view_form',form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous() and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(request, messages.WARNING, 
                    'Please edit the form to include an email field ' + \
                    'as it is required for setting up a recurring ' + \
                    'payment for anonymous users.')

    form_for_form = FormForForm(form, request.user, request.POST or None, request.FILES or None)
    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid():
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous():
                if entry.get_email_address():
                    emailfield = entry.get_email_address()
                    firstnamefield = entry.get_first_name()
                    lastnamefield = entry.get_last_name()
                    phonefield = entry.get_phone_number()
                    password = ''
                    for i in range(0, 10):
                        password += random.choice(string.ascii_lowercase + string.ascii_uppercase)

                    user_list = User.objects.filter(email=emailfield).order_by('-last_login')
                    if user_list:
                        anonymous_creator = user_list[0]
                    else:
                        anonymous_creator = User(username=emailfield[:30], email=emailfield, 
                                                 first_name=firstnamefield, last_name=lastnamefield)
                        anonymous_creator.set_password(password)
                        anonymous_creator.is_active = False
                        anonymous_creator.save()
                        anonymous_profile = Profile(user=anonymous_creator, owner=anonymous_creator,
                                                    creator=anonymous_creator, phone=phonefield)
                        anonymous_profile.save()
                    entry.creator = anonymous_creator
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To':form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=True)

            # Email copies to admin
            admin_body = generate_admin_email_body(entry, form_for_form)
            email_from = email_to or email_from # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To':email_from})
            email_copies = [e.strip() for e in form.email_copies.split(',') if e.strip()]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            
            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                try:
                    for f in form_for_form.files.values():
                        f.seek(0)
                        attachments.append((f.name, f.read()))
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                            try:
                                f = default_storage.open(field_entry.value)
                            except IOError:
                                pass
                            else:
                                f.seek(0)
                                attachments.append((f.name.split('/')[-1], f.read()))

                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    email.send(fail_silently=True, attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=True, attachments=attachments)

            # payment redirect
            if (form.custom_payment or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get('custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous():
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                             user=rp_user,
                             description=form.title,
                             billing_period=entry.pricing.billing_period,
                             billing_start_dt=billing_start_dt,
                             num_days=entry.pricing.num_days,
                             due_sore=entry.pricing.due_sore,
                             payment_amount=price,
                             taxable=entry.pricing.taxable,
                             tax_rate=entry.pricing.tax_rate,
                             has_trial_period=entry.pricing.has_trial_period,
                             trial_period_start_dt=trial_period_start_dt,
                             trial_period_end_dt=trial_period_end_dt,
                             trial_amount=entry.pricing.trial_amount,
                             creator=rp_user,
                             creator_username=rp_user.username,
                             owner=rp_user,
                             owner_username=rp_user.username,
                         )
                    rp.save()
                    rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS, 'Successful transaction.')
                    return redirect('recurring_payment.view_account', rp.id, rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)
                    # log an event for invoice add

                    EventLog.objects.log(instance=form)

                    # redirect to billing form
                    return redirect('form_entry_payment', invoice.id, invoice.guid)

            # default redirect
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url)
            return redirect("form_sent", form.slug)
    # set form's template to default if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "default.html"
    context = {
        "form": form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 4
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user, 'forms.view_form', form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(
            field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous() and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(request, messages.WARNING,
                    'Please edit the form to include an email field ' + \
                    'as it is required for setting up a recurring ' + \
                    'payment for anonymous users.')

    form_for_form = FormForForm(form, request.user, request.POST or None,
                                request.FILES or None)
    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid():
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous():
                if entry.get_email_address():
                    emailfield = entry.get_email_address()
                    firstnamefield = entry.get_first_name()
                    lastnamefield = entry.get_last_name()
                    phonefield = entry.get_phone_number()
                    password = ''
                    for i in range(0, 10):
                        password += random.choice(string.ascii_lowercase +
                                                  string.ascii_uppercase)

                    user_list = User.objects.filter(
                        email=emailfield).order_by('-last_login')
                    if user_list:
                        anonymous_creator = user_list[0]
                    else:
                        anonymous_creator = User(username=emailfield[:30],
                                                 email=emailfield,
                                                 first_name=firstnamefield,
                                                 last_name=lastnamefield)
                        anonymous_creator.set_password(password)
                        anonymous_creator.is_active = False
                        anonymous_creator.save()
                        anonymous_profile = Profile(user=anonymous_creator,
                                                    owner=anonymous_creator,
                                                    creator=anonymous_creator,
                                                    phone=phonefield)
                        anonymous_profile.save()
                    entry.creator = anonymous_creator
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To': form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(
                entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=True)

            # Email copies to admin
            admin_body = generate_admin_email_body(entry, form_for_form)
            email_from = email_to or email_from  # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To': email_from})
            email_copies = [
                e.strip() for e in form.email_copies.split(',') if e.strip()
            ]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                try:
                    for f in form_for_form.files.values():
                        f.seek(0)
                        attachments.append((f.name, f.read()))
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                            try:
                                f = default_storage.open(field_entry.value)
                            except IOError:
                                pass
                            else:
                                f.seek(0)
                                attachments.append(
                                    (f.name.split('/')[-1], f.read()))

                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    email.send(fail_silently=True, attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=True, attachments=attachments)

            # payment redirect
            if (form.custom_payment
                    or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get(
                    'custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous():
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(
                            1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                        user=rp_user,
                        description=form.title,
                        billing_period=entry.pricing.billing_period,
                        billing_start_dt=billing_start_dt,
                        num_days=entry.pricing.num_days,
                        due_sore=entry.pricing.due_sore,
                        payment_amount=price,
                        taxable=entry.pricing.taxable,
                        tax_rate=entry.pricing.tax_rate,
                        has_trial_period=entry.pricing.has_trial_period,
                        trial_period_start_dt=trial_period_start_dt,
                        trial_period_end_dt=trial_period_end_dt,
                        trial_amount=entry.pricing.trial_amount,
                        creator=rp_user,
                        creator_username=rp_user.username,
                        owner=rp_user,
                        owner_username=rp_user.username,
                    )
                    rp.save()
                    rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS,
                                         'Successful transaction.')
                    return redirect('recurring_payment.view_account', rp.id,
                                    rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)
                    # log an event for invoice add

                    EventLog.objects.log(instance=form)

                    # redirect to billing form
                    return redirect('form_entry_payment', invoice.id,
                                    invoice.guid)

            # default redirect
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url)
            return redirect("form_sent", form.slug)
    # set form's template to default if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "default.html"
    context = {
        "form": form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 5
0
def message(request, group_slug, template_name='user_groups/message.html'):
    """
    Send a message to the group
    """
    from tendenci.core.emails.models import Email

    group = get_object_or_404(Group, slug=group_slug)
    EventLog.objects.log(instance=group)

    members = GroupMembership.objects.filter(
        group=group,
        status=True,
        status_detail='active')

    num_members = members.count()

    form = MessageForm(request.POST or None,
        request=request,
        num_members=num_members)


    if request.method == 'POST' and form.is_valid():

        email = Email()
        email.sender_display = request.user.get_full_name()
        email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        email.reply_to = email.sender
        email.content_type = 'text/html'
        email.subject = form.cleaned_data['subject']
        email.body = form.cleaned_data['body']
        email.save(request.user)

        # send email to myself (testing email)
        if form.cleaned_data['is_test']:
            email.recipient = request.user.email
            email.send()

            messages.add_message(
                request,
                messages.SUCCESS,
                'Successfully sent test email to yourself')

            EventLog.objects.log(instance=email)

        else:
            # send email to members
            for member in members:
                email.recipient = member.member.email
                email.send()

            messages.add_message(
                request,
                messages.SUCCESS,
                'Successfully sent email to all %s members in this group' % num_members)

            EventLog.objects.log(instance=email)
    else:
        print 'form errors', form.errors.items()


    return render(request, template_name, {
        'group': group,
        'num_members': num_members,
        'form': form})
    def handle(self, *args, **options):
        verbosity = 1
        if 'verbosity' in options:
            verbosity = options['verbosity']

        from django.conf import settings
        from tendenci.addons.memberships.models import (Notice,
                                                        MembershipDefault,
                                                        NoticeLog,
                                                        NoticeDefaultLogRecord)
        from tendenci.core.base.utils import fieldify
        from tendenci.core.emails.models import Email
        from tendenci.core.site_settings.utils import get_setting

        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        site_contact_name = get_setting('site', 'global', 'sitecontactname')
        site_contact_email = get_setting('site', 'global', 'sitecontactemail')
        site_url = get_setting('site', 'global', 'siteurl')

        corp_replace_str = """
                            <br /><br />
                            <font color="#FF0000">
                            Organizational Members, please contact your company
                            Membership coordinator
                            to ensure that your membership is being renewed.
                            </font>
                            """

        email = Email()
        email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        email.sender_display = site_display_name
        email.reply_to = site_contact_email

        now = datetime.now()
        nowstr = time.strftime("%d-%b-%y %I:%M %p", now.timetuple())

        def email_admins_recap(notices, total_sent):
            """Send admins recap after the notices were processed.
            """
            email.recipient = get_admin_emails()
            if email.recipient:
                template_name = "memberships/notices/email_recap.html"
                try:
                    recap_email_content = render_to_string(
                               template_name,
                               {'notices': notices,
                              'total_sent': total_sent,
                              'site_url': site_url,
                              'site_display_name': site_display_name,
                              'site_contact_name': site_contact_name,
                              'site_contact_email': site_contact_email})
                    email.body = recap_email_content
                    email.content_type = "html"
                    email.subject = '%s Membership Notices Distributed' % (
                                                    site_display_name)

                    email.send()
                except TemplateDoesNotExist:
                    pass

        def email_script_errors(err_msg):
            """Send error message to us if any.
            """
            email.recipient = get_script_support_emails()
            if email.recipient:
                email.body = '%s \n\nTime Submitted: %s\n' % (err_msg, nowstr)
                email.content_type = "text"
                email.subject = 'Error Processing Membership Notices on %s' % (
                                                            site_url)

                email.send()

        def get_script_support_emails():
            admins = getattr(settings, 'ADMINS', None)
            if admins:
                recipients_list = [admin[1] for admin in admins]
                return ','.join(recipients_list)

            return None

        def get_admin_emails():
            admin_emails = get_setting('module', 'memberships',
                                       'membershiprecipients').strip()
            if admin_emails:
                admin_emails = admin_emails.split(',')
            if not admin_emails:
                admin_emails = (get_setting('site', 'global',
                                            'admincontactemail'
                                            ).strip()).split(',')

            if admin_emails:
                admin_emails = ','.join(admin_emails)
            return admin_emails

        def process_notice(notice):
            notice.members_sent = []
            num_sent = 0
            if notice.notice_time == 'before':
                start_dt = now + timedelta(days=notice.num_days)
            else:
                start_dt = now - timedelta(days=notice.num_days)

            if notice.notice_type == 'disapprove':
                status_detail_list = ['disapproved']
            else:
                status_detail_list = ['active', 'expired']
            memberships = MembershipDefault.objects.filter(
                                    status=True,
                                    status_detail__in=status_detail_list
                                    )
            if notice.notice_type == 'join':
                memberships = memberships.filter(
                                    join_dt__year=start_dt.year,
                                    join_dt__month=start_dt.month,
                                    join_dt__day=start_dt.day,
                                    renewal=False)
            elif notice.notice_type == 'renewal':
                memberships = memberships.filter(
                                    renew_dt__year=start_dt.year,
                                    renew_dt__month=start_dt.month,
                                    renew_dt__day=start_dt.day,
                                    renewal=True)
            elif notice.notice_type == 'approve':
                memberships = memberships.filter(
                                    application_approved_denied_dt__year=start_dt.year,
                                    application_approved_denied_dt__month=start_dt.month,
                                    application_approved_denied_dt__day=start_dt.day,
                                    application_approved=True)
            elif notice.notice_type == 'disapprove':
                memberships = memberships.filter(
                                    application_approved_denied_dt__year=start_dt.year,
                                    application_approved_denied_dt__month=start_dt.month,
                                    application_approved_denied_dt__day=start_dt.day,
                                    application_approved=False)
            else:  # 'expire'
                memberships = memberships.filter(
                                    expire_dt__year=start_dt.year,
                                    expire_dt__month=start_dt.month,
                                    expire_dt__day=start_dt.day)

            # filter by membership type
            if notice.membership_type:
                memberships = memberships.filter(
                                membership_type=notice.membership_type)

            memberships_count = memberships.count()

            if memberships_count > 0:
                email.content_type = notice.content_type

                # password
                passwd_str = """
                        If you've forgotten your password or need to reset
                        the auto-generated one, click <a href="%s%s">here</a>
                        and follow the instructions on the page to
                        reset your password.
                        """ % (site_url, reverse('auth_password_reset'))

                global_context = {'sitedisplayname': site_display_name,
                                  'sitecontactname': site_contact_name,
                                  'sitecontactemail': site_contact_email,
                                  'timesubmitted': nowstr,
                                  'password': passwd_str
                                  }

                # log notice sent
                notice_log = NoticeLog(notice=notice,
                                       num_sent=0)
                notice_log.save()
                notice.log = notice_log
                notice.err = ''

                for membership in memberships:
                    try:
                        email_member(notice, membership, global_context)
                        if memberships_count <= 50:
                            notice.members_sent.append(membership)
                        num_sent += 1

                        # log record
                        notice_log_record = NoticeDefaultLogRecord(
                                                notice_log=notice_log,
                                                membership=membership)
                        notice_log_record.save()
                    except:
                        # catch the exception and email
                        notice.err += traceback.format_exc()
                        print traceback.format_exc()

                if num_sent > 0:
                    notice_log.num_sent = num_sent
                    notice_log.save()

            return num_sent

        def email_member(notice, membership, global_context):
            user = membership.user

            body = notice.email_content
            context = membership.get_field_items()
            context['membership'] = membership
            context.update(global_context)

            # memberships page ------------
            memberships_page = "%s%s" % \
                (site_url, reverse('profile', args=[membership.user]))

            body = body.replace("[membershiptypeid]",
                                str(membership.membership_type.id))
            body = body.replace("[membershiplink]",
                                '%s' % memberships_page)

            body = body.replace("[renewlink]", memberships_page)

            if membership.expire_dt:
                body = body.replace("[expirationdatetime]",
                                    time.strftime(
                                      "%d-%b-%y %I:%M %p",
                                      membership.expire_dt.timetuple()))
            else:
                body = body.replace("[expirationdatetime]", '')

            # corporate member corp_replace_str
            if membership.corporate_membership_id:
                body = body.replace("<!--[corporatemembernotice]-->",
                                    corp_replace_str)
            else:
                body = body.replace("<!--[corporatemembernotice]-->", "")

            context.update({'membershiptypeid':
                                str(membership.membership_type.id),
                            'membershiplink': memberships_page,
                            'renewlink': memberships_page,
                            'membernumber': membership.member_number,
                            'membershiptype': membership.membership_type.name,
                            })
            if membership.expire_dt:
                context['expirationdatetime'] = time.strftime(
                                            "%d-%b-%y %I:%M %p",
                                            membership.expire_dt.timetuple())

            # corporate member corp_replace_str
            if membership.corporate_membership_id:
                context['corporatemembernotice'] = corp_replace_str

            body = fieldify(body)

            body = '%s <br /><br />%s' % (body, get_footer())

            context = Context(context)
            template = Template(body)
            body = template.render(context)

            email.recipient = user.email
            subject = notice.subject.replace('(name)',
                                        user.get_full_name())
            template = Template(subject)
            subject = template.render(context)

            email.subject = subject
            email.body = body
            if notice.sender:
                email.sender = notice.sender
                email.reply_to = notice.sender
            if notice.sender_display:
                email.sender_display = notice.sender_display

            email.send()
            if verbosity > 1:
                print 'To ', email.recipient, email.subject

        def get_footer():
            return """
                    This e-mail was generated by Tendenci&reg; Software -
                    a web based membership management software solution
                    www.tendenci.com developed by Schipul - The Web
                    Marketing Company
                    """

        exception_str = ""

        notices = Notice.objects.filter(status=True, status_detail='active'
                                    ).exclude(notice_time='attimeof')

        if notices:
            if verbosity > 1:
                print "Start sending out notices to members:"
            total_notices = 0
            total_sent = 0
            for notice in notices:
                total_notices += 1
                total_sent += process_notice(notice)
                if hasattr(notice, 'err'):
                    exception_str += notice.err

            if total_sent > 0:
                processed_notices = [notice for notice in notices if hasattr(
                                        notice, 'log'
                                        ) and notice.log.num_sent > 0]
                email_admins_recap(processed_notices, total_sent)

            # if there is any error, notify us
            if exception_str:
                email_script_errors(exception_str)

            if verbosity > 1:
                print 'Total notice processed: %d' % (total_notices)
                print 'Total email sent: %d' % (total_sent)
                print "Done"
        else:
            if verbosity > 1:
                print "No notices on the site."
Ejemplo n.º 7
0
def message(request, group_slug, template_name='user_groups/message.html'):
    """
    Send a message to the group
    """
    from tendenci.core.emails.models import Email

    group = get_object_or_404(Group, slug=group_slug)
    EventLog.objects.log(instance=group)

    members = GroupMembership.objects.filter(group=group,
                                             status=True,
                                             status_detail='active')

    num_members = members.count()

    form = MessageForm(request.POST or None,
                       request=request,
                       num_members=num_members)

    if request.method == 'POST' and form.is_valid():

        email = Email()
        email.sender_display = request.user.get_full_name()
        email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        email.reply_to = email.sender
        email.content_type = 'text/html'
        email.subject = form.cleaned_data['subject']
        email.body = form.cleaned_data['body']
        email.save(request.user)

        # send email to myself (testing email)
        if form.cleaned_data['is_test']:
            email.recipient = request.user.email
            email.send()

            messages.add_message(request, messages.SUCCESS,
                                 _('Successfully sent test email to yourself'))

            EventLog.objects.log(instance=email)

        else:
            # send email to members
            for member in members:
                email.recipient = member.member.email
                email.send()

            messages.add_message(
                request, messages.SUCCESS,
                _('Successfully sent email to all %(num)s members in this group'
                  % {'num': num_members}))

            EventLog.objects.log(instance=email)

        return redirect('group.detail', group_slug=group_slug)

    else:
        print 'form errors', form.errors.items()

    return render(request, template_name, {
        'group': group,
        'num_members': num_members,
        'form': form
    })
Ejemplo n.º 8
0
    def handle(self, *args, **options):
        verbosity = 1
        if 'verbosity' in options:
            verbosity = options['verbosity']
        # first test if we have notices set up
        from tendenci.addons.corporate_memberships.models import Notice
        if not Notice.objects.filter(status=True,
                                     status_detail='active'
                                    ).exclude(
                                    notice_time='attimeof'
                                    ).exists():
            if verbosity > 1:
                print('No notices set up...existing...')
            # no active notices to process. stop here
            return

        from tendenci.addons.corporate_memberships.models import (
            CorpMembership,
            NoticeLog,
            NoticeLogRecord)
        from tendenci.core.base.utils import fieldify
        from tendenci.core.emails.models import Email
        from tendenci.core.site_settings.utils import get_setting

        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        site_contact_name = get_setting('site', 'global', 'sitecontactname')
        site_contact_email = get_setting('site', 'global', 'sitecontactemail')
        site_url = get_setting('site', 'global', 'siteurl')

        email = Email()
        email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        email.sender_display = site_display_name
        email.reply_to = site_contact_email

        now = datetime.now()
        nowstr = time.strftime("%d-%b-%y %I:%M %p", now.timetuple())

        def email_admins_recap(notices, total_sent):
            """Send admins recap after the notices were processed.
            """
            email.recipient = get_admin_emails()
            if email.recipient:
                template_name = "corporate_memberships/notices/email_recap.html"
                try:
                    recap_email_content = render_to_string(
                               template_name,
                               {'notices': notices,
                              'total_sent': total_sent,
                              'site_url': site_url,
                              'site_display_name': site_display_name,
                              'site_contact_name': site_contact_name,
                              'site_contact_email': site_contact_email})
                    email.body = recap_email_content
                    email.content_type = "html"
                    email.subject = '%s Corporate Membership Notices Distributed' % (
                                                    site_display_name)
                    email.send()
                except TemplateDoesNotExist:
                    pass

        def email_script_errors(err_msg):
            """Send error message to us if any.
            """
            email.recipient = get_script_support_emails()
            if email.recipient:
                email.body = '%s \n\nTime Submitted: %s\n' % (err_msg, nowstr)
                email.content_type = "text"
                email.subject = 'Error Processing Corporate Membership Notices on %s' % (
                                                            site_url)
                email.send()

        def get_script_support_emails():
            admins = getattr(settings, 'ADMINS', None)
            if admins:
                recipients_list = [admin[1] for admin in admins]
                return ','.join(recipients_list)
            return None

        def get_admin_emails():
            admin_emails = get_setting('module', 'corporate_memberships',
                                       'corporatemembershiprecipients').strip()
            if admin_emails:
                admin_emails = admin_emails.split(',')
            if not admin_emails:
                admin_emails = (get_setting('site', 'global',
                                            'admincontactemail'
                                            ).strip()).split(',')
            if admin_emails:
                admin_emails = ','.join(admin_emails)
            return admin_emails

        def process_notice(notice):
            notice.members_sent = []
            num_sent = 0
            if notice.notice_time == 'before':
                start_dt = now + timedelta(days=notice.num_days)
            else:
                start_dt = now - timedelta(days=notice.num_days)

            if notice.notice_type == 'disapprove':
                status_detail_list = ['inactive']
            else:
                status_detail_list = ['active', 'expired']

            memberships = CorpMembership.objects.filter(
                                    status=True,
                                    status_detail__in=status_detail_list
                                    )
            if notice.notice_type in ['approve_join', 'disapprove_join'
                                      'approve_renewal', 'disapprove_renewal']:
                filters = {'approved_denied_dt__year': start_dt.year,
                           'approved_denied_dt__month': start_dt.month,
                           'approved_denied_dt__day': start_dt.day,
                           'renewal': False,
                           'approved': True
                           }
                if notice.notice_type in ['approve_renewal',
                                          'disapprove_renewal']:
                    filters.update({'renewal': True})
                if notice.notice_type in ['disapprove_join',
                                          'disapprove_renewal']:
                    filters.update({'approved': False})

                memberships = memberships.filter(**filters)
            else:  # 'expire'
                memberships = memberships.filter(
                    expiration_dt__year=start_dt.year,
                    expiration_dt__month=start_dt.month,
                    expiration_dt__day=start_dt.day)

            # filter by membership type
            if notice.corporate_membership_type:
                memberships = memberships.filter(
                                corporate_membership_type=notice.corporate_membership_type)

            memberships_count = memberships.count()

            if memberships_count > 0:
                email.content_type = notice.content_type

                global_context = {'site_display_name': site_display_name,
                                  'site_contact_name': site_contact_name,
                                  'site_contact_email': site_contact_email,
                                  'time_submitted': nowstr,
                                  }

                # log notice sent
                notice_log = NoticeLog(notice=notice,
                                       num_sent=0)
                notice_log.save()
                notice.log = notice_log
                notice.err = ''

                for membership in memberships:
                    try:
                        num_sent += email_member(notice, membership, global_context)
                        if memberships_count <= 50:
                            notice.members_sent.append(membership)

                        # log record
                        notice_log_record = NoticeLogRecord(
                            notice_log=notice_log,
                            corp_membership=membership)
                        notice_log_record.save()
                    except:
                        # catch the exception and email
                        notice.err += traceback.format_exc()
                        print traceback.format_exc()

                if num_sent > 0:
                    notice_log.num_sent = num_sent
                    notice_log.save()

            return num_sent

        def email_member(notice, membership, global_context):
            corp_profile = membership.corp_profile

            representatives = corp_profile.reps.filter(Q(is_dues_rep=True)|(Q(is_member_rep=True)))
            sent = 0

            for recipient in representatives:
                body = notice.email_content
                context = membership.get_field_items()
                context['membership'] = membership
                context.update(global_context)

                context.update({
                    'rep_first_name': recipient.user.first_name,
                })

                if membership.expiration_dt:
                    body = body.replace("[expirationdatetime]",
                                        time.strftime(
                                          "%d-%b-%y %I:%M %p",
                                          membership.expiration_dt.timetuple()))
                else:
                    body = body.replace("[expirationdatetime]", '')

                context.update({
                    'corporatemembershiptypeid': str(membership.corporate_membership_type.id),
                    'corporatemembershiptype': membership.corporate_membership_type.name,
                    'view_link': "%s%s" % (site_url, membership.get_absolute_url()),
                    'renew_link': "%s%s" % (site_url, membership.get_renewal_url()),
                    'renewed_individuals_list': render_to_string(('notification/corp_memb_notice_email/renew_list.html'),
                                                             {'corp_membership': membership, }),
                })

                body = fieldify(body)

                body = '%s <br /><br />%s' % (body, get_footer())

                context = Context(context)
                template = Template(body)
                body = template.render(context)

                email.recipient = recipient.user.email
                subject = notice.subject.replace('(name)',
                                            corp_profile.name)
                template = Template(subject)
                subject = template.render(context)

                email.subject = subject
                email.body = body
                if notice.sender:
                    email.sender = notice.sender
                    email.reply_to = notice.sender
                if notice.sender_display:
                    email.sender_display = notice.sender_display

                email.send()
                sent += 1
                if verbosity > 1:
                    print 'To ', email.recipient, email.subject
            return sent

        def get_footer():
            return """
                    This e-mail was generated by Tendenci&reg; Software -
                    a web based membership management software solution
                    www.tendenci.com developed by Schipul - The Web
                    Marketing Company
                    """

        exception_str = ""

        notices = Notice.objects.filter(status=True, status_detail='active'
                                    ).exclude(notice_time='attimeof')

        if notices:
            if verbosity > 1:
                print "Start sending out notices to members:"
            total_notices = 0
            total_sent = 0
            for notice in notices:
                total_notices += 1
                total_sent += process_notice(notice)
                if hasattr(notice, 'err'):
                    exception_str += notice.err

            if total_sent > 0:
                processed_notices = [notice for notice in notices if hasattr(
                                        notice, 'log'
                                        ) and notice.log.num_sent > 0]
                email_admins_recap(processed_notices, total_sent)

            # if there is any error, notify us
            if exception_str:
                email_script_errors(exception_str)

            if verbosity > 1:
                print 'Total notice processed: %d' % (total_notices)
                print 'Total email sent: %d' % (total_sent)
                print "Done"
        else:
            if verbosity > 1:
                print "No notices on the site."
Ejemplo n.º 9
0
    def handle(self, *args, **options):
        verbosity = 1
        if 'verbosity' in options:
            verbosity = options['verbosity']
            
        from django.conf import settings
        from tendenci.addons.memberships.models import Notice, Membership, NoticeLog, NoticeLogRecord
        from tendenci.core.base.utils import fieldify
        from tendenci.core.emails.models import Email
        from tendenci.apps.profiles.models import Profile
        from tendenci.core.site_settings.utils import get_setting
        
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        site_contact_name = get_setting('site', 'global', 'sitecontactname')
        site_contact_email = get_setting('site', 'global', 'sitecontactemail')
        site_url = get_setting('site', 'global', 'siteurl')
        
        corp_replace_str = """
                            <br /><br />
                            <font color="#FF0000">
                            Organizational Members, please contact your company Membership coordinator
                            to ensure that your membership is being renewed.
                            </font>
                            """
        
        email = Email()
        email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        email.sender_display = site_display_name
        email.reply_to = site_contact_email
        
        now = datetime.now()
        nowstr = time.strftime("%d-%b-%y %I:%M %p", now.timetuple())
        
        def email_admins_recap(notices, total_sent):
            """Send admins recap after the notices were processed.
            """
            email.recipient = get_admin_emails()
            if email.recipient:
                template_name = "memberships/notices/email_recap.html"
                try:
                    recap_email_content = render_to_string(template_name, {'notices':notices,
                                                                      'total_sent':total_sent,
                                                                      'site_url': site_url,
                                                                      'site_display_name': site_display_name,
                                                                      'site_contact_name': site_contact_name,
                                                                      'site_contact_email': site_contact_email})
                    email.body = recap_email_content
                    email.content_type = "html"
                    email.subject = '%s Membership Notices Distributed' % site_display_name
                    
                    email.send()
                except TemplateDoesNotExist:
                    pass
        
        def email_script_errors(err_msg):
            """Send error message to us if any.
            """
            email.recipient = get_script_support_emails()
            if email.recipient:
                email.body = '%s \n\nTime Submitted: %s\n' % (err_msg, nowstr)
                email.content_type = "text"
                email.subject = 'Error Processing Membership Notices on %s' % site_url
                
                email.send()
        
        def get_script_support_emails():
            admins = getattr(settings, 'ADMINS', None) 
            if admins:
                recipients_list = [admin[1] for admin in admins]
                return ','.join(recipients_list)
            
            return None
        
        def get_admin_emails():
            admin_emails = get_setting('module', 'memberships', 'membershiprecipients').strip()
            if admin_emails:
                admin_emails = admin_emails.split(',')
            if not user.profile.is_superuser_emails:
                admin_emails = (get_setting('site', 'global', 'admincontactemail').strip()).split(',')
                
            if admin_emails:
                admin_emails = ','.join(admin_emails)
            return admin_emails
            
            
        
        def process_notice(notice):
            notice.members_sent = []
            num_sent = 0
            if notice.notice_time == 'before':
                start_dt = now + timedelta(days=notice.num_days)
            else:
                start_dt = now - timedelta(days=notice.num_days)
            
            memberships = Membership.objects.active()
            if notice.notice_type == 'join':
                memberships = memberships.filter(subscribe_dt__year=start_dt.year,
                                                subscribe_dt__month=start_dt.month,
                                                subscribe_dt__day=start_dt.day,
                                                renewal=False)
            elif notice.notice_type == 'renew':
                memberships = memberships.filter(subscribe_dt__year=start_dt.year,
                                                subscribe_dt__month=start_dt.month,
                                                subscribe_dt__day=start_dt.day,
                                                renewal=True)
            else: # 'expire'
                memberships = memberships.filter(expire_dt__year=start_dt.year,
                                                expire_dt__month=start_dt.month,
                                                expire_dt__day=start_dt.day)
                
            # filter by membership type
            if notice.membership_type:
                memberships = memberships.filter(membership_type=notice.membership_type)
                
            if memberships:
                email.content_type = notice.content_type
                
                # password
                passwd_str = """
                            If you've forgotten your password or need to reset the auto-generated one,
                            click <a href="%s%s">here</a> and follow the instructions on the page to 
                            reset your password.
                            """ % (site_url, reverse('auth_password_reset'))
#                notice.email_content = notice.email_content.replace("[password]", passwd_str)
                
                global_context = {'sitedisplayname': site_display_name,
                                  'sitecontactname': site_contact_name,
                                  'sitecontactemail': site_contact_email,
                                  'timesubmitted': nowstr,
                                  'password': passwd_str
                                  }
                
                
                # log notice sent
                notice_log = NoticeLog(notice=notice,
                                       num_sent=0)
                notice_log.save()
                notice.log = notice_log
                notice.err = ''
                
                memberships_count = memberships.count()
                
                for membership in memberships:
                    try:
                        email_member(notice, membership, global_context)
                        if memberships_count <= 50:
                            notice.members_sent.append(membership)
                        num_sent += 1
                        
                        # log record
                        notice_log_record = NoticeLogRecord(notice_log=notice_log,
                                                            membership=membership)
                        notice_log_record.save()
                    except:
                        # catch the exception and email
                        notice.err += traceback.format_exc()
                        
                if num_sent > 0:
                    notice_log.num_sent = num_sent
                    notice_log.save()
                    
            return num_sent    
            
        def email_member(notice, membership, global_context):
            user = membership.user

            body = notice.email_content
            context = membership.entry_items
            context.update(global_context)
            
            body = body.replace("[membershiptypeid]", str(membership.membership_type.id))
            body = body.replace("[membershiplink]", '%s%s' % (site_url, membership.get_absolute_url()))

            # memberships page ------------
            memberships_page = "%s%s%s" % \
                (site_url, reverse('profile', args=[membership.user]), "#userview-memberships")
            body = body.replace("[renewlink]", memberships_page)

            if membership.expire_dt:
                body = body.replace("[expirationdatetime]", 
                                    time.strftime("%d-%b-%y %I:%M %p", membership.expire_dt.timetuple()))
            else:
                body = body.replace("[expirationdatetime]", '')
                
            # corporate member corp_replace_str
            if membership.corporate_membership_id:
                body = body.replace("<!--[corporatemembernotice]-->", corp_replace_str)
            else:
                body = body.replace("<!--[corporatemembernotice]-->", "")
                
                
            context.update({'membershiptypeid': str(membership.membership_type.id),
                            'membershiplink': '%s%s' % (site_url, membership.get_absolute_url()),
                            'renewlink': memberships_page,
                            'membernumber': membership.member_number,
                            'membershiptype': membership.membership_type.name,
                            })
            if membership.expire_dt:
                context['expirationdatetime'] = time.strftime("%d-%b-%y %I:%M %p", 
                                                    membership.expire_dt.timetuple())
                
            # corporate member corp_replace_str
            if membership.corporate_membership_id:
                context['corporatemembernotice'] =  corp_replace_str
           
            body = fieldify(body)
                
            body = '%s <br /><br />%s' % (body, get_footer())
            
            context = Context(context)
            template = Template(body)
            body = template.render(context)
            
            email.recipient = user.email
            email.subject = notice.subject.replace('(name)', user.get_full_name())
            email.body = body
            if notice.sender:
                email.sender = notice.sender
                email.reply_to = notice.sender
            if notice.sender_display:
                email.sender_display = notice.sender_display
                
            email.send()
            if verbosity > 1:
                print 'To ', email.recipient, email.subject
            
                
        def get_footer():
            return """
                    This e-mail was generated by Tendenci&reg; Software - a 
                    web based membership management software solution 
                    www.tendenci.com developed by Schipul - The Web Marketing Company
                    """   
                    
                    
        
        exception_str = ""
        
        notices = Notice.objects.filter(status=True, status_detail='active').exclude(notice_time='attimeof')
        
        if notices:
            if verbosity > 1:
                print "Start sending out notices to members:"
            total_notices = 0
            total_sent = 0
            for notice in notices:
                total_notices += 1
                total_sent += process_notice(notice)
                if hasattr(notice, 'err'):
                    exception_str += notice.err
                
            if total_sent > 0:
                processed_notices = [notice for notice in notices if hasattr(notice, 'log') and notice.log.num_sent>0]
                email_admins_recap(processed_notices, total_sent)
              
            # if there is any error, notify us  
            if exception_str:
                email_script_errors(exception_str)
                
            if verbosity > 1:
                print 'Total notice processed: %d' % (total_notices)
                print 'Total email sent: %d' % (total_sent)
                print "Done"
        else:
            if verbosity > 1:
                print "No notices on the site."
Ejemplo n.º 10
0
    def handle(self, *args, **options):
        from tendenci.addons.events.models import Event, Registrant, Organizer
        from tendenci.core.emails.models import Email
        from tendenci.core.site_settings.utils import get_setting
        from tendenci.core.base.utils import convert_absolute_urls
        from tendenci.addons.events.utils import (render_event_email,
                                  get_default_reminder_template)

        verbosity = options['verbosity']
        site_url = get_setting('site', 'global', 'siteurl')
        now = datetime.now()
        today_tuple = (datetime(now.year, now.month, now.day, 0, 0, 0),
                       datetime(now.year, now.month, now.day, 23, 59, 59))

        # get a list of upcoming events that are specified to send reminders.
        events = Event.objects.filter(start_dt__gt=now,
                                registration_configuration__enabled=True,
                                registration_configuration__send_reminder=True,
                                status=True,
                                status_detail='active')
        events_list = []

        if events:
            for event in events:
                reg_conf = event.registration_configuration
                reminder_days = reg_conf.reminder_days
                if not reminder_days:
                    reminder_days = '1'
                days_list = reminder_days.split(',')

                for day in days_list:
                    try:
                        day = int(day)
                    except:
                        continue

                    start_dt = event.start_dt - timedelta(days=day)

                    if today_tuple[0] <= start_dt and start_dt <= today_tuple[1]:
                        events_list.append(event)

                        break

            for event in events_list:
                registrants = Registrant.objects.filter(
                                reminder=True,
                                registration__event=event,
                                cancel_dt=None
                                )

                reg_conf = event.registration_configuration
                [organizer] = Organizer.objects.filter(event=event)[:1] or [None]
                event.organizer = organizer

                email = reg_conf.email
                if not email:
                    email = Email()

                if not email.sender_display:
                    if organizer.name:
                        email.sender_display = organizer.name

                if not email.reply_to:
                    if organizer.user and organizer.user.email:
                        email.reply_to = organizer.user.email

                if not email.subject:
                    email.subject = 'Reminder: %s' % event.title
                else:
                    email.subject = 'Reminder: %s' % email.subject

                if not email.body:
                    email.body = get_default_reminder_template(event)

                email = render_event_email(event, email)

                # replace the relative links with absolute urls
                # in the email body and subject
                email.body = convert_absolute_urls(email.body, site_url)

                event.email = email
                self.send_reminders(event, registrants, verbosity=verbosity)
    def handle(self, *args, **options):
        verbosity = 1
        if "verbosity" in options:
            verbosity = options["verbosity"]
        # first test if we have notices set up
        from tendenci.addons.corporate_memberships.models import Notice

        if not Notice.objects.filter(status=True, status_detail="active").exclude(notice_time="attimeof").exists():
            if verbosity > 1:
                print ("No notices set up...existing...")
            # no active notices to process. stop here
            return

        from tendenci.addons.corporate_memberships.models import CorpMembership, NoticeLog, NoticeLogRecord
        from tendenci.core.base.utils import fieldify
        from tendenci.core.emails.models import Email
        from tendenci.core.site_settings.utils import get_setting

        site_display_name = get_setting("site", "global", "sitedisplayname")
        site_contact_name = get_setting("site", "global", "sitecontactname")
        site_contact_email = get_setting("site", "global", "sitecontactemail")
        site_url = get_setting("site", "global", "siteurl")

        email = Email()
        email.sender = get_setting("site", "global", "siteemailnoreplyaddress")
        email.sender_display = site_display_name
        email.reply_to = site_contact_email

        now = datetime.now()
        nowstr = time.strftime("%d-%b-%y %I:%M %p", now.timetuple())

        def email_admins_recap(notices, total_sent):
            """Send admins recap after the notices were processed.
            """
            email.recipient = get_admin_emails()
            if email.recipient:
                template_name = "corporate_memberships/notices/email_recap.html"
                try:
                    recap_email_content = render_to_string(
                        template_name,
                        {
                            "notices": notices,
                            "total_sent": total_sent,
                            "site_url": site_url,
                            "site_display_name": site_display_name,
                            "site_contact_name": site_contact_name,
                            "site_contact_email": site_contact_email,
                        },
                    )
                    email.body = recap_email_content
                    email.content_type = "html"
                    email.subject = "%s Corporate Membership Notices Distributed" % (site_display_name)
                    email.send()
                except TemplateDoesNotExist:
                    pass

        def email_script_errors(err_msg):
            """Send error message to us if any.
            """
            email.recipient = get_script_support_emails()
            if email.recipient:
                email.body = "%s \n\nTime Submitted: %s\n" % (err_msg, nowstr)
                email.content_type = "text"
                email.subject = "Error Processing Corporate Membership Notices on %s" % (site_url)
                email.send()

        def get_script_support_emails():
            admins = getattr(settings, "ADMINS", None)
            if admins:
                recipients_list = [admin[1] for admin in admins]
                return ",".join(recipients_list)
            return None

        def get_admin_emails():
            admin_emails = get_setting("module", "corporate_memberships", "corporatemembershiprecipients").strip()
            if admin_emails:
                admin_emails = admin_emails.split(",")
            if not admin_emails:
                admin_emails = (get_setting("site", "global", "admincontactemail").strip()).split(",")
            if admin_emails:
                admin_emails = ",".join(admin_emails)
            return admin_emails

        def process_notice(notice):
            notice.members_sent = []
            num_sent = 0
            if notice.notice_time == "before":
                start_dt = now + timedelta(days=notice.num_days)
            else:
                start_dt = now - timedelta(days=notice.num_days)

            memberships = CorpMembership.objects.filter(status=True, status_detail__in=["active", "expired"])
            if notice.notice_type in ["approve_join", "disapprove_join"]:
                memberships = memberships.filter(
                    approved_denied_dt__year=start_dt.year,
                    approved_denied_dt__month=start_dt.month,
                    approved_denied_dt__day=start_dt.day,
                    renewal=False,
                )
            elif notice.notice_type in ["approve_renewal", "disapprove_renewal"]:
                memberships = memberships.filter(
                    approved_denied_dt__year=start_dt.year,
                    approved_denied_dt__month=start_dt.month,
                    approved_denied_dt__day=start_dt.day,
                    renewal=True,
                )
            else:  # 'expire'
                memberships = memberships.filter(
                    expiration_dt__year=start_dt.year,
                    expiration_dt__month=start_dt.month,
                    expiration_dt__day=start_dt.day,
                )

            # filter by membership type
            if notice.corporate_membership_type:
                memberships = memberships.filter(corporate_membership_type=notice.corporate_membership_type)

            memberships_count = memberships.count()

            if memberships_count > 0:
                email.content_type = notice.content_type

                global_context = {
                    "site_display_name": site_display_name,
                    "site_contact_name": site_contact_name,
                    "site_contact_email": site_contact_email,
                    "time_submitted": nowstr,
                }

                # log notice sent
                notice_log = NoticeLog(notice=notice, num_sent=0)
                notice_log.save()
                notice.log = notice_log
                notice.err = ""

                for membership in memberships:
                    try:
                        num_sent += email_member(notice, membership, global_context)
                        if memberships_count <= 50:
                            notice.members_sent.append(membership)

                        # log record
                        notice_log_record = NoticeLogRecord(notice_log=notice_log, corp_membership=membership)
                        notice_log_record.save()
                    except:
                        # catch the exception and email
                        notice.err += traceback.format_exc()
                        print traceback.format_exc()

                if num_sent > 0:
                    notice_log.num_sent = num_sent
                    notice_log.save()

            return num_sent

        def email_member(notice, membership, global_context):
            corp_profile = membership.corp_profile

            representatives = corp_profile.reps.filter(Q(is_dues_rep=True) | (Q(is_member_rep=True)))
            sent = 0

            for recipient in representatives:
                body = notice.email_content
                context = membership.get_field_items()
                context["membership"] = membership
                context.update(global_context)

                context.update({"rep_first_name": recipient.user.first_name})

                if membership.expiration_dt:
                    body = body.replace(
                        "[expirationdatetime]", time.strftime("%d-%b-%y %I:%M %p", membership.expiration_dt.timetuple())
                    )
                else:
                    body = body.replace("[expirationdatetime]", "")

                context.update(
                    {
                        "corporatemembershiptypeid": str(membership.corporate_membership_type.id),
                        "corporatemembershiptype": membership.corporate_membership_type.name,
                        "view_link": "%s%s" % (site_url, membership.get_absolute_url()),
                        "renew_link": "%s%s" % (site_url, membership.get_renewal_url()),
                        "renewed_individuals_list": render_to_string(
                            ("notification/corp_memb_notice_email/renew_list.html"), {"corp_membership": membership}
                        ),
                    }
                )

                body = fieldify(body)

                body = "%s <br /><br />%s" % (body, get_footer())

                context = Context(context)
                template = Template(body)
                body = template.render(context)

                email.recipient = recipient.user.email
                email.subject = notice.subject.replace("(name)", corp_profile.name)
                email.body = body
                if notice.sender:
                    email.sender = notice.sender
                    email.reply_to = notice.sender
                if notice.sender_display:
                    email.sender_display = notice.sender_display

                email.send()
                sent += 1
                if verbosity > 1:
                    print "To ", email.recipient, email.subject
            return sent

        def get_footer():
            return """
                    This e-mail was generated by Tendenci&reg; Software -
                    a web based membership management software solution
                    www.tendenci.com developed by Schipul - The Web
                    Marketing Company
                    """

        exception_str = ""

        notices = Notice.objects.filter(status=True, status_detail="active").exclude(notice_time="attimeof")

        if notices:
            if verbosity > 1:
                print "Start sending out notices to members:"
            total_notices = 0
            total_sent = 0
            for notice in notices:
                total_notices += 1
                total_sent += process_notice(notice)
                if hasattr(notice, "err"):
                    exception_str += notice.err

            if total_sent > 0:
                processed_notices = [notice for notice in notices if hasattr(notice, "log") and notice.log.num_sent > 0]
                email_admins_recap(processed_notices, total_sent)

            # if there is any error, notify us
            if exception_str:
                email_script_errors(exception_str)

            if verbosity > 1:
                print "Total notice processed: %d" % (total_notices)
                print "Total email sent: %d" % (total_sent)
                print "Done"
        else:
            if verbosity > 1:
                print "No notices on the site."
Ejemplo n.º 12
0
    def handle(self, *args, **options):
        from tendenci.addons.events.models import Event, Registrant, Organizer
        from tendenci.core.emails.models import Email
        from tendenci.core.site_settings.utils import get_setting
        from tendenci.core.base.utils import convert_absolute_urls
        from tendenci.addons.events.utils import (render_event_email,
                                  get_default_reminder_template)

        verbosity = options['verbosity']
        site_url = get_setting('site', 'global', 'siteurl')
        now = datetime.now()
        today_tuple = (datetime(now.year, now.month, now.day, 0, 0, 0),
                       datetime(now.year, now.month, now.day, 23, 59, 59))

        # get a list of upcoming events that are specified to send reminders.
        events = Event.objects.filter(start_dt__gt=now,
                                registration_configuration__enabled=True,
                                registration_configuration__send_reminder=True,
                                status=True,
                                status_detail='active')
        events_list = []

        if events:
            for event in events:
                reg_conf = event.registration_configuration
                reminder_days = reg_conf.reminder_days
                if not reminder_days:
                    reminder_days = '1'
                days_list = reminder_days.split(',')

                for day in days_list:
                    try:
                        day = int(day)
                    except:
                        continue

                    start_dt = event.start_dt - timedelta(days=day)

                    if today_tuple[0] <= start_dt and start_dt <= today_tuple[1]:
                        events_list.append(event)

                        break

            for event in events_list:
                registrants = Registrant.objects.filter(
                                reminder=True,
                                registration__event=event
                                )

                reg_conf = event.registration_configuration
                [organizer] = Organizer.objects.filter(event=event)[:1] or [None]
                event.organizer = organizer

                email = reg_conf.email
                if not email:
                    email = Email()

                if not email.sender_display:
                    if organizer.name:
                        email.sender_display = organizer.name

                if not email.reply_to:
                    if organizer.user and organizer.user.email:
                        email.reply_to = organizer.user.email

                if not email.subject:
                    email.subject = 'Reminder: %s' % event.title
                else:
                    email.subject = 'Reminder: %s' % email.subject

                if not email.body:
                    email.body = get_default_reminder_template(event)

                email = render_event_email(event, email)

                # replace the relative links with absolute urls
                # in the email body and subject
                email.body = convert_absolute_urls(email.body, site_url)

                event.email = email
                self.send_reminders(event, registrants, verbosity=verbosity)