def send_posts_ind_draft_reminder():

    date = datetime.datetime.now() - datetime.timedelta(hours=24)
    posts = Post.objects.filter(draft=True, date_time__lt=date).order_by("shop")
    already_notified = set()

    try:
        for post in posts:
            shop = post.shop
            if shop not in already_notified:
                link = "http://%s%s" % (shop.default_dns, reverse("post_edit", args=[post.id]))
                msg = (
                    "\n\nWe remember you that you have posts in a draft status on your %s shop. If you want that posts appears on you site you must publish them.\n\nGo to %s and make it public!"
                    % (shop, link)
                )
                mail = EmailMessage(
                    subject="Posts in draft reminder",
                    body=msg,
                    from_email=settings.EMAIL_FROM,
                    to=[shop.owner().email],
                    headers={"X-SMTPAPI": '{"category": "Posts In Draft Reminder"}'},
                )
                mail.send(fail_silently=True)
                #                send_mail('Posts in draft reminder', msg, settings.EMAIL_FROM, [shop.owner().email], fail_silently=True)
                already_notified.add(shop)
    except Exception, e:
        mail = EmailMessage(
            subject='Error when trying to send email notifying that customer have "posts in draft"',
            body=e,
            from_email=settings.EMAIL_FROM,
            to=[mail for (name, mail) in settings.STAFF],
            headers={"X-SMTPAPI": '{"category": "Error"}'},
        )
        mail.send(fail_silently=True)
Beispiel #2
0
    def send_mail(self, form, files=[]):
        # TODO: refactor, move to utils
        form_data = self.get_form_data(form)
        message = self.compile_message(form_data)
        context_dict = self.get_form_data_context(form_data)

        mail_to = re.compile('\s*[,;]+\s*').split(self.mail_to)
        for key, email in enumerate(mail_to):
            mail_to[key] = self.string_template_replace(email, context_dict)

        mail_from = self.mail_from or None
        if mail_from:
            mail_from = self.string_template_replace(mail_from, context_dict)

        if self.mail_subject:
            mail_subject = self.string_template_replace(self.mail_subject, context_dict)
        else:
            mail_subject = self.title

        from django.core.mail import EmailMessage
        message = EmailMessage(mail_subject, message, mail_from or None, mail_to)

        if self.mail_uploaded_files:
            for file_path in files:
                message.attach_file(file_path)

        message.send(fail_silently=False)
Beispiel #3
0
def request_access(request, requester=None, requestee=None):

	# send_mail('Subject here', 'Here is the message.', '*****@*****.**', ['*****@*****.**'], fail_silently=False)


	'''
	- need to flag the requester as having requested a specific group
	- need to capture name, email, username, group name, group_pk
	- how do I capture the target recipient's email to populate in the "to" field 
	'''
	show_this_group = request.session['show_this_group']

	requester_name = '%s %s' % (User.objects.get(username=requester).first_name, User.objects.get(username=requester).last_name)
	requester_email = User.objects.get(username=requester).email
	requester_username = User.objects.get(username=requester).username
	requested_group_name = Group.objects.get(name=show_this_group)
	requested_group_pk = requested_group_name.id



	message = EmailMessage('Approve access for %s - %s' % (requester_name, requester_email), 'Click this link ____ to approve access for %s (%s, %s) to the group %s at primary key %s.' % (requester_name, requester_username, requester_email, requested_group_name, requested_group_pk), '*****@*****.**', [], ['*****@*****.**'])

	message.send()

	return HttpResponseRedirect('/introkick/home')
Beispiel #4
0
def follow(request,username):
    """
    Let one user follow another.
    """

    follower = get_object_or_404(Profile,user=request.user)
    followee = get_object_or_404(Profile,user__username=username)

    # Is current user already following this list/profile?
    if followee in follower.followees.all():
        messages.info(request, "You were already following %s" % followee)
    else:
        follower.followees.add(followee)

        # Only send email if followee has that option enabled in their profile
        if followee.email_on_follow == True:

            site = Site.objects.get(id=1) # Need this for link in email template.
            recipients = [followee.user.email,]
            email_subject = render_to_string("people/follow/followed-subject.txt", { 'follower': follower, 'followee': followee })
            email_body_txt = render_to_string("people/follow/followed-body.txt", { 'follower': follower, 'followee': followee, 'site': site, })

            msg = EmailMessage(email_subject, email_body_txt, settings.DEFAULT_FROM_EMAIL, recipients)
            msg.send(fail_silently=False)

        messages.success(request, "You are now following %s" % followee)

    return HttpResponseRedirect(reverse('people_profile_detail',args=[username]))
Beispiel #5
0
    def test_file_sessions(self):
        """Make sure opening a connection creates a new file"""
        msg = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
        connection = mail.get_connection()
        connection.send_messages([msg])

        self.assertEqual(len(os.listdir(self.tmp_dir)), 1)
        with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]), 'rb') as fp:
            message = message_from_binary_file(fp)
        self.assertEqual(message.get_content_type(), 'text/plain')
        self.assertEqual(message.get('subject'), 'Subject')
        self.assertEqual(message.get('from'), '*****@*****.**')
        self.assertEqual(message.get('to'), '*****@*****.**')

        connection2 = mail.get_connection()
        connection2.send_messages([msg])
        self.assertEqual(len(os.listdir(self.tmp_dir)), 2)

        connection.send_messages([msg])
        self.assertEqual(len(os.listdir(self.tmp_dir)), 2)

        msg.connection = mail.get_connection()
        self.assertTrue(connection.open())
        msg.send()
        self.assertEqual(len(os.listdir(self.tmp_dir)), 3)
        msg.send()
        self.assertEqual(len(os.listdir(self.tmp_dir)), 3)

        connection.close()
Beispiel #6
0
def write(request, slug_story, activation_key, t='stories/write.html', d={}):
    story = get_object_or_404(Story, slug=slug_story)
    active_membership = story.active_membership()
    d['story']=story
    if not active_membership:
        story.turn_membership()
        return render(request, 'stories/done.html', d)
    membership = get_object_or_404(Membership, activation_key=activation_key)
    if active_membership.id != membership.id:
        return render(request, 'stories/done.html', d)
    new_line = Line(story=story)
    if request.POST:
        line_form=LineForm(request.POST, prefix='line', instance=new_line)
        if line_form.is_valid():
            line_form.save()
            next = story.turn_membership()
            mail_d = {
                'story': story,
                'site': get_current_site(request)
            }
            message = render_to_string('stories/email.txt', mail_d)
            email = EmailMessage(
                'Estas participando del concurso',
                message,
                to=[next.user.email])
            email.send()
            return render(request, 'stories/done.html', d)  
    else:
        line_form=LineForm(prefix='line')
    d = {
        'form': line_form,
        'story': story,
        'site': get_current_site(request)
    }
    return render(request, t, d)
Beispiel #7
0
def send_claim_email(request, list_id):
    if request.method == "POST":
        listing = Listing.objects.get(pk=list_id)
        if listing.email != '':
            emails = ['emails/claim_email.html', 'emails/claim_email_2.html']
            choice = random.choice(emails)
            logger.debug('Listing claim sending email to : ' + listing.email + ' with ' + choice)
            t = get_template(choice)
            context = RequestContext(request, {'listing': listing})
            content = t.render(context)
            msg = EmailMessage('Picasso - Claim your Business', content, '*****@*****.**',
                               [listing.email])
            msg.content_subtype = "html"
            msg.send()
            return HttpResponse(json.dumps({'fail': False}), content_type='application/json')
        elif request.POST.get('email', '') != '':
            listing.email = request.POST.get('email', '')
            listing.save()
            emails = ['emails/claim_email.html', 'emails/claim_email_2.html']
            choice = random.choice(emails)
            logger.debug('Listing claim sending email to : ' + listing.email + ' with ' + choice)
            t = get_template(choice)
            context = RequestContext(request, {'listing': listing})
            content = t.render(context)
            msg = EmailMessage('Picasso - Claim your Business', content, '*****@*****.**',
                               [listing.email])
            msg.content_subtype = "html"
            msg.send()
            return HttpResponse(json.dumps({'fail': False}), content_type='application/json')
        else:
            return HttpResponse(json.dumps({'fail': True}), content_type='application/json')
    return HttpResponse("")
Beispiel #8
0
    def run(self, submission, template_code):
        logger.info('SendEmailFromTemplate:%d template %s' % (
                submission.id, template_code
        ))
        
        try:
            translation.activate(submission.submission_language)

            letter = LetterTemplate.objects.language().get(code=template_code)
            email = EmailMessage(
                letter.subject,
                letter.text % {'name': submission.applicant},
                '*****@*****.**',
                [submission.applicant_email],
                list(settings.MAIL_BCC_LIST),
                headers = {'Reply-To': '*****@*****.**'}
            )
            email.send()
        except:
            logger.info('SendEmailFromTemplate:%d template %s exception' % (
                submission.id, template_code
            ))
            raise
        finally:
            translation.deactivate()
        logger.info('SendEmailFromTemplate:%d template %s done' % (
            submission.id, template_code
        ))
def contact(request):
    form_class = ContactForm

    # new logic!
    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            contact_name = form.cleaned_data['contact_name']
            contact_email = form.cleaned_data['contact_email']
            form_content = form.cleaned_data['content']

            # email the profile with the contact info
            template = get_template('contact_template.txt')

            context = Context({
                'contact_name': contact_name,
                'contact_email': contact_email,
                'form_content': form_content,
            })
            content = template.render(context)

            email = EmailMessage(
                'New contact form submission',
                content,
                'Your website <*****@*****.**>',
                ['*****@*****.**'],
                headers = {'Reply-To': contact_email }
            )
            email.send()
            return redirect('contact')

    return render(request, 'contact.html', {
        'form': form_class,
    })
Beispiel #10
0
def send_response(original_message, message_text, recipient_email, cc=None):
    """
    Helper function which sends an email message in response to a control
    message.

    :param original_message: The received control message.
    :type original_message: :py:class:`email.message.Message` or an object with
        an equivalent interface
    :param message_text: The text which should be included in the body of the
        response.
    :param cc: A list of emails which should receive a CC of the response.
    """
    subject = original_message.get('Subject')
    if not subject:
        subject = 'Your mail'
    message = EmailMessage(
        subject='Re: ' + subject,
        to=[original_message['From']],
        cc=cc,
        from_email=DISTRO_TRACKER_BOUNCES_EMAIL,
        headers={
            'From': DISTRO_TRACKER_CONTACT_EMAIL,
            'X-Loop': DISTRO_TRACKER_CONTROL_EMAIL,
            'References': ' '.join((original_message.get('References', ''),
                                    original_message.get('Message-ID', ''))),
            'In-Reply-To': original_message.get('Message-ID', ''),
        },
        body=message_text,
    )

    logger.info("control => %(to)s %(cc)s", {
        'to': recipient_email,
        'cc': " ".join(cc) if cc else "",
    })
    message.send()
Beispiel #11
0
    def run(self, submission):
        logger.info('SendSubmissionEmail for submission %s' % (
            submission.id
        ))
        try:
            translation.activate(submission.submission_language)

            email = EmailMessage(
                'Cinema Perpetuum Mobile 2013',
                self.get_email_message(submission),
                '*****@*****.**',
                [submission.applicant_email],
                list(settings.MAIL_BCC_LIST),
                headers = {'Reply-To': '*****@*****.**'})

            email.attach(
                'cpm2013.pdf', self.create_pdf(submission), 'application/pdf'
            )

            email.send()
        except:
            logger.exception('')
            raise
        finally:
            translation.deactivate()
            try:
                submission = Submission.objects.get(pk=submission.pk)
            except Submission.DoesNotExist:
                logger.exception('Failed to update "email sent" status')
            else:
                submission.comment_email_sent = True
                submission.save()
Beispiel #12
0
def send_bookmark_reminder_email():
    for profile in UserProfile.objects.all():
        user = profile.user
        # Get all bookmarked events ending in the next 7 days from today
        # What day will it be 7 days from now-
        now = timezone.now().date()
        seven_days = now + timedelta(days=7)
        my_bookmarks = Bookmark.objects.filter(user=user, event__end_date__gte=now, event__end_date__lte=seven_days)

        if my_bookmarks:
            bookmarked_events = []

            for bookmark in my_bookmarks:
                bookmarked_events.append({"EVENT_TITLE": bookmark.event.title,
                                     "IMAGE_URL": bookmark.event.image.url,
                                     "EVENT_DESCRIPTION": bookmark.event.description,
                                     "EVENT_URL": "http://www." + Site.objects.get_current().domain + bookmark.event.get_absolute_url(),
                                     "END_DATE": "{}".format(bookmark.event.end_date.strftime("%A, %d. %B"))})
            subject = "Events ending soon on Alltoez"

            msg = EmailMessage(subject=subject, from_email=("Alltoez", "*****@*****.**"),
                               to=[user.email])
            msg.template_name = "Bookmarked Events Ending"
            msg.global_merge_vars = {
                "USER_NAME": profile.first_name,
                "events": bookmarked_events,
            }
            msg.send()
Beispiel #13
0
def server_error(request):
    """Own view in order to pass RequestContext and send an error message.
    """
    exc_type, exc_info, tb = sys.exc_info()
    response = "%s\n" % exc_type.__name__
    response += "%s\n" % exc_info
    response += "TRACEBACK:\n"
    for tb in traceback.format_tb(tb):
        response += "%s\n" % tb

    if hasattr(request, 'user') and request.user:
        response += "User: %s\n" % request.user.username

    response += "\nREQUEST:\n%s" % request

    try:
        from_email = settings.ADMINS[0][1]
        to_emails = [a[1] for a in settings.ADMINS]
    except IndexError:
        pass
    else:
        mail = EmailMessage(
            subject="Error LFS", body=response, from_email=from_email, to=to_emails)
        mail.send(fail_silently=True)

    t = loader.get_template('500.html')
    return HttpResponseServerError(t.render(RequestContext(request)))
Beispiel #14
0
def cdclient_cargo(request, id):
    cdClient = get_object_or_404(CdClient, id=id)
    if request.method == "POST":
        form = CargoForm(request.POST.copy())
        if form.is_valid():
            cargo = form.save(commit=False)
            cargo.cdclient = cdClient
            cargo.save()
            message = loader.get_template("shipit/sent_email.html").render(Context({"cdClient":cdClient,"cargo":cargo}))
            mail = EmailMessage(
                "Pardus DVD isteğiniz",
                message,
                "Özgürlükiçin <%s>" % DEFAULT_FROM_EMAIL,
                [DVD_MAIL_LIST, cdClient.email],
                headers={"Message-ID":"%s-%s" % (cdClient.id, cdClient.hash)}
            )
            mail.content_subtype = "html"
            mail.send(fail_silently=True)
            cdClient.sent = True
            cdClient.save()

            return HttpResponseRedirect(cdClient.get_absoulte_url())
    else:
        form = CargoForm()
    return render_response(request, "shipit/cargo.html", locals())
Beispiel #15
0
def send_invitation_key(sender, invitation, **kwargs):
    from django.core.mail import EmailMessage
    body = """
    Hello there,

    This is an invitation to be part of the {group_name} group on a StartupWeekend event.

    Click on the following link to activate your Startup Weekend Manager account:
    
    http://localhost:8000/#!/user/registration?email={email}&code={code}
    

    Best of lucks on th event, and remember: Stop talk, more action!


    --
    Startup Weekend Team
    """.format(group_name=invitation.to.name, email=invitation.email, code=invitation.key)

    print body
    
    msg = EmailMessage(subject="[swmanager] Invitation to an swmanager event",
                         body=body,
                         to=[invitation.email])
                         #[email protected])
    print "msg : %s" % msg
    print msg.send()
    print "######## Invitation key: %s" % invitation.key
def send_mail_task(subject, message, to, only_print=False, history_line=None, headers=None):
    if not isinstance(to, (list, tuple)):
        to = [to]

    to = [t for t in to if t is not None]

    to = list(set(to)) # remove duplicates
    if history_line is not None:
        if headers is None:
            headers = {}
        history_header = '<%s>' % history_line
        headers['In-Reply-To'] = history_header
        headers['References'] = history_header

    if settings.EPO_EMAIL_ONLY_PRINT or only_print:
        info(u'printing portal email to: %s: %s (%r)\n%s', to, subject, headers, message)
    else:

        info('sending email to: %s', to)
        try:
            email_message = EmailMessage(subject, message, settings.SMTP_CONF["from"], to)
            if headers is not None:
                email_message.extra_headers = headers
            email_message.send()
        except Exception as e:
            error('failed to send email: %s', e)
            raise
Beispiel #17
0
def sendemail(request , id ):
    """
    For send emails toa partitcular student parents
    """
    print request.path
    p = request.POST
    student = Student.objects.get(id = id)
    studentemail = "*****@*****.**" #str(student.Email)
    if request.method == 'GET':
        emailform = Emailform()

    if request.method =='POST':
        emailform = Emailform(request.POST)
        if emailform.is_valid():
            subject = p.get('subject','')
            body = p.get('body','')
            emailsubject = "%(subprfx)s %(subject)s" % {'subprfx':subprfx , 'subject':subject}
            try:
                email = EmailMessage(emailsubject,body,"*****@*****.**",['*****@*****.**',])
                email.send()
                print "Email sent"
            except:
                print "Msg not sent"
            try:    
                Email.objects.create(student = student , subject = subject ,body = body, sent_by=request.user)
            except:
                print "Email was not saves"
            return HttpResponse("Msg Sent")
    return render_to_response('msgs/sendmsg.html', dict(student = student ,emailform = emailform , user = request.user ,action="email"))
