Exemple #1
0
    def post(self, request):
        """
		"""
        if not request.user:
            raise GenericException(
                status_type=STATUS_TYPE["APP"],
                exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
                detail="Access token expired.",
                request=request,
                http_code=403)
        if request.user and not request.user.is_authenticated():
            raise GenericException(
                status_type=STATUS_TYPE["APP"],
                exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
                detail="User is not authorize",
                request=request,
                http_code=403)
        message = '[ User: {0} logged out successfully ]'.format(
            request.user.email)
        log_action(message, request)
        if accounts_utils.logout(request):
            return apps_utils.response(
                {"message": "User logged out successfully"},
                status.HTTP_200_OK)
        else:
            raise GenericException(
                status_type=status_type["APP"],
                exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
                detail="Some \ error occurred. Please try again in sometime.",
                request=request,
                http_code=403)
	def post(self, request):
		"""
		"""
		if request.user and not request.user.is_authenticated:
			raise GenericException(status_type=STATUS_TYPE["APP"],
				exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
				detail="You're not logged in", request=request)
		user = request.user.username
		actual_date = request.data.get('params').get('month')
		actual_date = actual_date[0]+" "+actual_date[1]+" "+actual_date[2]+" "+actual_date[3] 
		actual_date =  datetime.datetime.strptime(actual_date,"%a %b %d %Y")
		# actual_date = datetime.datetime.strptime(request.data.get('params').get('month')[0:-22],"%a %b %d %Y %H:%M:%S %Z+%f")
		date = datetime.datetime.strftime(actual_date,"%Y-%m-%d")
		month = date.split("-")[0]+date.split("-")[1]
		# month = datetime.datetime.strftime(datetime.datetime.strptime(request.data.get('params').get('month'),"%Y-%m-%dT%H:%M:%S.%fZ"),"%Y%m")
		country = request.data.get('params').get('country')
		template_types = ''
		template_types_list = []
		action_dict = {}
		for obj in request.data.get('params').get('template_list'):
			if obj.get('status'):
				status = obj.get('status')
				if status == '1':
					template_types_list.append(upload_constants.XLSX_TEMPLATE_TYPE_NAME_MAPPING[obj.get('type')])
					action_dict.setdefault(upload_constants.XLSX_TEMPLATE_TYPE_NAME_MAPPING[obj.get('type')],{}).update({'status':True,'remark':obj.get('remark')})
				if status == '0':
					template_types_list.append(upload_constants.XLSX_TEMPLATE_TYPE_NAME_MAPPING[obj.get('type')])
					action_dict.setdefault(upload_constants.XLSX_TEMPLATE_TYPE_NAME_MAPPING[obj.get('type')],{}).update({'status':False,'remark':obj.get('remark')})
		upload_tasks.asyn_approve_task.delay(country,month,user,template_types_list,action_dict)
		return Response({"status":True,"message":"Thank you! Submitted action completed. Approved data (if any) shall only reflect upon the MET release schedule."})
	def post(self,request):
		"""
		This API for checking the checking the excel data.
		"""
		if request.user and not request.user.is_authenticated:
			raise GenericException(status_type=STATUS_TYPE["APP"],
				exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
				detail="You're not logged in", request=request)

		is_file_valid = upload_utils.get_decoded_data(request.data.get('params').get('file'),10)
		if not is_file_valid.get('status'):
			raise GenericException(status_type=STATUS_TYPE["APP"],
				exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
				detail=is_file_valid.get('error'), request=request)
		file_data = upload_utils.read_excel_file(is_file_valid.get('data'),
					str(request.data.get('params').get('type')))
		if not file_data.get('status'):
			raise GenericException(status_type=STATUS_TYPE["APP"],
				exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
				detail=[file_data.get('error')], request=request)
		# actual_date =  datetime.datetime.strptime(request.data.get('params').get('date')[0:-22],"%a %b %d %Y %H:%M:%S %Z+%f")
		# actual_date =  datetime.datetime.strptime(request.data.get('params').get('date')[0:33],"%a %b %d %Y %H:%M:%S %Z+%f")
		actual_date = request.data.get('params').get('date')
		actual_date = actual_date[0]+" "+actual_date[1]+" "+actual_date[2]+" "+actual_date[3] 
		actual_date =  datetime.datetime.strptime(actual_date,"%a %b %d %Y")
		date = datetime.datetime.strftime(actual_date,"%Y-%m-%d")
		date = date.split("-")[0]+date.split("-")[1]
		country = request.data.get('params').get('country')
		currency = request.data.get('params').get('currency')
		is_data_missing = upload_utils.check_excel_data(file_data['data'],
														str(request.data.get('params').get('type')),
														date,currency,country,actual_date)
		if not is_data_missing.get('status'):
			raise GenericException(status_type=STATUS_TYPE["APP"],
				exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
				detail=is_data_missing.get('errordict'), request=request)

		upload_utils.save_excel(is_file_valid.get('data'),
								str(request.data.get('params').get('type')),
								request.user.username,
								request.user.id,
								request.data.get('params').get('file_name'),
								request.data.get('params').get('country'),
								request.data.get('params').get('type'))
		# upload_utils.send_mail("testing","","","*****@*****.**")
		return Response({"status":True,"message":"The template uploaded is error-free. Please proceed to “Submit”.",'data':is_data_missing.get('xls_data')})
