def handle(self, *args, **kwargs): try: currencies_out = requests.get( str.format( 'https://openexchangerates.org/api/latest.json?app_id={}', OPENEXCHANGE_KEY)) if currencies_out.status_code == 200: currencies = currencies_out.json() inr_rate = currencies['rates']['INR'] if ConversionRates.objects.filter(id=1).count() == 0: conversionRate = ConversionRates() conversionRate.rate = inr_rate conversionRate.created_at = datetime.datetime.now() conversionRate.save() else: conversion_Rate_object = ConversionRates.objects.get(id=1) conversion_Rate_object.rate = inr_rate conversion_Rate_object.created_at = datetime.datetime.now() conversion_Rate_object.save() print("Got INR Conversion Rate of ", inr_rate, "at ", datetime.datetime.now()) except Exception as e: from cloudapp.generics.functions import get_traceback exception = get_traceback(e) from common.mails.BaseMails import BaseMails from cloudapp.generics.constant import AppContants BaseMails.send_mail( subject='REDINGTON: Throws error get inr value value', recipients=['*****@*****.**'], template_name='product_error.html', template_data={'details': exception})
def notify_to_respects(self): subject = 'Service Request Rejected' BaseMails.send_mail( subject=subject, recipients=[ self.details['isv_details']['isv']['contacts'][0]['email'] ], template_name=choose_template(self.action)['business_html'], template_data=self.template_data) return True
def send_task_status_email(subject='Celery Task Status', title='Celery Task Status ', message='No Message Received'): """ Sends a email to Technical Team regarding celery task status""" BaseMails.send_mail(subject=subject, recipients=settings.TECH_TEAM, template_name='plain.html', template_data={ 'Title': title, 'message': message, 'domain_name': AppContants.DOMAIN_NAME })
def send_mail_to_business_team(self, to, data): """ Function to send mail to the business team :param data: :return: """ from common.mails.BaseMails import BaseMails BaseMails.send_mail(subject=data['subject'], recipients=to, template_name='plain.html', template_data={'message': data['message']}) return True
def notify_to_partner(self): partner_user_mail= self.details['user'].email email=list() email.append(partner_user_mail) if len(email)>0: '''sending email to partner starts here''' data={'request_number':self.details['pending_request'].reference_number, 'vendor_name':self.details['vendor'].vendor_name, 'discount':self.details['discount']} BaseMails.send_mail(subject=self.details['subject'], recipients=email, template_name=choose_template(self.action)['partner'], template_data=data) return True
def send_mail_notification(self, data, email, partner_email): """ Function to sent Email for relationship request :param data: :param email: :param partner_email: :return: """ from common.mails.BaseMails import BaseMails BaseMails.send_mail(subject='REDINGTON: Relationship Request', recipients=[email, partner_email], template_name='ms_relationship_request.html', template_data={'ms_link': data}) return True
def notify_to_redington(self): nf_groups = NotificationGroups.objects.filter( actions__action=self.action).exclude(recipients='') non_users_emails = list( nf_groups.values_list('non_user_recipients__email', flat=True)) sets = list(nf_groups.values_list('recipients', flat=True)) available_user_ids_in_groups = [] if len(sets) > 0: available_user_ids_in_groups = [ user_id for set_string in sets for user_id in set_string.split(',') ] available_user_ids_in_groups = list( set(available_user_ids_in_groups)) available_user_ids_in_groups = list( map(lambda x: str(x), available_user_ids_in_groups)) """ Send Notifications """ if len(available_user_ids_in_groups) > 0: nf_recipients = ','.join(available_user_ids_in_groups) NfActions.publish( params={ 'user': RedUser.objects.filter(is_superuser=True).first(), 'nf_type': "message", 'recipients': nf_recipients, 'message': "Reject ISV Service Request: %s" % (self.details['rejection_reason']), 'status': "unread", 'details_obj': self.details['isv_marketplace_service_instance'] }) users_emails = RedUser.objects.filter( id__in=available_user_ids_in_groups).values_list('email', flat=True) users_emails = list(users_emails) recipients = users_emails + non_users_emails """ Send Emails """ subject = 'Service Request Rejected: %s ' % ( self.template_data['isv_detail']['service_name']) if len(recipients) > 0: BaseMails.send_mail(subject=subject, recipients=recipients, template_name=choose_template( self.action)['business_html'], template_data=self.template_data)
def post(self, request, *args, **kwargs): data = request.data """ Checking is user exists for the provided username """ if not RedUser.objects.filter(username=data['username']).exists(): raise RedValidationErr("Username doesn't exists.") user = RedUser.objects.get(username=data['username']) """ Verifying users email """ if user.email != data['email']: email = user.email last = len(user.email) - 1 at_sign_position = email.index('@') dot_position = email.index('.') email_hint = '%s%s%s%s%s' % ( email[0:2], '*' * len(email[2:at_sign_position]), email[at_sign_position:(at_sign_position + 2)], '*' * (dot_position - (at_sign_position + 2)), email[dot_position:(last + 1)]) raise RedValidationErr( "Email couldn't match with username. Hint: %s" % email_hint) """ Generating token for password reset link """ jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) """ Setting expiration time """ payload['exp'] = datetime.datetime.now() + datetime.timedelta(days=1) token = jwt_encode_handler(payload) """ Storing token for future reference """ session = PasswordResetTokens.objects.create(user=user, token=token) session.save() BaseMails.send_mail(subject='REDINGTON: Password reset link', recipients=[user.email], template_name='password_resetting.html', template_data={ 'user': user.__dict__, 'reset_link': '%s?tk=%s' % (data['base_path'], token) }) return Response({ 'msg': "Reset link sent successfully", 'email': user.email })
def post(self, request, *args, **kwargs): user = request.user data = request.data """ Updating password """ user.set_password(data['password']) user.save() """ Removing token from password reset session after changing password """ session = PasswordResetTokens.objects.filter(user=user) session.delete() BaseMails.send_mail(subject='REDINGTON: Password changed', recipients=[user.email], template_name='password_changed.html', template_data={'user': user.__dict__}) serializer = UsersSerializer(user, context={'request': request}) return Response(serializer.data)
def notify_to_redington(self): """ Sending emails & notifications to the respective persons in REDINGTON """ nf_groups = NotificationGroups.objects.filter(actions__action=self.action) non_users_emails = list(nf_groups.values_list('non_user_recipients__email', flat=True)) sets = list(nf_groups.values_list('recipients', flat=True)) available_user_ids_in_groups = [] partner_jbacode = self.details['partner'].jba_code partner_jbacode=partner_jbacode.strip() if len(sets) > 0: user_ids = list(set(UserProfileVendorCategory.objects.filter(Q(location__icontains=partner_jbacode[0:2]) | Q(location='CO')).values_list('user_profile__user__id', flat=True))) available_user_ids_in_groups = [user_id for set_string in sets for user_id in set_string.split(',')] available_user_ids_in_groups = list(set(available_user_ids_in_groups)) available_user_ids_in_groups = list(filter(lambda x: re.match(r'[0-9]', x) and int(x) in user_ids, available_user_ids_in_groups)) available_user_ids_in_groups = RedUser.objects\ .filter(id__in=available_user_ids_in_groups, profile__vendor_category=self.details['vendor']).values_list('id', flat=True) available_user_ids_in_groups = list(map(lambda x: str(x), available_user_ids_in_groups)) """ Send Notifications """ if len(available_user_ids_in_groups) > 0: NfActions.publish(params={ 'user': self.details['user'], 'nf_type': "message", 'recipients': ','.join(available_user_ids_in_groups), 'message': "New Account request", 'status': "unread", 'details_obj': self.details['pending_request'] }) users_emails = RedUser.objects.filter(id__in=available_user_ids_in_groups).values_list('email', flat=True) users_emails = list(users_emails) """ Send Emails """ if len(users_emails) > 0: data = {'customer_name': self.details['customer'].company_name, 'partner_name': self.details['partner'].company_name, 'message': self.details['message'], 'domain_name': settings.DOMAIN_NAME} BaseMails.send_mail(subject=self.details['subject'], recipients=users_emails + non_users_emails, template_name=choose_template(self.action)['business'], template_data=data) return True
def change_password(self, request): user = self.request.user old_password = request.data['old_password'] from django.contrib.auth import authenticate credentials = {'username': user.username, 'password': old_password} user = authenticate(**credentials) if user: user.set_password(request.data['password']) user.save() BaseMails.send_mail(subject='REDINGTON: Password changed', recipients=[user.email], template_name='password_changed.html', template_data={'user': user.__dict__}) return Response({'suc_msg': "Your Password changed"}) else: return Response( {'msg': "Your old password was entered incorrectly"})
def handle(self, *args, **options): # read the all from csv file from django.db import connection cursor = connection.cursor() query = 'SELECT o.order_number, s.subscription, s.effective_start_date, s.commitment_end_date, c.company_name, p.company_name AS "Partner name", p.jba_code, o.billing_type, pr.product_name, pr.product_jbacode, s.quantity, oi.price_per_unit, s.quantity * oi.price_per_unit as "cost" FROM orders_subscriptions s LEFT JOIN orders_orders o ON s.order_id=o.id LEFT JOIN customers_customers c ON s.customer_id=c.id LEFT JOIN partner_partner p ON c.partner_id=p.id LEFT JOIN products_products pr ON s.product_id=pr.prod_id LEFT JOIN orders_orderitems oi ON s.order_id=oi.order_id and s.product_id=oi.product_id WHERE DAY(s.effective_start_date) < 23 AND YEAR(s.effective_start_date) < 2017 AND MONTH(s.effective_start_date) in (7,8) AND s.status="active" AND s.renewed=0 and s.billing_type!="usage";' cursor.execute(query) records = cursor.fetchall() if len(records) != 0: csv_file = StringIO() writer = csv.writer(csv_file) header = [ 'Order Number', 'Subscription ID', 'Subscription start date', 'Subscription end date', 'Customer name', 'Partner name', 'Partnercode', 'Billing Type', 'Product', 'JBA code', 'Quantity', 'Unit price', 'Total' ] writer.writerow(header) for list_record in records: list_record = list(list_record) writer.writerow(list_record) current_date = date.today() attachments_data = [{ 'filename': 'all_ms_order(' + current_date.isoformat() + ').csv', 'content': csv_file.getvalue().encode('utf-8'), 'mimetype': 'text/csv' }] data = dict() data['subject'] = 'Microsoft Order report' data[ 'data'] = "Please find the attachment of microsoft renewed report." BaseMails.send_mail(subject='Microsoft renewed report', recipients=self.recipients, template_name='common_template.html', template_data=data, attachements=None, attachments_full_path=None, data_attachments=attachments_data) self.stdout.write(self.style.SUCCESS('Report sent'))
def notify_to_partner(self): from partner.models import PartnerUserDetails partneruserdetails = PartnerUserDetails.objects.filter( partner=self.details['partner']) if len(partneruserdetails) != 0: parteruser_id = list( partneruserdetails.values_list('user_id', flat=True)) NfActions.publish( params={ 'user': self.details['user'], 'nf_type': "message", 'recipients': str(parteruser_id[0]), 'message': "New Account request(%s) rejected" % (self.details['pending_request'].cloud_account. details['reference_number']), 'status': 'unread', 'details_obj': self.details['pending_request'] }) data = { 'request_number': self.details['pending_request'].reference_number, 'discount': self.details['discount'], 'partner_name': self.details['partner'].company_name, 'reject_msg': self.details['reject_msg'], 'customer_name': self.details['customer'].company_name, } red_user_object = RedUser.objects.filter( id=parteruser_id[0]).first() BaseMails.send_mail(subject=self.details['subject'], recipients=[red_user_object.email], template_name=choose_template( self.action)['partner'], template_data=data) return True
def __init__(self, user_detail): self.send_creation_mail(user_detail) BaseMails.__init__(self, user_detail['user_detail'], 'UserCreation')
def getUtilization(self): azure_subscriptions = Subscriptions.objects.filter( customer__in=Partner.objects.get( pk=self.partner).customers_set.all(), name='Microsoft Azure', status='active') log_file = open(os.path.join(self.log_dir, self.log_file), 'a') log_file.write('<%s>\n' % ('-' * 120, )) log_file.write('%s %s <-> %s\n' % ((' ' * 35), self.start_date, self.end_date)) log_file.write('<%s>\n' % ('-' * 120, )) fails = list() for subscription in azure_subscriptions: try: cloudaccount = CloudAccounts.objects.filter( type='MS', customer=subscription.customer) if cloudaccount.exists(): cloudaccount = cloudaccount.first() else: raise ValueError('Seems there is no cloud account for %s' % cloudaccount.customer.company_name) # Azure tenant id tenant_id = cloudaccount.details.get('tenant_id', None) if not tenant_id: raise ValueError('Seems there is no tenant ID for %s' % cloudaccount.customer.company_name) print(tenant_id, subscription.subscription, self.start_date, self.end_date) util = UtilizationRecords( tenantId=tenant_id, subscriptionId=subscription.subscription, startDate=self.start_date, endDate=self.end_date) util.getUtilization() success = 'Loaded utilization for subscription : %s \n\n' % ( subscription.subscription, ) print(success) # log_file.write(success) except Exception as e: error_title = 'Failed to fetch utilization for subscription : %s \n ' % subscription.subscription print(error_title) print(str(e)) log_file.write(error_title) log_file.write('%s \n' % str(e)) fails.append({ 'subscription': subscription.subscription, 'error': str(e) }) continue if len(fails) > 0: """ Error notification """ content = "<p><strong>Failed to fetch utilization on the following cases : </strong></p>" content += "<table><thead><tr><th style='min-width: 300px;'>Subscription</th><th>Error</th></tr></thead><tbody>" for fail in fails: content += "<tr><td>%s</td><td>%s</td></tr>" % ( fail['subscription'], fail['error']) content += "</tbody></table>" BaseMails.send_mail( subject='ERROR: Loading Azure bills into database', recipients=settings.TECH_TEAM, template_name='plain.html', template_data={ 'Title': 'ERROR', 'message': content }) log_file.close()
def __init__(self, partner_detail): self.send_incompletion_mail(partner_detail) BaseMails.__init__(self, partner_detail, 'PartnerActivation')
def notify_to_redington(self): nf_groups = NotificationGroups.objects.filter( actions__action=self.action).exclude(recipients='') non_users_emails = list( nf_groups.values_list('non_user_recipients__email', flat=True)) sets = list(nf_groups.values_list('recipients', flat=True)) available_user_ids_in_groups = [] if len(sets) > 0: available_user_ids_in_groups = [ user_id for set_string in sets for user_id in set_string.split(',') ] available_user_ids_in_groups = list( set(available_user_ids_in_groups)) available_user_ids_in_groups = list( map(lambda x: str(x), available_user_ids_in_groups)) """ Send Notifications """ if len(available_user_ids_in_groups) > 0: nf_recipients = ','.join(available_user_ids_in_groups) NfActions.publish( params={ 'user': self.details['user'], 'nf_type': "message", 'recipients': nf_recipients, 'message': "Partner Support", 'status': "unread", 'details_obj': self.details['feedback_details'] }) users_emails = RedUser.objects.filter( id__in=available_user_ids_in_groups).values_list('email', flat=True) users_emails = list(users_emails) from cloudapp.generics.constant import AppContants recipients = users_emails + non_users_emails + AppContants.DEVELOPER_EMAILS subject = 'Support from Partner: ' + self.details[ 'feedback_details'].reason """ Send Emails """ if len(recipients) > 0: if self.details['feedback_details'].attachment.name != '': import magic mime = magic.Magic(mime=True) attachements_url = self.details[ 'feedback_details'].attachment.url file_extension = mime.from_file(settings.BASE_DIR + '/' + attachements_url) attchements = dict() attchements['url'] = attachements_url attchements['extenstions'] = file_extension BaseMails.send_mail(subject=subject, recipients=recipients, template_name=choose_template( self.action)['html'], template_data=self.template_data, attachements=attchements) else: BaseMails.send_mail(subject=subject, recipients=recipients, template_name=choose_template( self.action)['html'], template_data=self.template_data)
])) for partner in partners: user = partner """ Generating token for password reset link """ jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) """ Setting expiration time """ payload['exp'] = datetime.datetime.now() + datetime.timedelta(days=1) token = jwt_encode_handler(payload) """ Storing token for future reference """ session = PasswordResetTokens.objects.create(user=user, token=token) session.save() BaseMails.send_mail( subject='REDINGTON: Password reset link', recipients=[user.email], template_name='password_resetting.html', template_data={ 'user': user.__dict__, 'reset_link': '%s?tk=%s' % ('https://portal.redingtoncloud.com/auth/password/reset/confirm', token) }) print('Sent to : ', user.username)