Beispiel #18
0
def send_email(email_body, email_type=settings.GENERIC,
               recipients=None, site=None, headers=None, **kwargs):
    recipients = recipients or []

    company_name = 'My.jobs'
    domain = 'my.jobs'

    if site:
        domain = site.email_domain
        if site.canonical_company:
            company_name = site.canonical_company.name

    kwargs['company_name'] = company_name
    kwargs['domain'] = domain.lower()

    sender = settings.EMAIL_FORMATS[email_type]['address']
    sender = sender.format(**kwargs)

    # Capitalize domain for display purposes.
    kwargs['domain'] = kwargs['domain'].lower()
    subject = settings.EMAIL_FORMATS[email_type]['subject']
    subject = subject.format(**kwargs)

    email_kwargs = {
        'subject': subject, 'body': email_body, 'from_email': sender,
        'to': recipients
    }
    if headers is not None:
        email_kwargs['headers'] = headers
    message = EmailMessage(**email_kwargs)
    message.content_subtype = 'html'
    message.send()

    return message
Beispiel #19
0
def SaleOrderEmail(order):
    """
    Send email Order
    order Int (ID)
    Return True/False
    """

    conn = connOOOP()
    shop = conn.SaleShop.get(OERP_SALE)

    context = {}
    context['active_id'] = shop.email_sale_order.id
    values = [
        [], #ids
        order, #rel_model_ref
        context, #context
    ]
    body_template = conn_webservice('poweremail.preview','on_change_ref', values)

    customer_email = body_template['value']['to']
    
    if customer_email != 'False':
        subject = body_template['value']['subject']
        body = body_template['value']['body_text']
        email = EmailMessage(subject, body, EMAIL_FROM, to=[customer_email], headers = {'Reply-To': EMAIL_REPPLY})

        try:
            email.send()
            return True
        except:
            error = _("Your order is in process but we don't send email. Check in your order customer section.")
            return False
Beispiel #20
0
    def send_editor_mail(self):
        """
        Send notification mails to all users in group editor.
        Only send if ChangeRequest is not yet accepted
        :return:
        """
        if self.status == ChangeRequest.PENDING:
            editors = User.objects.filter(groups__name='editor')

            body = render_to_string('frontend/email/new_change_request.txt',
                                    {
                                        'change_request': self,
                                        'document_url': self.document_url()
                                    })

            bcc = []
            for editor in editors:
                bcc.append(get_user_email(editor))

            email = EmailMessage(_("New change request", ),
                                 body,
                                 bcc=bcc)
            email.send()
            logger.info("Sent change request notification mail to editors",
                        extra={
                            'body': body,
                            'bcc': bcc,
                        })
Beispiel #21
0
    def send_new_status_notification_mail(self):
        subject, body = "", ""
        if self.status == ChangeRequest.ACCEPTED:
            subject = _("Your change request has been accepted")
            body = render_to_string(
                'frontend/email/change_request_accepted.txt',
                {
                    'change_request': self,
                    'document_url': self.document_url()
                })
        if self.status == ChangeRequest.DECLINED:
            subject = _("Your change request has been declined")
            body = render_to_string(
                'frontend/email/change_request_declined.txt',
                {
                    'change_request': self,
                    'document_url': self.document_url()
                })

        to = get_user_email(self.author)
        email = EmailMessage(subject,
                             body,
                             to=[to])
        email.send(fail_silently=True)
        logger.info("Sent change request status notification mail to author",
                    extra={
                        'body': body,
                        'to': to,
                    })
    def do_email_reply(self, comment, content_object, request):
        """Send email notification of a new comment to the authors of
        the previous comments when email notifications have been requested."""
        exclude_list = self.mail_comment_notification_recipients + \
                       [author.email
                        for author in content_object.authors.all()] + \
                       [comment.email]
        recipient_list = set([comment.email
                              for comment in content_object.comments
                              if comment.email]) - \
                              set(exclude_list)

        if recipient_list:
            site = Site.objects.get_current()
            template = loader.get_template('comments/comment_reply_email.txt')
            context = Context({'comment': comment, 'site': site,
                               'protocol': PROTOCOL,
                               'content_object': content_object})
            subject = _('[%(site)s] New comment posted on "%(title)s"') % \
                      {'site': site.name,
                       'title': content_object.title}
            message = template.render(context)
            mail = EmailMessage(subject, message,
                                settings.DEFAULT_FROM_EMAIL,
                                bcc=recipient_list)
            mail.send(fail_silently=not settings.DEBUG)
Beispiel #23
0
 def request_new_password(self, request):
     email = self.cleaned_data['username']
     try:
         user = EmailUser.objects.get(email=email)
     except:
         raise PermissionDenied
     user.is_active = False
     user.save()
     try:
         tmp = TempUrl.objects.get(email=email)
     except:
         tmp = TempUrl(email=email, first_name=user.first_name, 
                       last_name=user.last_name)
     tmp.hash = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(20))
     now = datetime.datetime.utcnow().replace(tzinfo=utc)
     tmp.invited = now
     tmp.created = now
     tmp.used = None
     tmp.save()
     #email...
     p = {'reason':'reset  password', 'service':'Django email username'}
     p['link'] = request.build_absolute_uri(reverse('django_email_user.views.activate_account', kwargs={'hasher': tmp.hash}))
     html = render_to_string('django_email_user/email-invitation.html', p)
     mail = EmailMessage('You have requested a password reset',
             html, '<Django email username>' + settings.EMAIL_HOST_USER,
             [tmp.email])
     mail.content_subtype = "html"
     mail.send()
     return email
 def send(self, **kwargs):
     protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
     current_site = kwargs["site"] if "site" in kwargs else Site.objects.get_current()
     signup_url = u"%s://%s%s?%s" % (
         protocol,
         unicode(current_site.domain),
         reverse("account_signup"),
         urllib.urlencode({"code": self.code})
     )
     ctx = {
         "signup_code": self,
         "current_site": current_site,
         "signup_url": signup_url,
     }
     ext = "html" if settings.EMAIL_CONTENT_HTML else "txt"
     subject = render_to_string(
         "account/email/invite_user_subject.{0}".format(ext), ctx)
     message = render_to_string(
         "account/email/invite_user.{0}".format(ext), ctx)
     msg = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email])
     if settings.EMAIL_CONTENT_HTML:
         msg.content_subtype = "html"
     msg.send()
     self.sent = timezone.now()
     self.save()
     signup_code_sent.send(sender=SignupCode, signup_code=self)
 def send(self, **kwargs):
     current_site = kwargs["site"] if "site" in kwargs else Site.objects.get_current()
     protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
     activate_url = u"%s://%s%s" % (
         protocol,
         unicode(current_site.domain),
         reverse("account_confirm_email", args=[self.key])
     )
     ctx = {
         "email_address": self.email_address,
         "user": self.email_address.user,
         "activate_url": activate_url,
         "current_site": current_site,
         "key": self.key,
     }
     ext = "html" if settings.EMAIL_CONTENT_HTML else "txt"
     subject = render_to_string(
         "account/email/email_confirmation_subject.{0}".format(ext), ctx)
     subject = "".join(subject.splitlines())  # remove superfluous line breaks
     message = render_to_string(
         "account/email/email_confirmation_message.{0}".format(ext), ctx)
     msg = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email_address.email])
     if settings.EMAIL_CONTENT_HTML:
         msg.content_subtype = "html"
     msg.send()
     self.sent = timezone.now()
     self.save()
     signals.email_confirmation_sent.send(sender=self.__class__, confirmation=self)
Beispiel #26
0
def send_order_email(email, order, products):
    subject, from_email, to_email = u'Your order in Prized.tv', \
                                    '*****@*****.**', \
                                    (email, )

    html_data = get_template('email/new_order.html')

    d = Context({
        'order_id': order.id,
        'order': order,
        'products': products,
    })

    #DEBUG NOTE: If you see an error 61 (connection refused) being thrown by the server
    #after the call to msg.send(), it means that your EMAIL_BACKEND is not correctly
    #defined in settings.py
    
    #Send email to client
    html_content = html_data.render(d)
    msg = EmailMessage(subject, html_content, from_email, to_email)
    msg.content_subtype = "html"  # Main content is now text/html
    msg.send()

    #Send email to site manager
    msg = EmailMessage(subject, html_content, from_email, to=['*****@*****.**'])
    msg.content_subtype = "html"  # Main content is now text/html
    msg.send()
Beispiel #27
0
def enviar_email(from_email, subject, template, tags):
    """Envia o email para o destinatário definido, a partir do template
    definido para ser renderizado. Os argumentos são:
        * from_email - Email do remetente
        * subject - Assunto da Mensagem
        * template - Template que será usado para gerar o corpo
        da mensagem
        * tags - Variáveis de contexto para ser renderizado no
        template.
    """
    if from_email is None:
        raise ValueError("Insira o email do remetente.")
    elif subject is None:
        raise ValueError("Insira o assunto da mensagem.")
    elif template is None:
        raise ValueError(u"Template da mensagem não encontrado")
    elif tags is None:
        raise ValueError("Insira o conteúdo da mensagem.")

    # Gerando a mensagem
    mensagem = render_to_string(template, tags)

    # Enviando a mensagem
    email = EmailMessage(settings.EMAIL_SUBJECT_PREFIX + " " + subject, mensagem,
        from_email, [from_email])
    email.send()
Beispiel #28
0
    def send_mail(self, form, files=[]):
        form_data = self.get_form_data(form)
        message = self.compile_message(form_data)
        context_dict = self.get_form_data_dict(form_data)

        import re
        mail_to = re.compile('\s*[,;]+\s*').split(self.mail_to)
        for key, email in enumerate(mail_to):
            mail_to[key] = self.string_template_replace(email, context_dict)

        mail_from = self.mail_from or None
        if mail_from:
            mail_from = self.string_template_replace(mail_from, context_dict)

        if self.mail_subject:
            mail_subject = self.string_template_replace(self.mail_subject, context_dict)
        else:
            mail_subject = self.title

        import logging
        logging.debug('Mail: '+repr(mail_from)+' --> '+repr(mail_to));

        from django.core.mail import EmailMessage
        message = EmailMessage(mail_subject, message, mail_from or None, mail_to)

        if self.mail_uploaded_files:
            for file_path in files:
                message.attach_file(file_path)

        message.send(fail_silently=False)
Beispiel #29
0
def preset_submit(request):
    if request.method == "POST":
        form = SubmitForm(request.POST, request.FILES)
        
        if form.is_valid():
            preset = request.FILES["preset_file"]
            message = EmailMessage(**{
                "subject": "[Arista] Preset for %s" % preset.name[:-8],
                "body": "A user has uploaded a new preset!",
                "from_email": form.cleaned_data["email"],
                "to": [x[1] for x in settings.ADMINS],
                "attachments": [
                    (preset.name, preset.read(), "application/x-bzip-compressed-tar"),
                ],
            })
            
            message.send()
        
            return HttpResponseRedirect("/presets/?thanks=1")
    else:
        form = SubmitForm()
    
    return render(request, "presets/submit.html", {
        "form": form,
    })
def notify_about_exception(exception_title):
    """
    If exception is identified as critical - send email to recipients.
    """
    if EXCEPTION_TITLE_WORDS_TO_NOTIFY and EXCEPTION_RECIPIENTS:
        pattern = r'|'.join(EXCEPTION_TITLE_WORDS_TO_NOTIFY)
        search_result = search(pattern, exception_title, I)

        if search_result is not None:
            message_content = (
                "<p>%(body)s</p><p>Server: "
                "<a href='%(protocol)s://%(domain)s'>%(domain)s</a></p>" % (
                    {
                        'body': exception_title,
                        'protocol': settings.SERVER_PROTOCOL,
                        'domain': settings.CURRENT_SERVER_DOMAIN
                    }
                )
            )
            message = EmailMessage(
                "Error Monitor notification",
                message_content,
                settings.EMAIL_HOST_USER,
                EXCEPTION_RECIPIENTS
            )
            message.content_subtype = 'html'
            message.send(fail_silently=True)
def approve_request(request, order_id):
    app_req = CancelledApproval.objects.get(order_id=order_id)
    can_req = CancelledOrder.objects.get(order_id=order_id)
    ord_req = Order.objects.get(order_id=order_id)

    emailapp = Email.objects.get(email_id=3)
    emailrej = Email.objects.get(email_id=4)


    if request.POST.get('approve'):

        template = get_template('orders/cancellationapproval.html')
        data = {
        "order_id": str(ord_req.order_id),
        "user": ord_req.user.username,
        "order_date":app_req.order_date,
        "cancelled_order_date":app_req.cancelled_order_date,
        "course_price":app_req.amount,
        "order_amount":app_req.final_amount,
        "refund_amount":app_req.refund_amount,
        }
        html = template.render(data)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        pdf = result.getvalue()
        filename = 'Invoice_' + data['order_id'] + '.pdf'
        template = get_template('orders/cancellationapproval.html')

        # Email to customer for order cancellation approval
        email = EmailMessage(
            emailapp.email_subject,
            emailapp.email_body.format(ord_req.user.username, ord_req.course.product_name, ord_req.order_id, app_req.refund_amount),
            emailapp.email_sender,
            [app_req.user.email, '*****@*****.**'])
        email.attach(filename, pdf, 'application/pdf')
        email.send()

        app_req.delete()
        can_req.delete()
        ord_req.delete()
        messages.info(request, "Order cancellation approved!!! Customer has been notified via email.")
        return redirect('orders:approvalrequestsall')
        

    if request.POST.get('reject'):

        template = get_template('orders/cancellationrejection.html')
        data = {
        "order_id": str(ord_req.order_id),
        "user": ord_req.user.username,
        "order_date":app_req.order_date,
        "cancelled_order_date":app_req.cancelled_order_date,
        "amount":app_req.amount,
        "refund_amount":app_req.refund_amount,
        }
        html = template.render(data)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        pdf = result.getvalue()
        filename = 'Invoice_' + data['order_id'] + '.pdf'
        template = get_template('orders/cancellationrejection.html')

        # Email to customer for order cancellation rejection
        email = EmailMessage(
        emailrej.email_subject,
        emailrej.email_body.format(ord_req.user.username, ord_req.course.product_name, ord_req.order_id,app_req.refund_amount),
        emailrej.email_sender,
        [app_req.user.email, '*****@*****.**'])
        email.attach(filename, pdf, 'application/pdf')
        email.send()

        app_req.delete()
        can_req.delete()
        ord_req.delete()
        messages.info(request, "Order cancellation rejected!!! Customer has been notified via email.")
        return redirect('orders:approvalrequestsall')

    return redirect('orders:approvalrequestsall')
Beispiel #32
0
def signup(request):
    if request.method == 'POST':
        print("Hello c")
        form = SignupForm(request.POST)
        if form.is_valid():
            username = request.POST.get("username")
            # print(username)
            try:
                # print("username ="******"anya Exception")
                con = "***College Id Does Not Exist***"
                return render(request, "signup.html", {
                    'form': form,
                    'con': con
                })
            else:
                user = User(email=email,
                            year=year,
                            name=name,
                            category=category,
                            gender=gender,
                            cet=cet,
                            cgpa=cgpa,
                            username=username,
                            status=0,
                            branch=branch)
                #user.save(commit=False)
                print(user.category)
                user.is_active = False
                user.save()
                current_site = get_current_site(request)
                mail_subject = 'Activate your blog account.'
                message = render_to_string(
                    'acc_active_email.html', {
                        'user': user,
                        'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(
                            user.pk)).decode(),
                        'token': account_activation_token.make_token(user),
                    })
                to_email = email
                email = EmailMessage(mail_subject, message, to=[to_email])
                email.send()
                return HttpResponse(
                    'Please confirm your email address to complete the registration'
                )
    else:
        form = SignupForm()
        print("sory")
    return render(request, 'signup.html', {'form': form})
Beispiel #33
0
 def send_verfication(self, email_address, title, message):
     verification_email = EmailMessage(title, message, to=[email_address])
     verification_email.send()
Beispiel #34
0
def send_credit_notifications(username, course_key):
    """Sends email notification to user on different phases during credit
    course e.g., credit eligibility, credit payment etc.
    """
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        log.error('No user with %s exist', username)
        return

    course = modulestore().get_course(course_key, depth=0)
    course_display_name = course.display_name
    tracking_context = tracker.get_tracker().resolve_context()
    tracking_id = str(tracking_context.get('user_id'))
    client_id = str(tracking_context.get('client_id'))
    events = '&t=event&ec=email&ea=open'
    tracking_pixel = 'https://www.google-analytics.com/collect?v=1&tid' + tracking_id + '&cid' + client_id + events
    dashboard_link = _email_url_parser('dashboard')
    credit_course_link = _email_url_parser('courses', '?type=credit')

    # get attached branded logo
    logo_image = cache.get('credit.email.attached-logo')
    if logo_image is None:
        branded_logo = {
            'title': 'Logo',
            'path': settings.NOTIFICATION_EMAIL_EDX_LOGO,
            'cid': str(uuid.uuid4())
        }
        logo_image_id = branded_logo['cid']
        logo_image = attach_image(branded_logo, 'Header Logo')
        if logo_image:
            cache.set('credit.email.attached-logo', logo_image,
                      settings.CREDIT_NOTIFICATION_CACHE_TIMEOUT)
    else:
        # strip enclosing angle brackets from 'logo_image' cache 'Content-ID'
        logo_image_id = logo_image.get('Content-ID', '')[1:-1]

    providers_names = get_credit_provider_display_names(course_key)
    providers_string = make_providers_strings(providers_names)
    context = {
        'full_name':
        user.get_full_name(),
        'platform_name':
        configuration_helpers.get_value('PLATFORM_NAME',
                                        settings.PLATFORM_NAME),
        'course_name':
        course_display_name,
        'branded_logo':
        logo_image_id,
        'dashboard_link':
        dashboard_link,
        'credit_course_link':
        credit_course_link,
        'tracking_pixel':
        tracking_pixel,
        'providers':
        providers_string,
    }

    # create the root email message
    notification_msg = MIMEMultipart('related')
    # add 'alternative' part to root email message to encapsulate the plain and
    # HTML versions, so message agents can decide which they want to display.
    msg_alternative = MIMEMultipart('alternative')
    notification_msg.attach(msg_alternative)
    # render the credit notification templates
    subject = _(u'Course Credit Eligibility')

    if providers_string:
        subject = _(u'You are eligible for credit from {providers_string}'
                    ).format(providers_string=providers_string)

    # add alternative plain text message
    email_body_plain = render_to_string(
        'credit_notifications/credit_eligibility_email.txt', context)
    msg_alternative.attach(
        SafeMIMEText(email_body_plain, _subtype='plain', _charset='utf-8'))

    # add alternative html message
    email_body_content = cache.get('credit.email.css-email-body')
    if email_body_content is None:
        html_file_path = file_path_finder(
            'templates/credit_notifications/credit_eligibility_email.html')
        if html_file_path:
            with open(html_file_path, 'r') as cur_file:
                cur_text = cur_file.read()
                # use html parser to unescape html characters which are changed
                # by the 'pynliner' while adding inline css to html content
                html_parser = HTMLParser.HTMLParser()
                email_body_content = html_parser.unescape(
                    with_inline_css(cur_text))
                # cache the email body content before rendering it since the
                # email context will change for each user e.g., 'full_name'
                cache.set('credit.email.css-email-body', email_body_content,
                          settings.CREDIT_NOTIFICATION_CACHE_TIMEOUT)
        else:
            email_body_content = ''

    email_body = Template(email_body_content).render([context])
    msg_alternative.attach(
        SafeMIMEText(email_body, _subtype='html', _charset='utf-8'))

    # attach logo image
    if logo_image:
        notification_msg.attach(logo_image)

    # add email addresses of sender and receiver
    from_address = configuration_helpers.get_value('email_from_address',
                                                   settings.DEFAULT_FROM_EMAIL)
    to_address = user.email

    # send the root email message
    msg = EmailMessage(subject, None, from_address, [to_address])
    msg.attach(notification_msg)
    msg.send()