Exemple #4
0
    def post(self, request):
        """
		This API logs the user in.with username and password.
        ---
        parameters:
            - name: username
            - name: password
		"""
        login_params = accounts_serializers.UserLoginSerializer(
            data=request.data)
        if not login_params.is_valid():
            raise GenericException(
                status_type=STATUS_TYPE["APP"],
                exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
                detail=login_params.errors,
                request=request)
        params = login_params.data
        response = accounts_utils.login(params, request)
        return apps_utils.response(response, status.HTTP_200_OK)
	def post(self,request):
		"""
		"""
		if request.user and not request.user.is_authenticated:
			raise GenericException(status_type=STATUS_TYPE["APP"],
				exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
				detail="You're not logged in", request=request)
		temp = json.loads(request.data.get('params').get('data'))
		excel_type = request.data.get('params').get('type')
		actual_date = request.data.get('params').get('date')
		actual_date = actual_date[0]+" "+actual_date[1]+" "+actual_date[2]+" "+actual_date[3] 
		actual_date =  datetime.datetime.strptime(actual_date,"%a %b %d %Y")
		# actual_date = datetime.datetime.strptime(request.data.get('params').get('date')[0:-22],"%a %b %d %Y %H:%M:%S %Z+%f")
		date = datetime.datetime.strftime(actual_date,"%Y-%m-%d")
		date = date.split("-")[0]+date.split("-")[1]
		country = request.data.get('params').get('country')
		currency = request.data.get('params').get('currency')
		upload_tasks.my_schedule_task.delay(temp,str(excel_type),country,currency,date,request.user.username)
		# upload_utils.upload_excel_data(temp,str(excel_type),country,currency,date,request.user.username)
		return Response({"status":True,"message":"Thank you! Your file has been accepted. \n Notification e-mail will be sent to the approver once the data is processed (typically within 15 mins)."})
def logout(request):
    """
        Logs out the user
        Params: access_token to be rendered invalid
    """
    try:
        data = {}
        data['client_id'] = settings.OAUTH_CLIENT_ID
        data['client_secret'] = settings.OAUTH_CLIENT_SECRET
        data['token'] = request.META["HTTP_AUTHORIZATION"].split(" ")[1]
        resp = requests.post(settings.BASE_URL + 'o/revoke_token/',
                             data=data,
                             verify=False)
        return resp.status_code == status.HTTP_200_OK
    except Exception as e:
        raise GenericException(status_type=STATUS_TYPE["APP"],
                               exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
                               detail=error(e),
                               request=request,
                               http_code=403)
	def post(self, request):
		"""
		"""
		if request.user and not request.user.is_authenticated:
			raise GenericException(status_type=STATUS_TYPE["APP"],
					exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
					detail="You're not logged in", request=request)
		
		requested_data = {}
		actual_date = request.data.get('params').get('Month')
		actual_date = actual_date[0]+" "+actual_date[1]+" "+actual_date[2]+" "+actual_date[3] 
		actual_date =  datetime.datetime.strptime(actual_date,"%a %b %d %Y")
		# actual_date = datetime.datetime.strptime(request.data.get('params').get('Month')[0:-22],"%a %b %d %Y %H:%M:%S %Z+%f")
		date = datetime.datetime.strftime(actual_date,"%Y-%m-%d")
		requested_data["Month"] = date.split("-")[0]+date.split("-")[1]
		# requested_data["Month"] = datetime.datetime.strftime(datetime.datetime.strptime(request.data.get('params').get('Month'),"%Y-%m-%dT%H:%M:%S.%fZ"),"%Y%m")
		requested_data["Country"] = request.data.get('params').get('Country')
		requested_data["Template_Type"] = upload_constants.XLSX_TEMPLATE_TYPE_NAME_MAPPING[str(request.data.get('params').get('Template_Type'))]
		response = upload_utils.download_excel(requested_data)
		if not response.get('status'):
			return Response({"status":False, "message": "Data is not available"})	
		return Response({"status":True, "data":response.get('data'), "template_name":response.get('template_name')})
