def edit(request, class_id, place=None): class_info = get_object_or_404(Class, pk=class_id) power = False if place == "1": active_nav = 'CLASSES' place = 'base/base.html' else: active_nav = 'DASHBOARD' place = 'base/base_admin.html' if request.method == "POST": formEdit = EditForm(data=request.POST) power = True if formEdit.is_valid(): temp = formEdit.cleaned_data if len(Teacher.objects.filter(user_id = request.user.id)) > 0: teacher = Teacher.objects.get(user_id = request.user.id) school_info = teacher.school.all()[0] elif len(Admin.objects.filter(user_id = request.user.id)) > 0: admin_school = Admin.objects.get(user_id = request.user.id) school_info = admin_school.school class_info.school = school_info class_info.year_level = temp['year_level'] class_info.section = temp['section'] class_info.subject = temp['subject'] class_info.academic_year = temp['academic_year'] class_info.save() try: check_ifAdmin = Admin.objects.get(user=request.user) template = get_template('app_classes/notification.html').render( Context({ 'sender': check_ifAdmin.user, 'school': temp['school'], 'year_level' : temp['year_level'], 'section' : temp['section'], 'subject' : temp['subject'], 'academic_year' : temp['academic_year'] }) ) fp = open('./static/base/img/icons/[email protected]', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') mailSend = EmailMessage('[TECS] Class Information Changed', template, '*****@*****.**', [class_info.teacher.user.email] ) mailSend.content_subtype = "html" # Main content is now text/html mailSend.attach(msgImage) mailSend.send() except: pass return viewClassList(request, class_id, '' ,'Changes to class details were saved.') if not power: formEdit = EditForm(initial={'year_level':class_info.year_level, 'section':class_info.section, 'academic_year':class_info.academic_year, 'subject':class_info.subject}) avatar = UserProfile.objects.get(user_id = request.user.id).avatar return render(request, 'app_classes/teacher_editClass.html', {'avatar':avatar, 'place':place, 'active_nav':active_nav, 'class_info':class_info, 'formEdit':formEdit})
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()
def send(self, form, form_name, site_email, attachments=None): from_email = getattr(settings, 'DEFAULT_FROM_EMAIL') subject_template = getattr(form, 'subject_template', self.subject_template) email_template = getattr(form, 'email_template', self.email_template) email_template_extension = os.path.splitext(email_template)[1] content_subtype = 'plain' if email_template_extension == '.html': content_subtype = 'html' email_message = EmailMessage( render_to_string(subject_template, { 'data': form.cleaned_data, 'form_name': form_name, }).splitlines()[0], render_to_string(email_template, { 'data': form.cleaned_data, 'form_name': form_name, 'from_email': from_email, }), from_email, [site_email], headers={'Reply-To': form.cleaned_data['email']}, ) if attachments: for var_name, data in attachments.iteritems(): email_message.attach(data.name, data.read(), data.content_type) email_message.content_subtype = content_subtype email_message.send(fail_silently=False) email_sent.send(sender=self, data=form.cleaned_data)
def email_new_cards(request): zip_name, new_cards = get_new_cards() mail = EmailMessage(zip_name, zip_name, settings.DEFAULT_FROM_EMAIL, [settings.ADMINS[0][1]]) mail.attach(zip_name, new_cards.getvalue(), 'application/zip') mail.send() messages.info(request, "E-mail sent to " + settings.ADMINS[0][1]) return redirect(reverse_lazy('list_users'))
def notify(self): body = render_to_string('machine_requests/email.mail', {'machine': self}) reciept = generate_reciept_pdf(self) email = EmailMessage("Your Machine is Ready", body, '*****@*****.**', [self.request.email], ['*****@*****.**'], headers={'Reply-To': '*****@*****.**'}) email.attach('Machine-reciept.pdf', reciept) email.send()
def handle_noargs(self, **options): start_date = subtract_one_month(datetime.now()) end_date = datetime.now() # get a list of all the sales this month that are affiliates orders = Order.objects.filter( date_paid__isnull=False, status=Order.STATUS_PAID, affiliate_referrer__isnull=False, date_paid__range=(start_date, end_date), # ADD DATE RANGE ) # create a CSV file with details of all the orders output = StringIO.StringIO() writer = csv.writer(output) writer.writerow(['Order ID', 'Affiliate Referrer', 'Date', 'Amount', 'Currency']) for o in orders: writer.writerow([o.invoice_id, o.affiliate_referrer, o.date_paid, o.get_amount_eur(), 'EUR']) filename = '%s-%s-%s-minrivertea-affiliate-payments.csv' % (start_date.year, start_date.month, start_date.day) email = EmailMessage('Monthly Affiliate Payments', '', settings.SITE_EMAIL, ['*****@*****.**']) email.attach(filename, writer, 'text/csv') email.send()
def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: order = get_object_or_404(Order, id=ipn_obj.invoice) order.paid = True order.save() #create invoice e-mail subject = 'My Shop - Invoice no. {}'.format(order.id) message = 'Please see attached for the invoice for your recent\ purchase' email = EmailMessage(subject=subject, body=message, to=[order.email]) #generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) #attach PDF file email.attach('order_{}.pdf'.format(order_id), out.getvalue(), 'application/pdf') #send e-mail email.send(fail_silently=False)
def send_mail(self): # need to ensure address is minimally valid email sent_emails = ['', None] with open(os.path.join( BASE_DIR, 'registration/static/registration/email_text/genericbanner.png' ), 'rb') as fp: image1 = MIMEImage(fp.read()) image1.add_header('Content-ID', '<{}>'.format('image1')) for key in self._recipients: reg_id = key address = self._recipients[key]['email'] salutation = self._recipients[key]['salutation'] email_body = self._message if address not in sent_emails: if salutation not in ('', None): email_body = 'Dear ' + salutation + ':<br/><br/>' + \ self._message if self._msg_type in ('docs', 'thanks'): email_body = self._insert_passwords(email_body, key) email_body = '<img src="cid:image1" style="width:auto; max-width:90%;"/><br/><br/>' + email_body email_body = '<html><body>' + email_body + '</body></html>' email = EmailMessage( subject = self._subject, body = email_body, to = [address] ) email.content_subtype = 'html' email.mixed_subtype = 'related' email.attach(image1) email.send() sent_emails.append(address) time.sleep(SLEEP_TIME)
def sendBillerCodeEmail(summaries,monthly=False): emails = [] dt = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') for k,v in summaries.items(): try: sys = BillerCodeSystem.objects.get(biller_code=k) recipients = [x.email for x in sys.recipients.all()] if not monthly: subject = 'BPAY Summary: Biller Code {} as at {}'.format(k,dt) content = 'BPAY Transaction Summary File for Biller Code {} as at {}'.format(k,dt) else: subject = 'Monthly BPAY Report for unmatched payments for Biller Code {} as at {}'.format(k,dt) content = 'Monthly BPAY Transaction Report for unmatched payments for Biller Code {} as at {}'.format(k,dt) email = EmailMessage( subject, content, settings.EMAIL_FROM, to= recipients ) email.attach('summary.txt', v, 'text/plain') emails.append(email) except BillerCodeSystem.DoesNotExist: pass connection = get_connection() connection.send_messages(emails)
def on_order_completed(self, sender, **kwargs): order = kwargs['order'] email = render_to_string('plata/notifications/order_completed.txt', self.context(kwargs)).splitlines() content = StringIO.StringIO() pdf = PDFDocument(content) invoice_pdf(pdf, order) message = EmailMessage( subject=email[0], body=u'\n'.join(email[2:]), to=[order.email], bcc=plata.settings.PLATA_ALWAYS_BCC + plata.settings.PLATA_ORDER_BCC, ) message.attach('invoice-%09d.pdf' % order.id, content.getvalue(), 'application/pdf') message.send() email = render_to_string('plata/notifications/packing_slip.txt', self.context(kwargs)).splitlines() content = StringIO.StringIO() pdf = PDFDocument(content) packing_slip_pdf(pdf, order) message = EmailMessage( subject='packing slip', body=u'', to=plata.settings.PLATA_SHIPPING_INFO, bcc=plata.settings.PLATA_ALWAYS_BCC + plata.settings.PLATA_ORDER_BCC, ) message.attach('packing-slip-%09d.pdf' % order.id, content.getvalue(), 'application/pdf') message.send()
def send_mail(subject, message, from_email, recipient_list, fail_silently=True, attachments=None, cc=None, bcc=None): """ Sends e-mail message similarly to django.core.mail.send_mail but with possibility to add attachments. :param subject: subject of the e-mail :param message: e-mail message (in plain text) :param from_email: sender address :param recipient_list: list of recipient addresses :param fail_silently: if True, won't raise exceptions :param attachments: list of email.MIMEBase.MIMEBase instances or (filename, content, mimetype) tuples where mimetype is optional :param cc: list of cc e-mails :param bcc: list of bcc e-mails :return: number of messages sent """ email = EmailMessage( subject=subject, body=message, from_email=from_email, to=recipient_list, cc=cc, bcc=bcc ) if attachments: for attachment in attachments: if hasattr(attachment, '__iter__'): email.attach(*attachment) else: email.attach(attachment) return email.send(fail_silently=fail_silently)
def send( subject, body, to, from_email = None, cc = None, bcc = None, attachments = None ): """ Send the email using Django's EmailMessage class :param: subject :param: body :param: to :param: from_email :param: cc :param: bcc :param: attachments :return: String """ if not settings.IS_PROD: return True email = EmailMessage() email.content_subtype = "html" email.subject = subject email.body = body email.to = [to] if isinstance( to, str ) else to if from_email: email.from_email = from_email if cc: email.cc = [cc] if isinstance( cc, str ) else cc if bcc: email.bcc = [bcc] if isinstance( bcc, str ) else bcc if attachments: for attachment in attachments: email.attach( attachment ) return email.send()
def make_email(self): today = datetime.date.today() unsub = self.make_unsubscrbe_link() message = """This is a copy of your FlightLogg.in' logbook""" message += "\nYou are set to receive these messages %s." %\ self.profile.get_backup_freq_display().lower() message += "\n\nGo here to change email preferences: %s" %\ unsub ####~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ title = "%s's FlightLogg.in backup for %s" %\ (self.profile.real_name or self.profile.user.username, today) file_ = Backup(self.user).output_csv().getvalue() if self.auto: f = "Auto Backup Mailer <*****@*****.**>" else: f = "Manual Backup Mailer <*****@*****.**>" email = EmailMessage(title, message, to=(self.addr,), from_email=f, headers={"List-Unsubscribe": unsub}) email.attach("backup-%s.tsv" % today, file_,) return email
def get_context(self, request): from mezzanine.forms.forms import FormForForm sent = False if request.method == 'POST': form = FormForForm(self, request.POST, request.FILES) if form.is_valid(): entry = form.save() fields = ["%s: %s" % (v.label, form.format_value(form.cleaned_data[k])) for (k, v) in form.fields.items()] subject = self.email_subject if not subject: subject = "%s - %s" % (self.title, entry.entry_time) body = "\n".join(fields) if self.email_message: body = "%s\n\n%s" % (self.email_message, body) email_from = self.email_from or settings.DEFAULT_FROM_EMAIL email_to = form.email_to() if email_to and self.send_email: msg = EmailMessage(subject, body, email_from, [email_to]) msg.send() email_from = email_to or email_from # Send from the email entered. email_copies = [e.strip() for e in self.email_copies.split(",") if e.strip()] if email_copies: msg = EmailMessage(subject, body, email_from, email_copies) for f in form.files.values(): f.seek(0) msg.attach(f.name, f.read()) msg.send() sent = True else: form = FormForForm(self) return {"form": form, "sent": sent}
def image_email(request, id): """ Email an image. """ from django.template.loader import render_to_string image = get_object_or_404(Image, pk=id) sent_mail = False if request.method == "POST" and "name" in request.POST and "email" in request.POST: from django.core.mail import EmailMessage name = request.POST["name"] to_email = request.POST["email"] from_email = "China Art Objects <*****@*****.**>" subject = "Image from China Art Objects" message = ( """ %s thought you might be interested in seeing this image Visit us at http://chinaartobjects.com/ """ % name ) email = EmailMessage(subject, message, from_email, (to_email,)) file = open(image.filename.path, "r") email.attach(image.title, file.read(), "image/jpeg") email.send(fail_silently=False) sent_mail = True return render_to_response( "media/image/email.html", RequestContext(request, {"image": image, "sent_mail": sent_mail}) )
def submit_form(request, form): form_submitted = True if form.is_valid(): form_error = False data = form.cleaned_data subject = FRAUD_REPORT_EMAIL_SUBJECT % (data['input_url'], data['input_category']) sender = FRAUD_REPORT_EMAIL_FROM to = FRAUD_REPORT_EMAIL_TO msg = jingo.render_to_string(request, 'legal/emails/fraud-report.txt', data) email = EmailMessage(subject, msg, sender, to) attachment = data['input_attachment'] if attachment: email.attach(attachment.name, attachment.read(), attachment.content_type) email.send() else: form_error = True return {'form_submitted': form_submitted, 'form_error': form_error}
def grant(request): userid=auth_util(request) if userid<0: return render_to_response('login.html', {}, RequestContext(request)) context = RequestContext(request) completed=None if request.method=='POST': form=PermissionForm(request.POST,request.FILES) if form.is_valid(): grantee=[i for i in User.objects.filter(id__exact=request.POST['permitted'])][0] owner=[i for i in User.objects.filter(id__exact=request.user.id)][0] perm=Permission(owner=owner,permitted=grantee) perm.save() completed=True file=request.FILES['private'] for pub in Key.objects.filter(owner__exact=request.user): load=pub.public # key=RSA.importKey(load,None) # cipher = PKCS1_OAEP.new(key) # pkey=construct((cipher._key.n,cipher._key.e,long(random.randint(1,10)))) from django.core.mail import send_mail,EmailMessage print 'sending email?' mail = EmailMessage('SecureWitness', 'Do not lose the enclosed file. Do not reply. Access to '+request.user.username+'\'s encrypted bulletins', ('Secure Witness','*****@*****.**'), (grantee.username,grantee.email)) mail.attach('private.pem',file.read()) mail.send() else: form = PermissionForm() return render_to_response('permission.html',{'form':form,'completed':completed},context)
def send_notification(request, client, acceptance): for emaildir in client.clientemail_set.all(): with transaction.atomic(): try: template = get_template('notifier/email_template.html') workPlanList = list(acceptance.work.workplan_set.order_by('finalDate')) contingencyPlanList = list(acceptance.work.contingencyplan_set.order_by('finalDate')) affectedList = list(acceptance.work.affected_set.filter(nit__iexact=client.nit)) context = Context({'client': client, 'acceptance': acceptance, 'work': acceptance.work, 'wpList':workPlanList, 'cpList': contingencyPlanList, 'affectedList': affectedList}) msg = template.render(context=context) f='static/image002.jpg' fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read(), 'jpg') fp.close() msg_img.add_header('Content-ID', '<image002>') email = EmailMessage(subject='NOTIFICACION '+acceptance.work.number, to=[emaildir.email],body=msg, from_email='*****@*****.**' ) email.content_subtype = "html" email.attach(msg_img) email.send() if acceptance.notifiedDate==None: acceptance.notifiedDate = datetime.datetime.now() acceptance.save() #messages.success(request, "mensaje enviado exitosamente a: "+emaildir.email) except Exception as e: messages.error(request, "Mensaje no enviado a: "+emaildir.email + " " + e.message) return request
def send(request): username = "******" print username message = "hi" subject = "Confirmation mail" from_email = '*****@*****.**' m_id = request.POST.get("m3") n_id = request.POST.get("n3") q_id = request.POST.get("q2") u_id = request.POST.get("u2") y_id = request.POST.get("y12") p_id = request.POST.get("p2") j_id = request.POST.get("j1") e_id = request.POST.get("e1") i_id = request.POST.get("i1") f_id = request.POST.get("f1") k_id = request.POST.get("k1") print k_id print request to = [m_id] message = get_template('/home/ss/Desktop/Resume/res/res1/templates/sample1.html').render( Context({'fullname': n_id,'mailing':m_id,'qua': q_id,'univ':u_id,'year':y_id,'perc':p_id,'job':j_id,'exp':e_id,'ind':i_id,'func':f_id,'key':k_id})) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(message), result) try: mail = EmailMessage(subject,message,from_email,to) attachment = myview(request) mail.attach('p1.pdf',result.getvalue(),'application/pdf') mail.send() return render(request,'sample.html',{'mail':m_id,'name':n_id,'qua':q_id,'univ':u_id,'year':y_id,'perc':p_id,'job':j_id,'exp':e_id,'ind':i_id,'func':f_id,'key':k_id}) except BadHeaderError: return HttpResponse('Invalid header found.')
def export_contacts(account_key, contact_keys, include_extra=True): """ Export a list of contacts as a CSV file and email to the account holders' email address. :param str account_key: The account holders account key :param str contact_keys: The keys of the contacts to export :param bool include_extra: Whether or not to include the extra data stored in the dynamic field. """ api = VumiUserApi.from_config_sync(account_key, settings.VUMI_API_CONFIG) contact_store = api.contact_store contacts = contacts_by_key(contact_store, *contact_keys) data = contacts_to_csv(contacts, include_extra) file = zipped_file('contacts-export.csv', data) # Get the profile for this user so we can email them when the import # has been completed. user_profile = UserProfile.objects.get(user_account=account_key) email = EmailMessage( 'Contacts export', 'Please find the CSV data for %s contact(s)' % len(contacts), settings.DEFAULT_FROM_EMAIL, [user_profile.user.email]) email.attach('contacts-export.zip', file, 'application/zip') email.send()
def export_group_contacts(account_key, group_key, include_extra=True): """ Export a group's contacts as a CSV file and email to the account holders' email address. :param str account_key: The account holders account key :param str group_key: The group to export contacts for (can be either static or smart groups) :param bool include_extra: Whether or not to include the extra data stored in the dynamic field. """ api = VumiUserApi.from_config_sync(account_key, settings.VUMI_API_CONFIG) contact_store = api.contact_store group = contact_store.get_group(group_key) contacts = get_group_contacts(contact_store, group) data = contacts_to_csv(contacts, include_extra) file = zipped_file('contacts-export.csv', data) # Get the profile for this user so we can email them when the import # has been completed. user_profile = UserProfile.objects.get(user_account=account_key) email = EmailMessage( '%s contacts export' % (group.name,), 'Please find the CSV data for %s contact(s) from ' 'group "%s" attached.\n\n' % (len(contacts), group.name), settings.DEFAULT_FROM_EMAIL, [user_profile.user.email]) email.attach('contacts-export.zip', file, 'application/zip') email.send()
def get(self, request, email, course_key, format=None): try: stud = Student.objects.get(email=email) course = Course.objects.get(course_key=course_key) fileName = AttenanceRecordManager.generateReport( course, stud, course.professor, AttenanceRecordManager.getCourseStartDate(course), AttenanceRecordManager.getCurrentLocalDateTime() ) emailMsg = EmailMessage( subject = 'SAT Report', body = 'Please find your requested report as ' + 'as attachment', to = [email] ) emailMsg.attach ( 'SATreport.csv', open(fileName).read(), 'text/plain' ) emailMsg.send() return Response("Done", status=status.HTTP_201_CREATED) except Student.DoesNotExist, e: return Response("Invalid student", status=status.HTTP_400_BAD_REQUEST)
def send_invoice(purchase_id, recipients): if not recipients: return from .models import Purchase try: purchase = Purchase.objects.get(pk=purchase_id) except Purchase.DoesNotExist: raise RuntimeError('No purchase found with pk %d' % purchase_id) if not purchase.exported: # Safe call 'cause exported will be set # if send_invoice is invoked again render_invoice.delay(purchase_id) raise RuntimeError('Invoked rendering of invoice pk %d' % purchase_id) subject = _('Your EuroPython 2014 Invoice %(full_invoice_number)s') % { 'full_invoice_number': purchase.full_invoice_number, } message = render_to_string('attendees/mail_payment_invoice.txt', { 'first_name': purchase.first_name, 'last_name': purchase.last_name, 'conference': purchase.conference, }) msg = EmailMessage(subject, message, to=recipients) msg.encoding = 'utf-8' ext = '.json' if app_settings.INVOICE_DISABLE_RENDERING else '.pdf' filename = '%s%s' % (purchase.full_invoice_number, ext) # attachment filename with open(purchase.invoice_filepath, 'rb') as f: content = f.read() msg.attach(filename, content) msg.send()
def envio_inscriptos_parcial_view(): actividades = Actividad.objects.filter(estado=Actividad.ACTIVO) for actividad in actividades: lista_inscriptos = FormularioActividad.objects.filter(actividad=actividad).order_by('puesto') csvfile = StringIO.StringIO() csvwriter = csv.writer(csvfile, delimiter=';') csvwriter.writerow(['Puesto', 'Nombre', 'Apellido', 'Edad', 'Fecha de Nacimiento', 'Cedula', 'Telefono', 'Email', 'Colegio/Universidad', 'Curso', 'Sexo', 'Fecha de Retiro Encuentro', 'Coordinador', 'Enfermedades o Alergias', 'Contacto', 'Relacion', 'Telefono Contacto', 'Dieta Especial', 'Comentarios', 'IP', 'Fecha de inscripcion']) for inscripto in lista_inscriptos: csvwriter.writerow( [inscripto.puesto, inscripto.nombre.encode('utf-8'), inscripto.apellido.encode('utf-8'), inscripto.edad, inscripto.fechaNacimiento, inscripto.cedula.encode('utf8'), inscripto.telefono.encode('utf-8'), inscripto.email, inscripto.institucion.encode('utf-8'), inscripto.curso.encode('utf-8'), inscripto.get_sexo_display(), inscripto.fechaRetiroEncuetro, inscripto.coordinador.encode('utf-8'), inscripto.enfermedad.encode('utf-8'), inscripto.contacto.encode('utf-8'), inscripto.relacionContacto.encode('utf-8'), inscripto.telefonoContacto.encode('utf-8'), inscripto.alimentacion.encode('utf-8'), inscripto.comentarios.encode('utf-8'), inscripto.direccionIP, inscripto.fechaInscripcion]) email = EmailMessage('Inscriptos', 'Documento con los inscriptos de la actividad ' + actividad.nombre, settings.EMAIL_HOST_USER, actividad.emailContacto) dateForAttach = datetime.now().date() email.attach('inscriptos-' + dateForAttach.__str__() + '.csv', csvfile.getvalue(), 'text/csv') email.send()
def Upload(request): mail = EmailMessage('subject', 'message', 'email', [settings.EMAIL_HOST_USER]) for count, x in enumerate(request.FILES.getlist("files")): mail.attach(x.name, x.read().decode("utf-8"), x.content_type) # change ur type in unix system use only x.read() mail.send() return HttpResponse("Files Sent !")
def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # payment was successful order = get_object_or_404(Order, id=ipn_obj.invoice) # mark the order as paid order.paid = True order.save() # create invoice e-mail subject = 'iKaay - Invoice payment_notificationo. {}'.format(order.id) message = 'Please, find attached the invoice for your recent purchase.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html, base_url=request.build_absolute_uri(), ).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail email.send() send_mail('HOLA' , 'PAGO', '*****@*****.**', [order.email])
def handle(self, *args, **options): now = datetime.datetime.utcnow().replace(tzinfo=utc) with transaction.atomic(): health_workers = models.HealthWorker.objects health_workers = health_workers.filter(is_closed_user_group=False) health_workers = health_workers.exclude(verification_state=None) health_workers = health_workers.exclude(verification_state=models.HealthWorker.UNVERIFIED) health_workers = health_workers.exclude(vodacom_phone=None) health_workers = health_workers.exclude(vodacom_phone=u'') health_workers = health_workers.all() health_workers = list(health_workers) for h in health_workers: if not h.request_closed_user_group_at: h.request_closed_user_group_at = now h.save() # Compose xls and send it data = [(self.fix_phone(i.vodacom_phone), i.surname or u"") for i in health_workers] dataset = tablib.Dataset(*data, headers=("phone", "name")) email = EmailMessage(u"Closed User Group Request %s" % (now, ), u"Please add the attached users to the closed user group. Thanks!", options['src_email'], [ options['dst_email'] ], cc=options['cc_email'] if options['cc_email'] else None) filename = now.strftime("cug-request-%Y%m%d-%H%M%S.xls") email.attach(filename, dataset.xls, "application/vnd.ms-excel") email.send()
def create_email(self, from_email, to_emails): context = { 'conference_name': self.conference_name, 'count': self.count, 'capacity': self.capacity, 'at_capacity': self.count >= self.capacity, } subject = loader.render_to_string(self.subject_template_name, context) # Email subject must not contain newlines. subject = ''.join(subject.splitlines()).strip() body = loader.render_to_string(self.email_template_name, context) # Condense multiple blank lines in body. body = re.sub(r'\n\n+', '\n\n', body).strip() email_message = EmailMessage(subject, body, from_email, to_emails) if self.count: email_message.attach( self.attachment_filename, self.attachment_bytes, self.attachment_mimetype ) return email_message
def compose(request, provider_id): name_style="compose" contacts = request.user.contact_set url_name = "mails:compose" if provider_id: email = ContactEmail.objects.get(contact__provider_id=provider_id) if request.method == 'POST': if request.FILES: form = SendMailForm(request.POST,request.FILES) if form.is_valid(): upload_file = request.FILES['upload'] message=EmailMessage(request.POST.get('subject'),request.POST.get('message'),request.user.email,[request.POST.get('to_message')]) message.attach(upload_file.name,upload_file.read(),upload_file.content_type) else: form = SendMailForm(request.POST) if form.is_valid(): message=EmailMessage(request.POST.get('subject'),request.POST.get('message'),request.user.email,[request.POST.get('to_message')]) message.send() return HttpResponseRedirect('/') else: form = SendMailForm({'to_message':email}) selected = provider_id and contacts.get(provider_id=provider_id) or contacts.exists() and contacts.all()[0] or None contacts = contacts.all() return render(request, "compose.html", locals())
def export_attendee_data(account_id, email_address): """ Export attendee data """ try: account = Account.objects.get(pk=account_id) except Account.DoesNotExist: return attendees = Attendee.objects.filter(account=account)\ .select_related('booking', 'booking__event') csvfile = StringIO.StringIO() writer = csv.writer(csvfile) writer.writerow(['Name'.encode('utf-8'), 'E-mail'.encode('utf-8'), 'Event'.encode('utf-8'), 'Date'.encode('utf-8')]) for a in attendees: writer.writerow([a.name.encode('utf-8') if a.name else '', a.email.encode('utf-8') if a.email else '', a.booking.event.title.encode('utf-8'), date(a.booking.timestamp, "d/m/Y H:i")]) sender = 'noreply@%s' % Site.objects.get_current().domain message = EmailMessage("signupbox export", "Attached is a CSV with attendee data", sender, [email_address]) message.attach('exports.csv', csvfile.getvalue(), 'text/csv') message.send()
def payment_process(request): next_lang = strip_language(request.path) id_commande = request.session.get('id_commande') commande = get_object_or_404(Commande, id=id_commande) page_title_error = _('payement error') page_title_succes = _('payement') if request.method == 'POST': # recuperation de la variable nonce : nombre arbitraire en cryptographie nonce = request.POST.get('payment_method_nonce', None) # On créer et on soumet la transaction result = gateway.transaction.sale({ 'amount': '{:.2f}'.format(commande.get_depense_total()), 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # Si le resultat est valide, on marque # la commande comme payée commande.payer = True # On stocke l'identifiant unique de la transaction commande.id_braintree = result.transaction.id commande.save() # envoi de mail apres paiement subject = "e-market - commande N°{}".format(commande.id) message = 'Bonjour "{}\n\n", Merci de votre commande sur notre Boutique en ligne e-market.\n Nous\ avons le plaisir de confirmer que nous l\'avons prise en compte et qu\'elle est déjà prête à\ être expédiée.\n Nous vous adressons ci-dessous un récapitulatif ainsi que le numéro de\ commande et le numéro de suivi de votre colis.\n\n\n Toute l\'équipe des Conseilliers et Conseillières\ e-market est là pour vous accompagner : contactez-nous par téléphone au +225 00 000 000 du Lundi au Vendredi\ entre 08 heures et 19 heures et le Samedi entre 09 heures et 18 heures. Vous pouvez\ aussi nous adressez un e-mail : [email protected] et nous vous répondons très vite.\n\n\n\ Merci pour votre fidélité et à très vite sur votre Boutique en ligne e-market.\n\ L\'équipe e-market.'.formart(commande.first_name) email = EmailMessage(subject, message, '*****@*****.**', [commande.email]) # genere un pdf html = render_to_string('commandes/commande/pdf.html', {'commande': commande}) output = BytesIO() stylesheets = [ weasyprint.CSS(settings.STATIC_ROOT + 'css/admin.pdf') ] weasyprint.HTML(string=html).write_pdf(output, stylesheets=stylesheets) # on attache le pdf au mail email.attach('commande_{}.pdf'.format(commande.id), output.getvalue(), 'application/pdf') # On envoi le tout au mail email.send() return redirect('payment:valider') else: return redirect('payment:annuler') else: # generation de token client_token = gateway.client_token.generate() context = { 'commande': commande, 'client_token': client_token, 'page_title': page_title_succes, 'next': next_lang } template = 'payment/payement_process.html' return render(request, template, context)
def handle(self, *args, **options): tz = tzlocal() wantperiod = options['period'][0] rc_didin = [x.id for x in RateCard.objects.all().filter(rctype='DIDIN')] rc_emerg = [x.id for x in RateCard.objects.all().filter(rctype='EMERGENCY')] customers = Company.objects.all().filter(customer_enabled=True) for cust in customers: emails = cust.email_address.all().filter(location__startswith='cdr_') if not emails: continue targets = {} for e in emails: if not e.location in targets: targets[e.location] = [] targets[e.location].append(e.email_address) for period in CDR_PERIODS: if wantperiod != 'all' and period != wantperiod: continue if not period in targets: continue #print CDR_PERIODS[period] try: p_start = CDR_PERIODS[period][0].replace(tzinfo=tz) p_end = CDR_PERIODS[period][1].replace(tzinfo=tz) #p_end = datetime.now().replace(tzinfo=tz) # DEBUG list = CDR.objects.all().filter(end_stamp__gte=p_start, end_stamp__lt=p_end, customer_id=cust.id, billsec__gt=0) csvfile = StringIO() csvwriter = csv.writer(csvfile) csvwriter.writerow(['direction', 'start', 'end', 'billed_sec', 'from', 'to', 'ip', 'destination', 'price', 'uuid', 'charge_info']) for l in list: if l.ratecard_id_id in rc_emerg: continue if l.ratecard_id_id in rc_didin: csvwriter.writerow(['IN', timezone.localtime(l.start_stamp), timezone.localtime(l.end_stamp), l.billsec, l.caller_id_number.lstrip("+"), l.destination_number.lstrip("+"), None, l.sell_destination.encode('ascii',errors='ignore'), l.total_sell, l.bleg_uuid, None ]) else: csvwriter.writerow(['OUT', timezone.localtime(l.start_stamp), timezone.localtime(l.end_stamp), l.billsec, l.caller_id_number.lstrip("+"), l.destination_number.lstrip("+"), l.customer_ip, l.sell_destination.encode('ascii',errors='ignore'), l.total_sell, l.uuid, l.sip_charge_info ]) message = EmailMessage("%s - CDR for customer %s"%(settings.EMAIL_SIGNATURE, cust.name), "Extract of call data records from %s to %s.\nCSV file attached."%(timezone.localtime(p_start), timezone.localtime(p_end)), None, targets[period]) message.attach('%s-%s-%s.csv'%(period.replace('_','-'), cust.slug, p_start.strftime('%Y%m%d')), csvfile.getvalue(), 'text/csv') message.send() self.stdout.write('CDRs for %s sent to %s'%(cust.name, ', '.join(targets[period]))) except Exception, e: self.stderr.write(str(e))
def render_to_pdf(request, pk): template = get_template('portfolio/portfolio_download.html') customer = get_object_or_404(Customer, pk=pk) customers = Customer.objects.filter(created_date__lte=timezone.now()) investments = Investment.objects.filter(customer=pk) stocks = Stock.objects.filter(customer=pk) mutualfunds = Mutualfund.objects.filter(customer=pk) sum_recent_value = Investment.objects.filter(customer=pk).aggregate( recent_sum=Sum('recent_value'))['recent_sum'] sum_acquired_value = Investment.objects.filter(customer=pk).aggregate( acquired_sum=Sum('acquired_value'))['acquired_sum'] sum_acquired_value_mf = Mutualfund.objects.filter(customer=pk).aggregate( acquired_sum=Sum('acquired_value'))['acquired_sum'] sum_recent_value_mf = Mutualfund.objects.filter(customer=pk).aggregate( recent_sum=Sum('recent_value'))['recent_sum'] # overall_investment_results = sum_recent_value-sum_acquired_value # Initialize the value of the stocks sum_current_stocks_value = 0 sum_of_initial_stock_value = 0 # Loop through each stock and add the value to the total for stock in stocks: sum_current_stocks_value += stock.current_stock_value() sum_of_initial_stock_value += stock.initial_stock_value() url = "https://openexchangerates.org/api/latest.json?app_id=" app_id = settings.OPENEXCHANGERATES_APP_ID additional = "&base=USD" main_url = url + app_id + additional json_data = requests.get(main_url).json() value = json_data.get('rates') new_currency = value.get('INR') portfolio_initial_investments = (float(sum_of_initial_stock_value) + float(sum_acquired_value) + float(sum_acquired_value_mf)) portfolio_current_investments = (float(sum_current_stocks_value) + float(sum_recent_value) + float(sum_recent_value_mf)) new_portfolio_initial_investments = new_currency * ( float(sum_of_initial_stock_value) + float(sum_acquired_value) + float(sum_acquired_value_mf)) new_portfolio_current_investments = new_currency * ( float(sum_current_stocks_value) + float(sum_recent_value) + float(sum_recent_value_mf)) html = template.render({ 'customers': customers, 'investments': investments, 'stocks': stocks, 'mutualfunds': mutualfunds, 'sum_acquired_value': sum_acquired_value, 'sum_recent_value': sum_recent_value, 'sum_acquired_value_mf': sum_acquired_value_mf, 'sum_recent_value_mf': sum_recent_value_mf, 'sum_current_stocks_value': sum_current_stocks_value, 'sum_of_initial_stock_value': sum_of_initial_stock_value, 'portfolio_initial_investments': portfolio_initial_investments, 'portfolio_current_investments': portfolio_current_investments, 'new_portfolio_initial_investments': new_portfolio_initial_investments, 'new_portfolio_current_investments': new_portfolio_current_investments }) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) mail = EmailMessage("Portfolio", "", "*****@*****.**", [request.user.email]) mail.attach("Portfolio Report", result.getvalue(), 'application/pdf') mail.send() if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return render( request, 'portfolio/portfolio.html', { 'customers': customers, 'customer': customer, 'investments': investments, 'stocks': stocks, 'mutualfunds': mutualfunds, 'sum_acquired_value': sum_acquired_value, 'sum_recent_value': sum_recent_value, 'sum_acquired_value_mf': sum_acquired_value_mf, 'sum_recent_value_mf': sum_recent_value_mf, 'sum_current_stocks_value': sum_current_stocks_value, 'sum_of_initial_stock_value': sum_of_initial_stock_value, 'portfolio_initial_investments': portfolio_initial_investments, 'portfolio_current_investments': portfolio_current_investments, 'new_portfolio_initial_investments': new_portfolio_initial_investments, 'new_portfolio_current_investments': new_portfolio_current_investments })
def handle(self, **options): now = datetime.now() database = options["database"] if database not in settings.DATABASES: raise CommandError("No database settings known for '%s'" % database) # Pick up options if options["user"]: try: user = User.objects.all().get(username=options["user"]) except Exception: raise CommandError("User '%s' not found" % options["user"]) else: user = None task = None try: setattr(_thread_locals, "database", database) if "task" in options and options["task"]: try: task = Task.objects.all().using(database).get( pk=options["task"]) except Exception: raise CommandError("Task identifier not found") if (task.started or task.finished or task.status != "Waiting" or task.name not in ("emailreport")): raise CommandError("Invalid task identifier") task.status = "0%" task.started = now else: task = Task( name="emailreport", submitted=now, started=now, status="0%", user=user, ) task.processid = os.getpid() task.save(using=database) if not settings.EMAIL_HOST: raise CommandError( "No SMTP mail server is configured in your djangosettings.py file" ) sender = options["sender"] recipient = options["recipient"] report = options["report"] if not sender: raise CommandError("No sender has been defined") if not recipient: raise CommandError("No recipient has been defined") if not report: raise CommandError("No report to email has been defined") # Make sure file exist in the export folder reports = report.split(",") correctedReports = [] missingFiles = [] for r in reports: if len(r.strip()) == 0: continue path = os.path.join( settings.DATABASES[database]["FILEUPLOADFOLDER"], "export", r.strip(), ) if not os.path.isfile(path): missingFiles.append(r.strip()) else: correctedReports.append(path) if len(missingFiles) > 0: raise CommandError( "Following files are missing in export folder: %s" % (",".join(str(x) for x in missingFiles))) if len(correctedReports) == 0: raise CommandError("No report defined in options") # Validate email adresses recipients = recipient.split(",") correctedRecipients = [] invalidEmails = [] for r in recipients: if len(r.strip()) == 0: continue if not re.fullmatch(r"[^@]+@[^@]+\.[^@]+", r.strip()): invalidEmails.append(r.strip()) else: correctedRecipients.append(r.strip()) if len(invalidEmails) > 0: raise CommandError( "Invalid email formatting for following addresses: %s" % (",".join(str(x) for x in invalidEmails))) if len(correctedRecipients) == 0: raise CommandError("No recipient defined in options") task.arguments = "--recipient=%s --report=%s" % (recipient, report) task.save(using=database) # create message message = EmailMessage( subject="Exported reports", body="", from_email=sender, to=correctedRecipients, ) b = BytesIO() with ZipFile(file=b, mode="w", compression=ZIP_DEFLATED) as zf: processedFiles = 0 for f in correctedReports: task.message = "Compressing file %s" % basename(f) task.status = (str( int(processedFiles / len(correctedReports) * 90.0)) + "%") task.save(using=database) zf.write(filename=f, arcname=basename(f)) processedFiles = processedFiles + 1 zf.close() # attach zip file task.status = "90%" task.message = "Sending email" task.save(using=database) message.attach("reports.zip", b.getvalue(), "application/zip") # send email message.send() b.close() # Logging message task.processid = None task.message = "" task.status = "Done" task.finished = datetime.now() except Exception as e: if task: task.status = "Failed" task.message = "%s" % e task.finished = datetime.now() raise e finally: setattr(_thread_locals, "database", None) if task: task.processid = None task.save(using=database)
def _send_printouts_email(recipients, subject, body, html, attachment_filename): email = EmailMessage(subject=subject, body=body, to=recipients) pdf = html_to_pdf(html, stylesheet_paths=["order_printouts/css/extra.css"]) email.attach(attachment_filename, pdf, mimetype="application/pdf") email.send()
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': theming_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 = theming_helpers.get_value('default_from_email', 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()
#print s_file_name subject = 'Customer and Sales confirmed order report of %s to %s' % ( yesterday, today) body = 'PFA Customer and Sales confirmed order Report of %s to %s' % ( yesterday, today) msg = EmailMessage(subject, body, '*****@*****.**', [ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ], '', None) if c_file_name: data1 = open(c_file_name, 'rb').read() msg.attach('customer-%s.txt' % today, data1) if s_file_name: data2 = open(s_file_name, 'rb').read() msg.attach('sales-%s.txt' % today, data2) if c_file_name or s_file_name: msg.send() #Cancelled orders report orders = Order.objects.using('tinla_slave').filter( state='cancelled', modified_on__gte=yesterday, modified_on__lt=today, client=12)
def send_sync_report_mail(*args, **kwargs): """Envoyer un e-mail contenant les dernières Tasks exécutées ; par exemple suite un une synchronisation des ressources exécutée avec le script `sync_resources`. """ tasks_tracking = TaskTracking.objects.filter( task='celeriac.tasks.save_resource', start__gte=timezone.datetime.today().date(), end__isnull=False, ) csv_data = [('state', 'starting', 'end', 'dataset_id', 'dataset_name', 'resource_id', 'resource_name', 'error')] for task_tracking in tasks_tracking: try: resource = Resource.objects.get(pk=task_tracking.detail['kwargs']['pk']) except KeyError as e: logger.error("Malformed JSON: please check instance TaskTracking '%d'" % task_tracking.pk) logger.warning("Error was ignored.") continue except Resource.DoesNotExist as e: logger.exception(e) logger.warning("Error was ignored.") continue # else: csv_data.append(( task_tracking.state, task_tracking.start.isoformat(), task_tracking.end.isoformat(), resource.dataset.id, resource.dataset.title, resource.id, resource.title, task_tracking.detail.get('error', None), )) f = StringIO() csv.writer(f).writerows(csv_data) mail_instance = Mail.objects.get(template_name='email_task') mail = EmailMessage( mail_instance.subject, mail_instance.message, DEFAULT_FROM_EMAIL, get_admins_mails()) mail.attach('log.csv', f.getvalue(), 'text/csv') if ENABLE_SENDING_MAIL: try: mail.send() except SMTPDataError as e: logger.error(e) # Activer l'exception lorsque gérée par l'application. # return MailError() else: logger.warning("Sending mail is disable.")
def order_notification(cart, order, user): cart_storages = make_cart_storages(cart, user) for cart_storage, items in cart_storages.items(): body = 'Новый заказ от {date} #{order_number}.\r\n\r\nИнформация о заказе:\r\n'.format( date=order.added.strftime('%d.%m.%Y %H:%M'), order_number=order.id) profile = UserProfile.objects.get(user=user) body += 'Заказчик: {name} \r\n'.format( name=profile.fullname or profile) body += 'Код заказчика: {vip_code}\r\n'.format( vip_code=profile.vip_code or 'код заказчика отсутствует') storage = cart_storage order_total = 0 for idx, item in enumerate(items): product = item.item price = product.get_price(user, item.storage) qty = item.quantity order_total += price * qty body += '{idx}. {title} {brand} {sku}, {qty} шт. x {price} руб.., на общую сумму: {line_total} руб.\r\n'.format( idx=idx + 1, title=product.title, brand=product.brand, sku=product.get_sku(), qty=qty, price=price, line_total=qty * price) op = OrderProduct(order=order, item=product, qty=qty, price=price) op.save() body += '\r\nИтого: {total} руб.'.format(total=order_total) body += '\r\nСклад: {storage}'.format(storage=storage.name) body += '\r\n\r\nEmail клиента: {email}'.format(email=user.email) body += '\r\n\r\nКомментарии к заказу:\r\n{comment}'.format( comment=order.comment) subject = 'Сформирован новый заказ от {date} № {order_num}!'.format( date=order.added.strftime("%d.%m.%Y %H:%M"), order_num=order.id) sender = User.objects.filter(username='******').first() recipient = user status = STATUS_ACCEPTED message_user = Message(subject=subject, body=body, sender=sender, recipient=recipient, moderation_status=status) message_user.save() message_admin = Message(subject=subject, body=body, sender=recipient, recipient=sender, moderation_status=status) message_admin.save() # XLS document wb = Workbook() ws = wb.active ws.title = 'Заказ' thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin')) data = [] for idx, item in enumerate(cart.cartitem_set.all()): product = item.item price = product.get_price(user, item.storage) print(item.storage) print(price) qty = item.quantity coordinate = 'B' + str(idx) article = '%s %s' % (product.brand, product.get_sku()) data.append( [idx + 1, product.title, article, qty, price, qty * price]) ws.append([ '#', 'Товар', 'Брэнд', 'Количество', 'Цена за единицу', 'Цена (общая)' ]) for row in data: ws.append(row) ws.append(['', '', '', '', 'Итого:', order_total]) row_count = ws.max_row + 1 column_count = ws.max_column + 1 for i in range(1, row_count): for j in range(1, column_count): ws.cell(row=i, column=j).border = thin_border ws.column_dimensions["A"].width = 5.0 ws.column_dimensions["B"].width = 17.0 ws.column_dimensions["C"].width = 23.0 ws.column_dimensions["D"].width = 13.0 ws.column_dimensions["E"].width = 18.0 ws.column_dimensions["F"].width = 18.0 email = EmailMessage( subject, body, EMAIL_NOREPLY, [storage.email], EMAIL_BCC, reply_to=EMAIL_NOREPLY_LIST, headers={'Message-ID': 'foo'}, ) output = BytesIO() wb.save(output) email.attach('order.xlsx', output.getvalue(), 'application/excel') email.send() return True
def dayswork(request): p = [] q = [] print(date.today) today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min) today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max) p.append( Work.objects.filter(entry_date__range=(today_min, today_max)).values_list( 'empid', 'pid', 'percent', 'description')) q.append( Concept_work.objects.filter(date__range=(today_min, today_max)).values_list( 'empl_id', 'c_id', 'hours', 'desc')) print(p[0]) ls = [] ls1 = [] if p[0]: for i in range(len(p[0])): z = User.objects.filter(id=p[0][i][0]).values_list('first_name', flat=True) ls.append(z[0]) if q[0]: for j in range(len(q[0])): t = User.objects.filter(id=q[0][i][0]).values_list('first_name', flat=True) ls1.append(t[0]) response = HttpResponse(content_type='text/csv') csvfile = StringIO() response['Content-Disposition'] = 'attachment; filename="daily_list.csv"' writer1 = csv.writer(response) writer = csv.writer(csvfile) writer.writerow( ['Employee name', 'Project Id', 'Description', 'No. of Hours']) writer1.writerow( ['Employee name', 'Project Id', 'Description', 'No. of Hours']) if p[0] or q[0]: if p[0]: for i in range(len(p[0])): row = [ls[i], p[0][i][1], p[0][i][3], p[0][i][2]] writer.writerow(row) writer1.writerow(row) writer.writerow(['', '', '', '']) writer1.writerow(['', '', '', '']) if q[0]: for i in range(len(q[0])): row = [ls1[i], q[0][i][1], q[0][i][3], q[0][i][2]] writer.writerow(row) writer1.writerow(row) email = EmailMessage( 'Django csv file attached', 'PFA daily work csv file', settings.EMAIL_HOST_USER, ['*****@*****.**'], ) email.attach('file.csv', csvfile.getvalue(), 'text/csv') email.send() print('kuch to hua hai') return response else: return HttpResponse('No work submitted today by employees')
barcode = x[4] avl_date = x[3] ghostmice.append((barcode, avl_date)) return headers, ghostmice if __name__=='__main__': group_list = [(ghostmice_experimental, 'Ghost mice (experimental)', 'Ghost mice - experimental'), (ghostmice_naive, 'Ghost mice (naive)', 'Ghost mice - naive')] mail_to = [] mail_bcc = [] mail_from = '' for f, subj, firstline in group_list: head, data = f() body = "\n".join(["\t".join(x) for x in data]) mail_subject = subj mail_body = "%s (%d):\n\n" % (firstline, len(data)) mail_body = mail_body + body e = EmailMessage(subject=mail_subject, body=mail_body, from_email=mail_from, to=mail_to, bcc=mail_bcc) e.attach(filename=subj + ".las", mimetype = "text/plain", content = '\t'.join(head) + '\n' + body) e.send() print "" print "%s: email sent" % subj print ""
def check_resources_last_update(*args, **kwargs): csv_data = [('dataset_slug', 'resource_uuid', 'sync_frequency', 'last_update', 'delay')] for resource in Resource.objects.filter(**kwargs): delta = { # '5mn': relativedelta(minutes=5), # '15mn': relativedelta(minutes=15), # '20mn': relativedelta(minutes=20), # '30mn': relativedelta(minutes=30), '1hour': relativedelta(hours=1), '3hours': relativedelta(hours=3), '6hours': relativedelta(hours=6), 'daily': relativedelta(days=1), 'weekly': relativedelta(days=7), 'bimonthly': relativedelta(days=15), 'monthly': relativedelta(months=1), 'quarterly': relativedelta(months=3), 'biannual': relativedelta(months=6), 'annual': relativedelta(year=1), }.get(resource.sync_frequency) if not delta: continue delay = timezone.now() - (resource.last_update + delta) if delay.total_seconds() > 0: csv_data.append(( resource.dataset.slug, resource.ckan_id, resource.sync_frequency, resource.last_update, delay, )) if not csv_data: # Nothing to do return f = StringIO() csv.writer(f).writerows(csv_data) mail_instance = Mail.objects.get(template_name='resources_update_with_delay') mail = EmailMessage( mail_instance.subject, mail_instance.message, DEFAULT_FROM_EMAIL, get_admins_mails()) mail.attach('log.csv', f.getvalue(), 'text/csv') if ENABLE_SENDING_MAIL: try: mail.send() except SMTPDataError as e: logger.error(e) # Activer l'exception lorsque gérée par l'application. # return MailError() else: logger.warning("Sending mail is disable.")
def successfulorder(request): today = datetime.datetime.now() current_time = datetime.datetime.now() expected_delivery = today + timedelta(days=2) day_name= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday'] if current_time.hour < 18: expected_delivery = today + timedelta(days=1) day = expected_delivery.weekday() if day_name[day] == 'Sunday' or day_name[day] == 'Monday': expected_delivery = expected_delivery + timedelta(days=1) else: expected_delivery = today + timedelta(days=2) day = expected_delivery.weekday() if day_name[day] == 'Sunday' or day_name[day] == 'Monday' or day_name[day] == 'Tuesday': expected_delivery = expected_delivery + timedelta(days=1) unique_id = get_random_string(length = 7) current_user = request.user consumer = Consumer.objects.get(user_id = current_user.id) grand_total = request.session['grand_total'] cust_addr = request.session['cust_addr'] cust_pt=Consumer_Address.objects.get(consumer_id = consumer.id,addr=cust_addr).point order=Order(total_price = grand_total, secondary_id = unique_id, date_placed = today, consumer = current_user.consumer, delivery_addr = cust_addr, delivery_point = cust_pt) order.save() order=Order.objects.get(secondary_id=unique_id) data = {} data['names']= request.session['names'] data['qty']=request.session['qty'] data['addr']=cust_addr data['username']=request.user.first_name+' '+request.user.last_name data['email']=request.user.email providers=request.session['provider'] available=request.session['available'] names=[] quantity=[] t_price=[] p=[] for i in range(len(data['names'])): if available[i]: prod=Product.objects.get(name=data['names'][i]) prov=Provider.objects.get(shop_name=providers[i]) price=Price.objects.get(provider=prov,product=prod).price total_price=price*data['qty'][i] names.append(data['names'][i]) quantity.append(data['qty'][i]) p.append(price) t_price.append(total_price) ProductInOrder(product = prod, provider = prov, order = order, quantity = data['qty'][i], total_price = total_price, expected_delivery_date = expected_delivery, last_tracked_on=today).save() data['length'] = range(len(names)) data['total_price']=t_price data['per_price']=p data['names']=names data['qty']=quantity data['expected_delivery']=expected_delivery data['grand_total']=grand_total data['unique_id']=unique_id html_string = render_to_string('invoice.html', data) html = HTML(string=html_string,base_url=request.build_absolute_uri()) result = html.write_pdf() to = [current_user.email] #send_mail('Test Mail','Practice for project',settings.EMAIL_HOST_USER,to,fail_silently=True) #pdf = render_to_pdf('invoice.html',data) email = EmailMessage( 'Order Confirmation', 'Invoice attatched as pdf', 'settings.EMAIL_HOST_USER',to) if result: email.attach('invoice2.pdf',result ,'application/pdf') email.send() return render(request,'csuccessfulorder.html',data)
def save(self, project, campaign, donation_id): """Do the talking to the payment processors and save a record in the older donation model""" cleaned_data = self.cleaned_data # Write donation details to the database credit_card = cleaned_data['credit_card'] expr_month, expr_year = cleaned_data['expr_date'] cnp_security = cleaned_data['cvv'] amount = cleaned_data['amount'] address_1 = cleaned_data['address_1'] zipcode = cleaned_data['zipcode'] ip_address = cleaned_data['ip_address'] #company = get_object_or_none(Company, id=cleaned_data['company_id']) from vibha.donations.models import Donation as MasterDonation d = MasterDonation( first_name=cleaned_data['first_name'], last_name=cleaned_data['last_name'], email=cleaned_data['email'], address_1=address_1, address_2=cleaned_data['address_2'], city=cleaned_data['city'], state=cleaned_data['state'], action_center=cleaned_data['action_center'], zipcode=zipcode, country=cleaned_data['country'], phone=cleaned_data['phone'], amount=amount, ip_address=ip_address, comments=cleaned_data['comments'], referrer=cleaned_data['referrer'], #company=company, company_name=cleaned_data['company_name'], paper_receipt=cleaned_data['paper_receipt'], project_subscription=cleaned_data['project_subscription'], event_subscription=cleaned_data['event_subscription'], #champion=champion, project=project, adopt_a_project=donation_id, anonymous=cleaned_data['anonymous']) d.save() import logging # Process the transaction logging.info('donorportal_donate: expr_month: %s, expr_year: %s', expr_month, expr_year) if project is not None: logging.info( 'donorportal_donate: project specific donation to: %s', unicode(project)) (trans_status, trans_summary, trans_response) = transact(credit_card, expr_month, expr_year, cnp_security, amount, address_1, zipcode, ip_address) # Write transaction information to the database d.trans_status = trans_status d.trans_summary = trans_summary d.trans_response = trans_response d.save() # Send e-mail to concered people in Vibha, if a transaction fails. if not trans_status: recipients = ['*****@*****.**', '*****@*****.**'] body = render_to_string('donations/singledonation-error-email.txt', {'model': d}) email = EmailMessage( 'Error while processing adopt-a-project donation, please take a look', body, '*****@*****.**', recipients) email.attach('response.html', d.trans_response, 'text/html') email.send(fail_silently=False)
def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) if request.method == 'POST': # retrieve nonce nonce = request.POST.get('payment_method_nonce', None) # create and submit transaction result = braintree.Transaction.sale({ 'amount': '{:.2f}'.format(order.get_total_cost()), 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # store the unique transaction id order.braintree_id = result.transaction.id order.save() # create invoice e-mail subject = 'My Shop - Invoice no. {}'.format(order.id) message = 'Please, find attached the invoice for your recent purchase.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [ weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css') ] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail email.send() # send sms # Your Account SID from twilio.com/console #account_sid = "AC1cac4d02cc38ebe54d55d730ca00703c" # Your Auth Token from twilio.com/console #auth_token = "423946a57f6b878f341abe7d66b3fe2f" #client = Client(account_sid, auth_token) #message = client.messages.create( # to="+14027066443", # from_="+117122484584", # body="Thank you {} {}, Your order {} has been placed successfully and will be delivered to {}, {}, {}".format(order.first_name,order.last_name,order.id,order.address,order.city,order.postal_code) #) #print(message.sid) client = nexmo.Client(key='afc1e627', secret='ddV43jqW79xSneKo') client.send_message({ 'from': '18595920844', 'to': '14027066443', 'text': 'Thank you {} {}, Your order {} has been placed successfully and will be delivered to {}, {}, {}' .format(order.first_name, order.last_name, order.id, order.address, order.city, order.postal_code) }) return redirect('payment:done') else: return redirect('payment:canceled') else: # generate token client_token = braintree.ClientToken.generate() return render(request, 'payment/process.html', { 'order': order, 'client_token': client_token })
def build_contact(request, slug=""): """ Builds appropriate contact form based on options set in the contact_form controller. """ controller = get_object_or_404(ContactFormController, slug=slug) site = Site.objects.get_current() UserModel = get_user_model() user = request.user form = ContactForm(request.POST or None, request.FILES or None, controller=controller) # if we know, fill in the user name and email if user.is_authenticated: # first, resolve username for tango and non-tango sites try: name = user.display_name except AttributeError: name = user.username form.fields['sender_name'].widget.attrs['readonly'] = 'true' form.fields['sender_name'].initial = name form.fields['sender_email'].widget.attrs['readonly'] = 'true' form.fields['sender_email'].initial = user.email if form.is_valid(): if controller.store_in_db: # To do: sanitize submission. new_msg = Contact(**form.cleaned_data) new_msg.controller = controller new_msg.site = site if controller.override_subject: # we're overriding the subject new_msg.subject = controller.override_subject new_msg.save() if controller.send_emails: form_data = form.cleaned_data if controller.override_subject: subject = controller.override_subject elif 'subject' in form_data: subject = form_data['subject'] else: subject = "{} message from {}".format(controller.name, form_data['sender_name']) body = "{} \n\n {}".format(form_data['body'], form_data['sender_name']) if controller.request_contact_info: body += "\nAddress: {} \nCity: {} \nState: {} \nPhone: {}".format( form_data['contact_address'], form_data['contact_city'], form_data['contact_state'], form_data['contact_phone']) if controller.email_options == '2': # Create selectable list from recipients try: to = [ UserModel.objects.get( username=form.cleaned_data['to']).email ] except Exception: to = [form.cleaned_data['to']] if controller.email_options == '1': to = [r.email for r in controller.recipients.all()] for r in controller.other_recipients.all(): to.append(r.email) if 'send_a_copy' in form.cleaned_data: to.append(form.cleaned_data['sender_email']) mail = EmailMessage(subject=subject, body=body, from_email=form.cleaned_data['sender_email'], to=to) if 'photo' in request.FILES: photo = request.FILES['photo'] mail.attach(photo.name, photo.read(), photo.content_type) mail.send() return render(request, 'success_url', {'controller': controller}) return render(request, 'contact/form.html', { 'form': form, 'site': site, 'controller': controller })
def save(self, *args, **kwargs): from_email = '*****@*****.**' to_email = DN_OBIT_EMAIL_RECIPIENTS message_email = 'Go to the obituary admin page for further information.' datatuple = () ''' Change/new e-mails for changed, saved obituaries ''' if not self.obituary_created: # a new Obituary message_subj = 'Obituary created for %s %s' % (self.death_notice.first_name, self.death_notice.last_name) datatuple = (message_subj, message_email, from_email, to_email,), # <- This trailing comma's vital! ''' Check for photo with an about-to-be-created Obituary. ''' if self.photo and not self.obituary_created: to_email = IMAGING_OBIT_EMAIL_RECIPIENTS message_subj = 'Photo has been attached to %s %s obituary' % (self.death_notice.first_name, self.death_notice.last_name) message_email = 'Photo file %s is attached.' % path.split(self.photo.name)[1] imaging_email = EmailMessage() imaging_email.subject = message_subj imaging_email.body = message_email imaging_email.to = to_email imaging_email.attach(path.split(self.photo.name)[1], self.photo.read(), 'image/jpg') imaging_email.send(fail_silently=False) ''' Check if obituary has 'publish_date' ''' if self.obituary_created and self.obituary_publish_date: to_email = BO_OBIT_EMAIL_RECIPIENTS # Compare what's in database vs. what's on current Web form. copy_existing = Obituary.objects.get(pk=self.pk) if not copy_existing.obituary_publish_date and self.obituary_publish_date: if self.prepaid_by: cost = self.COST['STAFF'] else: cost = self.COST['FH'] if self.user and (self.user.username in ('sbecraft', 'lcrossley', 'weeditor',)): message_subj = '[Accounting] Obituary printed for %s %s' % (self.death_notice.first_name, self.death_notice.last_name) message_email = 'Add %s to the invoice of %s.' % (cost, self.death_notice.funeral_home.fh_user2.full_name) elif self.user and (self.user.username in INSIDE_OBIT_USERNAMES): message_subj = '[Accounting] PRE-PAID obituary printed for %s %s' % (self.death_notice.first_name, self.death_notice.last_name) message_email = '%s for the %s obituary was prepaid: %s.' % (cost, self.death_notice.funeral_home.fh_user2.full_name, self.prepaid_by) else: message_subj = '[Accounting] Obituary printed for %s %s' % (self.death_notice.first_name, self.death_notice.last_name) message_email = 'Add %s to the invoice of %s. (You can also check http://www.registerguard.com/web/news/obituaries/)' % (cost, self.death_notice.funeral_home.fh_user2.full_name) datatuple = (message_subj, message_email, from_email, to_email,), # <- This trailing comma's vital! ''' Check for attachment of photo to an existing Obituary. ''' # I think maybe we don't care if it's live, if a photo's been attached? # if self.obituary_created and self.photo and self.status == 'live': if self.obituary_created and self.photo: to_email = IMAGING_OBIT_EMAIL_RECIPIENTS copy_existing = Obituary.objects.get(pk=self.pk) if not copy_existing.photo and self.photo: ''' TODO: Factor this e-mailer out; rename image to that of decedent; take out mime-type; ''' message_subj = 'Photo has been attached to %s %s obituary' % (self.death_notice.first_name, self.death_notice.last_name) message_email = 'Photo file %s is attached.' % path.split(self.photo.name)[1] imaging_email = EmailMessage() imaging_email.subject = message_subj imaging_email.body = message_email imaging_email.to = to_email imaging_email.attach(path.split(self.photo.name)[1], self.photo.read(), 'image/jpg') imaging_email.send(fail_silently=False) ''' Check for change of status from draft to live and notifying appropriate classified representative ''' # http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed ''' Can't check state of Obituary using self.pk as the Obituary has a OneToOneField relationship to the Death Notice, so they share a pk, so we use the self.obituary_created field to see if the Obituary's in the database. ''' ''' This two-part obituary_created or self.status/self.obituary_created test is to catch Obituaries that have changed state from 'Draft' to 'Submitted' from both saved-exist-in-the-database or Saved on initial form filling out. ''' if self.obituary_created is not None or (self.status == 'live' and self.obituary_created == None): try: orig = Obituary.objects.get(pk=self.pk) except Obituary.DoesNotExist: orig = None ''' This ( self.status/self.obituary_created ) or ( orig.status/self.status ) bit is the second part of the machinery to catch the change from 'Draft' to 'Submitted' Obituaries for both the saved-in-the-database and those that are 'Submitted" on initial Save. ''' if (self.status =='live' and self.obituary_created == None) or (orig.status == 'drft' and self.status == 'live'): # status of obituary based on an FH-created death notice changed by FH if self.user == self.death_notice.funeral_home: message_subj = 'Obituary for %s %s has been released by %s' % (self.death_notice.first_name.strip(), self.death_notice.last_name.strip(), self.death_notice.funeral_home.fh_user2.full_name) # Get the relevant class_rep, so we can notify via email, # but also try/except check that FH has a rep ... it may not. try: class_rep_to_notify = self.death_notice.funeral_home.fh_user2.rg_rep.email # FH has no rg_rep assigned, therefore no email to send. except AttributeError: class_rep_to_notify = None # status of obituary based on an FH-created death notice changed by internal R-G user else: message_subj = 'Obituary for %s %s has been released by %s' % (self.death_notice.first_name.strip(), self.death_notice.last_name.strip(), self.user.get_full_name()) class_rep_to_notify = None message_email = u'* Obituary text below:\n\n %s'% self.obituary_body if self.flag: message_email = '* Flag insignia requested.\n\n' + message_email if self.service_insignia: message_email = ('* Service insignia requested: %s' % self.service_insignia) + '\n\n' + message_email try: class_rep = self.user.email except AttributeError: class_rep = None if class_rep_to_notify: to_email = [class_rep_to_notify, '*****@*****.**',] elif class_rep: to_email = [class_rep, '*****@*****.**',] ''' If there's a photo, attach it ''' if self.photo: img_class_message = EmailMessage() img_class_message.subject, img_class_message.body, img_class_message.to = message_subj, message_email, to_email img_class_message.attach(path.split(self.photo.name)[1], self.photo.read(), 'image/jpg') ''' If there's a second photo, attach it too. ''' if self.photo_two: img_class_message.attach(path.split(self.photo_two.name)[1], self.photo_two.read(), 'image/jpg') img_class_message.send(fail_silently=False) else: datatuple = (message_subj, message_email, from_email, to_email,), # <- This trailing comma's vital! if datatuple: try: send_mass_mail(datatuple) except SMTPDataError: pass super(Obituary, self).save(*args, **kwargs)
def dna_extraction(): q = "start c=node(*) match (c)-[:hasChild]->(cc) where c.entity ='C' and cc.entity='C' return id(cc), cc.genid" print "Retrieving mice to exclude from aliquot extraction..." mice_to_exclude = set(find_mice_to_exclude()) print "Retrieving cases..." cq = neo4j.CypherQuery(gdb, q) cases = cq.execute() print len(cases), " case(s) found" for c in cases: case_id = c[0] case_gid = c[1] gid = GenealogyID(case_gid) if gid.getOrigin() == 'CRC' and int(gid.getCaseCode()) <= 430: continue print "===[ Case %s ]====================" % case_gid check_case(case_id, case_gid) print "" print "" print "Aliquots for extraction (%d):" % len(rl_aliquots) rl = sorted(rl_aliquots) al_recent, al_old = sortAliquots(rl_aliquots) recipients = [] sender = '' subject = 'Aliquots for DNA Extraction' text_content = "" #text_content = "Red Node = Aliquot selected for extraction\nBlue Border = DNA already extracted\nBox Shape = RNAlater aliquots present\n\n" text_content = text_content + "Recent aliquots (" + ( datetime.now() - timedelta(days=days_recent) ).strftime("%a, %d %b %Y") + " - " + datetime.now().strftime( "%a, %d %b %Y") + "): " + str(len(al_recent)) + "\n" for a in al_recent: #urlimg = "" #if aliquots.index(a) != 0: # # if a[:9] == aliquots[aliquots.index(a)-1][:9]: # urlimg = "" # # else: # urlimg = ' http://devircc.polito.it/tree_images/'+ a[:9] +'00000000000000000.png' #else: # urlimg = ' http://devircc.polito.it/tree_images/'+ a[:9] +'00000000000000000.png' #urlimg = ' http://lasircc.polito.it/tree_images/'+ a[:9] +'00000000000000000.png' #text_content = text_content + a + urlimg + '\n' text_content = text_content + a + '\n' text_content = text_content + "\nOlder aliquots: " + str( len(al_old)) + "\n" for a in al_old: #urlimg = ' http://lasircc.polito.it/tree_images/'+ a[:9] +'00000000000000000.png' #text_content = text_content + a + urlimg + '\n' text_content = text_content + a + '\n' print "" print "Sending email" print "Recipients: ", ", ".join(recipients) print "Content:" cprint(text_content, 'cyan') try: e = EmailMessage(subject=subject, body=text_content, from_email=sender, to=recipients) e.attach(filename="Recent_aliquots.las", mimetype="text/plain", content='\n'.join(al_recent)) e.attach(filename="Old_aliquots.las", mimetype="text/plain", content='\n'.join(al_old)) e.send() print print 'Email sent' except Exception, e: print e cprint('Error sending email', 'red')
def catalog_category(request, category_path): out = {} category_slug = category_path.split('/')[-2] if len(category_path.split('/')) > 2: parent_category_slug = category_path.split('/')[-3] category = CategoryProduct.objects.filter(slug=category_slug).first() out.update({'menu_active_item': 'catalog'}) out.update({'category_path': category_path}) if category: category.number = Product.objects.filter(published=True, category=category).count() for child_category in CategoryProduct.objects.filter( published=True, parent_id=category.id).all(): category.number += Product.objects.filter( published=True, category=child_category).count() if CategoryProduct.objects.filter(parent_id=category.id): title = 'Вложенные категории' subcategories = CategoryProduct.objects.filter( parent_id=category.id, published=True).all() for subcategory in subcategories: subcategory_products_all = Product.objects.filter( published=True, category=subcategory) subcategory.number = subcategory_products_all.count() for child_category in CategoryProduct.objects.filter( published=True, parent_id=subcategory.id).all(): subcategory_products_all = subcategory_products_all | Product.objects.filter( published=True, category=child_category) subcategory.number += Product.objects.filter( published=True, category=child_category).count() subcategory.min_price = None for product in subcategory_products_all: current = product.properties.filter( Q(property__title__contains='Цена')).first() try: if current and not subcategory.min_price: subcategory.min_price = float( unicode(current.value).replace( u' ', u'').replace(u'\xa0', u'')) if current and float( current.value.replace(' ', '').replace( u'\xa0', '')) < subcategory.min_price: subcategory.min_price = float( current.value.replace(' ', '').replace(u'\xa0', '')) except Exception: pass template_name = 'catalog_category.html' ind_subcategory = enumerate(subcategories) if request.GET.get('expand', 'true') == 'true': template_name = 'catalog_category_expand.html' out.update({ 'subcategories': subcategories, 'title': title, 'category': category, 'request': request, 'ind_subcategory': ind_subcategory }) out.update({'title': category.name}) return render(request, template_name, out) else: title = 'Список продуктов' products = Product.objects.filter(category=category, published=True) for product in products.all(): product.properties_dict = product.properties.values( 'property__title', 'value') template_name = 'catalog_category_products.html' ind_products = enumerate(products.all()) properties = [] properties_ids = ProductProperty.objects.filter( product__in=products).values_list('property', flat=True).distinct().all() for property_id in properties_ids: properties.append(Property.objects.get(pk=property_id)) properties.sort() # найти минимальное и максимальное значение в каждом свойстве for property in properties: all_value = list( ProductProperty.objects.filter( product__in=products, property=property).values_list('value', flat=True)) all_value_int = [] for value in all_value: try: all_value_int.append( float( value.replace(',', '.').replace( ' ', '').replace(u'\xa0', '').replace( u'\u2014', '').replace('-', ''))) except Exception: all_value_int = [0] property.min = unicode(min(all_value_int)).replace(',', '.') property.max = unicode(max(all_value_int)).replace(',', '.') property.get_min = property.min property.get_max = property.max # фильтрация по гет-параметрам for property in properties: property_get_param_from = property.slug + '_from' property_value_from = request.GET.get(property_get_param_from, None) if property_value_from: property.get_min = property_value_from for product in products: if not float( product.properties.filter( property=property).first().value.replace( ',', '.')) >= float(property_value_from): products = products.exclude(pk=product.pk) property_get_param_to = property.slug + '_to' property_value_to = request.GET.get(property_get_param_to, None) if property_value_to: property.get_max = property_value_to for product in products: if not float( product.properties.filter( property=property).first().value.replace( ',', '.')) <= float(property_value_to): products = products.exclude(pk=product.pk) # отфильтровали products = products.all() for product in products: product.properties_dict = {} for property in properties: prop = ProductProperty.objects.filter( product=product, property=property).first() if prop: product.properties_dict.update({ property.title + ', ' + property.units: prop.value }) else: product.properties_dict.update( {property.title + ', ' + property.units: ' - '}) product.properties_dict = collections.OrderedDict( sorted(product.properties_dict.items())) new_properties = [] for property in properties: new_properties.append(u'{}, {}'.format(property.title, property.units)) new_properties.sort() if request.GET.get('expand', 'true') == 'true': template_name = 'catalog_category_products_expand.html' out.update({ 'products': products, 'parent': category, 'title': title, 'category': category, 'request': request, 'ind_products': ind_products, 'properties': new_properties, 'properties_objs': properties }) if request.method == 'POST': callback_form = CallbackForm(request.POST, request.FILES) if callback_form.is_valid(): kwargs = dict( to=EMAILS_FOR_CALLBACK, from_email='*****@*****.**', subject=u'Заказ продукции', body= u'Поступил запрос на заказ продукции {} в количестве {} штук от {} (телефон для связи - {}, email - {}) с комментарием:\n\n"{}"' .format( callback_form.cleaned_data['product'], callback_form.cleaned_data['count'], callback_form.cleaned_data['name'], callback_form.cleaned_data['phone'], callback_form.cleaned_data['email'], callback_form.cleaned_data['comment'], ), ) message = EmailMessage(**kwargs) for attachment in request.FILES.getlist('file_field'): message.attach(attachment.name, attachment.read(), attachment.content_type) message.send() logger.info(u'Send callback with text: {}'.format( kwargs['body'])) callback_form = CallbackForm() out.update({'callback_form': callback_form}) out.update({'title': category.name}) return render(request, template_name, out) else: return get_product(request, category_path, out)
def pdf_generate(user_pk): user = User.objects.get(pk=user_pk) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=landscape(legal), verbosity=1, leftMargin=0.25 * inch, rightMargin=0.25 * inch, topMargin=0.5 * inch, bottomMargin=1.25 * inch) styles = getSampleStyleSheet() story = [] def entry(object, flight): if not object or object is False: entry = '-' elif object is True: entry = str(flight.duration) else: entry = str(object) return entry # cover page starts here def title_page(canvas, doc): canvas.saveState() canvas.drawImage('pdf_output/wings.png', 103, 205, width=800, height=229) canvas.setFont('Helvetica-Oblique', 7) canvas.drawString( 800, 30, "Powered by Direct2Logbook.com and ReportLab") canvas.setFont('Helvetica', 10) page_number_text = "%d" % (doc.page) canvas.drawCentredString( 14 * inch / 2, 30, page_number_text ) canvas.restoreState() def add_later_page_number(canvas, doc): canvas.saveState() canvas.setFont('Helvetica-Oblique', 7) canvas.drawString( 800, 30, "Powered by Direct2Logbook.com and ReportLab") if Signature.objects.filter(user=user).exists(): sig = Signature.objects.get(user=user) signature_path = sig.signature.url canvas.drawImage(str(signature_path), 240, 50, width=100, height=40) else: None canvas.setFont('Helvetica', 10) canvas.drawString( 30, 50, "I certify that the entries in this logbook are true.") canvas.setStrokeColorRGB(0, 0, 0) canvas.setLineWidth(0.5) canvas.line(240, 50, 480, 50) canvas.setFont('Helvetica', 10) page_number_text = "%d" % (doc.page) canvas.drawCentredString( 14 * inch / 2, 30, page_number_text ) canvas.restoreState() spacer15 = Spacer(1, 1.5 * inch) spacer025 = Spacer(1, .25 * inch) story.append(spacer15) story.append(spacer025) text = "<para size=50 align=center>Logbook for {} {}</para>".format( user.first_name, user.last_name) title = Paragraph(text, style=styles["Normal"]) story.append(title) story.append(spacer15) story.append(spacer15) text = "<para size=15 align=center>Data current as of {}</para>".format( datetime.date.today().strftime("%m/%d/%Y")) title = Paragraph(text, style=styles["Normal"]) story.append(title) story.append(PageBreak()) # summary page starts here spacer = Spacer(1, 0.25 * inch) text = "<para size=15 align=left><u><b>Category and Class Summary</b></u></para>" cat_class_title = Paragraph(text, style=styles["Normal"]) story.append(cat_class_title) story.append(spacer) # total table total_objects = Total.objects.filter(user=user) totals_that_exist = [] for total in total_objects: if total.total_time > 0.0: totals_that_exist.append(str(total.total)) total_data = [] for total in totals_that_exist: total = Total.objects.filter(user=user).get(total=total) row = [str(total.total), str(total.total_time), str(total.pilot_in_command), str(total.second_in_command), str(total.cross_country), str(total.instructor), str(total.dual), str(total.solo), str( total.instrument), str(total.night), str(total.simulated_instrument), str(total.simulator), str(total.landings_day), str( total.landings_night), str(total.landings_day + total.landings_night), str(total.last_flown.strftime("%m/%d/%Y")), str(total.last_30), str( total.last_60), str(total.last_90), str(total.last_180), str(total.last_yr), str(total.last_2yr), str(total.ytd)] total_data.append(row) total_header = ["Cat/Class", "Time", "PIC", "SIC", "XC", "CFI", "Dual", "Solo", "IFR", "Night", "Hood", "Sim", "D Ldg", "N Ldg", "Total Ldg", "Last Flown", "30", "60", "90", "6mo", "1yr", "2yr", "Ytd"] total_data.insert(0, total_header) total_table = Table(total_data, hAlign='LEFT') cat_class_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) total_table.setStyle(cat_class_tablestyle) story.append(total_table) story.append(spacer) # misc tables start here # role_table role_objects = Power.objects.filter(user=user) role_data = [] for role in role_objects: row = [str(role.role), str(role.turbine), str(role.piston)] role_data.append(row) role_header = ["Role", "Turbine", "Piston"] role_data.insert(0, role_header) role_table = Table(role_data, hAlign="LEFT") role_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) role_table.setStyle(role_tablestyle) # regs_table regs_objects = Regs.objects.filter(user=user) regs_data = [] for regs in regs_objects: row = [str(regs.reg_type), str(regs.pilot_in_command), str(regs.second_in_command)] regs_data.append(row) regs_header = ["FAR", "PIC", "SIC"] regs_data.insert(0, regs_header) regs_table = Table(regs_data, hAlign='LEFT') reg_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ]) regs_table.setStyle(reg_tablestyle) # weight_table weight_objects = Weight.objects.filter(user=user) weights_that_exist = [] for weight in weight_objects: if weight.total > 0.0: weights_that_exist.append(weight) weight_data = [] for weight in weights_that_exist: row = [str(weight.weight), str(weight.total)] weight_data.append(row) weight_header = ['Weight', 'Total'] weight_data.insert(0, weight_header) weight_table = Table(weight_data, hAlign='LEFT') weight_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) weight_table.setStyle(weight_tablestyle) # endoresment_table endorsement_objects = Endorsement.objects.filter(user=user) endorsements_that_exist = [] for endorsement in endorsement_objects: if endorsement.total > 0.0: endorsements_that_exist.append(endorsement) endorsement_data = [] for endorsement in endorsements_that_exist: row = [str(endorsement.endorsement), str(endorsement.total)] endorsement_data.append(row) endorsement_header = ['Endorsement', 'Total'] endorsement_data.insert(0, endorsement_header) endorsement_table = Table(endorsement_data, hAlign='LEFT') endorsement_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) endorsement_table.setStyle(endorsement_tablestyle) # misc_table text = "<para size=15 align=left><u><b>Misc Summary</b></u></para>" misc_title = Paragraph(text, style=styles["Normal"]) story.append(misc_title) story.append(spacer) misc_data = [ [role_table, regs_table, weight_table, endorsement_table] ] misc_table = Table(misc_data, hAlign="LEFT") story.append(misc_table) story.append(spacer) # aircraft stats table text = "<para size=15 align=left><u><b>Aircraft Summary</b></u></para>" aircraft_stats_title = Paragraph(text, style=styles["Normal"]) story.append(aircraft_stats_title) story.append(spacer) stat_objects = Stat.objects.filter(user=user) stat_data = [] for stat in stat_objects: # avoids None failure when user hasn't logged time in aircraft date_condition = [stat.last_flown, stat.last_30, stat.last_60, stat.last_90, stat.last_180, stat.last_yr, stat.last_2yr, stat.ytd] if None not in date_condition: row = [str(stat.aircraft_type), str(stat.total_time), str(stat.pilot_in_command), str(stat.second_in_command), str(stat.cross_country), str(stat.instructor), str(stat.dual), str(stat.solo), str( stat.instrument), str(stat.night), str(stat.simulated_instrument), str(stat.simulator), str( stat.landings_day), str(stat.landings_night), str(stat.last_flown.strftime("%m/%d/%Y")), str(stat.last_30), str( stat.last_60), str(stat.last_90), str(stat.last_180), str(stat.last_yr), str(stat.last_2yr), str(stat.ytd)] stat_data.append(row) else: pass stat_header = ["Type", "Time", "PIC", "SIC", "XC", "CFI", "Dual", "Solo", "IFR", "Night", "Hood", "Sim", "D Ldg", "N Ldg", "Last Flown", "30", "60", "90", "6mo", "1yr", "2yr", "Ytd"] stat_data.insert(0, stat_header) stat_table = Table(stat_data, repeatRows=(1), hAlign='LEFT') stat_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ]) stat_table.setStyle(stat_tablestyle) story.append(stat_table) story.append(spacer) # story.append(PageBreak()) # logbook starts here if os.getenv('DEBUG') is True: flight_objects = Flight.objects.filter(user=user).order_by('-date')[:100] else: flight_objects = Flight.objects.filter(user=user).order_by('-date') logbook_data = [] logbook_header = ['Date', 'Type', 'Reg', 'Route', 'Block', 'PIC', 'SIC', 'XC', 'Night', 'IFR', 'Appr', 'Hold', 'D Ldg', 'N Ldg', 'Hood', 'CFI', 'Dual', 'Solo', 'Sim'] for flight in flight_objects: date = flight.date Date = date.strftime("%m/%d/%Y") PIC = entry(flight.pilot_in_command, flight) SIC = entry(flight.second_in_command, flight) XC = entry(flight.cross_country, flight) Night = entry(flight.night, flight) IFR = entry(flight.instrument, flight) CFI = entry(flight.instructor, flight) Dual = entry(flight.dual, flight) Solo = entry(flight.solo, flight) Sim = entry(flight.simulator, flight) Day_LDG = entry(flight.landings_day, flight) Night_LDG = entry(flight.landings_night, flight) Hood = entry(flight.simulated_instrument, flight) appr = '' for approach in flight.approach_set.all(): appr = appr + str(approach.approach_type) + \ '-' + str(approach.number) + ' ' hold = '' for holding in flight.holding_set.all(): if holding.hold: hold = 'Yes' else: hold = '-' row = [Date, str(flight.aircraft_type), str(flight.registration), str(flight.route), str( flight.duration), PIC, SIC, XC, Night, IFR, appr, hold, Day_LDG, Night_LDG, Hood, CFI, Dual, Solo, Sim] logbook_data.append(row) logbook_data.insert(0, logbook_header) logbook_table = LongTable(logbook_data, repeatRows=(1), hAlign='LEFT') logbook_tablestyle = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10), ('LINEBELOW', (0, 0), (-1, 0), 1.0, colors.black), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('LINEBELOW', (0, 0), (-1, -1), .25, colors.black), ('ALIGN', (4, 0), (-1, -1), 'RIGHT'), ]) logbook_table.setStyle(logbook_tablestyle) styles = getSampleStyleSheet() text = "<para size=15 align=left><u><b>Logbook</b></u></para>" logbook_title = Paragraph(text, style=styles["Normal"]) story.append(logbook_title) story.append(spacer) story.append(logbook_table) # build pdf # doc.multiBuild(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc.multiBuild(story, onFirstPage=title_page, onLaterPages=add_later_page_number) # doc.build(story) # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() # email message/attachment subject = "Logbook for {} {}".format(user.first_name, user.last_name) user_email = user.email email = EmailMessage( subject, 'Good luck on your interview!', '*****@*****.**', [user_email], reply_to=['*****@*****.**'], headers={'Message-ID': 'logbook'}, ) email.attach('Logbook.pdf', pdf, 'application/pdf') email.send() return None
def checkout(request): """Gets payment information and send an email with the data """ lista = request.POST.lists() for item in lista: item = json.loads(item[0]) amount = item['amount'] monthly_check = item['monthly_check'] fee_check = item['fee_check'] honor_memory_radio = item['honor_memory_radio'] message_tribute = item['message'] card_number = item['card_number'] card_end_date = item['card_end_date'] card_cvc = item['card_cvc'] hide_amount = item['hide_amount'] first_name = item['first_name'] last_name = item['last_name'] email = item['email'] address = item['address'] from_name = item['from'] to = item['to'] frecuency = 'once' serial = generate_serial(8) if monthly_check: frequency = 'monthly' context = { 'name': first_name + last_name, 'amount' : amount, 'address' : address, 'message': message_tribute, 'now' : date.today(), 'serial': serial } # pdf = render_to_pdf('en/pdfs/donation.html', context) # return HttpResponse(pdf, content_type='application/pdf') # return render(request, 'en/pdfs/donation.html', context) generate_pdf('en/pdfs/donation.html', context) # Send response email after a donation with generated pdf with transaction.atomic(): message = render_to_string('en/emails/donation.html', context, request=request) subject = 'Thank you for your help!' email_address = email email = EmailMessage(subject, message, '*****@*****.**', [email_address]) email.content_subtype = 'html' file = open('media/invoice.pdf', encoding="utf8", errors='ignore') email.attach('invoice.pdf',file.read(),'text/plain') email.send() # Send card data for manual payment context = { 'name': first_name + last_name, 'amount' : amount, 'address' : address, 'message': message_tribute, 'frequency': frequency, 'honor_memory_radio': honor_memory_radio, 'card_number': card_number, 'card_end_date': card_end_date, 'card_cvc': card_cvc, 'hide_amount': hide_amount, 'email':email, 'now' : date.today(), 'serial': serial, 'from_name': from_name, 'to': to, } message = render_to_string('en/emails/card-data.html', context, request=request) subject = 'Donation request' email_address = settings.EMAIL_HOST_USER email = EmailMessage(subject, message, '*****@*****.**', [email_address]) email.content_subtype = 'html' email.send() return JsonResponse({'status': 'success'}, safe=False)
def confirm_data(page, request, id): if not request.user.is_authenticated(): messages.info(request, 'You need to be logged in to perform this action.') return HttpResponseRedirect('/dashboard/login/' + "?next={}".format(request.path)) try: impact_model = ImpactModel.objects.get(id=id) except ImpactModel.DoesNotExist: messages.warning(request, 'Unknown model') return HttpResponseRedirect('/impactmodels/') if not (impact_model.base_model in request.user.userprofile.owner.all() or request.user.is_superuser): messages.info(request, 'You need to be logged in to perform this action.') nexturl = reverse('wagtailadmin_login') + "?next={}".format( request.path) return HttpResponseRedirect(nexturl) if not impact_model.can_confirm_data(): messages.warning( request, 'Data confirmation for this model is not possible at the moment.') return HttpResponseRedirect('/impactmodels/') confirmation = impact_model.confirmation if request.method == 'GET': title = 'Confirm data for : %s' % impact_model subpage = {'title': title, 'url': ''} context = { 'page': page, 'subpage': subpage, 'user': request.user, 'simulation_round': impact_model.simulation_round, 'sector': impact_model.base_model.sector, 'impact_model_name': impact_model.base_model.name, 'custom_text': confirmation.email_text, 'impact_model_url': '/impactmodels/edit/%s/' % impact_model.pk, } template = 'climatemodels/confirm_data.html' return render(request, template, context) elif request.method == 'POST': # raise Exception(request.POST) form = DataConfirmationForm(request.POST) if not form.is_valid(): if 'license' in form.cleaned_data: messages.error( request, 'You need to confirm that your impact model is correct and complete!' ) else: messages.error(request, 'You need to select a valid license!') return HttpResponseRedirect(request.path) license = form.cleaned_data['license'] if license == 'other' and form.cleaned_data['other_license_name'] == '': messages.error( request, 'If you choose the "Other" license you need to fill out the name!' ) return HttpResponseRedirect(request.path) # build and send confirm email confirm_email = DataPublicationConfirmation.for_site(request.site) license = license == 'other' and form.cleaned_data[ 'other_license_name'] or license context = { 'model_contact_person': request.user.get_full_name(), 'simulation_round': impact_model.simulation_round, 'impact_model_name': confirmation.impact_model.base_model.name, 'custom_text': confirmation.email_text, 'license': license, } confirm_body = Template(confirm_email.body) confirm_body = confirm_body.render(Context(context)) # add newlines to the end of body to split attachment from text confirm_body += "\n\n" ccs = impact_model.base_model.impact_model_owner.exclude( pk=request.user.pk) pdf = render_impact_model_to_pdf(impact_model) subject = "%s for %s" % (confirm_email.subject, confirmation.impact_model.base_model.name) email = EmailMessage( subject=subject, body=confirm_body, reply_to=[request.user.email], from_email='ISIMIP Data Confirmation <%s>' % settings.DATA_CONFIRMATION_EMAIL, to=[settings.DATA_CONFIRMATION_EMAIL], cc=[cc.email for cc in ccs], ) filename = "DataConfirmation_%s_%s_%s.pdf" % ( impact_model.simulation_round.slug, impact_model.base_model.sector.slug, slugify(impact_model.base_model.name)) email.attach(filename, pdf, "application/pdf") email.send() # update confirmation state confirmation.is_confirmed = True confirmation.confirmed_by = request.user confirmation.confirmed_date = datetime.now() confirmation.confirmed_license = license confirmation.save() messages.success(request, 'The data confirmation email has been sent.') return HttpResponseRedirect('/dashboard/')
def post(self, request): allowed_types = ['jpg', 'jpeg', 'pdf', 'png', 'html', 'htm'] data = request.data # Get data from body email = data.get('email') msg = data.get('msg', None) full_name = data.get('fullName') phone_num = data.get('phoneNum') project_subject = data.get('subject') project_quoutation = data.get('quoutRange') project_type = data.get('projectType') level = data.get('level', None) file1 = data.get('file1') file2 = data.get('file2') file3 = data.get('file3') file4 = data.get('file4') file5 = data.get('file5') # Check file type. if ( file1.name.split('.')[1] not in allowed_types or file2.name.split('.')[1] not in allowed_types or file3.name.split('.')[1] not in allowed_types or file4.name.split('.')[1] not in allowed_types or file5.name.split('.')[1] not in allowed_types ): return Response({"detail": "file is not allowed."}, status=status.HTTP_406_NOT_ACCEPTABLE) # Check file size. if ( round(file1.size / (1024 * 1024), 3) > 10 or round(file2.size / (1024 * 1024), 3) > 10 or round(file3.size / (1024 * 1024), 3) > 10 or round(file4.size / (1024 * 1024), 3) > 10 or round(file5.size / (1024 * 1024), 3) > 10 ): return Response({"detail": "file is greater than 10 mb."}, status=status.HTTP_406_NOT_ACCEPTABLE) if (len(email) > 0 and len(full_name) > 0 and len(phone_num) > 0 and len(project_subject) > 0 and len(project_type) > 0 and len(project_quoutation) > 0 and len(level) > 0 and file1 and file2 and file3 and file4 and file5): try: body = get_template("email_with_files_template.html").render({ "email": email, "msg": msg, "phone_num": phone_num, "full_name": full_name, "project_quoutation": project_quoutation, "project_subject": project_subject, "project_type": project_type, "level": level, }) to = "*****@*****.**" msg = EmailMessage(f"{full_name} - رسالة حجز موعد من ", body, email, [to]) msg.attach(filename=file1.name, content=file1.read(), mimetype=file1.content_type) msg.attach(filename=file2.name, content=file2.read(), mimetype=file2.content_type) msg.attach(filename=file3.name, content=file3.read(), mimetype=file3.content_type) msg.attach(filename=file4.name, content=file4.read(), mimetype=file4.content_type) msg.attach(filename=file5.name, content=file5.read(), mimetype=file5.content_type) msg.content_subtype = "html" msg.send() return Response({"detail": "Your booking was sent"}, status=status.HTTP_200_OK) except BadHeaderError: return Response({"detail": "Invalid header found."}, status=status.HTTP_400_BAD_REQUEST) else: return Response({"detail": "Data is invalid"}, status=status.HTTP_400_BAD_REQUEST)
def get_product(request, path, out={}): slug = path.split('/')[-2] if len(path.split('/')) > 2: category_slug = path.split('/')[-3] if category_slug: product = get_object_or_404(Product, slug=slug, category__slug=category_slug) else: product = get_object_or_404(Product, slug=slug) tab = request.GET.get('tab', 'description') template_name = 'product.html' if tab == 'description': template_name = 'product.html' elif tab == 'docs': template_name = 'product_docs.html' elif tab == 'photo': galleries = product.category.galleries.filter(published=True).all() if product.category.parent_id: galleries = chain( galleries, product.category.parent_id.galleries.filter( published=True).all()) galleries = set(galleries) out.update({'galleries': galleries}) template_name = 'product_photo.html' elif tab == 'articles': template_name = 'product_articles.html' articles = set(product.category.articles.all()) | set( product.articles.all()) product.ind_articles = enumerate(articles) elif tab == 'review': template_name = 'product_review.html' out.update({'product': product}) out.update({'menu_active_item': 'catalog'}) if request.method == 'POST': callback_form = CallbackForm(request.POST, request.FILES) if callback_form.is_valid(): kwargs = dict( to=EMAILS_FOR_CALLBACK, from_email='*****@*****.**', subject=u'Заказ продукции', body= u'Поступил запрос на заказ продукции {} в количестве {} штук от {} (телефон для связи - {}, email - {}) с комментарием:\n\n"{}"' .format( callback_form.cleaned_data['product'], callback_form.cleaned_data['count'], callback_form.cleaned_data['name'], callback_form.cleaned_data['phone'], callback_form.cleaned_data['email'], callback_form.cleaned_data['comment'], ), ) message = EmailMessage(**kwargs) for attachment in request.FILES.getlist('file_field'): message.attach(attachment.name, attachment.read(), attachment.content_type) message.send() logger.info(u'Send callback with text: {}'.format(kwargs['body'])) callback_form = CallbackForm() out.update({'callback_form': callback_form}) out.update({'title': product.name}) return render(request, template_name, out)
def payment_process(request): # cart = Cart(request) order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) if request.method == 'POST': # retrieve nonce nonce = request.POST.get('payment_method_nonce', None) # create and submit transaction result = braintree.Transaction.sale({ 'amount': '{:.2f}'.format(order.get_total_cost()), 'payment_method_nonce': nonce, "order_id" : order_id, 'options': { 'submit_for_settlement': True, "paypal": { "custom_field" : "PayPal custom field", "description" : "Description for PayPal email receipt", }, } }) if result.is_success: # mark order as paid order.paid = True # store unique transaction id order.braintree_id = result.transaction.id # pass through total order amount order.amount = result.transaction.amount order.save() # create invoice e-mail subject = 'birdie lou - invoice no. {}'.format(order.id) message = 'Thank you for ordering from birdie lou! Please see attached for your invoice.\n\nIf you have any questions about your order please contact us at [email protected].' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail email.send() # clear the cart # cart.clear() return redirect('payment:done') else: return redirect('payment:canceled') else: # generate token client_token = braintree.ClientToken.generate() return render(request, 'payment/process.html', {'order': order, 'client_token': client_token})
def formulaire(request): logiciels = Logiciel.objects.all() batiments = Batiment.objects.all() result = "null" if request.method == "POST": try: res = Demande(nom=request.POST.get('nom'), prenom=request.POST.get('prenom'), email=request.POST.get('email'), phone=request.POST.get('phone'), batiment_id=request.POST.get('batiment'), bureau=request.POST.get('bureau'), logiciel_id=request.POST.get('logiciel'), version_id=request.POST.get('version'), os=request.POST.get('os'), host=request.POST.get('host')) res.save() buffer = BytesIO() p = canvas.Canvas(buffer) p.drawImage(ImageReader('geeps/static/img/geeps2.png'), 50, 740, 230, 100, mask='auto') p.drawCentredString(279, 710, "Demande de renouvellement de licence") p.drawCentredString(279, 650, res.nom + " " + res.prenom) p.drawCentredString(279, 600, res.email) p.drawCentredString(279, 550, res.phone) p.drawCentredString(279, 500, "Batiment : " + res.batiment.nom) p.drawCentredString(279, 450, "Logiciel : " + res.logiciel.nom) p.drawCentredString(279, 400, "Version : " + res.version.nom) p.drawCentredString(279, 350, "Système : " + res.os) p.drawCentredString(279, 300, "Host ID : " + res.host) p.drawCentredString( 279, 250, "Date : " + convertDatetimeToString(res.created_date)) p.save() pdf = buffer.getvalue() buffer.close() email = EmailMessage( "[GEEPS] Demande de renouvellement de licence " + res.logiciel.nom, convertDatetimeToString(res.created_date) + "\n\nDemande de renouvellement de licence de " + res.logiciel.nom + " de " + res.nom + " " + res.prenom + " pour le systeme " + res.os + ".", '*****@*****.**', ['*****@*****.**']) email.attach( res.logiciel.nom + '-' + res.version.nom + '-' + res.nom + '-' + res.prenom + '-' + convertDatetimeToString(res.created_date) + '.pdf', pdf, 'application/pdf') email.send(fail_silently=False) send_mail( "[GEEPS] License renewal request - Demande de renouvellement de licence" + res.logiciel.nom, convertDatetimeToString(res.created_date) + "\n\nYour " + res.logiciel.nom + " renewal request for " + res.os + " operating system has been taken into account." + "\n\nVotre demande de renouvellement de " + res.logiciel.nom + " pour le système " + res.os + " a bien ete prise en compte." + "\n\nLe CRI du GeePs", '*****@*****.**', [res.email], fail_silently=False, ) result = res.pk except Exception as e: result = "error" print(e) return render(request, 'geeps/formulaire.html', { 'logiciels': logiciels, 'batiments': batiments, 'result': result })
def facturar(contrato_id, descripcion=None, sub_total=None): logger.info('Task facturar iniciada') # Configurar redondeo getcontext().rounding = ROUND_HALF_UP # Calcular fecha actual fecha = timezone.localtime() # Consultar contrato contrato = models.Contrato.objects.get(id=contrato_id) # Si no se envia descripcion factura el mes correspondiente a la fecha actual if descripcion is None: sub_total = contrato.precio_mensual descripcion = u'Renta correspondiente al mes {0} del {1} {2}'.format( nombre_mes(fecha.month), fecha.year, contrato.nombre_predio) # Calcular impuestos iva_tra = (sub_total * Decimal('0.160000')).quantize(TWO_PLACES) iva_ret = Decimal('0.00') isr_ret = Decimal('0.00') if contrato.retener_impuestos: iva_ret = (sub_total * Decimal('0.106666')).quantize(TWO_PLACES) isr_ret = (sub_total * Decimal('0.100000')).quantize(TWO_PLACES) total_tra = iva_tra total_ret = (iva_ret + isr_ret).quantize(TWO_PLACES) total = ((sub_total + total_tra) - total_ret).quantize(TWO_PLACES) # Cargar certificado CSD cer = X509.load_cert(settings.CSD_CER, X509.FORMAT_DER) # Cargar llave privada CSD key = RSA.load_key(settings.CSD_KEY) # Obtener numero de serie serial_number = '{:x}'.format(int(cer.get_serial_number())).decode('hex') # Obtener folio folio_conf = models.Configuracion.objects.get(nombre='U_FOLIO') folio_conf.valor = folio_conf.valor + 1 folio_conf.save() nsmap = { 'cfdi': 'http://www.sat.gob.mx/cfd/3', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', } attrib = { '{http://www.w3.org/2001/XMLSchema-instance}schemaLocation': 'http://www.sat.gob.mx/cfd/3' } # Nodo cfdi:Comprobante cfdi = etree.Element('{http://www.sat.gob.mx/cfd/3}Comprobante', nsmap=nsmap, attrib=attrib) cfdi.set('Version', '3.3') cfdi.set('Serie', settings.SERIE) cfdi.set('Folio', str(folio_conf.valor)) cfdi.set('Fecha', fecha.isoformat()[:19]) cfdi.set('FormaPago', contrato.forma_pago) cfdi.set('NoCertificado', serial_number) cfdi.set('Certificado', base64.b64encode(cer.as_der())) cfdi.set('SubTotal', '{}'.format(sub_total)) cfdi.set('Moneda', settings.MONEDA) cfdi.set('Total', '{}'.format(total)) cfdi.set('TipoDeComprobante', 'I') cfdi.set('MetodoPago', contrato.metodo_pago) cfdi.set('LugarExpedicion', settings.CODIGO_POSTAL) # Nodo cfdi:Emisor emisor = etree.SubElement(cfdi, '{http://www.sat.gob.mx/cfd/3}Emisor') emisor.set('Rfc', settings.RFC) emisor.set('Nombre', settings.RAZON_SOCIAL) emisor.set('RegimenFiscal', settings.REGIMEN_FISCAL) # Nodo cfdi:Receptor receptor = etree.SubElement(cfdi, '{http://www.sat.gob.mx/cfd/3}Receptor') receptor.set('Rfc', contrato.rfc_cliente) receptor.set('Nombre', contrato.nombre_cliente) receptor.set('UsoCFDI', contrato.uso_cfdi) # Nodo cfdi:Conceptos conceptos = etree.SubElement(cfdi, '{http://www.sat.gob.mx/cfd/3}Conceptos') # Nodo cfdi:Concepto concepto = etree.SubElement(conceptos, '{http://www.sat.gob.mx/cfd/3}Concepto') concepto.set('ClaveProdServ', settings.CLAVE_PROD_SERV) concepto.set('Cantidad', '1') concepto.set('ClaveUnidad', settings.CLAVE_UNIDAD) concepto.set('Descripcion', descripcion) concepto.set('ValorUnitario', '{}'.format(sub_total)) concepto.set('Importe', '{}'.format(sub_total)) # Nodo cfdi:Impuestos impuestos = etree.SubElement(concepto, '{http://www.sat.gob.mx/cfd/3}Impuestos') # Nodo cfdi:Traslados traslados = etree.SubElement(impuestos, '{http://www.sat.gob.mx/cfd/3}Traslados') # Nodo cfdi:Traslado traslado = etree.SubElement(traslados, '{http://www.sat.gob.mx/cfd/3}Traslado') traslado.set('Base', '{}'.format(sub_total)) traslado.set('Impuesto', '002') traslado.set('TipoFactor', 'Tasa') traslado.set('TasaOCuota', '0.160000') traslado.set('Importe', '{}'.format(iva_tra)) if contrato.retener_impuestos: # Nodo cfdi:Retenciones retenciones = etree.SubElement( impuestos, '{http://www.sat.gob.mx/cfd/3}Retenciones') # Nodo cfdi:Retencion IVA traslado = etree.SubElement(retenciones, '{http://www.sat.gob.mx/cfd/3}Retencion') traslado.set('Base', '{}'.format(sub_total)) traslado.set('Impuesto', '002') traslado.set('TipoFactor', 'Tasa') traslado.set('TasaOCuota', '0.106666') traslado.set('Importe', '{}'.format(iva_ret)) # Nodo cfdi:Retencion ISR retencion = etree.SubElement(retenciones, '{http://www.sat.gob.mx/cfd/3}Retencion') retencion.set('Base', '{}'.format(sub_total)) retencion.set('Impuesto', '001') retencion.set('TipoFactor', 'Tasa') retencion.set('TasaOCuota', '0.100000') retencion.set('Importe', '{}'.format(isr_ret)) if contrato.cuenta_predial is not None: cuenta_predial = etree.SubElement( concepto, '{http://www.sat.gob.mx/cfd/3}CuentaPredial') cuenta_predial.set('Numero', str(contrato.cuenta_predial)) # Nodo cfdi:Impuestos impuestos = etree.SubElement(cfdi, '{http://www.sat.gob.mx/cfd/3}Impuestos') impuestos.set('TotalImpuestosTrasladados', '{}'.format(total_tra)) if contrato.retener_impuestos: impuestos.set('TotalImpuestosRetenidos', '{}'.format(total_ret)) # Nodo cfdi:Retenciones retenciones = etree.SubElement( impuestos, '{http://www.sat.gob.mx/cfd/3}Retenciones') # Nodo cfdi:Retencion IVA retencion_iva = etree.SubElement( retenciones, '{http://www.sat.gob.mx/cfd/3}Retencion') retencion_iva.set('Impuesto', '002') retencion_iva.set('Importe', '{}'.format(iva_ret)) # Nodo cfdi:Retencion ISR retencion_isr = etree.SubElement( retenciones, '{http://www.sat.gob.mx/cfd/3}Retencion') retencion_isr.set('Impuesto', '001') retencion_isr.set('Importe', '{}'.format(isr_ret)) # Nodo cfdi:Traslados traslados = etree.SubElement(impuestos, '{http://www.sat.gob.mx/cfd/3}Traslados') # Nodo cfdi:Traslado traslado_iva = etree.SubElement(traslados, '{http://www.sat.gob.mx/cfd/3}Traslado') traslado_iva.set('Impuesto', '002') traslado_iva.set('TipoFactor', 'Tasa') traslado_iva.set('TasaOCuota', '0.160000') traslado_iva.set('Importe', '{}'.format(iva_tra)) # Cargar xslt para generar cadena original xslt = etree.XSLT(etree.parse(settings.PATH_XLST)) # Generar cadena original cadena_original = xslt(cfdi) # sacar hash a cadena original digest = hashlib.new('sha256', str(cadena_original)).digest() # Firmar digest de cadena original sign = key.sign(digest, "sha256") # Pasar sello de Bytes a b64 sello = base64.b64encode(sign) # Agrefar sello a documento xml cfdi.set('Sello', sello) # Generar archivo xml xml = etree.tostring(cfdi, pretty_print=True) # Format token token = 'bearer %s' % str(settings.PAC_TOKEN) # Crear mensaje multiparte para adjuntar archivo m = MultipartEncoder(fields={ 'xml': ('xml', xml, 'text/xml', { 'Content-Transfer-Encoding': 'binary' }) }) # Crear headers headers = {'Content-Type': m.content_type, 'Authorization': token} # Realizar request tipo post al pac req = requests.post(settings.PAC_URL, headers=headers, data=m.to_string()) # Verificar request if req.status_code != 200: raise Exception(u'id_contrato: {} Error {}'.format( contrato.id, req.json())) # Extraer xml xml_timbrado = req.json()['data']['cfdi'].encode('utf-8') # Parsear XML timpado cfdi_timbrado = etree.fromstring(xml_timbrado) # Buscar UUID uuid = cfdi_timbrado.find('{http://www.sat.gob.mx/cfd/3}Complemento').find( '{http://www.sat.gob.mx/TimbreFiscalDigital}TimbreFiscalDigital' ).attrib.get('UUID') # Generar PDF xml_dict = xmltodict.parse(xml_timbrado)['cfdi:Comprobante'] cbb_url = 'https://verificacfdi.facturaelectronica.sat.gob.mx/' \ 'default.aspx?id={0}re={1}&rr={2}&tt={3}&fe={4}'.format( uuid, settings.RFC, contrato.rfc_cliente, total, sello[(len(sello) - 8):], ) # Generar codigo qr de cbb qrdata = qrcode.make(cbb_url) raw = StringIO() qrdata.save(raw) cbb = b64encode(raw.getvalue()) # Renderizar HTML html = get_template('webapp/factura-pdf.html').render({ 'xml': xml_dict, 'cadena_original': cadena_original, 'cbb': cbb, }) # Generar PDF pdf = pdfkit.from_string(html, False, options={ 'page-size': 'Letter', 'encoding': "UTF-8", 'quiet': '', }) # Guardar factura en base de datos factura = models.Factura() factura.fecha = fecha factura.contrato = contrato factura.uuid = uuid factura.serie = settings.SERIE factura.folio = folio_conf.valor factura.nombre_cliente = contrato.nombre_cliente factura.rfc_cliente = contrato.rfc_cliente factura.correo_cliente = contrato.correo_cliente factura.concepto = descripcion factura.sub_total = sub_total factura.iva_trasladado = iva_tra factura.iva_retenido = iva_ret factura.isr_retenido = isr_ret factura.total = total factura.xml = ContentFile(xml_timbrado, name='{0}.xml'.format(uuid)) factura.pdf = ContentFile(pdf, name='{0}.pdf'.format(uuid)) factura.save() # sumar saldo en contrato contrato.saldo_contrato = contrato.saldo_contrato + total contrato.save() # Enviar correo html_email = get_template('webapp/factura-correo.txt').render( {'factura': factura}) msg = EmailMessage('{} Nueva Factura {} {} Generada'.format( settings.RAZON_SOCIAL, factura.serie, factura.folio), html_email, settings.DEFAULT_FROM_EMAIL, to=[factura.correo_cliente], reply_to=[settings.TENANT_EMAIL], cc=[settings.TENANT_EMAIL]) msg.attach('{}_{}.xml'.format(factura.serie, factura.folio), factura.xml.read(), 'application/xml') msg.attach('{}_{}.pdf'.format(factura.serie, factura.folio), factura.pdf.read(), 'application/pdf') msg.send() logger.info('Task facturar terminada') return factura.id
def render(self, context): page = context[self.page] try: contact_form = page.contactform_set.get() request = context['request'] except: # ContactForm.DoesNotExist or "django.core.context_processors.request" is not in default context processors return "" FormClass = contact_form.get_form_class() my_context = Context( { 'contact_form': contact_form, 'form_instance': FormClass(), # 'current_page': page, # 'page': page, }, autoescape=context.autoescape) if request.method == 'POST' and "contactform_id" in request.POST \ and request.POST['contactform_id'] == str(contact_form.id): # process the submitted form form = FormClass(request.POST, request.FILES) if form.is_valid(): site = Site.objects.get_current() try: from siteinfo.models import SiteSettings contact = SiteSettings.objects.get_current() except: contact = None subject = _(u"[%s] Contact form sent") % (site.domain) # render fields rows = '' files = [] for field in contact_form.field_set.all(): field_label = slugify(field.get_label()) value = form.cleaned_data[field_label] if isinstance(value, bool): value = yesno( value, u"%s,%s" % (_('yes'), _('no')), ) if field.field_type == 'FileField': if field_label in request.FILES: this_file = request.FILES[field_label] if this_file.size > 10240: # check if file is bigger than 10 MB (which is not good) files.append(this_file) rows += u"%s: %s\n" % (form.fields[field_label].label, value) message_context = Context( { 'site': site, 'form': form, 'contact_form': contact_form, 'rows': rows, }, autoescape=False) text_template = loader.get_template('dbform/form_email.txt') text_content = text_template.render(message_context) recipient_list = [ recipient['email'] for recipient in contact_form.recipients.values('email') ] bcc = [] if contact_form.cc_managers: bcc += [manager[1] for manager in settings.MANAGERS] if contact_form.cc_site_contact and contact: bcc += [contact.email] message = EmailMessage(subject=subject, body=text_content, from_email=settings.DEFAULT_FROM_EMAIL, to=recipient_list, bcc=bcc) for file in files: message.attach(file.name, file.read(2621440), file.content_type) message.send() my_context.update({ 'form_instance': form, 'success': contact_form.success_message.strip() or _("Your request has been submitted. We will process it as soon as possible." ), }) else: my_context.update({ 'form_instance': form, 'dbform': contact_form, }) return loader.render_to_string("dbform/form.html", my_context)
def facturar_rep(factura_id): logger.info('Task facturar iniciada') # Configurar redondeo getcontext().rounding = ROUND_HALF_UP # Calcular fecha actual fecha = timezone.localtime() # Consultar contrato factura = models.Factura.objects.get(id=factura_id) # Calcular impuestos # Cargar certificado CSD cer = X509.load_cert(settings.CSD_CER, X509.FORMAT_DER) # Cargar llave privada CSD key = RSA.load_key(settings.CSD_KEY) # Obtener numero de serie serial_number = '{:x}'.format(int(cer.get_serial_number())).decode('hex') # Obtener folio folio_conf = models.Configuracion.objects.get(nombre='U_FOLIO') folio_conf.valor = folio_conf.valor + 1 folio_conf.save() nsmap = { 'cfdi': 'http://www.sat.gob.mx/cfd/3', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'pago10': 'http://www.sat.gob.mx/Pagos', } attrib = { '{http://www.w3.org/2001/XMLSchema-instance}schemaLocation': 'http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd http://www.sat.gob.mx/Pagos http://www.sat.gob.mx/sitio_internet/cfd/Pagos/Pagos10.xsd' } # Nodo cfdi:Comprobante cfdi = etree.Element('{http://www.sat.gob.mx/cfd/3}Comprobante', nsmap=nsmap, attrib=attrib) cfdi.set('Version', '3.3') cfdi.set('Serie', settings.SERIE_REP) cfdi.set('Folio', str(folio_conf.valor)) cfdi.set('Fecha', fecha.isoformat()[:19]) cfdi.set('NoCertificado', serial_number) cfdi.set('Certificado', base64.b64encode(cer.as_der())) cfdi.set('SubTotal', '0') cfdi.set('Moneda', 'XXX') cfdi.set('Total', '0') cfdi.set('TipoDeComprobante', 'P') cfdi.set('LugarExpedicion', settings.CODIGO_POSTAL) # Nodo cfdi:Emisor emisor = etree.SubElement(cfdi, '{http://www.sat.gob.mx/cfd/3}Emisor') emisor.set('Rfc', settings.RFC) emisor.set('Nombre', settings.RAZON_SOCIAL) emisor.set('RegimenFiscal', settings.REGIMEN_FISCAL) # Nodo cfdi:Receptor receptor = etree.SubElement(cfdi, '{http://www.sat.gob.mx/cfd/3}Receptor') receptor.set('Rfc', factura.rfc_cliente) receptor.set('Nombre', factura.nombre_cliente) receptor.set('UsoCFDI', 'P01') # Nodo cfdi:Conceptos conceptos = etree.SubElement(cfdi, '{http://www.sat.gob.mx/cfd/3}Conceptos') # Nodo cfdi:Concepto concepto = etree.SubElement(conceptos, '{http://www.sat.gob.mx/cfd/3}Concepto') concepto.set('ClaveProdServ', '84111506') concepto.set('Cantidad', '1') concepto.set('ClaveUnidad', 'ACT') concepto.set('Descripcion', 'Pago') concepto.set('ValorUnitario', '0.000000') concepto.set('Importe', '0.00') # Nodo cfdi:Conceptos complemento = etree.SubElement(cfdi, '{http://www.sat.gob.mx/cfd/3}Complemento') # Nodo pago10:Pagos pagos = etree.SubElement(complemento, '{http://www.sat.gob.mx/Pagos}Pagos') pagos.set('Version', '1.0') # Nodo pago10:Pagos pago = etree.SubElement(pagos, '{http://www.sat.gob.mx/Pagos}Pago') pago.set('FechaPago', '{}T01:00:00'.format(factura.fecha_pago.isoformat())) pago.set('FormaDePagoP', factura.forma_pago_rep) pago.set('MonedaP', settings.MONEDA) pago.set('Monto', '{}'.format(factura.total)) pago.set('NumOperacion', factura.num_operacion) # Nonda pago10:DoctoRelacionado docto_relacionado = etree.SubElement( pago, '{http://www.sat.gob.mx/Pagos}DoctoRelacionado') docto_relacionado.set('IdDocumento', '{}'.format(factura.uuid)) docto_relacionado.set('Serie', factura.serie) docto_relacionado.set('Folio', '{}'.format(factura.folio)) docto_relacionado.set('MonedaDR', settings.MONEDA) docto_relacionado.set('MetodoDePagoDR', factura.contrato.metodo_pago) docto_relacionado.set('NumParcialidad', '1') docto_relacionado.set('ImpSaldoAnt', '{}'.format(factura.total)) docto_relacionado.set('ImpPagado', '{}'.format(factura.total)) docto_relacionado.set('ImpSaldoInsoluto', '0') # Cargar xslt para generar cadena original xslt = etree.XSLT(etree.parse(settings.PATH_XLST)) # Generar cadena original cadena_original = xslt(cfdi) # sacar hash a cadena original digest = hashlib.new('sha256', str(cadena_original)).digest() # Firmar digest de cadena original sign = key.sign(digest, "sha256") # Pasar sello de Bytes a b64 sello = base64.b64encode(sign) # Agrefar sello a documento xml cfdi.set('Sello', sello) # Generar archivo xml xml = etree.tostring(cfdi, pretty_print=True) # Format token token = 'bearer %s' % str(settings.PAC_TOKEN) # Crear mensaje multiparte para adjuntar archivo m = MultipartEncoder(fields={ 'xml': ('xml', xml, 'text/xml', { 'Content-Transfer-Encoding': 'binary' }) }) # Crear headers headers = {'Content-Type': m.content_type, 'Authorization': token} # Realizar request tipo post al pac req = requests.post(settings.PAC_URL, headers=headers, data=m.to_string()) # Verificar request if req.status_code != 200: raise Exception(u'id_factura: {} Error {}'.format( factura.id, req.json())) # Extraer xml xml_timbrado = req.json()['data']['cfdi'].encode('utf-8') # Parsear XML timpado cfdi_timbrado = etree.fromstring(xml_timbrado) # Buscar UUID uuid = cfdi_timbrado.find('{http://www.sat.gob.mx/cfd/3}Complemento').find( '{http://www.sat.gob.mx/TimbreFiscalDigital}TimbreFiscalDigital' ).attrib.get('UUID') # Generar PDF xml_dict = xmltodict.parse(xml_timbrado)['cfdi:Comprobante'] cbb_url = 'https://verificacfdi.facturaelectronica.sat.gob.mx/' \ 'default.aspx?id={0}re={1}&rr={2}&tt={3}&fe={4}'.format( uuid, settings.RFC, factura.rfc_cliente, factura.total, sello[(len(sello) - 8):], ) # Generar codigo qr de cbb qrdata = qrcode.make(cbb_url) raw = StringIO() qrdata.save(raw) cbb = b64encode(raw.getvalue()) # Renderizar HTML html = get_template('webapp/factura-pago-pdf.html').render({ 'xml': xml_dict, 'cadena_original': cadena_original, 'cbb': cbb, }) # Generar PDF pdf = pdfkit.from_string(html, False, options={ 'page-size': 'Letter', 'encoding': "UTF-8", 'quiet': '', }) # Guardar factura en base de datos factura.uuid_rep = uuid factura.xml_rep = ContentFile(xml_timbrado, name='{0}.xml'.format(uuid)) factura.pdf_rep = ContentFile(pdf, name='{0}.pdf'.format(uuid)) factura.save() # Enviar correo html_email = get_template('webapp/factura-correo.txt').render( {'factura': factura}) msg = EmailMessage('{} Nuevo REP {} {} Generada'.format( settings.RAZON_SOCIAL, factura.serie, factura.folio), html_email, settings.DEFAULT_FROM_EMAIL, to=[factura.correo_cliente], reply_to=[settings.TENANT_EMAIL], cc=[settings.TENANT_EMAIL]) msg.attach('{}_{}.xml'.format(factura.serie, factura.folio), factura.xml.read(), 'application/xml') msg.attach('{}_{}.pdf'.format(factura.serie, factura.folio), factura.pdf.read(), 'application/pdf') msg.attach('{}_{}.xml'.format(factura.serie, factura.folio), factura.xml_rep.read(), 'application/xml') msg.attach('{}_{}.pdf'.format(factura.serie, factura.folio), factura.pdf_rep.read(), 'application/pdf') msg.send() logger.info('Task facturar terminada') return factura.id
def dispatch_notification_to_user(self, user_id, msg, channel_context=None): """ Send a notification to a user, which - in a TriggerEmailChannel Notification """ # call into one of the registered resolvers to get the email for this # user scope_results = resolve_user_scope( 'user_email_resolver', { 'user_id': user_id, 'fields': { 'user_id': True, 'email': True, 'first_name': True, 'last_name': True, } }) msg = self._get_linked_resolved_msg(msg) msg.created = datetime.datetime.now(pytz.UTC) user_msg = UserNotification(user_id=user_id, msg=msg) config = const.NOTIFICATION_DIGEST_GROUP_CONFIG for result in scope_results: # # Do the rendering and the sending of the email # if isinstance(result, dict): email = result['email'] else: email = result renderer = get_renderer_for_type(user_msg.msg.msg_type) notification_html = '' if renderer and renderer.can_render_format( const.RENDER_FORMAT_HTML): notification_html = renderer.render( # pylint: disable=unused-variable user_msg.msg, const.RENDER_FORMAT_HTML, None) # create the image dictionary to store the # img_path, unique id and title for the image. branded_logo = dict(title='Logo', path=const.NOTIFICATION_BRANDED_DEFAULT_LOGO, cid=str(uuid.uuid4())) group_name = get_group_name_for_msg_type( user_msg.msg.msg_type.name) resolve_links = user_msg.msg.resolve_links click_link = user_msg.msg.payload['_click_link'] if resolve_links and not click_link.startswith('http'): click_link = const.NOTIFICATION_EMAIL_CLICK_LINK_URL_FORMAT.format( url_path=click_link, encoded_url_path=urllib.quote(click_link), user_msg_id=user_msg.id, msg_id=user_msg.msg.id, hostname=const.NOTIFICATION_APP_HOSTNAME) context = { 'branded_logo': branded_logo['cid'], 'notification_html': notification_html, 'user_first_name': result['first_name'] if isinstance(result, dict) else None, 'user_last_name': result['last_name'] if isinstance(result, dict) else None, 'group_name': group_name, 'group_title': config['groups'][group_name]['display_name'], 'click_link': click_link } # render the notifications html template email_body = with_inline_css( render_to_string( "django/triggered_notification_email/triggered_email.html", context)) html_part = MIMEMultipart(_subtype='related') html_part.attach(MIMEText(email_body, _subtype='html')) logo_image = attach_image(branded_logo, 'Header Logo') if logo_image: html_part.attach(logo_image) log.info( 'Sending Notification email to {email}'.format(email=email)) msg = EmailMessage(const.NOTIFICATION_TRIGGERED_EMAIL_SUBJECT, '', const.NOTIFICATION_EMAIL_FROM_ADDRESS, [email]) msg.attach(html_part) msg.send() return user_msg