Beispiel #35
0
def hello():
	start = datetime.datetime.now()
	response = request.urlopen(url)
	csv = response.read()
	csv_str = str(csv)
	lines = csv_str.split("\\n")
	dest_url=r'C:\Users\rishith\Desktop\Patch-Remainder-master\backend\mysite\core\new.csv'
	fx = open(dest_url,"w")
	for line in lines:
		fx.write(line + "\n")
	fx.close()
	print("Download complete")
	with open(r'C:\Users\rishith\Desktop\Patch-remainder-master\backend\mysite\core\old.csv', 'r',encoding="utf8", errors='ignore') as t1, open(r'C:\Users\rishith\Desktop\Patch-Remainder-master\backend\mysite\core\new.csv', 'r', encoding="utf8", errors='ignore') as t2:
		fileone = t1.readlines()
		filetwo = t2.readlines()
	print("Reading Complete")
	with open(r'C:\Users\rishith\Desktop\Patch-remainder-master\backend\mysite\core\update.csv', 'w', encoding="utf8", errors='ignore') as outFile:
		for line in filetwo:
			if line not in fileone:
				outFile.write(line)
	print("Update Complete")
	#os.remove(r'C:\Users\rishith\Desktop\Patch-remainder-master\backend\mysite\core\old.csv')
	#os.rename(r'C:\Users\rishith\Desktop\Patch-remainder-master\backend\mysite\core\new.csv', r'C:\Users\rishith\Desktop\Patch-remainder-master\backend\mysite\core\old.csv')
	messages = []
	with open('mysite/core/update.csv','rt')as f:
		data = f.readlines()
	#print(data)
	for user in User.objects.all():
		#recievers.append(user.email)
		id = user.id
		try:
			
			s = Subscribers.objects.get(user_id=user.id)
			
			sb=s.subscriptions
			sb = sb.split(",")
			#print(sb)
			ma = list()
			#print("LOL")
			for row in data:
				#print(row)
				row = row.split(",")
				for sub in sb:
					#row = ",".join(row)
					#print(row[2], sub)
					if sub in row[2]:
						#print(sub)
						ma.append(str(row[0]))
			
			msg = "\n".join(ma)
			#print(len(msg))
			reciever = []
			if len(msg)!=0:
				reciever = [user.email]
			print(reciever)
			try:
				subject = "CVE asdasdaa"
				message = msg
				email = EmailMessage(subject, message, to=reciever)
				email.send()
				success = True
			except Exception as e:
				print("Unable to send email to (%s)\n%s" % ('*****@*****.**', e))
			print("Hello World!")
			os.remove(r'C:\Users\rishith\Desktop\Patch-remainder-master\backend\mysite\core\update.csv')
			end = datetime.datetime.now()
			print(end -start)
		except:
			pass
Beispiel #36
0
    def post(self, request):
        organization_list = get_organizations_ordered_by_name()
        if organization_list:
            if request.method == 'POST':
                user_form = UserForm(request.POST, prefix="usr")
                volunteer_form = VolunteerForm(request.POST,
                                               request.FILES,
                                               prefix="vol")

                if user_form.is_valid() and volunteer_form.is_valid():
                    password1 = request.POST.get('usr-password')
                    password2 = request.POST.get('usr-confirm_password')
                    if not match_password(password1, password2):
                        self.match_error = True
                        return render(
                            request, 'registration/signup_volunteer.html', {
                                'user_form': user_form,
                                'volunteer_form': volunteer_form,
                                'registered': self.registered,
                                'phone_error': self.phone_error,
                                'match_error': self.match_error,
                                'organization_list': self.organization_list,
                            })

                    vol_country = request.POST.get('vol-country')
                    vol_phone = request.POST.get('vol-phone_number')
                    if (vol_country and vol_phone):
                        if not validate_phone(vol_country, vol_phone):
                            self.phone_error = True
                            return render(
                                request, 'registration/signup_volunteer.html',
                                {
                                    'user_form': user_form,
                                    'volunteer_form': volunteer_form,
                                    'registered': self.registered,
                                    'phone_error': self.phone_error,
                                    'organization_list':
                                    self.organization_list,
                                })

                    if 'resume_file' in request.FILES:
                        my_file = volunteer_form.cleaned_data['resume_file']
                        if not validate_file(my_file):
                            return render(
                                request, 'registration/signup_volunteer.html',
                                {
                                    'user_form': user_form,
                                    'volunteer_form': volunteer_form,
                                    'registered': self.registered,
                                    'phone_error': self.phone_error,
                                    'organization_list':
                                    self.organization_list,
                                })

                    user = user_form.save()

                    user.set_password(user.password)
                    user.save()

                    volunteer = volunteer_form.save(commit=False)
                    volunteer.user = user

                    # if an organization isn't chosen from the dropdown,
                    # then organization_id will be 0
                    organization_id = request.POST.get('organization_name')
                    organization = get_organization_by_id(organization_id)

                    if organization:
                        volunteer.organization = organization
                    else:
                        unlisted_org = request.POST.get(
                            'vol-unlisted_organization')
                        org = Organization.objects.create(
                            name=unlisted_org, approved_status=False)
                        org.save()
                        volunteer.organization = org

                    volunteer.reminder_days = 1
                    volunteer.save()
                    current_site = get_current_site(request)
                    mail_subject = 'Activate your account.'
                    message = render_to_string(
                        'registration/acc_active_email.html', {
                            'user': user,
                            'domain': current_site.domain,
                            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                            'token': account_activation_token.make_token(user),
                        })
                    to_email = volunteer_form.cleaned_data.get('email')
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
                    return render(request, 'home/email_ask_confirm.html')
                else:
                    return render(
                        request, 'registration/signup_volunteer.html', {
                            'user_form': user_form,
                            'volunteer_form': volunteer_form,
                            'registered': self.registered,
                            'phone_error': self.phone_error,
                            'organization_list': self.organization_list,
                        })
        else:
            return render(request, 'home/home.html', {'error': True})
Beispiel #37
0
def on_payment_verified(request, sender, ref, amount, **kwargs):
    order = Order.objects.get(user=request.user, ordered=False)

    user = request.user
    email = request.user.email
    name = request.user.first_name
    name_2 = request.user.last_name
    number = order.shipping_address.phone
    address = order.shipping_address.street_address
    country = order.shipping_address.country
    state = order.shipping_address.state

    context = {
        'order': order,
        'amount': amount,
        'email': email,
        'name': name,
        'user': user,
        'ref': ref,
        "name_2": name_2,
        "address": address,
        "country": country,
        'state': state,
        'number': number
    }

    payment = Payment()
    order.ordered = True
    order.ref_code = ref
    # order_item.ordered = True
    payment.user = user
    payment.amount = amount
    payment.reference = ref
    payment.save()
    # attach payment to order

    order_items = order.items.all()

    order_items.update(ordered=True)
    for item in order_items:
        item.save()
    order.payment = payment
    order.save()
    # send email to user
    template = render_to_string('email_template.html', context)
    sale = EmailMessage(
        'Thank you for your order!!',
        template,
        "*****@*****.**",
        [email]

    )
    sale.fail_silently = False
    sale.send()
    template = render_to_string('sale_template.html', context)
    jane = EmailMessage(
        'We have received an order!!',
        template,
        "*****@*****.**",
        ['*****@*****.**']

    )
    jane.fail_silently = False
    jane.send()
    def handle(self, *args, **options):
        echeance = Echeance.objects.filter(monthly_rent_paid=False,
                                           rental__archived=False)
        today = datetime.date.today()
        current_month = _(today.strftime('%B'))

        for item in echeance:
            try:
                id = item.rental
                name = slugify(item.rental.occupant)
                date = today.strftime('%Y-%m-%d')
                sum_rent = item.rental.charges + item.rental.rent_amount
                occupant_email = item.rental.occupant.user.email
                filename = '{}-{}.pdf'.format(date, name)

                html_string = render_to_string("quittance/echeance_base.html",
                                               {
                                                   'rentals': id,
                                                   'today': today,
                                                   'sum_rent': sum_rent,
                                               })
                html = HTML(string=html_string)
                with tempfile.TemporaryDirectory(
                        dir=settings.MEDIA_ROOT) as tmpdirname:
                    result = html.write_pdf(
                        target='{tmpdirname}{filename}'.format(
                            tmpdirname=tmpdirname, filename=filename))
                    echeance_to_store = open(
                        '{tmpdirname}{filename}'.format(tmpdirname=tmpdirname,
                                                        filename=filename),
                        'rb+')
                    # Convert it to a Django File.
                    django_file = File(echeance_to_store)
                    stored_echeance = Echeance()
                    item.date_of_issue = today
                    item.rental = id
                    saved_echeance = item.echeance.save(filename,
                                                        django_file,
                                                        save=True)
                    self.stdout.write(
                        self.style.SUCCESS(
                            "Le locataire {} recevra l\n'écheance {}".format(
                                item.rental.occupant, filename)))

                    try:
                        occupant_name = item.rental.occupant.user.last_name
                        occupant_firstname = item.rental.occupant.user.first_name
                        admin_name = item.rental.property.administrator.user.last_name
                        admin_firstname = item.rental.property.administrator.user.first_name
                        message = "Bonjour {} {}, \nVous trouverez ci-joint l'avis d'échéance de loyer pour {}. Il sera à régler dans les délais prévus dans votre contrat de location. \nSi vous avez déjà réglé votre loyer entretemps pour cette période, merci de ne pas tenir compte de ce mail. \nCordialement, \n{} {}".format(
                            occupant_firstname, occupant_name, current_month,
                            admin_firstname, admin_name)
                        email_from = settings.EMAIL_HOST_USER
                        email = EmailMessage(
                            "Avis d\'échéance de loyer",
                            message,
                            email_from,
                            [occupant_email],
                        )
                        email.attach_file(item.echeance.path)
                        email.send(fail_silently=False)
                        self.stdout.write(
                            self.style.SUCCESS(
                                "Le mail pour {} a bien été envoyé".format(
                                    item.rental.occupant)))
                    except Echeance.DoesNotExist:
                        self.stdout.write(
                            self.style.WARNING(
                                "Le mail pour {} n\'a pas pu être envoyé".
                                format(item.rental.occupant)))

            except Exception as e:
                self.stdout.write(self.style.WARNING(e))