def login(params, request):
    """
    username can be a valid email or a valid phone with 10 digits.
    :parameter
        - request: request parameter
        - params: parameters
    :return: access token
    """
    auth = (settings.OAUTH_CLIENT_ID, settings.OAUTH_CLIENT_SECRET)
    username = params['username']
    password = params['password']
    upload_country_list = []
    approval_country_list = []
    download_country_list = []
    is_eligible = False
    is_eligible_for_approved = False
    last_uploads = False
    user_obj = User.objects.filter(username=username).first()
    last_update = {
        "ATL": {
            "date": '',
            'status': ''
        },
        "CRM": {
            "date": '',
            'status': ''
        },
        "PR": {
            "date": '',
            'status': ''
        },
        "Digital": {
            "date": '',
            'status': ''
        }
    }
    last_upload = {
        "ATL": {
            "date": '',
            'status': ''
        },
        "CRM": {
            "date": '',
            'status': ''
        },
        "PR": {
            "date": '',
            'status': ''
        },
        "Digital": {
            "date": '',
            'status': ''
        }
    }
    if not user_obj:
        raise GenericException(status_type=STATUS_TYPE["APP"],
                               exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
                               detail=repr("Invalid Username"),
                               request=request)
    if user_obj and not user_obj.is_active:
        raise GenericException(status_type=STATUS_TYPE["APP"],
                               exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
                               detail=repr("This User is not active"),
                               request=request)
    is_authenticate_user = authenticate(username=username, password=password)
    if not is_authenticate_user:
        raise GenericException(status_type=STATUS_TYPE["APP"],
                               exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
                               detail=repr("Invalid Password"),
                               request=request)
    response = requests.post(settings.BASE_URL + 'o/token/',
                             data={
                                 'username': username,
                                 'password': password,
                                 'grant_type': 'password'
                             },
                             auth=auth,
                             verify=False)
    user_details = accounts_serializers.GetUserDetailsSerializer(user_obj).data
    if response.status_code == status.HTTP_200_OK:
        result = json.loads(response.text)
        query = "SELECT Access_Type, Country FROM User_Access where Access_Type = 'MKT_SPEND_UPLOAD' and Okta_Id = '{0}';"
        eligibility = apps_utils.run_query(query.format(username))
        query_approved = "SELECT Access_Type, Country FROM User_Access where Access_Type = 'MKT_SPEND_APPROVE' and Okta_Id = '{0}';"
        # last_update_query = "SELECT Updated_Date,Template_Name FROM MKT_Template_Spend where Approved_By = '{0}' GROUP BY Template_Name;"
        last_update_query = "select * from (SELECT distinct Template_Type,Created_Date,Status,row_number() over (partition by Template_Type order by Created_Date desc) as rank \
                                FROM Mail_Info where Approved_By = '{0}') a where rank = 1;"

        last_upload_query = "select * from (SELECT distinct Template_Type,Created_Date,Status,row_number() over (partition by Template_Type order by Created_Date desc) as rank \
                                FROM Mail_Info where Country = '{0}' and Status = 'upload') a where rank = 1;"

        eligibility_for_download_country = "SELECT Country from User_Access where Okta_Id = '{0}' group by Country;"
        eligibility_for_download_country = apps_utils.run_query(
            eligibility_for_download_country.format(username))
        if eligibility_for_download_country:
            is_eligible_for_download = True
            for obj in eligibility_for_download_country:
                download_country_list.append(obj.get('Country'))
        if eligibility:
            is_eligible = True
            for obj in eligibility:
                upload_country_list.append(obj.get('Country'))

        approved_eligibility = apps_utils.run_query(
            query_approved.format(username))
        if approved_eligibility:
            is_eligible_for_approved = True
            for obj in approved_eligibility:
                approval_country_list.append(obj.get('Country'))
        last_updates = apps_utils.run_query(last_update_query.format(username))
        if last_updates:
            for obj in last_updates:
                last_update.setdefault(obj.get('Template_Type'), {}).update({
                    'date':
                    obj.get('Created_Date'),
                    'status':
                    obj.get('Status')
                })
        if is_eligible:
            last_uploads = apps_utils.run_query(
                last_upload_query.format(upload_country_list[0]))
        if approved_eligibility:
            last_uploads = apps_utils.run_query(
                last_upload_query.format(approval_country_list[0]))
        if last_uploads:
            for obj in last_uploads:
                last_upload.setdefault(obj.get('Template_Type'), {}).update({
                    'date':
                    obj.get('Created_Date'),
                    'status':
                    obj.get('Status')
                })
        return {
            "status": True,
            "access_token": result['access_token'],
            "user_details": user_details,
            "is_eligible_for_upload": is_eligible,
            "uploader_for_country": upload_country_list,
            "last_updates": last_update,
            "last_uploads": last_upload,
            "is_eligible_for_approved": is_eligible_for_approved,
            "approval_for_country": approval_country_list,
            "is_eligible_for_download": is_eligible_for_download,
            "download_for_country": download_country_list
        }
    else:
        raise GenericException(status_type=STATUS_TYPE["APP"],
                               exception_code=NONRETRYABLE_CODE["BAD_REQUEST"],
                               detail=str(
                                   response.json().get('error_description')),
                               request=request)