Beispiel #39
0
def booking(request):
    try:
        with transaction.atomic():
            seats_booking = int(request.data['seats_booking'])
            available_seat = MovieScreenTime.objects.get(
                id=request.data['MovieScreenTime_id']).available_seats
            seat_left = available_seat - seats_booking
            if available_seat >= seats_booking:

                user = User.objects.create(
                    username=uuid.uuid4().hex[:6].upper(),
                    email=request.data['email'],
                    phone_no=request.data['phone'],
                    first_name=request.data['first_name'],
                    last_name=request.data['last_name'])

                bookingid = Bookings.objects.create(
                    user=user,
                    movie_screens=MovieScreens.objects.get(
                        id=request.data['movie_screens_id']),
                    movie_screen_time=MovieScreenTime.objects.get(
                        id=request.data['MovieScreenTime_id']))
                MovieScreenTime.objects.filter(
                    id=request.data['MovieScreenTime_id']).update(
                        available_seats=seat_left)
                Screens.objects.filter(id=request.data['screen_id']).update(
                    seats=seat_left)
                movie_id = MovieScreens.objects.filter(
                    id=request.data['movie_screens_id']).values('movie')
                movie = Movie.objects.get(id__in=movie_id)

                hall_id = Screens.objects.filter(
                    id=request.data['screen_id']).values('cinema_halls')
                hall = Cinema_Halls.objects.get(id__in=hall_id)

                screen = Screens.objects.get(id=request.data['screen_id'])

                time = MovieScreenTime.objects.get(
                    id=request.data['MovieScreenTime_id'])

                list = []
                list.append(request.data['email'])
                try:
                    subject = "Booking Details"

                    email_body = """\
                        <html>
                            <head></head>
                            <body>
                                <h2>Dear %s, </h2>
                                <p> Thanks for the booking,
                                Here is your booking details:</p>
                                <p>Booking ID: %s</p>
                                <p>Movie: %s</p>
                                <p>Cinema Hall: %s</p>
                                <p>Screen No: %s</p>
                                <p>Booked Seats: %s</p>
                                <p>Show Timmings: %s to %s</p>
                                <p>Team BookMyShow
                                </p>
                            </body>
                        </html>
                        """ % (request.data['first_name'], bookingid.bookingId,
                               movie.name, hall.name, screen.number,
                               seats_booking, time.from_time, time.to_time)
                    email = EmailMessage('Booking Details',
                                         email_body,
                                         to=list)
                    email.content_subtype = "html"
                    response = email.send()
                    return Response(
                        {"message": "booking successfully completed"},
                        status=status.HTTP_200_OK)
                except Exception:
                    print(traceback.format_exc())
                    return Response(
                        {
                            "message": "something went wrong!",
                            "status": "0"
                        },
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            return Response(
                {
                    "message": "only" + seat_left + "seats left",
                    "status": "0"
                },
                status=status.HTTP_400_BAD_REQUEST)

    except Exception:
        print(traceback.format_exc())
        return Response({
            "message": "something went wrong!",
            "status": "0"
        },
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Beispiel #40
0
def contact(request):

    form_class = ContactForm

    context = {"contact_page":"active", 
              "page_name":"Global Water Explorer | Contact" }
    
    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            contact_name = request.POST.get(
                'contact_name'
            , '')
            contact_email = request.POST.get(
                'contact_email'
            , '')
            form_content = request.POST.get('content', '')

            # Email the profile with the
            # contact information
            template = get_template('contact_template.txt')
#            context = {
#                'contact_name': contact_name,
#                'contact_email': contact_email,
#                'form_content': form_content,
#            }

            context['contact_name'] = contact_name
            context['contact_email'] = contact_email
#            context['form_content'] = form_content   

            content = template.render(context)
#            content = 'waterExplorer/search.html')
            email = EmailMessage(
                "New contact form submission",
                content,
                "Your website" +'',
                ['*****@*****.**'],
                headers = {'Reply-To': contact_email }
            )

            email.send()

#            context["contact_page"] = "active"
#            context["page_name"] = "Global Water Explorer | Contact"
            context["message"] = 'Message sent. Thank you!'
#            context["form"] = form_class
#            return redirect('contact')
            return render(request, 'waterExplorer/contact.html', context)
        
        else: # form not valid 
#            context["contact_page"] = "active"
#            context["form"] = form_class
#            context["page_name"] = "Global Water Explorer | Contact"
            context["message"] = "Please try again"


    #context = {"form": form_class, "contact_page": "active", "page_name": "Global Water Explorer | Contact"}
    context["form"] = form_class
#    context["contact_page"] = "active"
#    context["page_name"] = "Global Water Explorer | Contact"
    return render(request, 'waterExplorer/contact.html', context)
Beispiel #41
0
def email_comment(gitlab, forge_id, author, comment, merge_id=None) -> None:
    """Email a comment made on Gitlab"""
    try:
        git_forge = GitForge.objects.get(host=urllib.parse.urlsplit(
            gitlab.url).hostname,
                                         forge_id=forge_id)
    except GitForge.DoesNotExist:
        _log.error(
            "Got comment event for project id %d, which isn't in the database",
            forge_id)
        return

    commit = comment.get("commit_id")
    try:
        bridged_submission = BridgedSubmission.objects.filter(
            git_forge=git_forge).order_by("-series_version")
        if merge_id:
            bridged_submission = bridged_submission.filter(
                merge_request=merge_id)
        if commit:
            bridged_submission = bridged_submission.filter(commit=commit)
        bridged_submission = bridged_submission[0]
    except IndexError:
        _log.info(
            "Unable to find a bridged submission for comment on MR %d, commit %s, forge %r",
            merge_id,
            commit,
            git_forge,
        )
        return

    from_email = settings.PATCHLAB_FROM_EMAIL.format(forge_user=author["name"])
    # From the bridged_submission, find the in-reply-to, create email.
    headers = {
        "Date": email_utils.formatdate(localtime=settings.EMAIL_USE_LOCALTIME),
        "Message-ID": email_utils.make_msgid(domain=DNS_NAME),
        "In-Reply-To": bridged_submission.submission.msgid,
        "X-Patchlab-Comment": comment["url"],
    }
    subject = "Re: " + " ".join(
        message_from_string(
            bridged_submission.submission.headers)["Subject"].splitlines())
    wrapped_description = "\n".join([
        textwrap.fill(line, width=72, replace_whitespace=False)
        for line in comment["note"].splitlines()
    ])
    body = (
        f"From: {author['name']} on {git_forge.host}\n{comment['url']}\n\n{wrapped_description}\n"
        f"")
    comment = EmailMessage(
        subject=subject,
        body=body,
        from_email=from_email,
        to=[git_forge.project.listemail],
        headers=headers,
        reply_to=[git_forge.project.listemail],
    )
    with get_connection(fail_silently=False) as conn:
        patchwork_parser.parse_mail(comment.message(),
                                    list_id=git_forge.project.listid)
        comment.connection = conn
        comment.send(fail_silently=False)
Beispiel #42
0
def generate_result(queries, email_address, username):
    N_RESULTS = 30
    queries = [query.strip() for query in queries]
    start_with = dict()
    end_with = dict()
    result = dict()
    for query in tqdm(queries):
        domain, length, zone = preprocess_domain(query)
        print('query: {}'.format(query))

        N = Domain.objects.all().count()
        print('Domain database size: %d' % N)
        print('Number of candidate domains: %d' % Domain.objects.filter(
            length__gte=length - 2).filter(length__lte=length + 5).count())

        all_domains = set()

        start_time = time()
        start_with_choices = Domain.objects.filter(name__startswith=domain)
        start_with[query] = [
            choice.name for choice in start_with_choices
            if choice.name not in all_domains
        ]
        domain_wo_hy = removeNonAlphanum(domain)
        if domain_wo_hy != domain:
            for d in Domain.objects.filter(name__startswith=domain_wo_hy):
                if d.name not in all_domains:
                    start_with[query].append(d.name)
        print('Start with selection: {}'.format(time() - start_time))
        start_with[query] = sorted(start_with[query])
        all_domains.update(start_with[query])

        start_time = time()
        end_with_choices = Domain.objects.filter(name__endswith=domain)
        end_with[query] = [
            choice.name for choice in end_with_choices
            if choice.name not in all_domains
        ]
        if domain_wo_hy != domain:
            for d in Domain.objects.filter(name__endswith=domain_wo_hy):
                if d.name not in all_domains:
                    end_with[query].append(d.name)
        print('End with selection: {}'.format(time() - start_time))
        end_with[query] = sorted(end_with[query])
        all_domains.update(end_with[query])

        n_workers = 4
        chunk = N // n_workers
        args = zip([N_RESULTS
                    for i in range(n_workers)], [i for i in range(n_workers)],
                   [chunk for _ in range(n_workers)],
                   repeat(domain, n_workers))
        print('Start map')
        with poolcontext(processes=n_workers) as pool:
            res = pool.starmap(findMatches, args)

        final_res = []
        for r in res:
            final_res += r
        final_res = sorted(final_res, key=lambda x: x[1])
        final_res = final_res[:N_RESULTS]

        final_res = [r for r in final_res if r[0] not in all_domains]
        all_domains.update([r[0] for r in final_res])

        for i in range(len(final_res)):
            final_res[i] = [str(r) for r in final_res[i]]
        final_res = [' '.join(res) for res in final_res]
        result[query] = final_res

    def pad_dict(d):
        values = d.values()
        length = max([len(val) for val in values])
        for key in d.keys():
            cur_len = len(d[key])
            if cur_len < length:
                for _ in range(length - cur_len):
                    d[key].append(None)
        return d

    pad_dict(start_with)
    pad_dict(end_with)
    pad_dict(result)

    result = pd.DataFrame(result)
    start_with = pd.DataFrame(start_with)
    end_with = pd.DataFrame(end_with)

    preview = ', '.join(queries[:3])
    preview += ' и др.' if len(queries) > 3 else ''
    print('email_address', email_address)
    file = (result.to_csv(sep='\t') + '\n\nStart matches:\n' +
            start_with.to_csv(sep='\t', header=None) + '\n\nEnd matches:\n' +
            end_with.to_csv(sep='\t', header=None))

    email = EmailMessage(
        'SwiftDaddy результаты для запросов: {}'.format(preview),
        'Привет, {0}! \nЛови похожие домены по твоим запросам: {1} в приложенном к письму файле.'
        .format(username, preview), '*****@*****.**', [email_address])
    email.attach('{}.xls'.format(preview), file, 'text/xls')
    email.send()
Beispiel #43
0
def completeaccount(request):
    if request.method == 'GET':
        if request.user.user_type == 'Patient':
            return render(request, 'mainapp/patientcompleteaccount.html')
        elif request.user.user_type == 'Doctor':
            return render(request, 'mainapp/doctorcompleteaccount.html')
        else:
            return HttpResponseRedirect(reverse('mainapp:reguser'))

    elif request.method == 'POST':
        if request.user.user_type == 'Patient':
            firstname = request.POST.get('firstname')
            lastname = request.POST.get('lastname')
            address = request.POST.get('address', default=None)
            phonenumber = request.POST.get('phonenumber', default=None)
            dateofbirth = request.POST.get('dateofbirth')
            age = dt.datetime.now().year - int(dateofbirth[0:4])
            sex = request.POST.get('sex')
            user = request.user
            patient_obj = Patient(user=user,
                                  firstname=firstname,
                                  lastname=lastname,
                                  dateofbirth=dateofbirth,
                                  address=address,
                                  phonenumber=phonenumber,
                                  age=age,
                                  sex=sex)
            if patient_obj:
                patient_obj.doctor = getmatchingdoctor()
                em = patient_obj.doctor.user.email
                body = "{} is now your patient! ".format(
                    patient_obj.user.username)
                mel = EmailMessage("New Patient", body, to=[em])
                mel.send()
                patient_obj.save()
                return HttpResponseRedirect(reverse('mainapp:dashboard'))
            else:
                return HttpResponseRedirect(reverse('mainapp:reguser'))

        elif request.user.user_type == 'Doctor':
            firstname = request.POST.get('firstname')
            lastname = request.POST.get('lastname')
            phonenumber = request.POST.get('phonenumber', default=None)
            user = request.user
            degrees = request.POST.get('degrees')
            registrationno = request.POST.get('registrationno')
            bio = request.POST.get('bio')
            doctor_obj = Doctor(user=user,
                                firstname=firstname,
                                lastname=lastname,
                                phonenumber=phonenumber,
                                degrees=degrees,
                                registrationno=registrationno,
                                bio=bio)
            if doctor_obj:
                doctor_obj.save()
                return HttpResponseRedirect(reverse('mainapp:dashboard'))
            else:
                return HttpResponseRedirect(reverse('mainapp:reguser'))
    else:
        return HttpResponseRedirect(reverse('mainapp:reguser'))
Beispiel #44
0
    def grade(self, page_context, page_data, answer_data, grade_data):
        if answer_data is None:
            return AnswerFeedback(correctness=0,
                                  feedback=_("No answer provided."))

        user_code = answer_data["answer"]

        # {{{ request run

        run_req = {"compile_only": False, "user_code": user_code}

        def transfer_attr(name):
            if hasattr(self.page_desc, name):
                run_req[name] = getattr(self.page_desc, name)

        transfer_attr("setup_code")
        transfer_attr("names_for_user")
        transfer_attr("names_from_user")

        run_req["test_code"] = self.get_test_code()

        if hasattr(self.page_desc, "data_files"):
            run_req["data_files"] = {}

            from course.content import get_repo_blob

            for data_file in self.page_desc.data_files:
                from base64 import b64encode
                run_req["data_files"][data_file] = \
                        b64encode(
                                get_repo_blob(
                                    page_context.repo, data_file,
                                    page_context.commit_sha).data).decode()

        try:
            response_dict = request_run_with_retries(
                run_req,
                run_timeout=self.page_desc.timeout,
                image=self.container_image)
        except Exception:
            from traceback import format_exc
            response_dict = {
                "result": "uncaught_error",
                "message": "Error connecting to container",
                "traceback": "".join(format_exc()),
            }

        # }}}

        feedback_bits = []

        correctness = None

        if "points" in response_dict:
            correctness = response_dict["points"]
            try:
                feedback_bits.append("<p><b>%s</b></p>" %
                                     _(get_auto_feedback(correctness)))
            except Exception as e:
                correctness = None
                response_dict["result"] = "setup_error"
                response_dict["message"] = ("%s: %s" %
                                            (type(e).__name__, str(e)))

        # {{{ send email if the grading code broke

        if response_dict["result"] in [
                "uncaught_error", "setup_compile_error", "setup_error",
                "test_compile_error", "test_error"
        ]:
            error_msg_parts = ["RESULT: %s" % response_dict["result"]]
            for key, val in sorted(response_dict.items()):
                if (key not in ["result", "figures"] and val
                        and isinstance(val, six.string_types)):
                    error_msg_parts.append(
                        "-------------------------------------")
                    error_msg_parts.append(key)
                    error_msg_parts.append(
                        "-------------------------------------")
                    error_msg_parts.append(val)
            error_msg_parts.append("-------------------------------------")
            error_msg_parts.append("user code")
            error_msg_parts.append("-------------------------------------")
            error_msg_parts.append(user_code)
            error_msg_parts.append("-------------------------------------")

            error_msg = "\n".join(error_msg_parts)

            from relate.utils import local_now, format_datetime_local
            from course.utils import LanguageOverride
            with LanguageOverride(page_context.course):
                from relate.utils import render_email_template
                message = render_email_template(
                    "course/broken-code-question-email.txt", {
                        "site": getattr(settings, "RELATE_BASE_URL"),
                        "page_id": self.page_desc.id,
                        "course": page_context.course,
                        "error_message": error_msg,
                        "review_uri": page_context.page_uri,
                        "time": format_datetime_local(local_now())
                    })

                if (not page_context.in_sandbox
                        and not is_nuisance_failure(response_dict)):
                    try:
                        from django.core.mail import EmailMessage
                        msg = EmailMessage(
                            "".join([
                                "[%s:%s] ",
                                _("code question execution failed")
                            ]) % (page_context.course.identifier,
                                  page_context.flow_session.flow_id
                                  if page_context.flow_session is not None else
                                  _("<unknown flow>")), message,
                            settings.ROBOT_EMAIL_FROM,
                            [page_context.course.notify_email])

                        from relate.utils import get_outbound_mail_connection
                        msg.connection = get_outbound_mail_connection("robot")
                        msg.send()

                    except Exception:
                        from traceback import format_exc
                        feedback_bits.append(
                            six.text_type(
                                string_concat(
                                    "<p>",
                                    _("Both the grading code and the attempt to "
                                      "notify course staff about the issue failed. "
                                      "Please contact the course or site staff and "
                                      "inform them of this issue, mentioning this "
                                      "entire error message:"), "</p>", "<p>",
                                    _("Sending an email to the course staff about the "
                                      "following failure failed with "
                                      "the following error message:"), "<pre>",
                                    "".join(format_exc()), "</pre>",
                                    _("The original failure message follows:"),
                                    "</p>")))

        # }}}

        if hasattr(self.page_desc, "correct_code"):

            def normalize_code(s):
                return (s.replace(" ", "").replace("\r", "").replace(
                    "\n", "").replace("\t", ""))

            if (normalize_code(user_code) == normalize_code(
                    self.page_desc.correct_code)):
                feedback_bits.append(
                    "<p><b>%s</b></p>" %
                    _("It looks like you submitted code that is identical to "
                      "the reference solution. This is not allowed."))

        from relate.utils import dict_to_struct
        response = dict_to_struct(response_dict)

        bulk_feedback_bits = []

        if response.result == "success":
            pass
        elif response.result in [
                "uncaught_error", "setup_compile_error", "setup_error",
                "test_compile_error", "test_error"
        ]:
            feedback_bits.append("".join([
                "<p>",
                _("The grading code failed. Sorry about that. "
                  "The staff has been informed, and if this problem is "
                  "due to an issue with the grading code, "
                  "it will be fixed as soon as possible. "
                  "In the meantime, you'll see a traceback "
                  "below that may help you figure out what went wrong."),
                "</p>"
            ]))
        elif response.result == "timeout":
            feedback_bits.append("".join([
                "<p>",
                _("Your code took too long to execute. The problem "
                  "specifies that your code may take at most %s seconds "
                  "to run. "
                  "It took longer than that and was aborted."), "</p>"
            ]) % self.page_desc.timeout)

            correctness = 0
        elif response.result == "user_compile_error":
            feedback_bits.append("".join([
                "<p>",
                _("Your code failed to compile. An error message is "
                  "below."), "</p>"
            ]))

            correctness = 0
        elif response.result == "user_error":
            feedback_bits.append("".join([
                "<p>",
                _("Your code failed with an exception. "
                  "A traceback is below."), "</p>"
            ]))

            correctness = 0
        else:
            raise RuntimeError("invalid run result: %s" % response.result)

        if hasattr(response, "feedback") and response.feedback:

            def sanitize(s):
                import bleach
                return bleach.clean(s, tags=["p", "pre"])

            feedback_bits.append("".join([
                "<p>",
                _("Here is some feedback on your code"), ":"
                "<ul>%s</ul></p>"
            ]) % "".join("<li>%s</li>" % sanitize(fb_item)
                         for fb_item in response.feedback))
        if hasattr(response, "traceback") and response.traceback:
            feedback_bits.append("".join([
                "<p>",
                _("This is the exception traceback"), ":"
                "<pre>%s</pre></p>"
            ]) % escape(response.traceback))
        if hasattr(response,
                   "exec_host") and response.exec_host != "localhost":
            import socket
            try:
                exec_host_name, dummy, dummy = socket.gethostbyaddr(
                    response.exec_host)
            except socket.error:
                exec_host_name = response.exec_host

            feedback_bits.append("".join(
                ["<p>",
                 _("Your code ran on %s.") % exec_host_name, "</p>"]))

        if hasattr(response, "stdout") and response.stdout:
            bulk_feedback_bits.append("".join([
                "<p>",
                _("Your code printed the following output"), ":"
                "<pre>%s</pre></p>"
            ]) % escape(response.stdout))
        if hasattr(response, "stderr") and response.stderr:
            bulk_feedback_bits.append("".join([
                "<p>",
                _("Your code printed the following error messages"), ":"
                "<pre>%s</pre></p>"
            ]) % escape(response.stderr))
        if hasattr(response, "figures") and response.figures:
            fig_lines = [
                "".join([
                    "<p>",
                    _("Your code produced the following plots"), ":</p>"
                ]),
                '<dl class="result-figure-list">',
            ]

            for nr, mime_type, b64data in response.figures:
                if mime_type in ["image/jpeg", "image/png"]:
                    fig_lines.extend([
                        "".join(["<dt>", _("Figure"), "%d<dt>"]) % nr,
                        '<dd><img alt="Figure %d" src="data:%s;base64,%s"></dd>'
                        % (nr, mime_type, b64data)
                    ])

            fig_lines.append("</dl>")
            bulk_feedback_bits.extend(fig_lines)

        # {{{ html output / santization

        if hasattr(response, "html") and response.html:

            def is_allowed_data_uri(allowed_mimetypes, uri):
                import re
                m = re.match(r"^data:([-a-z0-9]+/[-a-z0-9]+);base64,", uri)
                if not m:
                    return False

                mimetype = m.group(1)
                return mimetype in allowed_mimetypes

            def sanitize(s):
                import bleach

                def filter_audio_attributes(tag, name, value):
                    if name in ["controls"]:
                        return True
                    else:
                        return False

                def filter_source_attributes(tag, name, value):
                    if name in ["type"]:
                        return True
                    elif name == "src":
                        if is_allowed_data_uri([
                                "audio/wav",
                        ], value):
                            return bleach.sanitizer.VALUE_SAFE
                        else:
                            return False
                    else:
                        return False

                def filter_img_attributes(tag, name, value):
                    if name in ["alt", "title"]:
                        return True
                    elif name == "src":
                        return is_allowed_data_uri([
                            "image/png",
                            "image/jpeg",
                        ], value)
                    else:
                        return False

                if not isinstance(s, six.text_type):
                    return _("(Non-string in 'HTML' output filtered out)")

                return bleach.clean(s,
                                    tags=bleach.ALLOWED_TAGS +
                                    ["audio", "video", "source"],
                                    attributes={
                                        "audio": filter_audio_attributes,
                                        "source": filter_source_attributes,
                                        "img": filter_img_attributes,
                                    })

            bulk_feedback_bits.extend(
                sanitize(snippet) for snippet in response.html)

        # }}}

        return AnswerFeedback(correctness=correctness,
                              feedback="\n".join(feedback_bits),
                              bulk_feedback="\n".join(bulk_feedback_bits))
Beispiel #45
0
    def send_email(data):

        email = EmailMessage(subject=data['email_subject'],
                             body=data['email_body'],
                             to=[data['to_email']])
        email.send()
Beispiel #46
0
    def form_valid(self, form, detalle_compra_form_set):

        #obtenemos la ultima de su  serie prara generar un nuevo numero
        qsComp_last = Compra.objects.filter(
            lfact=form.instance.titular.letra).order_by('nfact').last()

        if qsComp_last:
            form.instance.nfact = qsComp_last.nfact + 1
        else:
            form.instance.nfact = 1
        form.instance.lfact = form.instance.titular.letra

        self.object = form.save()
        detalle_compra_form_set.instance = self.object
        detalle_compra_form_set.save()
        total_base = 0

        detalles = DetalleCompra.objects.filter(
            compra=self.object).order_by('pk')
        for detalle in detalles:
            d = {
                'producto': detalle.producto,
                'cantidad': detalle.cantidad,
                'precio_compra': detalle.precio_compra
            }

            #sumamos los kilos de cada detalle en su almacen(silo)
            #p = Producto.objects.get(descripcion=detalle.producto)
            #p.kilos = p.kilos + detalle.cantidad
            #p.save()

            detalle.producto.kilos += detalle.cantidad
            detalle.producto.save()

            # si el producto entra a un silo con lote
            if detalle.producto.lote:
                detalle.lote_heredado = detalle.producto.lote
                print("detalle lote", detalle.lote_heredado)
                detalle.save()
                #detalle.save(update_fields=["lote_heredado"])
                #DetalleVenta.objects.get(pk=detalle.pk).save(update_fields=["lote_heredado"])

            #qs = DetalleVenta.objects.get(pk =detalle.pk)
            #print("guardado en historico ", qs.producto, qs.cantidad, qs.precio_venta, qs.lote_heredado)
            Historico.objects.create(compra=detalle.compra,
                                     producto=detalle.producto,
                                     cantidad=detalle.cantidad,
                                     precio_compra=detalle.precio_compra,
                                     fecha=detalle.fecha,
                                     lote_heredado=detalle.lote_heredado,
                                     kilos_actuales=detalle.producto.kilos)

            #calculamos su precio base
            total_detalle = detalle.cantidad * detalle.precio_compra
            print("valores en €")
            print(detalle.producto, total_detalle)
            total_base = total_base + total_detalle

        print("base ", total_base)
        #aplicamos impuestos
        form.instance.base = total_base
        form.instance.imp_aplicado = total_base * form.instance.impuestos.impuesto1 / 100
        print("valor de impuestto 1 ", form.instance.imp_aplicado)
        #Comprobamos si hay un segundo impuesto a aplicar
        if form.instance.impuestos.impuesto2:
            if form.instance.impuestos.se_calcula_con == "BASE":
                form.instance.imp_aplicado = form.instance.imp_aplicado + total_base * form.instance.impuestos.impuesto2 / 100
                print("calculando impuesto 2 BASE ",
                      form.instance.imp_aplicado)
            if form.instance.impuestos.se_calcula_con == "TOTAL":
                form.instance.imp_aplicado = form.instance.imp_aplicado + (
                    form.instance.imp_aplicado +
                    total_base) * form.instance.impuestos.impuesto2 / 100
                print("calculando impuesto 2 TOTAL",
                      form.instance.imp_aplicado)
        form.instance.total = total_base + form.instance.imp_aplicado

        print("impuestos ", form.instance.imp_aplicado)
        print("total", form.instance.total)

        form.instance.save()

        ############# PDF ###################

        # obtenemos los detalles de esta facuta para crear un nested dict
        detalles = DetalleCompra.objects.filter(compra=form.instance.pk)
        lineas = {}
        i = 1
        for d in detalles:
            detalle_total = d.precio_compra * d.cantidad
            lineas['linea' + str(i)] = {
                'producto': d.producto.variedad,
                'cantidad': d.cantidad,
                'precio': d.precio_compra,
                'total': detalle_total,
                'lote_heredado': d.lote_heredado
            }
            i = i + 1

        compra = Compra.objects.get(pk=form.instance.pk)
        context = {
            'numero': compra.nfact,
            'fecha': compra.fecha,
            'forma_pago': compra.forma_pago,
            'titular_nombre': compra.titular.nombre,
            'titular_cif': compra.titular.cif,
            'titular_direccion': compra.titular.direccion,
            'proveedor_nombre': compra.proveedor.razon_social,
            'proveedor_ruc': compra.proveedor.ruc,
            'proveedor_direccion': compra.proveedor.direccion,
            'proveedor_certificado': compra.proveedor.entidad_certificadora,
            'base': compra.base,
            'impuestos': compra.impuestos,
            'imp_aplicado': compra.imp_aplicado,
            'total': compra.total,
            'lineas': lineas
        }
        print(context)
        '''context = {
            'acta': qsacta,
            'laboratorio': qslaboratorio,
            'muestreo': qsmuestreo,
            'pk': pk,
            'tipo': tipo
        }'''

        template_path = 'plantilla_email.html'
        template = get_template(template_path)
        # html = template.render(form.instance.__dict__)
        html = template.render(context)
        # print(form.instance.__dict__)

        ## definir los datos del diccionario, este no sirve
        ## hacer bien los estilos, los de boostrap no funcionan
        ## los estilos que soporta estan bastante limitados
        ## https://xhtml2pdf.readthedocs.io/en/latest/reference.html#supported-css-properties

        ndocumento1 = "factura" + str(form.instance.nfact) + ".pdf"
        #ddocumento = os.path.join(settings.MEDIA_ROOT, ndocumento1)
        ddocumento = ndocumento1
        outFilename = ddocumento
        outFile = open(outFilename.encode("utf-8"), "w+b")
        pisaStatus = pisa.CreatePDF(html.encode('utf-8'),
                                    dest=outFile,
                                    encoding='utf-8')
        outFile.close()
        ndocumento = ddocumento
        # ddocumento = os.path.join(settings.MEDIA_ROOT, ndocumento)
        leerdocumento = open(ddocumento.encode("utf-8"), "rb").read()

        ############### EMAIL ##################33

        b = base64.b64encode(leerdocumento).decode("utf-8", "ignore")

        nombredocumento = "factura" + str(form.instance.nfact) + ".pdf"
        email = "*****@*****.**"
        asunto = "Factura de compra"
        cuerpo = "Buenos dias, adjuntamos factura de compra"
        body = cuerpo
        # Replace this texto in plantilla cuerpo
        body_content = mark_safe(body)
        html_content = mark_safe(body_content)
        remitente = settings.EMAIL_HOST_USER
        destinatario = email
        try:
            msg = EmailMessage(asunto, html_content, remitente, [destinatario])
            msg.attach(nombredocumento, leerdocumento, "application/pdf")
            msg.content_subtype = "pdf"  # Main content is now text/html
            msg.encoding = 'utf-8'
            msg.send()
            print("mensaje enviado ")
        except Exception as e:
            print("no se ha podido enviar ", e)

        return HttpResponseRedirect(self.success_url)
Beispiel #47
0
 def run(self):
     time.sleep(20)
     print "Sending Mail....."
     self = self.voucher
     output_path = os.getcwd() + '/templates/output/test.pdf'
     if not self.confirmed:
         # NORMAL VOUCHER
         if self.type == 'normal':
             data = {
                 'current_date': date.today(),
                 'image_path': os.getcwd() + '/templates/images/logo.png',
                 'no_of_pax': self.no_of_pax,
                 'arrival': self.arrival,
                 'departure': self.pickup_place,
                 'rooms': self.no_of_rooms,
                 'duration': self.package_type,
                 'itinerary': self.itenary_set.all().values(),
                 'hotels': self.hotel_set.all().values(),
                 'vehicle': self.vehicle_set.all().values(),
                 'amount': self.price,
                 'inclusion': self.package_inclusion.split("\n"),
                 'exclusion': self.package_exclusion.split("\n"),
                 'reservation_policy': self.reservation_policy.split("\n"),
                 'cancellation_policy':
                 self.cancellation_policy.split("\n"),
                 'terms': self.terms_conditions.split("\n"),
                 'special_service': self.specialservice_set.all().values()
             }
             output_path = os.getcwd(
             ) + '/templates/output/' + self.name_of_guest + ".pdf"
             template = get_template('quoteVoucher.html')
             html = template.render(data)
             pdfkit.from_string(html, output_path)
             msg = EmailMessage('Quote Voucher',
                                'Please find the quotation attached',
                                '*****@*****.**', [self.email_id])
             msg.content_subtype = "html"
             msg.attach_file(output_path)
             msg.send()
             # ANDAMAN VOUCHER
         elif self.type == 'andaman':
             data = {
                 'current_date':
                 date.today(),
                 'image_path':
                 os.getcwd() + '/templates/images/logo.png',
                 'confirmation_no':
                 self.hotel_set.all().values()[0]['confirmation_number'],
                 'tour_manager':
                 self.hotel_set.all().values()[0]['contact_person'] +
                 " - " +
                 str(self.hotel_set.all().values()[0]['phone_number']),
                 'city':
                 self.package_type,
                 'hotels':
                 self.hotel_set.all().values(),
                 'name_of_guest':
                 self.name_of_guest,
                 'arrival':
                 self.arrival,
                 'pickup_place':
                 self.pickup_place,
                 'rooms':
                 self.no_of_rooms,
                 'no_of_pax':
                 self.no_of_pax,
                 'meal_plan':
                 self.hotel_set.all().values()[0]['meal_plan'],
                 'vehicle_name':
                 self.vehicle_set.all().values()[0]['name'],
                 'itinerary':
                 self.itenary_set.all().values()
             }
             template = get_template('andamanVoucher.html')
             html = template.render(data)
             pdfkit.from_string(html, output_path)
             msg = EmailMessage('Andaman Voucher',
                                'Please find the quotation attached',
                                '*****@*****.**', [self.email_id])
             msg.content_subtype = "html"
             msg.attach_file(output_path)
             msg.send()
             # GOA VOUCHER
         elif self.type == 'goa':
             hotel = self.hotel_set.all().values()[0]
             data = {
                 'current_date':
                 date.today(),
                 'image_path':
                 os.getcwd() + '/templates/images/logo.png',
                 'confirmation_no':
                 self.hotel_set.all().values()[0]['confirmation_number'],
                 'hotel':
                 hotel['name'] + "<br />\n" + hotel['address'],
                 'name_of_guest':
                 self.name_of_guest,
                 'check_in':
                 hotel['check_in'],
                 'check_out':
                 hotel['check_out'],
                 'no_of_pax':
                 self.no_of_pax,
                 'no_of_nights':
                 hotel['no_of_nights'],
                 'rooms':
                 self.no_of_rooms,
                 'room_type':
                 hotel['room_type'],
                 'meal_plan':
                 hotel['meal_plan'],
                 'inclusion':
                 self.package_inclusion.split("\n"),
                 'cancellation_policy':
                 self.cancellation_policy.split("\n")
             }
             template = get_template('goaVoucher.html')
             html = template.render(data)
             pdfkit.from_string(html, output_path)
             msg = EmailMessage('Goa Voucher',
                                'Please find the quotation attached',
                                '*****@*****.**', [self.email_id])
             msg.content_subtype = "html"
             msg.attach_file(output_path)
             msg.send()
         # HIMACHAL VOUCHER
         elif self.type == 'himachal':
             data = {
                 'current_date':
                 date.today(),
                 'image_path':
                 os.getcwd() + '/templates/images/logo.png',
                 'confirmation_no':
                 self.hotel_set.all().values()[0]['confirmation_number'],
                 'tour_manager':
                 self.hotel_set.all().values()[0]['contact_person'] +
                 " - " +
                 str(self.hotel_set.all().values()[0]['phone_number']),
                 'city':
                 self.package_type,
                 'hotels':
                 self.hotel_set.all().values(),
                 'name_of_guest':
                 self.name_of_guest,
                 'arrival':
                 self.arrival,
                 'pickup_place':
                 self.pickup_place,
                 'rooms':
                 self.no_of_rooms,
                 'no_of_pax':
                 self.no_of_pax,
                 'vehicle_name':
                 self.vehicle_set.all().values()[0]['name'],
                 'itinerary':
                 self.itenary_set.all().values()
             }
             template = get_template('himachalVoucher.html')
             html = template.render(data)
             pdfkit.from_string(html, output_path)
             msg = EmailMessage('Himachal Voucher',
                                'Please find the quotation attached',
                                '*****@*****.**', [self.email_id])
             msg.content_subtype = "html"
             msg.attach_file(output_path)
             msg.send()
     # HOTEL AND DRIVER VOUCHER
     else:
         msg = EmailMessage('Hotel and Driver Voucher',
                            'Please find the voucher attached',
                            '*****@*****.**', [self.email_id])
         for i in self.hotel_set.all().values():
             data = {
                 'current_date': date.today(),
                 'image_path': os.getcwd() + '/templates/images/logo.png',
                 'hotel_name': i['name'],
                 'address': i['address'],
                 'guest_name': self.name_of_guest,
                 'check_in': i['check_in'],
                 'check_out': i['check_out'],
                 'no_of_pax': self.no_of_pax,
                 'meal_plan': i['meal_plan'],
                 'room_type': i['room_type'],
                 'no_of_nights': i['no_of_nights'],
                 'occupancy_type': i['occupancy_type'],
                 'no_of_rooms': i['no_of_rooms'],
                 'contact_name': i['contact_person'],
                 'mobile_no': i['phone_number'],
                 'contact_position': i['contact_person_position'],
                 'place': i['place'],
                 'confirmation_no': i['confirmation_number']
             }
             template = get_template('hotelVoucher.html')
             html = template.render(data)
             pdfkit.from_string(html, output_path)
             msg.content_subtype = "html"
             msg.attach_file(output_path)
         driver_data = {
             'current_date':
             date.today(),
             'confirmation_no':
             self.vehicle_set.all().values()[0]['confirmation_number'],
             'guest_name':
             self.name_of_guest,
             'image_path':
             os.getcwd() + '/templates/images/logo.png',
             'arrival':
             self.arrival,
             'departure':
             self.pickup_place,
             'duration':
             self.package_type,
             'itinerary':
             self.itenary_set.all().values,
             'hotels':
             self.hotel_set.all().values,
             'vehicle':
             self.vehicle_set.all().values,
             'special_service':
             self.specialservice_set.all().values
         }
         template = get_template('driverVoucher.html')
         html = template.render(driver_data)
         pdfkit.from_string(html, output_path)
         msg.content_subtype = "html"
         msg.attach_file(output_path)
         msg.send()
Beispiel #48
0
def processado_function(banco, course, datestart, datefinish, PROJECT_PATH,
                        request):
    if banco.historico_treino.find({'course': str(course)}).count() > 0:
        messages.error(
            request,
            'Disciplina já processada pelo sistema, se quiser processa-la em outro período delete o existente!'
        )
        return redirect('home')
    else:
        #pré processamento e contagem para alunos, data e período de tempo
        banco.intermediaria_processado.insert_many(
            list(
                banco.data_lake.find({
                    'roleid': 5,
                    'courseid': course,
                    'timecreated': {
                        "$gt": datestart,
                        "$lt": datefinish
                    }
                })))

        #consultas a serem realizadas no banco do mongodb
        pre_processamento(banco)

        #prepara os dados criando colunas, caso elas não existam
        all_entries = banco.processado.find({})
        df = pd.DataFrame(list(all_entries))
        df = df.fillna(0)
        target_list = [
            'Created_Discussion_Subscription', 'Created_Post',
            'Created_Submission', 'Total_Action', 'Total_Created',
            'Total_Viewed', 'Viewed_Attempt', 'Viewed_Course',
            'Viewed_Course_Module', 'Viewed_Discussion', 'Viewed_Grade_Report',
            'Viewed_Message', 'Viewed_Submission_Form',
            'Viewed_Submission_Status'
        ]
        df = df.reindex(sorted(df.columns), axis=1)
        if len(df.columns) < 16:
            l = [x for x in target_list if x not in df.columns]
            for i in range(len(l)):
                df[l[i]] = 0
        df = df.reindex(sorted(df.columns), axis=1)

        #inicio da passagem pelo kmeans para obter a conta utilizada
        X = df.drop(columns={'_id'})
        kmeans = KMeans(n_clusters=5, init='k-means++', max_iter=3000)
        kmeans.fit(X)
        clusters = kmeans.cluster_centers_
        #conta a partir do cluster
        clusters = pd.DataFrame(clusters)
        contas = pd.DataFrame([{
            "mean": clusters.mean().mean(),
            "max": clusters.max().max(),
            "min": clusters[clusters != 0].min().min()
        }])
        conta = contas.sum(axis=1) / X['Total_Action'].count()
        conta = conta.iloc[0]

        #verifica se existem redes treinadas no sistema
        all_entries = banco.historico_redes.find({})
        redes = pd.DataFrame(list(all_entries))
        if redes.empty:
            opcoes = pd.DataFrame()
        #se existirem redes e verificado se esta pode ser utilizada
        #para que possa ser utilizada o resultado da conta precisa estar dentro de uma margem de 5 de diferença com a rede treinada
        else:
            opcoes = redes['contas'][redes[["contas"]].apply(np.isclose,
                                                             b=conta,
                                                             atol=5).any(1)]

        import keras
        from keras.utils.np_utils import to_categorical
        from keras import backend as K

        if opcoes.empty:
            #sem opcão de rede ou de tabela de rotulos
            print('Rede nova')
            K.clear_session()
            #encontra todos os alunos cadastrados nesse curso, independete do acesso no período
            users = banco.data_lake.find({
                'action': 'viewed',
                'target': 'course',
                'roleid': 5,
                'courseid': course
            })
            users = pd.DataFrame(list(users))
            #cria o rotulo de acesso no período
            users['acao'] = users['timecreated'].apply(create_rotulo,
                                                       datestart=datestart,
                                                       datefinish=datefinish)
            users = users.groupby(['userid'])['acao'].sum().reset_index()
            users['rotulo'] = users['acao'].apply(numerar_rotulo)
            #junta alunos cadastrados que não acessaram com os que acessaram
            j_users = users.join(df.set_index("_id"), on="userid", how='left')
            #dados limpos para a rede
            X = j_users.fillna(0).drop(columns={'userid', 'acao', 'rotulo'})
            y = j_users['rotulo']
            classifier = criar_primeira_rede(X, y)
            #retira o predict pos treino
            j_users['rede'] = classifier.predict(X)
            j_users['rede'] = j_users['rede'].apply(saida_rede)
            course = str(course)
            historico = {
                'course': course,
                'datestart': datestart,
                'datefinish': datefinish,
                'conta': conta
            }
            datestart = pd.to_datetime(datestart, unit='s')
            datestart = datestart.strftime('%Y-%m-%d')
            datefinish = pd.to_datetime(datefinish, unit='s')
            datefinish = datefinish.strftime('%Y-%m-%d')
            collect = banco[course + "_" + datestart + "_" + datefinish]

            #salva os dados para acesso do treinamento na tabela ponteiro
            banco.historico_treino.insert_one(historico)
            j_users = j_users.drop(columns={'acao', 'rotulo'})
            j_users = j_users.rename(columns={'userid': '_id'})

            #salva os dados do treinamento na tabela endereçada
            collect.insert_many(j_users.to_dict('records'))
            #salva o treinamento da rede
            joblib.dump(classifier,
                        PROJECT_PATH + "/models/rede" + str(conta) + ".sav")
            banco.historico_redes.insert_one({'contas': conta})
            messages.success(request, 'Dados processados com sucesso!')

            #enviar mensagem
            collect = banco[course + "_" + datestart + "_" + datefinish]
            all_entries = collect.find({})
            df = pd.DataFrame(list(all_entries))
            df = df.fillna(0)
            all_entries = banco.mdl_user.find({})
            users = pd.DataFrame(list(all_entries))

            join = df.join(users.set_index("id"),
                           on="_id",
                           how='left',
                           lsuffix='_left',
                           rsuffix='_right')
            subset = join[['_id_left', 'firstname', 'lastname', 'rede']]
            subset = subset.rename(columns={'_id_left': '_id'})
            subset['rede'] = subset['rede'].apply(nomear_classificacao)
            subset['nome'] = subset['firstname'] + ' ' + subset['lastname']
            historico = banco.historico_treino.find({'course': str(course)})
            historico = pd.DataFrame(list(historico))
            rotulados = banco["h" + str(historico['conta'].iloc[0])]
            rotulos = rotulados.find({})
            rotulos = pd.DataFrame(list(rotulos))
            if rotulos.empty:
                subset = subset.rename(columns={'rede': 'rotulo'})
                subset.rotulo = pd.Categorical(subset.rotulo,
                                               categories=[
                                                   "Alto Risco",
                                                   "Risco Intermediário",
                                                   "Sem Risco", "Não Ativo",
                                                   "Ativo"
                                               ],
                                               ordered=True)
                subset = subset.sort_values(by=["rotulo", "nome"])
            else:
                r_join = subset.join(rotulos.set_index("_id"),
                                     on="_id",
                                     how='left')
                r_join['rotulo'] = r_join['rotulo'].fillna(r_join['rede'])
                r_join['rotulo'] = r_join['rotulo'].apply(nomear_rotulo)

                subset = r_join[[
                    '_id', 'firstname', 'lastname', 'rotulo', 'nome'
                ]]
                subset = subset.rename(columns={'_id_left': '_id'})
                subset.rotulo = pd.Categorical(subset.rotulo,
                                               categories=[
                                                   "Alto Risco",
                                                   "Risco Intermediário",
                                                   "Sem Risco", "Não Ativo",
                                                   "Ativo"
                                               ],
                                               ordered=True)
                subset = subset.sort_values(by=["rotulo", "nome"])

            admin = User.objects.filter(groups__name='admin')
            coordenador = User.objects.filter(groups__name='coordenador')
            email = []
            email2 = []
            for i in range(len(admin)):
                email.append(admin[i].email)
            for j in range(len(coordenador)):
                email2.append(coordenador[j].email)

            email_final = email + email2
            email = EmailMessage('Relatorio-alunos',
                                 'relatorio dos alunos',
                                 '*****@*****.**',
                                 bcc=email_final)

            all_entries = banco.historico_treino.find({'course': course})
            df = pd.DataFrame(list(all_entries))
            df = df.fillna(0)

            all_entries = banco.mdl_course.find({})
            df2 = pd.DataFrame(list(all_entries))
            df2 = df2.fillna(0)
            df["course"] = df["course"].astype(int)
            join = df.join(df2.set_index("id"),
                           on="course",
                           how='left',
                           lsuffix='_left',
                           rsuffix='_right')
            join = join[[
                'course', 'datestart', 'datefinish', 'fullname', 'category'
            ]]

            all_entries = banco.mdl_course_categories.find({})
            df3 = pd.DataFrame(list(all_entries))
            df3 = df3.fillna(0)
            join = join.join(df3.set_index("id"), on="category", how='left')
            join = join[[
                'course', 'datestart', 'datefinish', 'fullname', 'category',
                'name'
            ]]
            join['datestart'] = pd.to_datetime(join['datestart'], unit='s')
            join['datestart'] = join['datestart'].apply(
                lambda x: x.strftime('%Y-%m-%d'))
            join['datefinish'] = pd.to_datetime(join['datefinish'], unit='s')
            join['datefinish'] = join['datefinish'].apply(
                lambda x: x.strftime('%Y-%m-%d'))

            subset = subset[["nome", "rotulo"]]
            subset.to_csv('relatorio.csv')
            data = []
            attachment_csv_file = StringIO()
            writer = csv.writer(attachment_csv_file)
            with open('relatorio.csv', 'r') as f:
                f_csv = csv.reader(f)
                # header = next(f_csv)
                for row in f_csv:
                    data.append(row)
            for i in range(int(len(data))):
                writer.writerow(data[i])
            email.attach(
                'relatorio_' + join['name'].iloc[0] + '_' +
                join['fullname'].iloc[0] + '.csv',
                attachment_csv_file.getvalue(), 'text/csv')
            email.send(fail_silently=False)
        else:
            #com opcão de rede para ser usada
            print('Rede usada')

            opcao = opcoes.iloc[0]
            collect = banco["h" + str(opcao)]
            rotulado = collect.find({})
            rotulado = pd.DataFrame(list(rotulado))

            if rotulado.empty or df.join(rotulado.set_index("_id"),
                                         on="_id",
                                         how='inner',
                                         lsuffix='_left',
                                         rsuffix='_right').empty:
                #sem tabela de rotulado para o treinamento
                #realiza processo de busca de todos os usuários cadastrados no curso
                users = banco.data_lake.find({
                    'action': 'viewed',
                    'target': 'course',
                    'roleid': 5,
                    'courseid': course
                })
                users = pd.DataFrame(list(users))
                #cria o rotulo para o periodo para todos os alunos
                users['acao'] = users['timecreated'].apply(
                    create_rotulo, datestart=datestart, datefinish=datefinish)
                users = users.groupby(['userid'])['acao'].sum().reset_index()
                users['rotulo'] = users['acao'].apply(numerar_rotulo)

                #prepara os dados da rede
                j_users = users.join(df.set_index("_id"),
                                     on="userid",
                                     how='left')
                X = j_users.fillna(0).drop(
                    columns={'userid', 'acao', 'rotulo'})
                y = j_users['rotulo']

                K.clear_session()
                #carrega a rede selecionada para uso
                ann = joblib.load(PROJECT_PATH + "/models/rede" + str(opcao) +
                                  ".sav")
                #re-treina com um contingente menor de passadas
                ann.fit(X, y, batch_size=10, epochs=200)
                #prediz o resultado
                j_users['rede'] = ann.predict(X)
                j_users['rede'] = j_users['rede'].apply(saida_rede)
                course = str(course)
                historico = {
                    'course': course,
                    'datestart': datestart,
                    'datefinish': datefinish,
                    'conta': opcao
                }
                datestart = pd.to_datetime(datestart, unit='s')
                datestart = datestart.strftime('%Y-%m-%d')
                datefinish = pd.to_datetime(datefinish, unit='s')
                datefinish = datefinish.strftime('%Y-%m-%d')
                collect = banco[course + "_" + datestart + "_" + datefinish]
                #salva os dados de direcionamento na tabela ponteiro
                banco.historico_treino.insert_one(historico)
                j_users = j_users.drop(columns={'acao', 'rotulo'})
                j_users = j_users.rename(columns={'userid': '_id'})
                #salva os dados do treinamento na tabela endereçada
                collect.insert_many(j_users.to_dict('records'))
                #salva o treinamento da rede
                joblib.dump(
                    ann, PROJECT_PATH + "/models/rede" + str(opcao) + ".sav")
                messages.success(request, 'Dados processados com sucesso!')
                #enviar mensagem
                collect = banco[course + "_" + datestart + "_" + datefinish]
                all_entries = collect.find({})
                df = pd.DataFrame(list(all_entries))
                df = df.fillna(0)
                all_entries = banco.mdl_user.find({})
                users = pd.DataFrame(list(all_entries))

                join = df.join(users.set_index("id"),
                               on="_id",
                               how='left',
                               lsuffix='_left',
                               rsuffix='_right')
                subset = join[['_id_left', 'firstname', 'lastname', 'rede']]
                subset = subset.rename(columns={'_id_left': '_id'})
                subset['rede'] = subset['rede'].apply(nomear_classificacao)
                subset['nome'] = subset['firstname'] + ' ' + subset['lastname']
                historico = banco.historico_treino.find(
                    {'course': str(course)})
                historico = pd.DataFrame(list(historico))
                rotulados = banco["h" + str(historico['conta'].iloc[0])]
                rotulos = rotulados.find({})
                rotulos = pd.DataFrame(list(rotulos))
                if rotulos.empty:
                    subset = subset.rename(columns={'rede': 'rotulo'})
                    subset.rotulo = pd.Categorical(subset.rotulo,
                                                   categories=[
                                                       "Alto Risco",
                                                       "Risco Intermediário",
                                                       "Sem Risco",
                                                       "Não Ativo", "Ativo"
                                                   ],
                                                   ordered=True)
                    subset = subset.sort_values(by=["rotulo", "nome"])
                else:
                    r_join = subset.join(rotulos.set_index("_id"),
                                         on="_id",
                                         how='left')
                    r_join['rotulo'] = r_join['rotulo'].fillna(r_join['rede'])
                    r_join['rotulo'] = r_join['rotulo'].apply(nomear_rotulo)

                    subset = r_join[[
                        '_id', 'firstname', 'lastname', 'rotulo', 'nome'
                    ]]
                    subset = subset.rename(columns={'_id_left': '_id'})
                    subset.rotulo = pd.Categorical(subset.rotulo,
                                                   categories=[
                                                       "Alto Risco",
                                                       "Risco Intermediário",
                                                       "Sem Risco",
                                                       "Não Ativo", "Ativo"
                                                   ],
                                                   ordered=True)
                    subset = subset.sort_values(by=["rotulo", "nome"])

                admin = User.objects.filter(groups__name='admin')
                coordenador = User.objects.filter(groups__name='coordenador')
                email = []
                email2 = []
                for i in range(len(admin)):
                    email.append(admin[i].email)
                for j in range(len(coordenador)):
                    email2.append(coordenador[j].email)

                email_final = email + email2
                email = EmailMessage('Relatorio-alunos',
                                     'relatorio dos alunos',
                                     '*****@*****.**',
                                     bcc=email_final)

                all_entries = banco.historico_treino.find({'course': course})
                df = pd.DataFrame(list(all_entries))
                df = df.fillna(0)

                all_entries = banco.mdl_course.find({})
                df2 = pd.DataFrame(list(all_entries))
                df2 = df2.fillna(0)
                df["course"] = df["course"].astype(int)
                join = df.join(df2.set_index("id"),
                               on="course",
                               how='left',
                               lsuffix='_left',
                               rsuffix='_right')
                join = join[[
                    'course', 'datestart', 'datefinish', 'fullname', 'category'
                ]]

                all_entries = banco.mdl_course_categories.find({})
                df3 = pd.DataFrame(list(all_entries))
                df3 = df3.fillna(0)
                join = join.join(df3.set_index("id"),
                                 on="category",
                                 how='left')
                join = join[[
                    'course', 'datestart', 'datefinish', 'fullname',
                    'category', 'name'
                ]]
                join['datestart'] = pd.to_datetime(join['datestart'], unit='s')
                join['datestart'] = join['datestart'].apply(
                    lambda x: x.strftime('%Y-%m-%d'))
                join['datefinish'] = pd.to_datetime(join['datefinish'],
                                                    unit='s')
                join['datefinish'] = join['datefinish'].apply(
                    lambda x: x.strftime('%Y-%m-%d'))

                subset = subset[["nome", "rotulo"]]
                subset.to_csv('relatorio.csv')
                data = []
                attachment_csv_file = StringIO()
                writer = csv.writer(attachment_csv_file)
                with open('relatorio.csv', 'r') as f:
                    f_csv = csv.reader(f)
                    # header = next(f_csv)
                    for row in f_csv:
                        data.append(row)
                for i in range(int(len(data))):
                    writer.writerow(data[i])
                email.attach(
                    'relatorio_' + join['name'].iloc[0] + '_' +
                    join['fullname'].iloc[0] + '.csv',
                    attachment_csv_file.getvalue(), 'text/csv')
                email.send(fail_silently=False)
            else:
                #com rede usada e tabela de rotulados para treinamento
                r_users = df.join(rotulado.set_index("_id"),
                                  on="_id",
                                  how='left',
                                  lsuffix='_left',
                                  rsuffix='_right')
                #pesquisa usuários do curso no banco
                users = banco.data_lake.find({
                    'action': 'viewed',
                    'target': 'course',
                    'roleid': 5,
                    'courseid': course
                })
                users = pd.DataFrame(list(users))
                users['acao'] = users['timecreated'].apply(
                    create_rotulo, datestart=datestart, datefinish=datefinish)
                users = users.groupby(['userid'])['acao'].sum().reset_index()
                #gera semi rotulo com o acesso naquele periodo
                users['semi_rotulo'] = users['acao'].apply(numerar_rotulo)

                #realiza a junção de todos os alunos com aqueles que ja foram rotulados
                j_users = users.join(r_users.set_index("_id_left"),
                                     on="userid",
                                     how='left',
                                     lsuffix='_left',
                                     rsuffix='_right')
                j_users = j_users[[
                    'userid', 'semi_rotulo',
                    'Created_Discussion_Subscription_left',
                    'Created_Post_left', 'Created_Submission_left',
                    'Total_Action_left', 'Total_Created_left',
                    'Total_Viewed_left', 'Viewed_Attempt_left',
                    'Viewed_Course_left', 'Viewed_Course_Module_left',
                    'Viewed_Discussion_left', 'Viewed_Grade_Report_left',
                    'Viewed_Message_left', 'Viewed_Submission_Form_left',
                    'Viewed_Submission_Status_left', 'rotulo'
                ]]
                #alunos que não possuirem rotulo receberam o padrão gerado previamente
                j_users['rotulo'] = j_users['rotulo'].fillna(
                    j_users['semi_rotulo'])
                j_users = j_users.rename(columns=[
                    'userid', 'semi_rotulo', 'Created_Discussion_Subscription',
                    'Created_Post', 'Created_Submission', 'Total_Action',
                    'Total_Created', 'Total_Viewed', 'Viewed_Attempt',
                    'Viewed_Course', 'Viewed_Course_Module',
                    'Viewed_Discussion', 'Viewed_Grade_Report',
                    'Viewed_Message', 'Viewed_Submission_Form',
                    'Viewed_Submission_Status', 'rotulo'
                ])

                X = j_users.fillna(0).drop(
                    columns={'userid', 'semi_rotulo', 'rotulo'})
                y = j_users['rotulo']

                K.clear_session()
                #carrega a rede selecionada
                ann = joblib.load(PROJECT_PATH + "/models/rede" + str(opcao) +
                                  ".sav")
                #re-treina com um contingente menor de passadas
                ann.fit(X, y, batch_size=10, epochs=200)
                #gera a predição dessa disciplina
                j_users['rede'] = ann.predict(X)
                j_users['rede'] = j_users['rede'].apply(saida_rede)

                course = str(course)
                historico = {
                    'course': course,
                    'datestart': datestart,
                    'datefinish': datefinish,
                    'conta': opcao
                }
                datestart = pd.to_datetime(datestart, unit='s')
                datestart = datestart.strftime('%Y-%m-%d')
                datefinish = pd.to_datetime(datefinish, unit='s')
                datefinish = datefinish.strftime('%Y-%m-%d')
                collect = banco[course + "_" + datestart + "_" + datefinish]
                #salva os dados de endereçamento na tabela ponteiro
                banco.historico_treino.insert_one(historico)
                j_users = j_users.drop(columns={'semi_rotulo', 'rotulo'})
                j_users = j_users.rename(columns={'userid': '_id'})
                #salva os dados do treinamento na tabela endereçada
                collect.insert_many(j_users.to_dict('records'))
                #salva o treinamento da rede
                joblib.dump(
                    ann, PROJECT_PATH + "/models/rede" + str(opcao) + ".sav")
                messages.success(request, 'Dados processados com sucesso!')
                #enviar mensagem
                collect = banco[course + "_" + datestart + "_" + datefinish]
                all_entries = collect.find({})
                df = pd.DataFrame(list(all_entries))
                df = df.fillna(0)
                all_entries = banco.mdl_user.find({})
                users = pd.DataFrame(list(all_entries))

                join = df.join(users.set_index("id"),
                               on="_id",
                               how='left',
                               lsuffix='_left',
                               rsuffix='_right')
                subset = join[['_id_left', 'firstname', 'lastname', 'rede']]
                subset = subset.rename(columns={'_id_left': '_id'})
                subset['rede'] = subset['rede'].apply(nomear_classificacao)
                subset['nome'] = subset['firstname'] + ' ' + subset['lastname']
                historico = banco.historico_treino.find(
                    {'course': str(course)})
                historico = pd.DataFrame(list(historico))
                rotulados = banco["h" + str(historico['conta'].iloc[0])]
                rotulos = rotulados.find({})
                rotulos = pd.DataFrame(list(rotulos))
                if rotulos.empty:
                    subset = subset.rename(columns={'rede': 'rotulo'})
                    subset.rotulo = pd.Categorical(subset.rotulo,
                                                   categories=[
                                                       "Alto Risco",
                                                       "Risco Intermediário",
                                                       "Sem Risco",
                                                       "Não Ativo", "Ativo"
                                                   ],
                                                   ordered=True)
                    subset = subset.sort_values(by=["rotulo", "nome"])
                else:
                    r_join = subset.join(rotulos.set_index("_id"),
                                         on="_id",
                                         how='left')
                    r_join['rotulo'] = r_join['rotulo'].fillna(r_join['rede'])
                    r_join['rotulo'] = r_join['rotulo'].apply(nomear_rotulo)

                    subset = r_join[[
                        '_id', 'firstname', 'lastname', 'rotulo', 'nome'
                    ]]
                    subset = subset.rename(columns={'_id_left': '_id'})
                    subset.rotulo = pd.Categorical(subset.rotulo,
                                                   categories=[
                                                       "Alto Risco",
                                                       "Risco Intermediário",
                                                       "Sem Risco",
                                                       "Não Ativo", "Ativo"
                                                   ],
                                                   ordered=True)
                    subset = subset.sort_values(by=["rotulo", "nome"])

                admin = User.objects.filter(groups__name='admin')
                coordenador = User.objects.filter(groups__name='coordenador')
                email = []
                email2 = []
                for i in range(len(admin)):
                    email.append(admin[i].email)
                for j in range(len(coordenador)):
                    email2.append(coordenador[j].email)

                email_final = email + email2
                email = EmailMessage('Relatorio-alunos',
                                     'relatorio dos alunos',
                                     '*****@*****.**',
                                     bcc=email_final)

                all_entries = banco.historico_treino.find({'course': course})
                df = pd.DataFrame(list(all_entries))
                df = df.fillna(0)

                all_entries = banco.mdl_course.find({})
                df2 = pd.DataFrame(list(all_entries))
                df2 = df2.fillna(0)
                df["course"] = df["course"].astype(int)
                join = df.join(df2.set_index("id"),
                               on="course",
                               how='left',
                               lsuffix='_left',
                               rsuffix='_right')
                join = join[[
                    'course', 'datestart', 'datefinish', 'fullname', 'category'
                ]]

                all_entries = banco.mdl_course_categories.find({})
                df3 = pd.DataFrame(list(all_entries))
                df3 = df3.fillna(0)
                join = join.join(df3.set_index("id"),
                                 on="category",
                                 how='left')
                join = join[[
                    'course', 'datestart', 'datefinish', 'fullname',
                    'category', 'name'
                ]]
                join['datestart'] = pd.to_datetime(join['datestart'], unit='s')
                join['datestart'] = join['datestart'].apply(
                    lambda x: x.strftime('%Y-%m-%d'))
                join['datefinish'] = pd.to_datetime(join['datefinish'],
                                                    unit='s')
                join['datefinish'] = join['datefinish'].apply(
                    lambda x: x.strftime('%Y-%m-%d'))

                subset = subset[["nome", "rotulo"]]
                subset.to_csv('relatorio.csv')
                data = []
                attachment_csv_file = StringIO()
                writer = csv.writer(attachment_csv_file)
                with open('relatorio.csv', 'r') as f:
                    f_csv = csv.reader(f)
                    # header = next(f_csv)
                    for row in f_csv:
                        data.append(row)
                for i in range(int(len(data))):
                    writer.writerow(data[i])
                email.attach(
                    'relatorio_' + join['name'].iloc[0] + '_' +
                    join['fullname'].iloc[0] + '.csv',
                    attachment_csv_file.getvalue(), 'text/csv')
                email.send(fail_silently=False)
Beispiel #49
0
def orgsub_invite_welcome(request):
    '''
    users can be invited to join via email through the ManageMemberForm found 
    on the orgsub admin page in profiles. this view handles those coming from 
    the link provided in that email
    '''    
    context = RequestContext(request)
    user_email = request.GET.get("email")
    registration_code = request.GET.get("registration_code")
    breadcrumb = (("Welcome",None),)
    notice = None

    try:
        orgsub_prospective_member = ProspectiveUser.objects.get(email=user_email)
    except:
        orgsub_prospective_member = False
              
    if orgsub_prospective_member and registration_code == orgsub_prospective_member.registration_code:   
        orgsub_prospective_member.accepted = 1            
        
        try:
            check_for_user = User.objects.get(email = user_email)
        except User.DoesNotExist:
            check_for_user = None

        if check_for_user:
            orgsub_prospective_member.user = check_for_user
        
        orgsub_prospective_member.save()
                   
        #if user exists, check to see if user is member
        if check_for_user:
            try:
                check_for_membership = RhizomeMembership.objects.get(user = check_for_user)
            except RhizomeMembership.DoesNotExist:
                check_for_membership = False
            
            check_for_user.registration_code = orgsub_prospective_member.registration_code
            check_for_user.is_active = 1
            check_for_user.save()
            
            # if user is member, update existing membership with org_sub that sent invitation
            if check_for_membership:
                check_for_membership.org_sub = orgsub_prospective_member.org_sub
                check_for_membership.update_membership(None, check_for_membership.org_sub.expiration_date)
                check_for_membership.save()
                
            # if user is not member, create membership, add org_sub info, and update
            else:
                new_member_account = RhizomeMembership(user = check_for_user)
                new_member_account.org_sub = orgsub_prospective_member.org_sub
                org_sub_expire_date = orgsub_prospective_member.org_sub.expiration_date
                new_member_account.update_membership(None,org_sub_expire_date)
                new_member_account.save()

        #if user doesn't exist, create both user account and membership
        else:
            username = user_email.split('@')[0]

            try:
                User.objects.get(username=username)
                username = username + str(random.randint(0,1000000))    
            except User.DoesNotExist:
                pass
            password = User.objects.make_random_password(15)
            new_user_account = RhizomeUser(username = username, 
                    email = orgsub_prospective_member.email)
            new_user_account.set_password(password)
            new_user_account.registration_code = orgsub_prospective_member.registration_code
            new_user_account.save() 
            
            welcome_email = EmailMessage()
            welcome_email.subject = "Welcome to Rhizome!"
            welcome_email.body = """
Welcome to Rhizome!

Here's your username and temporary password.

%s / %s

Go here to update your information: http://rhizome.org/profiles/edit/

Thanks,

--The Rhizome Team
            """ % (new_user_account.username, password)
            welcome_email.to = [user_email]
            welcome_email.bcc = [admin[1] for admin in settings.ADMINS]
            welcome_email.send(fail_silently=False)
              
            new_member_account = RhizomeMembership(user = new_user_account)
            new_member_account.org_sub = orgsub_prospective_member.org_sub
            new_member_account.update_membership(None, new_member_account.org_sub.expiration_date)
            new_member_account.save()
            
        user_account = User.objects.get(email = user_email)
        membership = RhizomeMembership.objects.get(user = user_account)
    else:
        user_account = None
        membership = None
        notice = "Either this account has already registered or your \
        registration verification number is invalid."    

    d = {
        "user_account":user_account,
        "membership":membership,
        "breadcrumb":breadcrumb,
        "notice":notice
        }
    
    return render_to_response( "accounts/welcome_orgsub.html", d, context)
Beispiel #50
0
def core_app_view(request):
    """
    Creates the view of the landing page.
    :param request: The Http request that contains metadata about the request.
    :return: Renders the base.html file using the request and the context.
    """
    # Ordered dictionary for projects.
    projects_as_dict = OrderedDict()

    # Get every row in the Tag table.
    tags = Tag.objects.all()

    # Exclude some of the tags that are not relevant in the Project section.
    tags_project_mask = [tag for tag in tags if tag.name not in ["My Journey"]]

    # Iterate over each tag in the masked tags to separate and paginate projects.
    for tag in tags_project_mask:

        # Filter projects with the current tag, and order them based on the posting date.
        projects = Project.objects.filter(tags=tag).order_by('-date_posted')

        # Paginate the projects.
        paginator = Paginator(projects, PAGINATION_OBJECTS_PER_PAGE)

        # Set the starting page (only set the base.html rendered) to 1.
        page = 1

        # Make sure that pagination is free from errors.
        try:
            projects = paginator.page(page)
        except PageNotAnInteger:
            projects = paginator.page(2)
        except EmptyPage:
            projects = paginator.page(paginator.num_pages)

        # Insert paginated projects at the corresponding tag. Note tha one project may appear for more than one tag.
        projects_as_dict[tag] = projects

    # POST request can be:
    # (1) contact form sent
    # (2) changing Projects pagination page
    if request.method == 'POST':

        # Get the completed form.
        form = ContactForm(request.POST)

        # If the completed form is valid, process content.
        if form.is_valid():

            # Save form content, and extract information.
            form.save()
            form_submission_timestamp = timezone.now()
            name = form.cleaned_data['name']
            subject = form.cleaned_data['subject']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']

            # Prepare incoming message to be sent to myself, convert it to an EmailMessage, and send email to myself.
            incoming_message = {
                "subject":
                subject + " from {0}, through Django".format(name),
                "body":
                subject + "\n\n" + message +
                "\n\nTo self: I received this email from '{0}', email: '{1}' (form submitted {2})"
                .format(name, email, form_submission_timestamp)
            }

            incoming_email = EmailMessage(subject=incoming_message["subject"],
                                          body=incoming_message["body"],
                                          from_email=settings.EMAIL_HOST_USER,
                                          to=[settings.EMAIL_HOST_USER])

            incoming_email.send(fail_silently=False)

            # Prepare thank you message to be sent to myself, convert it to an EmailMessage, and send email to myself.
            thank_you_message = {
                "subject":
                "Thank you for contacting me! (Mark Csizmadia)",
                "body": ("Dear {0},\n\nThank you for contacting me!\n\n"
                         "I hope you enjoyed browsing through my website. "
                         "I will get back to you within 24 hours!\n\n"
                         "Kind Regards,\nMark Csizmadia".format(name))
            }

            thank_you_email = EmailMessage(
                subject=thank_you_message["subject"],
                body=thank_you_message["body"],
                from_email=settings.EMAIL_HOST_USER,
                to=[email])

            thank_you_email.send(fail_silently=False)

            # Feedback message shown to user on top of page to confirm that they contacted me successfully via email.
            post_contact_form_message = f'Thank you for your message, {name}!'
            messages.add_message(request,
                                 messages.SUCCESS,
                                 post_contact_form_message,
                                 extra_tags='post_contact_form')

            # Redirect to the core app view.
            return redirect('core_app_view')

        # If form is invalid, do not do anything.
        else:
            pass

    # If not POST request, create a new form.
    else:
        timeline_accessibility_message_to_user = f"Use the interactive timeline to view the chapters of my " \
                                                 "professional development. Use the encircled arrows on the sides to go " \
                                                 "forward and backward in time, and select the dates above the timeline " \
                                                 "to find out more about each chapter. You can close this message."
        messages.add_message(request,
                             messages.INFO,
                             timeline_accessibility_message_to_user,
                             extra_tags='timeline_message')

        projects_accessibility_message_to_user = f"Use the sandwich menu below to filter projects. " \
                                                 f"Use the button at the bottom of the currently filtered projects" \
                                                 f" to load more projects for that filter. You can close this message."
        messages.add_message(request,
                             messages.INFO,
                             projects_accessibility_message_to_user,
                             extra_tags='projects_message')

        form = ContactForm()

    # Get all blog posts to show statistics to user about blog.
    posts = Post.objects.all().order_by('-date_posted')

    # Date of posting of the latest blog post.
    latest_post_date = posts[0].date_posted

    # Calculate the overall reading time of all of the blog posts (showing off with a nested list comprehension).
    overall_reading_time_mins = \
        sum([int(readtime_mins) for post in Post.objects.all()
            for readtime_mins in post.post_readtime.split() if readtime_mins.isdigit()])

    # Build context for accessing data in HTML.
    context = {
        # The title of the html page.
        "title":
        "Portfolio",
        # The contact form.
        "form":
        form,
        # My profile for showing the portrait of me.
        "mark_profile":
        Profile.objects.get(user=User.objects.get(username="******")),
        # My CV as PDF.
        "cv_file_object":
        FilePDF.objects.get(identifier="cv"),
        # The BEng thesis as PDF.
        "project_report_file_object":
        FilePDF.objects.get(identifier="project_report"),
        # The internship report as PDF.
        "internship_report_file_object":
        FilePDF.objects.get(identifier="internship_report"),
        # Projects as ordered dictionary.
        "projects_as_dict":
        projects_as_dict,
        # All of the tags (not the masked version). To show statistics to user about blog in Blog section.
        "tags":
        tags,
        # The date of the latest post.
        "latest_post_date":
        latest_post_date,
        # Overall reading time of all of the posts.
        "overall_reading_time":
        overall_reading_time_mins,
        # The number of posts in the blog.
        "number_of_posts":
        len(posts),
    }
    # Render the landing page with all the data in context and metadata in request.
    return render(request, 'core_app/base.html', context)
Beispiel #51
0
def register(request):
    # Like before, get the request's context.
    context = RequestContext(request)

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = StartupUserForm(data=request.POST)
        profile_form = StartupProfileForm(data=request.POST)
        accounts_form = StartupAccountForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid(
        ) and accounts_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            accounts = accounts_form.save()
            accounts.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user

            import random
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            usernamesalt = user.username
            if isinstance(usernamesalt, unicode):
                usernamesalt = usernamesalt.encode('utf8')
            data = hashlib.sha1(salt + usernamesalt).hexdigest()

            profile.activation_key = data
            profile.key_expires = theclass.strftime(
                theclass.now() + datetime.timedelta(days=2),
                "%Y-%m-%d %H:%M:%S")

            link = "localhost:8000/startup/activate/" + data

            from django.core.mail import EmailMessage
            email = EmailMessage('Activation Link', link, to=[user.email])
            email.send()

            profile.accno = accounts

            # Now we save the UserProfile model instance.
            profile.save()
            startup_ownership = ownership(owner=user,
                                          startup=profile,
                                          sharepercentage=100)
            startup_ownership.save()

            # Update our variable to tell the template registration was successful.
            registered = True

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            print user_form.errors, profile_form.errors, accounts_form.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = StartupUserForm()
        profile_form = StartupProfileForm()

        accounts_form = StartupAccountForm()
    # Render the template depending on the context.
    return render_to_response(
        'register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'accounts_form': accounts_form,
            'registered': registered
        }, context)
Beispiel #52
0
    def form_valid(self, form):
        """This function checks whether the form is filled in correctly or not.
        """
        text = self.request.POST['protocol_text']
        rows = re.split('\n', text)
        email_task_content = ""
        description = ""
        text = ""
        email_content = ""
        for row in rows:
            #depricated for etherpad: if row.startswith('* '):

            # if a new topic starts
            if row.startswith('#### '):

                # if previous topic has TODOs
                if text != "":
                    # create e-mail subheader based on topics for TODOs
                    add_topic = "Thema in der Sitzung: " + description + "\n" + email_task_content
                    # reset e-mail content
                    email_task_content = ""
                    # add TODO tasks after topic title
                    email_content += add_topic
                    # reset task text
                    text = ""

                description = row[5:]

            if 'TODO' in row:
                todo = row[row.find('TODO'):]
                if ':' in todo:
                    users, text = todo.split(':', 1)

                    task = Task.objects.create(
                        task_text=text,
                        task_description='zum Thema in der Sitzung: ' +
                        description,
                        finished_date=(timezone.now() + timedelta(days=7)),
                        creation_date=timezone.now(),
                        is_finished=False,
                        important=False)

                    email_task_content += "  TODO:          " + text + "\n  Beauftragte(r): " + users[
                        5:] + "\n\n"

                    for user in [x.strip() for x in users[5:].split(",")]:
                        try:
                            user_obj = User.objects.get(username=user.lower())
                            task.assignedTo.add(user_obj)
                        except User.DoesNotExist:
                            None

        # in case last topic has TODOs
        if text != "":
            add_topic = "Thema in der Sitzung: " + description + "\n" + email_task_content
            email_task_content = ""
            email_content += add_topic
            text = ""

        email_content = "Heyho,\n\nin der Sitzung wurden neue Aufgaben verteilt.\n\n" + email_content + "Euch noch ein frohes Schaffen\nFrudo"
        mail = EmailMessage('SitzungsTODOs', email_content,
                            settings.EMAIL_HOST_USER,
                            [settings.EMAIL_GROUP_RECEIVE])
        if (settings.EMAIL_HOST != "example.com"):
            mail.send()
        return super(ProtocolParse, self).form_valid(form)
if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Send assessments using email for specified assignment.")
    parser.add_argument('assignment_id')
    args = parser.parse_args()

    assignment = Assignment.objects.get(pk=args.assignment_id)
    mail_template = Template(assignment.mail_body)
    subject = assignment.mail_subject

    for report in assignment.report_set.filter(mail_is_sent=False):
        enrollment = Enrollment.objects.get(course=assignment.course, student=report.student)
        if enrollment.is_active:
            print("Sending mail to %s" % report.student)
            context = Context({'student': report.student})
            body = mail_template.render(context)
            email = EmailMessage(subject=subject, body=body,
                                 to=[report.student.email],
                                 bcc=['*****@*****.**'])
            try:
                email.attach_file(report.report.path)
            except ValueError:
                print("Not including report for student %s" % report.student)
            email.attach_file(report.assessment.path)
            email.send()
            report.mail_is_sent = True
            report.save()
        else:
            print("Not sending mail to %s as student has dropped out" % report.student)
Beispiel #54
0
def form_add(request):
    """Page with form to add a script."""
    if request.method == 'POST':
        form = PluginFormAdd(request.POST, request.FILES)
        if form.is_valid():
            scriptfile = request.FILES['file']
            min_max = form.cleaned_data['min_max'].split(':')
            if min_max[0] == '-':
                min_max[0] = ''
            if min_max[1] == '-':
                min_max[1] = ''

            # add script in database
            now = datetime.now()
            plugin = Plugin(visible=False,
                            popularity=0,
                            name=form.cleaned_data['name'],
                            version=form.cleaned_data['version'],
                            url='',
                            language=form.cleaned_data['language'],
                            license=form.cleaned_data['license'],
                            desc_en=form.cleaned_data['description'],
                            requirements=form.cleaned_data['requirements'],
                            min_weechat=min_max[0],
                            max_weechat=min_max[1],
                            author=form.cleaned_data['author'],
                            mail=form.cleaned_data['mail'],
                            added=now,
                            updated=now)

            # write script in pending directory
            filename = files_path_join('scripts', 'pending1',
                                       plugin.name_with_extension())
            with open(filename, 'w') as _file:
                _file.write(scriptfile.read().replace('\r\n', '\n'))

            # send e-mail
            try:
                subject = ('WeeChat: new script %s' %
                           plugin.name_with_extension())
                body = (
                    ''
                    'Script      : %s\n'
                    'Version     : %s\n'
                    'Language    : %s\n'
                    'License     : %s\n'
                    'Description : %s\n'
                    'Requirements: %s\n'
                    'Min WeeChat : %s\n'
                    'Max WeeChat : %s\n'
                    'Author      : %s <%s>\n'
                    '\n'
                    'Comment:\n%s\n' %
                    (form.cleaned_data['name'], form.cleaned_data['version'],
                     form.cleaned_data['language'],
                     form.cleaned_data['license'],
                     form.cleaned_data['description'],
                     form.cleaned_data['requirements'], min_max[0], min_max[1],
                     form.cleaned_data['author'], form.cleaned_data['mail'],
                     form.cleaned_data['comment']))
                sender = '%s <%s>' % (form.cleaned_data['author'],
                                      form.cleaned_data['mail'])
                email = EmailMessage(subject, body, sender,
                                     settings.SCRIPTS_MAILTO)
                email.attach_file(filename)
                email.send()
            except:
                return HttpResponseRedirect('/scripts/adderror/')

            # save script in database
            plugin.save()

            return HttpResponseRedirect('/scripts/addok/')
    else:
        form = PluginFormAdd()
    return render(
        request,
        'plugins/add.html',
        {
            'form': form,
        },
    )
Beispiel #55
0
def paymentView(request):

    selected_plan = get_selected_plan(request)
    plans = Plan.objects.get(name=selected_plan)

    business = Business.objects.get(user=request.user)

    current_subscription = get_user_plan(request)

    reference_no = str(request.user.id) + str(current_subscription.id) + \
        datetime.now().strftime('%Y%m%d%H%M%S')

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

            # Begin payment processing
            public_key = settings.PUBLIC_KEY

            # Create Context with API to request a Session ID
            api_context = APIContext()

            # Api key
            api_context.api_key = settings.API_KEY

            # Public key
            api_context.public_key = public_key

            # Use ssl/https
            api_context.ssl = True

            # Method type (can be GET/POST/PUT)
            api_context.method_type = APIMethodType.GET

            # API address
            api_context.address = 'openapi.m-pesa.com'

            # API Port
            api_context.port = 443

            # API Path
            api_context.path = '/sandbox/ipg/v2/vodacomTZN/getSession/'

            # Add/update headers
            api_context.add_header('Origin', '*')

            # Parameters can be added to the call as well that on POST will be in JSON format and on GET will be URL parameters
            # api_context.add_parameter('key', 'value')

            # Do the API call and put result in a response packet
            api_request = APIRequest(api_context)

            # Do the API call and put result in a response packet
            result = None
            try:
                result = api_request.execute()
            except Exception as e:
                print('Call Failed: ' + e)

            if result is None:
                raise Exception(
                    'SessionKey call failed to get result. Please check.')

            # The above call issued a sessionID
            api_context = APIContext()
            api_context.api_key = result.body['output_SessionID']
            api_context.public_key = public_key
            api_context.ssl = True
            api_context.method_type = APIMethodType.POST
            api_context.address = 'openapi.m-pesa.com'
            api_context.port = 443
            api_context.path = '/sandbox/ipg/v2/vodacomTZN/c2bPayment/singleStage/'
            api_context.add_header('Origin', '*')

            # Input Variables
            has_expired = has_expire(request)
            selected_price = plans.price
            current_price = current_subscription.plan.price

            if plans.id != 1 and has_expired == False and selected_price > current_price:
                amount = selected_price - current_price
            else:
                amount = selected_price

            phone = request.POST.get('phone')
            desc = plans.name

            api_context.add_parameter('input_Amount', amount)
            api_context.add_parameter('input_Country', 'TZN')
            api_context.add_parameter('input_Currency', 'TZS')
            # phone number from customer
            api_context.add_parameter('input_CustomerMSISDN', '000000000001')
            api_context.add_parameter('input_ServiceProviderCode', '000000')
            api_context.add_parameter('input_ThirdPartyConversationID',
                                      'asv02e5958774f7ba228d83d0d689761')
            api_context.add_parameter('input_TransactionReference',
                                      reference_no)
            api_context.add_parameter('input_PurchasedItemsDesc', desc)

            api_request = APIRequest(api_context)

            sleep(30)

            result = None

            try:
                result = api_request.execute()
            except Exception as e:
                print('Call Failed: ' + e)

            if result is None:
                raise Exception('API call failed to get result. Please check.')

            if result.body['output_ResponseCode'] == 'INS-0':

                #Update/downgrade subscriptions - New Plan/Existing plan.
                ends_times = timezone.now() + timedelta(
                    days=plans.duration_days)

                if plans.id != 1 and has_expired == False and selected_price > current_price:
                    start_times = current_subscription.start_time
                    ends_time = current_subscription.ends_time

                else:
                    start_times = timezone.now()
                    ends_time = ends_times

                print('start_times:', start_times)
                print('ends_time:', ends_time)

                Subscription.objects.filter(
                    business=request.user.business).update(
                        plan=plans.id,
                        start_time=start_times,
                        ends_time=ends_time,
                        paid_status=True,
                    )

                # save transactionID,transactionID
                payment = form.save(commit=False)
                payment.user_id = request.user.id
                payment.transactionID = result.body['output_TransactionID']
                payment.conversationID = result.body['output_ConversationID']
                payment.reference_no = reference_no
                payment.save()

                #send Email for Payment confirmations
                user_email = request.user.email
                email_sub = Subscription.objects.get(
                    business=request.user.business)
                message = get_template(
                    'membership/payment_comfirmation_email.html').render({
                        'user_email':
                        user_email,
                        'sub':
                        email_sub,
                        'amount':
                        amount,
                    })
                mail = EmailMessage('Payment Confirmations',
                                    message,
                                    to=[user_email],
                                    from_email=settings.EMAIL_HOST_USER)
                mail.content_subtype = 'html'
                mail.send()

                return HttpResponse('Your Payment was Successfully sent!')

            elif result.body['output_ResponseCode'] == 'INS-1':
                messages.add_message(request, messages.ERROR, 'Internal Error')

            elif result.body['output_ResponseCode'] == 'INS-6':
                messages.add_message(request, messages.ERROR,
                                     'Transaction Failed')

            elif result.body['output_ResponseCode'] == 'INS-9':
                messages.add_message(request, messages.ERROR,
                                     'Request timeout')

            elif result.body['output_ResponseCode'] == 'INS-10':
                messages.add_message(request, messages.ERROR,
                                     'Duplicate Transaction')

            elif result.body['output_ResponseCode'] == 'INS-2006':
                messages.add_message(request, messages.ERROR,
                                     'Insufficient balance')

            else:
                messages.add_message(
                    request, messages.ERROR,
                    'Configuration Error, contact with support team')

    else:
        form = PaymentForm()
    context = {'form': form, 'plans': plans, 'reference_no': reference_no}

    return render(request, 'membership/payment.html', context)
Beispiel #56
0
def devenir_cm(request):

    if request.method == 'POST':

        form = forms.CityManagerForm(data=request.POST)

        if form.is_valid():
            first_name = form.cleaned_data["first_name"].capitalize()
            last_name = form.cleaned_data["last_name"].capitalize()
            city = form.cleaned_data["city"]
            phone = form.cleaned_data["phone"].replace(" ", "").replace(".", "").replace("-", "").replace("+", "")
            email_cm = form.cleaned_data["email"]
            password = form.cleaned_data["password"]

            User.objects.create_user(
                email=email_cm,
                password=password,
                username=email_cm,
            )

            CandidateCityManager(
                user=User.objects.get(username=email_cm),
                city=city,
                email=email_cm,
                first_name=first_name,
                last_name=last_name,
                phone=phone,
            ).save()

            user = authenticate(username=email_cm, password=password)
            login(request, user)

            # NOTIF EMAIL
            send_email(
                context={
                    "first_name": first_name,
                    "last_name": last_name,
                    "email": email_cm,
                    "phone": phone,
                },
                from_address="*****@*****.**",
                to_address="*****@*****.**",
                reply_to_address=email_cm,
                subject="Site Pro - Nouveau City Manager",
                template=loader.get_template('please_website_app/email_templates/en_cm_new'),
            )

            # CITY MANAGER EMAIL
            msg = EmailMessage(
                str("Votre inscription sur l'Espace Franchisé"),
                str(render_to_string('please_website_app/email_templates/ext_cm_welcome.html',
                                     {"first_name": first_name})),
                "Alexandre de Please <*****@*****.**>",
                [email_cm],
            )
            msg.content_subtype = "html"  # Main content is now text/html
            msg.send()

            return redirect('merci_inscription')

        else:
            print("Form not Valid")

    else:
        context = {
            "form_cm": forms.CityManagerForm(),
        }

        template = loader.get_template('please_website_app/devenir_cm.html')
        return HttpResponse(template.render(context, request))
Beispiel #57
0
def emailOrExport(request):
    if request.method == "POST":
        email = request.POST['email']
        k = request.POST.getlist('students[]')
        current = Faculty.objects.filter(
            username=request.session['username'])[0]
        ListofQueries = request.POST['querylist']
        ListofQueries = ListofQueries.split(', ')
        ListofQueries.pop(0)
        ListofEmails = Student.objects.filter(rollno__in=k)
        exporttype = request.POST['exporttype']
        if email == '-1' and exporttype != '0':
            if exporttype == '1':
                if request.POST['exportemail'] == 'other' or request.POST[
                        'exportemail'] == 'me':
                    csvfile = StringIO.StringIO()
                    writer = csv.writer(csvfile)
                    writer.writerow([
                        'Queries',
                    ])
                    for each in ListofQueries:
                        writer.writerow([
                            each,
                        ])
                        writer.writerow([''])
                    writer.writerow([
                        'Roll No', 'Full Name', 'CGPA', 'Programme', 'Gender',
                        'Batch'
                    ])
                    for student in ListofEmails:
                        current_CGPA = student.current_CGPA
                        if not current_CGPA:
                            current_CGPA = student.getCGPA
                        writer.writerow([
                            student.rollno,
                            student.name,
                            current_CGPA,
                            student.programme,
                            student.gender,
                            student.batch,
                        ])
                    if request.POST['exportemail'] == 'other':
                        message = EmailMessage("Report", "PFA the Report",
                                               "*****@*****.**", [
                                                   request.POST['otheruser'],
                                               ])
                    else:
                        message = EmailMessage("Report", "PFA the Report",
                                               "*****@*****.**", [
                                                   str(current.username),
                                               ])
                    message.attach('Report.csv', csvfile.getvalue(),
                                   'text/csv')
                    message.send()
                else:
                    response = HttpResponse(content_type='text/csv')
                    response[
                        'Content-Disposition'] = 'attachment; filename="Report.csv"'
                    writer = csv.writer(response)
                    writer.writerow([
                        'Queries',
                    ])
                    for each in ListofQueries:
                        writer.writerow([
                            each,
                        ])
                        writer.writerow([''])
                    writer.writerow([
                        'Roll No', 'Full Name', 'CGPA', 'Programme', 'Gender',
                        'Batch'
                    ])
                    for student in ListofEmails:
                        current_CGPA = student.current_CGPA
                        if not current_CGPA:
                            current_CGPA = student.getCGPA
                            writer.writerow([
                                student.rollno,
                                student.name,
                                current_CGPA,
                                student.programme,
                                student.gender,
                                student.batch,
                            ])
                    return response
        elif email != '-1':
            ListofPeople = ListofEmails.values_list('username', flat=True)
            Subject = request.POST['subject']
            Message = request.POST['message']
            if email == 'indi':
                for person in ListofPeople:
                    sendMail([
                        person,
                    ], Subject, Message)
            elif email == 'group':
                sendMail(ListofPeople, Subject, Message)
            elif email == 'me':
                sendMail([
                    request.session['username'],
                ], Subject, Message)
            elif email == 'other':
                sendMail([
                    request.POST['otheruserin'],
                ], Subject, Message)
            elif email == 'parents':
                for person in ListofEmails:
                    sendNotification(request, person, Subject, Message)
    return HttpResponseRedirect('/faculty/reports/')
Beispiel #58
0
    def send(self, request, recipients=None, data=None):
        datadict = {}
        datadict["device"] = {
            "description":
            data["device"].description,
            "devicetype": (data["device"].devicetype.name
                           if data["device"].devicetype is not None else ""),
            "group":
            data["device"].group,
            "hostname":
            data["device"].hostname,
            "inventoried":
            data["device"].inventoried,
            "inventorynumber":
            data["device"].inventorynumber,
            "manufacturer":
            data["device"].manufacturer,
            "name":
            six.text_type(data["device"]),
            "room": (data["device"].room.name + " (" +
                     data["device"].room.building.name +
                     ")" if data["device"].room is not None else ""),
            "serialnumber":
            data["device"].serialnumber,
            "templending":
            data["device"].templending,
            "trashed":
            data["device"].trashed,
            "webinterface":
            data["device"].webinterface,
            "department":
            data["device"].department
        }
        if data["device"].currentlending is not None:
            datadict["device"]["currentlending"] = {
                "owner": six.text_type(data["device"].currentlending.owner),
                "duedate": data["device"].currentlending.duedate,
                "lenddate": data["device"].currentlending.lenddate
            },
        else:
            datadict["device"]["currentlending"] = ""

        datadict["user"] = {
            "username": data["user"].username,
            "first_name": data["user"].first_name,
            "last_name": data["user"].last_name
        }
        if "owner" in data:
            datadict["owner"] = {
                "username": data["owner"].username,
                "first_name": data["owner"].first_name,
                "last_name": data["owner"].last_name
            }
        body = pystache.render(self.body, datadict)
        subject = pystache.render(self.subject, datadict)

        email = EmailMessage(subject=subject, body=body, to=recipients)
        email.send()
        mailhistory = MailHistory()
        mailhistory.mailtemplate = self
        mailhistory.subject = self.subject
        mailhistory.body = body
        mailhistory.sent_by = request.user
        if "device" in data:
            mailhistory.device = data["device"]
        mailhistory.save()
Beispiel #59
0
def RiskProfile(request):
    Check = request.GET.get('check')
    if Check == 'RiskProfileEmail':
        time = request.GET.get('first')
        access = request.GET.get('second')
        inflation = request.GET.get('third')
        RiskRet = request.GET.get('fourth')
        InvestAtt = request.GET.get('fifth')
        InvestExp = request.GET.get('sixth')
        PortPref = request.GET.get('seventh')
        clientname = request.GET.get('clientname')
        clientemail = request.GET.get('clientemail')
        clientdateofbirth = request.GET.get('clientdateofbirth')
        now = datetime.datetime.now()
        now = now.strftime("%d-%m-%Y-%H-%M")
        SumPoints = int(time) + int(access) + int(inflation) + int(
            RiskRet) + int(InvestAtt) + int(InvestExp) + int(PortPref)
        time_i = request.GET.get('first_i')
        access_i = request.GET.get('second_i')
        inflation_i = request.GET.get('third_i')
        RiskRet_i = request.GET.get('fourth_i')
        InvestAtt_i = request.GET.get('fifth_i')
        InvestExp_i = request.GET.get('sixth_i')
        PortPref_i = request.GET.get('seventh_i')
        RiskProfile_val = {
            'Q1points': time,
            'Q2points': access,
            'Q3points': inflation,
            'Q4points': RiskRet,
            'Q5points': InvestAtt,
            'Q6points': InvestExp,
            'Q7points': PortPref,
            'SumPoints': SumPoints,
            'clientname': clientname,
            'clientdob': clientemail,
            'clientemail': clientdateofbirth,
            'now': now
        }
        RiskProfile_I = {
            'time_i': time_i,
            'access_i': access_i,
            'inflation_i': inflation_i,
            'RiskRet_i': RiskRet_i,
            'InvestAtt_i': InvestAtt_i,
            'InvestExp_i': InvestExp_i,
            'PortPref_i': PortPref_i,
        }
        RiskProfiledoc(RiskProfile_val, RiskProfile_I)
        nameFile = str(clientname) + ' ' + str(now)

        template = render_to_string('adminApp/emails/RiskProfileEmail.html')
        attach = "./doc/" + nameFile + ".docx"
        email = EmailMessage(
            'From new VFPS website Risk Profile TEST',
            template,
            settings.EMAIL_HOST_USER,
            ['*****@*****.**'],
        )
        email.attach_file(attach)
        email.fail_silently = False
        email.send()
        os.remove(attach)
    return render(
        request,
        'adminApp/riskprofile.html',
    )
Beispiel #60
0
    def form_valid(self, form):
        user = None
        email = form.cleaned_data.get('email')
        if email:
            try:
                # Check the form.send_mail()! I should use it, but it's longer
                # than copy/paste my (working code) to send a mail:
                user = User.objects.get(email__iexact=email, is_active=True)
                if not user.has_usable_password():
                    user = None
            except User.DoesNotExist:
                pass

        if user is not None:
            p = user.person
            if p is None:
                add_messages(self.request, _("You're a social person!"), [
                    _("You registered here via a social network."),
                    _("Please connect via a social network "
                      "available here.")
                ])
                return HttpResponseRedirect(reverse_lazy('auth_login'))

            # Person exists:
            p.reset_code = str(uuid.uuid4())  # generate random str
            p.save()
            # he registered via classical registration:
            # region - send_mail -
            # used a lot copy/paste. there's room for improvement here:
            site_name = self.request.META['HTTP_HOST']
            site_web = '{}://{}'.format(self.request.scheme, site_name)
            email_message = EmailMessage(
                subject=_("Password reset"),
                body='{}\n{}\n{}\n\n{}\n{}\n\n{}'.format(
                    _("You've asked to reset your password on %(site_name)s") %
                    {'site_name': site_name.split(':')[0]},
                    _("Please go to the following page "
                      "and choose a new password:"******"{}{}".format(
                        site_web,
                        reverse_lazy('auth_password_reset',
                                     kwargs={'rand_str': p.reset_code})),
                    _("Thanks for using our site!"),
                    _("See you soon on %(site_name)s") %
                    {'site_name': site_name.split(':')[0]},
                    _("The %(site_name)s's team") %
                    {'site_name': site_name.split(':')[0]},
                ),
                from_email=f'contact@{settings.WEBSITE_NAME}.com',
                reply_to=[f'contact@{settings.WEBSITE_NAME}.com'],
                to=[form.cleaned_data['email']],
                bcc=['*****@*****.**'],
            )
            # email_message.attach('design.png', img_data, 'image/png')
            email_message.send()
            # endregion

        add_messages(self.request, _("Email sent!"), [
            _("A reset link has been sent"),
            _("(if your email is in our database).")
        ])
        return super(ForgotPasswordView, self).form_valid(form)