diff options
Diffstat (limited to 'django/engagementmanager/service')
23 files changed, 1075 insertions, 612 deletions
diff --git a/django/engagementmanager/service/__init__.py b/django/engagementmanager/service/__init__.py index 1726c13..16f81cb 100644 --- a/django/engagementmanager/service/__init__.py +++ b/django/engagementmanager/service/__init__.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. diff --git a/django/engagementmanager/service/activities_service.py b/django/engagementmanager/service/activities_service.py index b7edca4..36ecaa7 100644 --- a/django/engagementmanager/service/activities_service.py +++ b/django/engagementmanager/service/activities_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -38,7 +38,8 @@ # ECOMP is a trademark and service mark of AT&T Intellectual Property. import json from django.utils import timezone -from engagementmanager.bus.messages.new_notification_message import NewNotificationMessage +from engagementmanager.bus.messages.new_notification_message \ + import NewNotificationMessage from engagementmanager.models import IceUserProfile, Activity, Notification from engagementmanager.utils import activities_data from engagementmanager.utils.constants import Constants @@ -55,7 +56,8 @@ class ActivitiesSvc: if hasattr(activity_data, "users_list") and activity_data.users_list: for user in activity_data.users_list: activity_data.user = user - if hasattr(activity_data, "multiple_users_as_owners") and activity_data.multiple_users_as_owners: + if hasattr(activity_data, "multiple_users_as_owners") and \ + activity_data.multiple_users_as_owners: activity_data.owner = activity_data.user self.set_description(activity_data) self.set_metadata(activity_data) @@ -67,13 +69,17 @@ class ActivitiesSvc: def __create_activity(self, activity_data): if activity_data.engagement is None: - msg = "Engagement provided is a None object, be careful not to generate " \ - "description and metadata with engagement properties." + msg = "Engagement provided is a None object, " +\ + "be careful not to generate description and metadata " +\ + "with engagement properties." logger.warn(msg) - if activity_data.owner and not isinstance(activity_data.owner, IceUserProfile): - raise ValueError("owner should be IceUserProfile, was %r", activity_data.owner) + if activity_data.owner and not isinstance(activity_data.owner, + IceUserProfile): + raise ValueError( + "owner should be IceUserProfile, was %r", activity_data.owner) if activity_data.description is None: - logger.warn('createActivity called with description=None; setting to ""') + logger.warn( + 'createActivity called with description=None; setting to ""') activity_data.description = '' new_activity = Activity.objects.create( @@ -93,50 +99,75 @@ class ActivitiesSvc: if activity_data.owner is None: if activity_data.engagement: - users_to_notify = activity_data.engagement.engagement_team.all() + users_to_notify = activity_data.engagement.\ + engagement_team.all() else: users_to_notify.append(activity_data.owner) for user_to_notify in users_to_notify: - new_notification = Notification.objects.create(user=user_to_notify, activity=new_activity) + new_notification = Notification.objects.create( + user=user_to_notify, activity=new_activity) new_activity.notification_set.add(new_notification) user_to_notify.notification_set.add(new_notification) new_notification.save() from engagementmanager.apps import bus_service - bus_service.send_message(NewNotificationMessage(new_notification)) + bus_service.send_message( + NewNotificationMessage(new_notification)) def pull_recent_activities(self, engagement, recent_activities_limit): - """ expected: engagement object (Activity), recent_activities_limit (integer) - number of recent activities + """ expected: engagement object (Activity), recent_activities_limit + (integer) - number of recent activities result: Top-X Dict Activity objects (sort by create_time) """ logger.debug("Pulling top X activities from DB") activities = Activity.objects.filter( - engagement=engagement, activity_owner=None).order_by('-create_time')[:recent_activities_limit] + engagement=engagement, activity_owner=None).order_by( + '-create_time')[:recent_activities_limit] return activities def set_description(self, activity_data): dt = timezone.now() description = '' - if isinstance(activity_data, activities_data.UserJoinedEngagementActivityData): + if isinstance(activity_data, activities_data. + UserJoinedEngagementActivityData): description = "##user_name## joined ##vf_name## " - elif isinstance(activity_data, activities_data.UpdateNextStepsActivityData): - description = "##user_name## " + activity_data.update_type.lower() + " a next step" - elif isinstance(activity_data, activities_data.VFProvisioningActivityData): - description = "Failed Gitlab and/or Jenkins Provision ##vf_name##: " + activity_data.description - elif isinstance(activity_data, activities_data.TestFinishedActivityData): - description = "Failure in Jenkins Job: " + activity_data.description - elif isinstance(activity_data, activities_data.ChangeEngagementStageActivityData): - description = "Engagement stage is now " + activity_data.stage + " for the following VF: ##vf_name##" - elif isinstance(activity_data, activities_data.DeleteNextStepsActivityData): + elif isinstance(activity_data, activities_data. + UpdateNextStepsActivityData): + description = "##user_name## " + activity_data.\ + update_type.lower() + " a next step" + elif isinstance(activity_data, activities_data. + VFProvisioningActivityData): + description = "Failed Gitlab and/or Jenkins Provision " +\ + "##vf_name##: " + activity_data.description + elif isinstance(activity_data, activities_data. + TestFinishedActivityData): + description = "Failure in Jenkins Job: "\ + + activity_data.description + elif isinstance(activity_data, activities_data. + ChangeEngagementStageActivityData): + description = "Engagement stage is now " + \ + activity_data.stage + " for the following VF: ##vf_name##" + elif isinstance(activity_data, activities_data. + DeleteNextStepsActivityData): + description = activity_data.user.full_name + \ + " has deleted a next step at " + \ + dt.strftime("%Y-%m-%d %H:%M:%S") + elif isinstance(activity_data, activities_data. + NoticeEmptyEngagementData): + description = "You have not added any parts of the VNF package " +\ + "to your engagement ##vf_name## since it was created " \ + + activity_data.delta_days_from_creation + \ + " days ago. Do note that if you have not added any " +\ + "parts of the VNF package by " + \ + activity_data.max_empty_time + ", we will be automatically " +\ + "archive it." + elif isinstance(activity_data, activities_data. + AddNextStepsActivityData): description = activity_data.user.full_name + \ - " has deleted a next step at " + dt.strftime("%Y-%m-%d %H:%M:%S") - elif isinstance(activity_data, activities_data.NoticeEmptyEngagementData): - description = "You have not added any parts of the VNF package to your engagement ##vf_name## since it was created " + activity_data.delta_days_from_creation +\ - " days ago. Do note that if you have not added any parts of the VNF package by " + \ - activity_data.max_empty_time + ", we will be automatically archive it." - elif isinstance(activity_data, activities_data.AddNextStepsActivityData): - description = activity_data.user.full_name + " has added a next step at " + dt.strftime("%Y-%m-%d %H:%M:%S") - elif isinstance(activity_data, activities_data.SSHKeyAddedActivityData): + " has added a next step at " + dt.strftime( + "%Y-%m-%d %H:%M:%S") + elif isinstance(activity_data, activities_data. + SSHKeyAddedActivityData): if activity_data.action == 'add': description = "You have added an SSH key to your profile" elif activity_data.action == 'set': @@ -150,11 +181,15 @@ class ActivitiesSvc: dt = timezone.now() metadata = {} - if isinstance(activity_data, activities_data.UserJoinedEngagementActivityData): + if isinstance(activity_data, activities_data. + UserJoinedEngagementActivityData): activity_data.is_notification = True - metadata['notification_subject'] = "Someone has joined the " + activity_data.vf.name + " team" - metadata['notification_message'] = activity_data.user.full_name + " joined the " + activity_data.vf.name + \ - " team. You can reach the dashboard by going to this link: " + \ + metadata['notification_subject'] = "Someone has joined the " + \ + activity_data.vf.name + " team" + metadata['notification_message'] = activity_data.user.full_name +\ + " joined the " + activity_data.vf.name + \ + " team. You can reach the dashboard by " +\ + "going to this link: " + \ Constants.dashboard_href metadata['macros'] = { '##vf_name##': { @@ -168,7 +203,8 @@ class ActivitiesSvc: 'long': activity_data.user.email, } } - elif isinstance(activity_data, activities_data.UpdateNextStepsActivityData): + elif isinstance(activity_data, activities_data. + UpdateNextStepsActivityData): metadata['macros'] = { '##user_name##': { 'type': 'popover', @@ -176,15 +212,24 @@ class ActivitiesSvc: 'long': activity_data.user.email, } } - elif isinstance(activity_data, activities_data.NoticeEmptyEngagementData): + elif isinstance(activity_data, activities_data. + NoticeEmptyEngagementData): activity_data.is_notification = True - metadata['notification_subject'] = "Inactive Engagement Alert - " + activity_data.vf_name + metadata['notification_subject'] = "Inactive Engagement Alert - "\ + + activity_data.vf_name - metadata['notification_message'] = "We have noticed that you have not added any parts of the VNF package to your engagement <em>" +\ - activity_data.engagement.engagement_manual_id + ": " + activity_data.vf_name + "</em> since it was created " + activity_data.delta_days_from_creation +\ - " days ago. If you have any questions around how you add your VNF package please check the relevant parts of the online documentation.<br/><br/>" +\ - "Do note that if you have not added any parts of the VNF package by " + \ - activity_data.max_empty_time + ", we will be automatically archive it." + metadata['notification_message'] = "We have noticed that " +\ + "you have not added any parts of the VNF " +\ + "package to your engagement <em>"\ + + activity_data.engagement.engagement_manual_id + ": "\ + + activity_data.vf_name + "</em> since it was created "\ + + activity_data.delta_days_from_creation +\ + " days ago. If you have any questions around how you add " +\ + "your VNF package please check the relevant parts of the " +\ + "online documentation.<br/><br/>" +\ + "Do note that if you have not added any parts of the VNF " +\ + "package by " + activity_data.max_empty_time + ", we will " +\ + "be automatically archive it." metadata['macros'] = { '##vf_name##': { @@ -194,9 +239,11 @@ class ActivitiesSvc: }, } - elif isinstance(activity_data, activities_data.VFProvisioningActivityData): + elif isinstance(activity_data, activities_data. + VFProvisioningActivityData): activity_data.is_notification = True - metadata['notification_subject'] = "Failed Gitlab and/or Jenkins Provision: " + activity_data.vf.name + metadata['notification_subject'] = "Failed Gitlab and/or " +\ + "Jenkins Provision: " + activity_data.vf.name metadata['notification_message'] = activity_data.description metadata['macros'] = { '##vf_name##': { @@ -205,16 +252,19 @@ class ActivitiesSvc: 'eng_uuid': activity_data.vf.engagement.uuid, }, } - elif isinstance(activity_data, activities_data.TestFinishedActivityData): + elif isinstance(activity_data, activities_data. + TestFinishedActivityData): activity_data.is_notification = True metadata['notification_subject'] = "Failed test_finished signal " metadata['notification_message'] = activity_data.description - elif isinstance(activity_data, activities_data.ChangeEngagementStageActivityData): + elif isinstance(activity_data, activities_data. + ChangeEngagementStageActivityData): activity_data.is_notification = True - metadata['notification_subject'] = "Engagement stage was changed for the following VF: " + \ - activity_data.vf.name - metadata['notification_message'] = "Engagement stage is now " + activity_data.stage +\ - " for the following VF: " + activity_data.vf.name + metadata['notification_subject'] = "Engagement stage was " +\ + "changed for the following VF: " + activity_data.vf.name + metadata['notification_message'] = "Engagement stage is now " \ + + activity_data.stage + " for the following VF: " \ + + activity_data.vf.name metadata['macros'] = { '##vf_name##': { 'type': 'select_engagement', @@ -222,17 +272,22 @@ class ActivitiesSvc: 'eng_uuid': activity_data.engagement.uuid, } } - elif isinstance(activity_data, activities_data.AddNextStepsActivityData): + elif isinstance(activity_data, + activities_data.AddNextStepsActivityData): activity_data.is_notification = True - metadata['notification_subject'] = "New next-step was added to the following VF: " + activity_data.vf.name - metadata['notification_message'] = activity_data.user.full_name + " has added a next step at " +\ + metadata['notification_subject'] = "New next-step was " +\ + "added to the following VF: " + activity_data.vf.name + metadata['notification_message'] = activity_data.user.full_name \ + + " has added a next step at " +\ dt.strftime("%Y-%m-%d %H:%M:%S") + \ ", You can reach the dashboard by going to this link: " \ + Constants.dashboard_href - elif isinstance(activity_data, activities_data.SSHKeyAddedActivityData): + elif isinstance( + activity_data, activities_data.SSHKeyAddedActivityData): activity_data.is_notification = True metadata['notification_subject'] = "You have set an SSH key" - metadata['notification_message'] = "You have set an SSH key to your profile. Please allow some time for" \ - " it to propagate across the system." + metadata['notification_message'] = "You have set an SSH key to " +\ + "your profile. Please allow some time for it to propagate " +\ + "across the system." activity_data.metadata = metadata diff --git a/django/engagementmanager/service/authorization_service.py b/django/engagementmanager/service/authorization_service.py index c850b4a..7a30d0e 100644 --- a/django/engagementmanager/service/authorization_service.py +++ b/django/engagementmanager/service/authorization_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -39,8 +39,8 @@ import json from enum import Enum import rest_framework -from engagementmanager.models import Role, Engagement, Checklist, NextStep, VFC, \ - VF, ChecklistDecision, Notification +from engagementmanager.models import Role, Engagement, Checklist, NextStep, \ + VFC, VF, ChecklistDecision, Notification from engagementmanager.utils.constants import Roles from engagementmanager.utils.request_data_mgr import request_data_mgr from engagementmanager.service.logging_service import LoggingServiceFactory @@ -119,8 +119,10 @@ class Permissions(Enum): class AuthorizationService: """ - The Authorization Service detemines whether a given action is authorized for a specific user. - The method: is_user_able_to performs the authorization check given a user and an action (from Permissions ENUM) + The Authorization Service detemines whether a given action is authorized + for a specific user. + The method: is_user_able_to performs the authorization check given a user + and an action (from Permissions ENUM) """ role_standard_user = None role_el = None @@ -129,8 +131,10 @@ class AuthorizationService: def __get_role_checks(self, user, action): """ - Returns the list of auth checks that should be performed per user action. - Returns None if the action is not listed in the authorized actions of the given user. + Returns the list of auth checks that should be \ + performed per user action. + Returns None if the action is not listed in the \ + authorized actions of the given user. """ result = None @@ -138,33 +142,40 @@ class AuthorizationService: if (user.role == self.role_el) and (action in self.el_permissions): result = self.el_permissions[action] # ADMIN # - elif user.role == self.role_admin and action in self.admin_permissions: + elif user.role == self.role_admin and action in \ + self.admin_permissions: result = self.admin_permissions[action] # ADMIN Read only # - elif user.role == self.role_admin_ro and action in self.admin_ro_permissions: + elif user.role == self.role_admin_ro and action in \ + self.admin_ro_permissions: result = self.admin_ro_permissions[action] # STANDRARD_USER # - if user.role == self.role_standard_user and action in self.standard_user_permissions: + if user.role == self.role_standard_user and \ + action in self.standard_user_permissions: result = self.standard_user_permissions[action] return result def __require_eng_membership(self, user, action, **kwargs): """ - Determines whether a given user is part of engagement team by the eng uuid + Determines whether a given user is part of engagement \ + team by the eng uuid. user = IceUser eng = UUID as a string :param user: user for auth check :param action: action for auth check :param kwargs: eng_uuid, checklist_uuid, ... - :return: Boolean, Message -> True/False if auth check succeeds/fails and a message describing auth failure + :return: Boolean, Message -> True/False if auth check \ + succeeds/fails and a message describing auth failure """ eng = kwargs['eng'] try: # @UndefinedVariable - if (user.email == eng.reviewer.email or user.email == eng.peer_reviewer.email or user.role.name == Roles.admin.name): + if (user.email == eng.reviewer.email or + user.email == eng.peer_reviewer.email or + user.role.name == Roles.admin.name): return True, 'OK' else: # validate if user in Team @@ -173,33 +184,39 @@ class AuthorizationService: else: return False, "" except Engagement.DoesNotExist: - msg = 'User ' + user.email + ' is not a member of engagement: ' + eng.uuid + \ - ' / User is a not peer reviewer / admin of the engagement / Engagement wasnt found while fetching from DB' + msg = 'User ' + user.email + ' is not a member of engagement: ' + \ + eng.uuid + \ + ' / User is a not peer reviewer / admin of the ' +\ + 'engagement / Engagement wasnt found while fetching from DB' logger.info(msg) return False, msg except Exception as e: print(e) - msg = 'A general error occurred while trying to validate that User ' + \ - user.email + ' is a member of engagement ' + msg = 'A general error occurred while trying to validate ' +\ + 'that User ' + user.email + ' is a member of engagement ' logger.info(msg + " Error: " + str(e)) return False, msg def __require_peer_review_ownership(self, user, action, **kwargs): """ - Determines whether the given user is the peer reviewer of the checklist + Determines whether the given user is \ + the peer reviewer of the checklist """ cl = kwargs['cl'] eng = kwargs['eng'] if cl and eng: # @UndefinedVariable - if (eng.peer_reviewer == user and cl.owner == user) or (user.role.name == Roles.admin.name): + if (eng.peer_reviewer == user and cl.owner == user) or \ + (user.role.name == Roles.admin.name): return True, 'OK' else: - return False, 'User is either not the owner of the checklist or not a peer reviewer of the checklist' + return False, 'User is either not the owner of ' +\ + 'the checklist or not a peer reviewer of the checklist' else: logger.error( - 'Internal Error - Checklist/Engagement not found while trying to check permissions for user ' + user.email) + 'Internal Error - Checklist/Engagement not found while ' + + 'trying to check permissions for user ' + user.email) return False, 'Internal Error - Checklist not found' def __require_cl_ownership(self, user, action, **kwargs): @@ -216,7 +233,8 @@ class AuthorizationService: return False, 'User is not the owner of the checklist' else: logger.error( - 'Internal Error - Checklist not found while trying to check permissions for user ' + user.email) + 'Internal Error - Checklist not found while trying to ' + + 'check permissions for user ' + user.email) return False, 'Internal Error - Checklist not found' def __require_el_of_engagement(self, user, action, **kwargs): @@ -234,7 +252,8 @@ class AuthorizationService: return False, 'Role Not authorized' else: logger.error( - 'Internal Error - Engagement not found while trying to check permissions for user ' + user.email) + 'Internal Error - Engagement not found while trying to ' + + 'check permissions for user ' + user.email) return False, 'Internal Error - Checklist not found' def __noop(self, user, action, **kwargs): @@ -266,7 +285,8 @@ class AuthorizationService: ###################### """ Each Permission Map is composed of the following key-val pairs: - Key='Action (Permission ENUM)' --> Value='Set of Checks to perform on this action.' + Key='Action (Permission ENUM)' --> Value='Set of Checks to + perform on this action.' """ el_permissions = { Permissions.add_vf: {__noop}, @@ -289,16 +309,20 @@ class AuthorizationService: Permissions.set_checklist_decision: {__require_cl_ownership}, Permissions.add_checklist_audit_log: {__require_cl_ownership}, Permissions.delete_checklist_audit_log: {__require_cl_ownership}, - Permissions.el_review_checklist: {__require_cl_ownership, __require_eng_membership}, + Permissions.el_review_checklist: {__require_cl_ownership, + __require_eng_membership}, Permissions.peer_review_checklist: {__require_peer_review_ownership}, - Permissions.handoff_checklist: {__require_cl_ownership, __require_eng_membership}, - Permissions.add_checklist_nextstep: {__require_cl_ownership, __require_eng_membership}, + Permissions.handoff_checklist: {__require_cl_ownership, + __require_eng_membership}, + Permissions.add_checklist_nextstep: {__require_cl_ownership, + __require_eng_membership}, Permissions.edit_nextstep: {__require_eng_membership}, Permissions.is_el_of_eng: {__require_el_of_engagement}, Permissions.update_personal_next_step: {__noop}, Permissions.create_checklist_audit_log: {__require_eng_membership}, Permissions.create_checklist_decision: {__require_eng_membership}, - Permissions.update_checklist_state: {__require_cl_ownership, __require_eng_membership}, + Permissions.update_checklist_state: {__require_cl_ownership, + __require_eng_membership}, Permissions.create_deployment_target_site: {__require_eng_membership}, Permissions.star_an_engagement: {__noop}, Permissions.invite: {__require_eng_membership}, @@ -338,7 +362,8 @@ class AuthorizationService: Permissions.update_vf: {__require_eng_membership}, Permissions.reset_nextstep: {__require_eng_membership}, Permissions.update_personal_next_step: {__noop}, - Permissions.update_checklist_state: {__require_cl_ownership, __require_eng_membership}, + Permissions.update_checklist_state: {__require_cl_ownership, + __require_eng_membership}, Permissions.create_deployment_target_site: {__require_eng_membership}, Permissions.star_an_engagement: {__noop}, Permissions.invite: {__require_eng_membership}, @@ -368,7 +393,8 @@ class AuthorizationService: admin_permissions.update( # Add Extra permissions to admin { Permissions.admin_approve_checklist: {__require_cl_ownership}, - Permissions.remove_from_engagement_team: {__require_eng_membership}, + Permissions.remove_from_engagement_team: { + __require_eng_membership}, Permissions.view_checklist_template: {__noop}, Permissions.edit_checklist_template: {__noop}, Permissions.archive_engagement: {__noop}, @@ -403,7 +429,8 @@ class AuthorizationService: ) def __init__(self): - self.role_standard_user = self.role_el = self.role_admin = self.role_admin_ro = None + self.role_standard_user = self.role_el = self.role_admin = \ + self.role_admin_ro = None self.__load_roles_from_db() def check_permissions(self, user, action, eng_uuid, role, eng, cl): @@ -411,7 +438,8 @@ class AuthorizationService: # role and action perm_checks = self.__get_role_checks(user, action) if not perm_checks: - # Permission Checks were not found, it means that the action is not listed in the permitted + # Permission Checks were not found, it means that the action is + # not listed in the permitted # actions for the role of the user ret = False, 'Role ' + str(role.name) + ' is not permitted to ' + \ str(action.name) + '/ Engagement: ' + \ @@ -456,7 +484,8 @@ class AuthorizationService: eng = Engagement.objects.get(uuid=eng_uuid) except Engagement.DoesNotExist: logger.error( - 'ENG was not found while checking permissions... returning 500') + 'ENG was not found while checking permissions... ' + + 'returning 500') return None, None try: @@ -490,7 +519,7 @@ class AuthorizationService: else: # Extract eng_uuid from request body for arg in args: - if eng_uuid != None: + if eng_uuid: break if isinstance(arg, rest_framework.request.Request): try: @@ -512,7 +541,8 @@ class AuthorizationService: if 'eng_uuid' in data and data['eng_uuid']: eng_uuid = data['eng_uuid'] - elif 'engagement_uuid' in data and data['engagement_uuid']: + elif 'engagement_uuid' in data and \ + data['engagement_uuid']: eng_uuid = data['engagement_uuid'] except Exception as e: print(e) @@ -523,80 +553,88 @@ class AuthorizationService: # Extract CHECKLIST_UUID # if 'checklistUuid' in kwargs: request_data_mgr.set_cl_uuid(kwargs['checklistUuid']) - if (eng_uuid == None): + if not eng_uuid: try: eng_uuid = Checklist.objects.get( uuid=request_data_mgr.get_cl_uuid()).engagement.uuid request_data_mgr.set_eng_uuid(eng_uuid) except Checklist.DoesNotExist: - raise Exception("auth service couldn't fetch Checklist by checklist uuid=" + + raise Exception("auth service couldn't fetch Checklist " + + "by checklist uuid=" + request_data_mgr.get_cl_uuid()) except Exception as e: raise Exception( - "Failed fetching engagement uuid from checklist " + request_data_mgr.get_cl_uuid()) + "Failed fetching engagement uuid from checklist " + + request_data_mgr.get_cl_uuid()) # Extract engagement by NEXTSTEP_UUID # if 'ns_uuid' in kwargs: request_data_mgr.set_ns_uuid(kwargs['ns_uuid']) - if (eng_uuid == None): + if not eng_uuid: next_step = None try: next_step = NextStep.objects.get( uuid=request_data_mgr.get_ns_uuid()) except NextStep.DoesNotExist: - raise Exception("auth service couldn't fetch NextStep by nextstep uuid=" + + raise Exception("auth service couldn't" + + "fetch NextStep by nextstep uuid=" + request_data_mgr.get_ns_uuid()) try: eng_uuid = next_step.engagement.uuid request_data_mgr.set_eng_uuid(eng_uuid) - except: - # If we've gotten here it means that the next_step doesn't have attached + except BaseException: + # If we've gotten here it means that the next_step + # doesn't have attached # engagement (e.g personal next_step) pass # Extract engagement by VFC if ('uuid' in kwargs): from engagementmanager.rest.vfc import VFCRest - if (isinstance(args[0], VFCRest) == True): + if (isinstance(args[0], VFCRest)): try: vfc = VFC.objects.get(uuid=kwargs['uuid']) - if (eng_uuid == None): + if not eng_uuid: eng_uuid = vfc.vf.engagement.uuid request_data_mgr.set_eng_uuid(eng_uuid) except VFC.DoesNotExist: raise Exception( - "auth service couldn't fetch vfc by vfc uuid=" + kwargs['uuid']) + "auth service couldn't fetch vfc by vfc uuid=" + + kwargs['uuid']) # Extract engagement by VF (unfortunately the url exposed by the server # get uuid as a parameter and serve both vf and vfc APIs) # - if 'vf_uuid' in kwargs and eng_uuid == None: + if 'vf_uuid' in kwargs and not eng_uuid: try: eng_uuid = VF.objects.get( uuid=kwargs['vf_uuid']).engagement.uuid request_data_mgr.set_eng_uuid(eng_uuid) except VF.DoesNotExist: logger.error( - "Prepare_data_for_auth: Couldn't fetch engagement object from VF, trying to fetch from VFC...") + "Prepare_data_for_auth: Couldn't fetch engagement " + + "object from VF, trying to fetch from VFC...") vfc = None try: vfc = VFC.objects.get(uuid=kwargs['vf_uuid']) - if (vfc != None): + if vfc: eng_uuid = vfc.vf.engagement.uuid request_data_mgr.set_eng_uuid(eng_uuid) except VFC.DoesNotExist: logger.error( - "Prepare_data_for_auth: Couldn't fetch engagement object from VFC") + "Prepare_data_for_auth: Couldn't fetch engagement " + + "object from VFC") # Extract engagement by ChecklistDecision - if 'decision_uuid' in kwargs and eng_uuid == None: + if 'decision_uuid' in kwargs and not eng_uuid: try: eng_uuid = ChecklistDecision.objects.get( uuid=kwargs['decision_uuid']).checklist.engagement.uuid request_data_mgr.set_eng_uuid(eng_uuid) except ChecklistDecision.DoesNotExist: logger.error( - "Prepare_data_for_auth: Couldn't fetch engagement object from ChecklistDecision") + "Prepare_data_for_auth: Couldn't fetch " + + "engagement object from ChecklistDecision") # Extract notification uuid for permission check if 'notif_uuid' in kwargs: diff --git a/django/engagementmanager/service/base_service.py b/django/engagementmanager/service/base_service.py index 93e48f8..b6b34e6 100644 --- a/django/engagementmanager/service/base_service.py +++ b/django/engagementmanager/service/base_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -43,7 +43,8 @@ from engagementmanager.service.logging_service import LoggingServiceFactory class BaseSvc(): ''' - classdocs This is the base abstract class of all ice Services delegated from the Rest layer + classdocs This is the base abstract class of all ice Services \ + delegated from the Rest layer ''' __metaclass__ = ABCMeta diff --git a/django/engagementmanager/service/bus_service.py b/django/engagementmanager/service/bus_service.py index 5096fbb..0595c7b 100644 --- a/django/engagementmanager/service/bus_service.py +++ b/django/engagementmanager/service/bus_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -36,7 +36,8 @@ # ============LICENSE_END============================================ # # ECOMP is a trademark and service mark of AT&T Intellectual Property. -from engagementmanager.bus.handlers.service_bus_base_handler import ServiceBusBaseHandler +from engagementmanager.bus.handlers.service_bus_base_handler \ + import ServiceBusBaseHandler from engagementmanager.utils.vvp_exceptions import VvpGeneralException @@ -49,7 +50,9 @@ class BusService: def register(self, handler, message_type): if not isinstance(handler, ServiceBusBaseHandler): - raise VvpGeneralException("You can't register handler which is not from type of ServiceBusBaseHandler") + raise VvpGeneralException( + "You can't register handler which is not from type " + + "of ServiceBusBaseHandler") handler_pair = self.__get_or_create_handler_pair(message_type) handler_pair["handlers"].append(handler) diff --git a/django/engagementmanager/service/checklist_audit_log_service.py b/django/engagementmanager/service/checklist_audit_log_service.py index f726950..84f0d9b 100644 --- a/django/engagementmanager/service/checklist_audit_log_service.py +++ b/django/engagementmanager/service/checklist_audit_log_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -37,7 +37,8 @@ # # ECOMP is a trademark and service mark of AT&T Intellectual Property. import json -from engagementmanager.models import ChecklistDecision, ChecklistAuditLog, Checklist +from engagementmanager.models import ChecklistDecision,\ + ChecklistAuditLog, Checklist from engagementmanager.serializers import ThinChecklistAuditLogModelSerializer from engagementmanager.service.logging_service import LoggingServiceFactory @@ -46,11 +47,14 @@ logger = LoggingServiceFactory.get_logger() def addAuditLogToDecision(decision, description, user, category=''): """ - expected: decisionUuid(string), description(string), user(object), category is optional(string) - result: new auditlog object would be create and attached to a decision object. + expected: decisionUuid(string), description(string),\ + user(object), category is optional(string) + result: new auditlog object would be create and \ + attached to a decision object. """ audit = ChecklistAuditLog.objects.create(decision=decision, - description=description, category=category, creator=user) + description=description, + category=category, creator=user) auditData = ThinChecklistAuditLogModelSerializer(audit).data return auditData @@ -58,10 +62,11 @@ def addAuditLogToDecision(decision, description, user, category=''): def getAuditLogsWithDecision(decisionUuid, user): """ expected: decisionUuid(string), user(object) - result: all audit logs objects that attached to a decision would be returned in a json. + result: all audit logs objects that attached to a decision \ + would be returned in a json. """ data = dict() - if checklistUuid == '' or not user: # @UndefinedVariable + if decisionUuid == '' or not user: msg = "checklistUuid or user == None" logger.error(msg) msg = "AuditLogs were not retrieved due to bad parameters" @@ -69,18 +74,22 @@ def getAuditLogsWithDecision(decisionUuid, user): decision = ChecklistDecision.objects.get(uuid=decisionUuid) audits = ChecklistAuditLog.objects.filter(decision=decision) - data['audits'] = ThinChecklistAuditLogModelSerializer(audits, many=True).data + data['audits'] = ThinChecklistAuditLogModelSerializer( + audits, many=True).data auditsData = json.dumps(data, ensure_ascii=False) return auditsData def addAuditLogToChecklist(checklist, description, user, category=''): """ - expected: checklistUuid(string), description(string), user(object), category is optional(string) - result: new auditlog object would be create and attached to a checklist object. + expected: checklistUuid(string), description(string), user(object), \ + category is optional(string) + result: new auditlog object would be create and attached \ + to a checklist object. """ audit = ChecklistAuditLog.objects.create(checklist=checklist, - description=description, category=category, creator=user) + description=description, + category=category, creator=user) auditData = ThinChecklistAuditLogModelSerializer(audit).data logger.debug("audit log was successfully updated") return auditData @@ -89,7 +98,8 @@ def addAuditLogToChecklist(checklist, description, user, category=''): def getAuditLogsWithChecklist(checklistUuid, user): """ expected: checklistUuid(string), user(object) - result: all audit logs objects that attached to a checklist would be returned in a json. + result: all audit logs objects that attached to a checklist \ + would be returned in a json. """ data = dict() if checklistUuid == '' or not user: # @UndefinedVariable @@ -100,6 +110,7 @@ def getAuditLogsWithChecklist(checklistUuid, user): checklist = Checklist.objects.get(uuid=checklistUuid) audits = ChecklistAuditLog.objects.filter(checklist=checklist) - data['audits'] = ThinChecklistAuditLogModelSerializer(audits, many=True).data + data['audits'] = ThinChecklistAuditLogModelSerializer( + audits, many=True).data auditsData = json.dumps(data, ensure_ascii=False) return auditsData diff --git a/django/engagementmanager/service/checklist_decision_service.py b/django/engagementmanager/service/checklist_decision_service.py index e94c059..14007fe 100644 --- a/django/engagementmanager/service/checklist_decision_service.py +++ b/django/engagementmanager/service/checklist_decision_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -52,7 +52,8 @@ logger = LoggingServiceFactory.get_logger() def setDecision(decisionUuid, user, value): logger.debug("attempting setDecision(user=%r, value=%r)...", user, value) - if not decisionUuid or not user or value not in CheckListDecisionValue.__members__: + if not decisionUuid or not user or value not in \ + CheckListDecisionValue.__members__: msg = "decisionUuid or value are empty or invalid / user == None" logger.error(msg) msg = "decision wasn't change due to bad parameters" @@ -61,48 +62,64 @@ def setDecision(decisionUuid, user, value): decision = ChecklistDecision.objects.get(uuid=decisionUuid) checklist = decision.checklist - # @UndefinedVariable - if (checklist.owner.email == user.email and user.role.name == Roles.el.name) or (user.role.name == Roles.admin.name): - if checklist.state == CheckListState.review.name: # @UndefinedVariable + if (checklist.owner.email == user.email and + user.role.name == Roles.el.name) or \ + (user.role.name == Roles.admin.name): + if checklist.state == CheckListState.review.name: if decision.review_value != value: decision.review_value = value decision.save() - msg = "review_value was successfully changed for decision: " + decision.uuid + " , value: " + value + msg = "review_value was successfully " +\ + "changed for decision: " + \ + decision.uuid + " , value: " + value else: - msg = "review_value was already the same: " + decision.uuid + " , value: " + value + msg = "review_value was already the same: " + \ + decision.uuid + " , value: " + value logger.debug(msg) - elif checklist.state == CheckListState.peer_review.name: # @UndefinedVariable + elif checklist.state == CheckListState.peer_review.name: if decision.peer_review_value != value: decision.peer_review_value = value decision.save() - msg = "peer_review_value was successfully changed for decision: " + decision.uuid + " , value: " + value + msg = "peer_review_value was successfully " +\ + "changed for decision: " + decision.uuid +\ + " , value: " + value else: - msg = "review_value was already the same: " + decision.uuid + " , value: " + value + msg = "review_value was already the same: " + \ + decision.uuid + " , value: " + value logger.debug(msg) - elif checklist.state == CheckListState.automation.name: # @UndefinedVariable + elif checklist.state == CheckListState.automation.name: if decision.review_value != value: decision.peer_review_value = value decision.save() - msg = "peer_review_value was successfully changed for decision: " + decision.uuid + " , value: " + value + msg = "peer_review_value was successfully " +\ + "changed for decision: " + decision.uuid +\ + " , value: " + value else: - msg = "review_value was already the same: " + decision.uuid + " , value: " + value + msg = "review_value was already the same: " + \ + decision.uuid + " , value: " + value if decision.review_value != value: decision.review_value = value decision.save() - msg = "review_value was successfully changed for decision: " + decision.uuid + " , value: " + value + msg = "review_value was successfully " +\ + "changed for decision: " + \ + decision.uuid + " , value: " + value else: - msg = "review_value was already the same: " + decision.uuid + " , value: " + value + msg = "review_value was already the same: " + \ + decision.uuid + " , value: " + value logger.debug(msg) else: - msg = "checklist's state is an invalid state for the decision change and should be different" + msg = "checklist's state is an invalid state for the decision " +\ + "change and should be different" logger.error(msg) - msg = "decision wasn't change, Checklist's state is not allowed to change the decision" + msg = "decision wasn't change, " +\ + "Checklist's state is not allowed to change the decision" raise MethodNotAllowed(msg) return msg else: msg = "user isn't an EL / The User (" + user.full_name + \ - ") tried to change the decision while the current owner is " + checklist.owner.full_name + ") tried to change the decision while the current owner is " \ + + checklist.owner.full_name logger.error(logEncoding(msg)) msg = "Action is forbidden" raise PermissionDenied(msg) @@ -110,13 +127,16 @@ def setDecision(decisionUuid, user, value): def getDecision(decisionUuid, user): data = dict() - if decisionUuid == '' or (not user and user.role.name == Roles.el.name): # @UndefinedVariable + # @UndefinedVariable + if decisionUuid == '' or (not user and user.role.name == Roles.el.name): msg = "decisionUuid or (user == None / user.role != EL)" logger.error(msg) - msg = "decision wasn't retrieved due to bad parameters / you are not authorized" + msg = "decision wasn't retrieved due to bad parameters / " +\ + "you are not authorized" raise KeyError(msg) decision = ChecklistDecision.objects.get(uuid=decisionUuid) - data['decision'] = ThinChecklistDecisionModelSerializer(decision, many=False).data + data['decision'] = ThinChecklistDecisionModelSerializer( + decision, many=False).data decisionData = json.dumps(data, ensure_ascii=False) return decisionData diff --git a/django/engagementmanager/service/checklist_service.py b/django/engagementmanager/service/checklist_service.py index 0df7edd..9132a3c 100644 --- a/django/engagementmanager/service/checklist_service.py +++ b/django/engagementmanager/service/checklist_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -43,12 +43,16 @@ from engagementmanager.apps import bus_service from engagementmanager.bus.messages.activity_event_message import \ ActivityEventMessage from engagementmanager.git.git_manager import GitManager -from engagementmanager.models import ChecklistTemplate, Checklist, Engagement, \ - ChecklistAuditLog, ChecklistDecision, ChecklistLineItem, IceUserProfile, VF, \ +from engagementmanager.models import ChecklistTemplate, \ + Checklist, Engagement, \ + ChecklistAuditLog, ChecklistDecision, ChecklistLineItem, \ + IceUserProfile, VF, \ ChecklistSection, Role from engagementmanager.serializers import ThinChecklistModelSerializer, \ - ThinChecklistAuditLogModelSerializer, ThinChecklistDecisionModelSerializer, \ - ThinPostChecklistResponseModelSerializer, ChecklistTemplateModelSerializer, \ + ThinChecklistAuditLogModelSerializer, \ + ThinChecklistDecisionModelSerializer, \ + ThinPostChecklistResponseModelSerializer, \ + ChecklistTemplateModelSerializer, \ ChecklistSectionModelSerializer, ChecklistLineItemModelSerializer from engagementmanager.service.checklist_audit_log_service import \ addAuditLogToDecision, addAuditLogToChecklist @@ -72,15 +76,19 @@ logger = LoggingServiceFactory.get_logger() class CheckListSvc(BaseSvc): + def retreive_cl_files_for_engagment(self, eng_uuid): vf_associated_files_list = [] - checklists_of_eng = Checklist.objects.filter(engagement__uuid=eng_uuid).exclude( - state=CheckListState.archive.name).exclude(state=CheckListState.closed.name) # @UndefinedVariable + checklists_of_eng = Checklist.objects.filter( + engagement__uuid=eng_uuid).exclude( + state=CheckListState.archive.name).exclude( + state=CheckListState.closed.name) for checklistObj in checklists_of_eng: associated_files = json.loads(checklistObj.associated_files) - vf_associated_files_list = vf_associated_files_list + associated_files + vf_associated_files_list = \ + vf_associated_files_list + associated_files return vf_associated_files_list def getDataForCreateNewChecklist(self, user, eng_uuid): @@ -95,12 +103,14 @@ class CheckListSvc(BaseSvc): # Get all templates data = self.getChecklistTemplates() - data['checkListAssociatedFiles'] = self.gitManager.getRepoAssociatedFilesForUser( + data['checkListAssociatedFiles'] = \ + self.gitManager.getRepoAssociatedFilesForUser( eng_uuid) return data def getChecklistTemplates(self, templateUuid=None): - """Return checklist template with nested sections and their nested line items""" + """Return checklist template with + nested sections and their nested line items""" data = dict() if not templateUuid: checkListTemplates = ChecklistTemplate.objects.all() @@ -109,11 +119,11 @@ class CheckListSvc(BaseSvc): checkListTemplates, many=True).data return data cl_template = ChecklistTemplate.objects.get(uuid=templateUuid) - if (cl_template != None): + if (cl_template is not None): data = ChecklistTemplateModelSerializer( cl_template, many=False).data sections = ChecklistSection.objects.filter(template=cl_template) - if (sections != None): + if (sections is not None): section_list = [] for sec in sections: section_data = dict() @@ -121,7 +131,8 @@ class CheckListSvc(BaseSvc): sec, many=False).data lineItems = ChecklistLineItem.objects.filter(section=sec) - section_data['lineItems'] = ChecklistLineItemModelSerializer( + section_data['lineItems'] = \ + ChecklistLineItemModelSerializer( lineItems, many=True).data section_list.append(section_data) @@ -134,8 +145,10 @@ class CheckListSvc(BaseSvc): logger.debug( "Creating a new section. Section name = " + section['name']) - weight = int(ChecklistSection.objects.filter(template=templateObj).aggregate( - max_weight=Max('weight'))['max_weight'] or 0) + 1 + weight = int( + ChecklistSection.objects.filter( + template=templateObj).aggregate( + max_weight=Max('weight'))['max_weight'] or 0) + 1 newSection = ChecklistSection.objects.create( name=section.get('name', None), @@ -147,11 +160,14 @@ class CheckListSvc(BaseSvc): return newSection - def createNewLineItemForSection(self, newSectionObj, listItem, templateObj): + def createNewLineItemForSection( + self, newSectionObj, listItem, templateObj): """Create new line item for a given section and template """ - weight = int(ChecklistLineItem.objects.filter(section=newSectionObj).aggregate( - max_weight=Max('weight'))['max_weight'] or 0) + 1 + weight = int( + ChecklistLineItem.objects.filter( + section=newSectionObj).aggregate( + max_weight=Max('weight'))['max_weight'] or 0) + 1 ChecklistLineItem.objects.create( name=listItem['name'], @@ -165,22 +181,27 @@ class CheckListSvc(BaseSvc): weight=weight) def delete(self, dict_structure, query_set, entity, isDirty): - """Generically find the xor result of the user input and the db data. Assumption: If entities exits in DB but not in user input they'll be deleted""" - uuid_client = [dict['uuid'] for dict in dict_structure] + """Generically find the xor result of the user input and the + db data. Assumption: If entities exits in DB but not in + user input they'll be deleted""" + uuid_client = [dictio['uuid'] for dictio in dict_structure] uuid_db = [record.uuid for record in query_set] uuids_to_delete = set(uuid_db) - set(uuid_client) for u_uid in uuids_to_delete: entity.objects.filter(uuid=u_uid).delete() - # Note: No need to delete ChecklistLineItem corresponding to this section + # Note: No need to delete ChecklistLineItem + # corresponding to this section # since there is a CASCADE operation on delete section isDirty[0] = True def editIfChanged(self, entity, uidict, fieldList): - """Generic function to check that set of fields are modified on a certain entity""" + """Generic function to check that set of fields + are modified on a certain entity""" isChanged = False for field in fieldList: if (field in uidict): - if (isChanged != True and entity.__dict__[field] == uidict[field]): + if (not isChanged and entity.__dict__[ + field] == uidict[field]): isChanged = False else: entity.__dict__[field] = uidict[field] @@ -198,13 +219,17 @@ class CheckListSvc(BaseSvc): isDirty[0] = True def updateLineItemFields(self, lineitem, li, isDirty): - if (self.editIfChanged(lineitem, li, ['name', 'description', 'validation_instructions', 'line_type'])): + if (self.editIfChanged(lineitem, li, [ + 'name', 'description', + 'validation_instructions', 'line_type'])): lineitem.save() isDirty[0] = True def editChecklistTemplate(self, checklistTemplate): """edit the template+section+line-item of user input""" - NEW_ENTITY = "newEntity" # this is an indication on top of the provided json to create the entity + # this is an indication on top of the provided json to create the + # entity + NEW_ENTITY = "newEntity" templateObj = None isDirty = [False] if ('uuid' in checklistTemplate): @@ -239,7 +264,8 @@ class CheckListSvc(BaseSvc): else: # line-item was only updated lineitem = ChecklistLineItem.objects.get( uuid=li['uuid']) - self.updateLineItemFields(lineitem, li, isDirty) + self.updateLineItemFields( + lineitem, li, isDirty) executor.submit(self.decline_all_template_checklists, isDirty[0], templateObj, request_data_mgr.get_user()) @@ -250,26 +276,36 @@ class CheckListSvc(BaseSvc): start = time.clock() try: - if (isDirty == True): - states_to_exclude = [CheckListState.archive.name, CheckListState.closed.name, - CheckListState.pending.name] # @UndefinedVariable + if (isDirty): + states_to_exclude = [ + CheckListState.archive.name, + CheckListState.closed.name, + CheckListState.pending.name] # @UndefinedVariable checklists = Checklist.objects.filter( template=templateObj).exclude(state__in=states_to_exclude) logger.debug("Number of checklists=" + - str(len(checklists))) + str(len(checklists))) for checklist in checklists: request_data_mgr.set_cl_uuid(checklist.uuid) request_data_mgr.set_eng_uuid(checklist.engagement.uuid) set_state( - True, # means that the checklist will be declined and a cloned one is created in PENDING status + # means that the checklist will be declined and a + # cloned one is created in PENDING status + True, checklist.uuid, isMoveToAutomation=True, - description="""Checklist {name} was rejected since its template ({template}) was edited/deleted""".format( - name=checklist.name, template=templateObj.name), # means the checklist will be triggered into automation cycle + description="""Checklist {name} was rejected """ +\ + """since its template ({template}) was """ +\ + """edited/deleted""".format( + name=checklist.name, template=templateObj.name), + # means the checklist will be triggered into automation + # cycle ) except Exception as e: - msg = """Something went wrong while trying to reject check-lists which its template was changed. template={template}. Error:""".format( - template=templateObj.name) + msg = """Something went wrong while trying to reject """ +\ + """check-lists which its template was changed. """ +\ + """template={template}. Error:""".format( + template=templateObj.name) logger.error(msg + " " + str(e)) raise e # Don't remove try-except, it supports async invocation end = time.clock() @@ -280,15 +316,17 @@ class CheckListSvc(BaseSvc): data = dict() checklist = None - if user.role.name == Roles.admin.name or user.role.name == Roles.admin_ro.name: # @UndefinedVariable + if user.role.name == Roles.admin.name or \ + user.role.name == Roles.admin_ro.name: checklist = Checklist.objects.get(uuid=checklistUuid) else: checklist = Checklist.objects.get( Q(uuid=checklistUuid), Q(creator=user) | Q(owner=user)) # CheckList - if checklist.state == CheckListState.archive.name: # @UndefinedVariable - msg = "got a request for a checklist which is an archived one, might have been due to an admin edit of a checklist template." + if checklist.state == CheckListState.archive.name: + msg = "got a request for a checklist which is an archived one, " +\ + "might have been due to an admin edit of a checklist template." logger.error(msg) msg = "Requested checklist is archived, reloading checklists list" raise VvpObjectNotAvailable(msg) @@ -322,15 +360,18 @@ class CheckListSvc(BaseSvc): section_key = str(section_weight) + "_" + section_uuid if section_key not in checklistLineItems: checklistLineItems[section_key] = {} - checklistLineItems[section_key]['section'] = checklistDecision['lineitem']['section'] + checklistLineItems[section_key]['section'] = \ + checklistDecision['lineitem']['section'] checklistLineItems[section_key]['decisions'] = {} checklistLineItems[section_key]['weight'] = section_weight decision_uuid = checklistDecision['uuid'] line_item_weight = checklistDecision['lineitem']['weight'] decision_key = str(line_item_weight) + "_" + decision_uuid - checklistLineItems[section_key]['decisions'][decision_key] = checklistDecision - checklistLineItems[section_key]['decisions'][decision_key]['weight'] = line_item_weight + checklistLineItems[section_key]['decisions'][decision_key] = \ + checklistDecision + checklistLineItems[section_key]['decisions'][ + decision_key]['weight'] = line_item_weight data['checklistDecisions'] = checklistLineItems @@ -343,10 +384,16 @@ class CheckListSvc(BaseSvc): if decisionAuditLogs.count() > 0: serializedAuditLogsData = ThinChecklistAuditLogModelSerializer( decisionAuditLogs, many=True).data - data['decisionAuditLogs'][checklistDecision.uuid] = serializedAuditLogsData + data['decisionAuditLogs'][ + checklistDecision.uuid] = serializedAuditLogsData - logger.debug("get existing checklist has succeeded for checklist.uuid=" + str(checklist.uuid) + - ", user.uuid=" + str(user.uuid) + ", checklist.uuid=" + str(checklistUuid)) + logger.debug("get existing checklist has " + + "succeeded for checklist.uuid=" + + str(checklist.uuid) + + ", user.uuid=" + + str(user.uuid) + + ", checklist.uuid=" + + str(checklistUuid)) return data @@ -354,7 +401,12 @@ class CheckListSvc(BaseSvc): repo_files = self.gitManager.getRepoAssociatedFilesForUser(eng_uuid) return repo_files - def createOrUpdateChecklist(self, checkListName, checkListTemplateUuid, checkListAssociatedFiles, checklistUuid=None): + def createOrUpdateChecklist( + self, + checkListName, + checkListTemplateUuid, + checkListAssociatedFiles, + checklistUuid=None): template = None checklist = None user = request_data_mgr.get_user() @@ -362,19 +414,18 @@ class CheckListSvc(BaseSvc): vf = VF.objects.get(engagement__uuid=eng_uuid) - if not send_jenkins_job_and_gitlab_repo_exists(vf): - msg = "Jenkins job or gitlab repo is still missing" - logger.error(msg) - msg = "Create or update checklist is not ready yet" - raise Exception(msg) - # associated_files may be delivered in this format - # [{"File": "bar"}, {"File": "baz"}, {"File": "foo"}, {"File": "quux"}] + # [{"File": "bar"}, {"File": "baz"}, + # {"File": "foo"}, {"File": "quux"}] # but we want to store it in this format # ["bar", "baz", "foo", "quux"] repo_files = self.gitManager.getRepoAssociatedFilesForUser(eng_uuid) -# checklist_files_list = [f['File'] if isinstance(f, dict) else f for f in checkListAssociatedFiles] + if not send_jenkins_job_and_gitlab_repo_exists(vf): + msg = "Jenkins job or gitlab repo is still missing" + logger.error(msg) + msg = "Create or update checklist is not ready yet" + raise Exception(msg) checklist_files_list = [] for file in checkListAssociatedFiles: if isinstance(file, dict): @@ -384,7 +435,7 @@ class CheckListSvc(BaseSvc): for added_name in checklist_files_list: if added_name not in repo_files: logger.error("Update checklist has failed. " + - added_name + " doesnt exist in repo") + added_name + " doesnt exist in repo") msg = "Failed to create checklist, please select valid file" raise ValueError(msg) @@ -393,19 +444,21 @@ class CheckListSvc(BaseSvc): engagement = Engagement.objects.get(uuid=eng_uuid) template = ChecklistTemplate.objects.get(uuid=checkListTemplateUuid) - if (checklistUuid != None): # Update Checklist + if (checklistUuid is not None): # Update Checklist checklist = Checklist.objects.get(uuid=checklistUuid) checklist.name = checkListName checklist.associated_files = associated_files checklist.template = template checklist.save() - - if (associated_files != None and len(checklist_files_list) > 0): + if (associated_files and len(checklist_files_list) > 0): set_state( decline=True, description="Checklist: " + checklist.name + - "in Pending state will transition to Automation because it has associated files", - isMoveToAutomation=True, # means the checklist will be triggered into automation cycle + "in Pending state will transition to \ + Automation because it has associated files", + isMoveToAutomation=True, + # means the checklist will be triggered into automation + # cycle checklist_uuid=checklist.uuid ) else: # create ChcekList @@ -416,35 +469,46 @@ class CheckListSvc(BaseSvc): vf = None vf = VF.objects.get(engagement=engagement) - if (vf.git_repo_url == None): + if (vf.git_repo_url is None): msg = "Can't create checklist since the attached VF (" + \ vf.name + ") doesn't contain git_repo_url" logger.error( "Update checklist has failed. " + logEncoding(msg)) raise ObjectDoesNotExist(msg) - checklist = Checklist(name=checkListName, validation_cycle=1, associated_files=associated_files, - state=CheckListState.pending.name, engagement=engagement, template=template, creator=user, owner=incharge_personal) # @UndefinedVariable + checklist = Checklist( + name=checkListName, + validation_cycle=1, + associated_files=associated_files, + state=CheckListState.pending.name, + engagement=engagement, + template=template, + creator=user, + owner=incharge_personal) # @UndefinedVariable line_items_list = ChecklistLineItem.objects.filter( template=template) checklist.save() for lineitem in line_items_list: - new_decision = ChecklistDecision(checklist=checklist, - template=template, lineitem=lineitem) + new_decision = ChecklistDecision( + checklist=checklist, template=template, lineitem=lineitem) new_decision.save() # When Checklist is created with files move it it automation - if (associated_files != None and len(checklist_files_list) > 0): + if (associated_files and len(checklist_files_list) > 0): set_state( decline=False, checklist_uuid=checklist.uuid, description="Checklist: " + checklist.name + - "in Pending state will transition to Automation because it has associated files", - isMoveToAutomation=True # means the checklist will be triggered into automation cycle + "in Pending state will transition to \ + Automation because it has associated files", + isMoveToAutomation=True + # means the checklist will be triggered into automation + # cycle ) logger.debug( - "Create/Update checklist has succeeded for checklist.uuid=" + str(checklist.uuid)) + "Create/Update checklist has succeeded for checklist.uuid=" + + str(checklist.uuid)) return ThinPostChecklistResponseModelSerializer(checklist).data @@ -453,14 +517,26 @@ class CheckListSvc(BaseSvc): checklist.delete() logger.debug( - "Delete checklist has succeeded for checklist.uuid=" + str(checklist_uuid)) - - def setChecklistDecisionsFromValMgr(self, user, checklist_uuid, decisions, checklist_results_from_jenkins): - checklist = Checklist.objects.get(uuid=checklist_uuid, owner=user, - state=CheckListState.automation.name) # @UndefinedVariable + "Delete checklist has succeeded for checklist.uuid=" + + str(checklist_uuid)) + + def setChecklistDecisionsFromValMgr( + self, + user, + checklist_uuid, + decisions, + checklist_results_from_jenkins): + checklist = Checklist.objects.get( + uuid=checklist_uuid, + owner=user, + state=CheckListState.automation.name) - logger.debug("setChecklistDecisionsFromValMgr() checklist_uuid=%r, len(decisions)=%d", - checklist_uuid, len(decisions),) + logger.debug( + "setChecklistDecisionsFromValMgr() " + + "checklist_uuid=%r, len(decisions)=%d", + checklist_uuid, + len(decisions), + ) if ('error' in checklist_results_from_jenkins): el_role = Role.objects.get(name=Roles.el.name) @@ -469,23 +545,24 @@ class CheckListSvc(BaseSvc): Q(role=el_role) | Q(role=admin_role)) activity_data = TestFinishedActivityData( - el_admin_list, checklist.engagement, checklist_results_from_jenkins['error']) + el_admin_list, checklist.engagement, + checklist_results_from_jenkins['error']) bus_service.send_message(ActivityEventMessage(activity_data)) - msg = "test_finished signal from Jenkins has arrived with error: {}".format( - checklist_results_from_jenkins['error']) + msg = "test_finished signal from Jenkins has arrived with " +\ + "error: {}".format(checklist_results_from_jenkins['error']) logger.error(msg) set_state(True, checklist_uuid, isMoveToAutomation=False, description=checklist_results_from_jenkins['error']) raise Exception(msg) ChecklistLineItem.objects.filter(template=checklist.template).update( - line_type=CheckListLineType.manual.name) # @UndefinedVariable + line_type=CheckListLineType.manual.name) for decision in decisions: lineitem_obj = ChecklistLineItem.objects.get( uuid=decision['line_item_id']) - lineitem_obj.line_type = CheckListLineType.auto.name # @UndefinedVariable + lineitem_obj.line_type = CheckListLineType.auto.name lineitem_obj.save() decision_obj = ChecklistDecision.objects.get( @@ -493,16 +570,22 @@ class CheckListSvc(BaseSvc): setDecision(decisionUuid=decision_obj.uuid, user=user, value=decision['value']) - if (decision['audit_log_text'] != '' and decision['audit_log_text'] != None): - addAuditLogToDecision(decision=decision_obj, - description=decision['audit_log_text'], user=user, category='') + if (decision['audit_log_text'] != + '' and decision['audit_log_text'] is not None): + addAuditLogToDecision( + decision=decision_obj, + description=decision['audit_log_text'], + user=user, + category='') desc = "The {} validation test suite has completed. The decisions " +\ - "based on the test results have successfully been set in the " +\ + "based on the test results \ + have successfully been set in the " +\ "checklist.".format(checklist.template.category) addAuditLogToChecklist(checklist=checklist, description=desc, user=user, category='') - checklistData = ThinChecklistModelSerializer(checklist, many=False).data + checklistData = ThinChecklistModelSerializer( + checklist, many=False).data set_state(False, checklist.uuid, isMoveToAutomation=True, description="") diff --git a/django/engagementmanager/service/checklist_state_service.py b/django/engagementmanager/service/checklist_state_service.py index 1903c47..e20d673 100644 --- a/django/engagementmanager/service/checklist_state_service.py +++ b/django/engagementmanager/service/checklist_state_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -60,7 +60,7 @@ logger = LoggingServiceFactory.get_logger() def insert_to_recent_engagements(owner=None, action=None, vf=None): - if vf == None: + if not vf: # If VF wasn't supplied let's fetch it using checklist and # checklist.engagement checkListObj = Checklist.objects.get( @@ -75,28 +75,36 @@ def insert_to_recent_engagements(owner=None, action=None, vf=None): def description_creator(checklist, next_state, additional_comment=""): if additional_comment: - description = "The " + checklist.name + " checklist was changed to the " +\ + description = "The " + checklist.name + " \ + checklist was changed to the " +\ next_state.lower() + " state. " + "\n" +\ additional_comment else: - description = "The " + checklist.name + " checklist was changed to the " +\ + description = "The " + checklist.name + \ + " checklist was changed to the " +\ next_state.lower() + " state." return description ''' - If kwargs['isMoveToAutomation']==True than the CL will not be cloned but reverted to automation, else (False) will be cloned and returned in pending + If kwargs['isMoveToAutomation']==True than the CL will not be \ + cloned but reverted to automation, else (False) will be cloned \ + and returned in pending ''' -def set_state(decline, checklist_uuid, isMoveToAutomation=True, description=None): - logger.debug('set_state(decline=%r,checklist_uuid=%r,get_request_data_vars= %r)', - decline, checklist_uuid, request_data_mgr.get_request_data_vars()) +def set_state(decline, checklist_uuid, isMoveToAutomation=True, + description=None): + logger.debug('set_state(decline=%r,checklist_uuid=%r,\ + get_request_data_vars= %r)', + decline, checklist_uuid, + request_data_mgr.get_request_data_vars()) - if checklist_uuid != None: # was sent explicitly + if checklist_uuid: request_data_mgr.set_cl_uuid(checklist_uuid) - if any(x is None for x in [checklist_uuid, request_data_mgr.get_user(), description]): + if any(x is None for x in [checklist_uuid, + request_data_mgr.get_user(), description]): msg = "checklist uuid or user or description is None" logger.error(msg) msg = "checklist state wasn't change due to bad parameters" @@ -126,79 +134,97 @@ def set_state(decline, checklist_uuid, isMoveToAutomation=True, description=None raise KeyError(msg) # @UndefinedVariable - if checklist.state == CheckListState.closed.name or checklist.state == CheckListState.archive.name: - msg = "attempt to change state to the next one from 'closed'/'archive', no actions were made." + if checklist.state == CheckListState.closed.name or \ + checklist.state == CheckListState.archive.name: + msg = "attempt to change state to the next one \ + from 'closed'/'archive', no actions were made." logger.error(msg) - msg = "checklist's state is already closed/archive, can not move forward in states." + msg = "checklist's state is already closed/archive, \ + can not move forward in states." raise FileExistsError(msg) - elif decline and checklist.state != CheckListState.pending.name: # @UndefinedVariable + elif decline and checklist.state != CheckListState.pending.name: logger.debug( - 'set_state: decline and not pending -< about to set the state to ARCHIVE and duplicate the checklist') + 'set_state: decline and not pending -< about to set the \ + state to ARCHIVE and duplicate the checklist') set_state_to_archive(isMoveToAutomation, description) # @UndefinedVariable - return check_sts(checklist, request_data_mgr.get_user(), CheckListState.archive.name, additional_comment) + return check_sts(checklist, request_data_mgr.get_user(), + CheckListState.archive.name, additional_comment) elif checklist.state == CheckListState.pending.name: # @UndefinedVariable logger.debug('set_state: pending to automation') set_state_to_automation() # @UndefinedVariable - return check_sts(checklist, request_data_mgr.get_user(), CheckListState.automation.name, additional_comment) + return check_sts(checklist, request_data_mgr.get_user(), + CheckListState.automation.name, additional_comment) # this case is when getting a signal from VM that jenkins has finished all # tests - elif checklist.state == CheckListState.automation.name: # @UndefinedVariable + elif checklist.state == CheckListState.automation.name: logger.debug('set_state: automation to review') set_state_to_review(checklist) slack_client.send_notification_to_reviewer_when_automation_completes( engagement_manual_id, vf_name, reviewer, checklist_name) # @UndefinedVariable - return check_sts(checklist, request_data_mgr.get_user(), CheckListState.review.name, additional_comment) + return check_sts(checklist, request_data_mgr.get_user(), + CheckListState.review.name, additional_comment) - elif checklist.state == CheckListState.review.name: # @UndefinedVariable + elif checklist.state == CheckListState.review.name: logger.debug('set_state: review to peer review') set_state_to_peer_review() - slack_client.send_notification_to_peer_reviewer_when_the_review_completes( - engagement_manual_id, vf_name, reviewer, peer_reviewer, checklist_name) + slack_client.\ + send_notification_to_peer_reviewer_when_the_review_completes( + engagement_manual_id, vf_name, reviewer, peer_reviewer, + checklist_name) # @UndefinedVariable - return check_sts(checklist, request_data_mgr.get_user(), CheckListState.peer_review.name, additional_comment) + return check_sts(checklist, request_data_mgr.get_user(), + CheckListState.peer_review.name, additional_comment) - elif checklist.state == CheckListState.peer_review.name: # @UndefinedVariable + elif checklist.state == CheckListState.peer_review.name: logger.debug('set_state: peer review to approval') set_state_to_approval() admins = IceUserProfile.objects.filter(role__name=Roles.admin.name) - slack_client.send_notification_to_admins_when_the_peer_review_completes( - engagement_manual_id, vf_name, reviewer, peer_reviewer, admins, checklist_name) + slack_client.\ + send_notification_to_admins_when_the_peer_review_completes( + engagement_manual_id, + vf_name, reviewer, peer_reviewer, admins, + checklist_name) # @UndefinedVariable - return check_sts(checklist, request_data_mgr.get_user(), CheckListState.approval.name, additional_comment) + return check_sts(checklist, request_data_mgr.get_user(), + CheckListState.approval.name, additional_comment) - elif checklist.state == CheckListState.approval.name: # @UndefinedVariable + elif checklist.state == CheckListState.approval.name: logger.debug('set_state: approval to handoff') set_state_to_handoff() slack_client.send_notification_to_reviewer_when_approved( engagement_manual_id, vf_name, reviewer, checklist_name) # @UndefinedVariable - return check_sts(checklist, request_data_mgr.get_user(), CheckListState.handoff.name, additional_comment) + return check_sts(checklist, request_data_mgr.get_user(), + CheckListState.handoff.name, additional_comment) - elif checklist.state == CheckListState.handoff.name: # @UndefinedVariable + elif checklist.state == CheckListState.handoff.name: logger.debug('set_state: handoff to closed') set_state_to_closed() admins = IceUserProfile.objects.filter(role__name=Roles.admin.name) slack_client.send_notifications_when_closed( - engagement_manual_id, vf_name, reviewer, peer_reviewer, admins, checklist_name) + engagement_manual_id, vf_name, reviewer, peer_reviewer, + admins, checklist_name) # @UndefinedVariable - return check_sts(checklist, request_data_mgr.get_user(), CheckListState.closed.name, additional_comment) + return check_sts(checklist, request_data_mgr.get_user(), + CheckListState.closed.name, additional_comment) def duplicate_checklist_and_its_auditlogs(checklist, isMoveToAutomation): - ''' Create the basic duplicated checklist object based on the original one ''' + ''' Create the basic duplicated checklist + object based on the original one ''' newState = CheckListState.pending.name # @UndefinedVariable checklistDupObject = Checklist.objects.create( @@ -211,7 +237,8 @@ def duplicate_checklist_and_its_auditlogs(checklist, isMoveToAutomation): owner=checklist.creator, state=newState) - ''' Fetch all original cl audit logs and attach it to the duplicated one ''' + ''' Fetch all original cl audit logs and attach it to the \ + duplicated one ''' audits = ChecklistAuditLog.objects.filter(checklist=checklist) for item in audits: audit = addAuditLogToChecklist( @@ -219,37 +246,42 @@ def duplicate_checklist_and_its_auditlogs(checklist, isMoveToAutomation): if not audit: logger.error( - "duplicate_checklist_and_its_auditlogs: Failed to create a duplicated audit log in the DB") + "duplicate_checklist_and_its_auditlogs: Failed to \ + create a duplicated audit log in the DB") msg = "checklist state wasn't change" raise Exception(msg) ''' Fetch all original line items and attach it to the duplicated one ''' line_items_list = ChecklistLineItem.objects.filter( template=checklist.template) - # Implementation is based on space and performance aspect and not particularly one of them - #(could have just change the internal object's cl field to the new object and reset their values) for lineitem in line_items_list: old_decisions = ChecklistDecision.objects.filter( - lineitem=lineitem, checklist=checklist, template=checklist.template) + lineitem=lineitem, checklist=checklist, + template=checklist.template) if len(old_decisions) == 0: new_decision = ChecklistDecision.objects.create( - checklist=checklistDupObject, template=checklistDupObject.template, lineitem=lineitem) + checklist=checklistDupObject, + template=checklistDupObject.template, lineitem=lineitem) else: for decision in old_decisions: new_decision = ChecklistDecision.objects.create( - checklist=checklistDupObject, template=checklist.template, lineitem=lineitem) + checklist=checklistDupObject, + template=checklist.template, lineitem=lineitem) old_decision_auditlogs = ChecklistAuditLog.objects.filter( decision=decision) for audit in old_decision_auditlogs: audit = ChecklistAuditLog.objects.create( - decision=new_decision, description=audit.description, category='', creator=audit.creator) - - if isMoveToAutomation == True: # This is a scenario in which we send to VM cl_from_pending_to_automation_event + decision=new_decision, description=audit.description, + category='', creator=audit.creator) + # This is a scenario in which we send to VM + # cl_from_pending_to_automation_event + if isMoveToAutomation: logger.debug("Cloned Checklist is triggered as to automation") try: set_state_to_automation(checklistDupObject) except KeyError: - # delete new checklist since we don't want duplicate checklist while + # delete new checklist since + # we don't want duplicate checklist while # the other one is still not archived checklistDupObject.delete() @@ -258,9 +290,10 @@ def duplicate_checklist_and_its_auditlogs(checklist, isMoveToAutomation): def check_sts(checklist, user, next_state, additional_comment): description = description_creator( - checklist, next_state, additional_comment=additional_comment) # @UndefinedVariable + checklist, next_state, additional_comment=additional_comment) if not description: - msg = "failed to set the state to the next one due to invalid parameters." + msg = "failed to set the state to the next one due to \ + invalid parameters." raise ValueError(msg) addAuditLogToChecklist(checklist, description, user) return checklist @@ -271,22 +304,25 @@ def check_decision_meet_criterias(checkListObj, review_type): return True if review_type == 'review_value': - invalid_decisions = ChecklistDecision.objects.filter(Q(checklist=checkListObj) & - ( - Q(review_value=CheckListDecisionValue.na.name) - | Q(review_value=CheckListDecisionValue.denied.name) - )).count() # @UndefinedVariable + invalid_decisions = ChecklistDecision.objects.filter( + Q(checklist=checkListObj) & + ( + Q(review_value=CheckListDecisionValue.na.name) + | Q(review_value=CheckListDecisionValue.denied.name) + )).count() # @UndefinedVariable elif review_type == 'peer_review_value': - invalid_decisions = ChecklistDecision.objects.filter(Q(checklist=checkListObj) & - ( - Q(peer_review_value=CheckListDecisionValue.na.name) | - Q(peer_review_value=CheckListDecisionValue.denied.name) - )).count() # @UndefinedVariable + invalid_decisions = ChecklistDecision.objects.filter( + Q(checklist=checkListObj) & + ( + Q(peer_review_value=CheckListDecisionValue.na.name) | + Q(peer_review_value=CheckListDecisionValue.denied.name) + )).count() # @UndefinedVariable else: return True if invalid_decisions: - msg = "checklist state wasn't change, not all decisions are approved / na" + msg = "checklist state wasn't change, \ + not all decisions are approved / na" raise MethodNotAllowed(msg) @@ -305,22 +341,23 @@ def retrieve_checklist_object(cluuid): """ -This method is called when an EL / Peer Reviewer declines a CL or creates a Next step for them after declining a specific line item in the CL. +This method is called when an EL / Peer Reviewer declines a CL or \ +creates a Next step for them after declining a specific line item in the CL. """ @auth(Permissions.set_checklist_decision, is_internal=True) def set_state_to_archive(isMoveToAutomation=True, description=None): checkListObj = retrieve_checklist_and_its_decisions( - request_data_mgr.get_cl_uuid(), '') # @UndefinedVariable + request_data_mgr.get_cl_uuid(), '') rejection_description = description_creator( - checkListObj, CheckListState.archive.name, description) # @UndefinedVariable + checkListObj, CheckListState.archive.name, description) addAuditLogToChecklist( checkListObj, rejection_description, request_data_mgr.get_user()) checklistDupObject = duplicate_checklist_and_its_auditlogs( checkListObj, isMoveToAutomation) - checkListObj.state = CheckListState.archive.name # @UndefinedVariable + checkListObj.state = CheckListState.archive.name checkListObj.owner = checkListObj.creator checkListObj.update_time = timezone.now() @@ -331,25 +368,29 @@ def set_state_to_archive(isMoveToAutomation=True, description=None): def set_state_to_automation(checkListObj=None): if checkListObj is None: - checkListObj = retrieve_checklist_object(request_data_mgr.get_cl_uuid()) + checkListObj = retrieve_checklist_object( + request_data_mgr.get_cl_uuid()) - if checkListObj.associated_files == [] or not checkListObj.associated_files: + if checkListObj.associated_files == [] or not \ + checkListObj.associated_files: logger.error( - "set_state_to_automation failed: no files were found in the checkListObj.associated_file") - msg = "checklist state wasn't change, please add files to the checklist in order to start Automation state" + "set_state_to_automation failed: no files were \ + found in the checkListObj.associated_file") + msg = "checklist state wasn't change, please add files \ + to the checklist in order to start Automation state" raise KeyError(msg) originalState = checkListObj.state - checkListObj.state = CheckListState.automation.name # @UndefinedVariable + checkListObj.state = CheckListState.automation.name checkListObj.update_time = timezone.now() checkListObj.save() - if originalState == CheckListState.pending.name: # @UndefinedVariable + if originalState == CheckListState.pending.name: send_cl_from_pending_to_automation_event(checkListObj) def set_state_to_review(checkListObj): - checkListObj.state = CheckListState.review.name # @UndefinedVariable + checkListObj.state = CheckListState.review.name checkListObj.update_time = timezone.now() # set the owner to reviewer and update_or_insert_to_recent_engagements(...) @@ -359,15 +400,17 @@ def set_state_to_review(checkListObj): @auth(Permissions.el_review_checklist, is_internal=True) def set_state_to_peer_review(): """ - This method is called when EL approves a review and moves a CL to peer_review + This method is called when EL approves a review + and moves a CL to peer_review """ checkListObj = retrieve_checklist_and_its_decisions( - request_data_mgr.get_cl_uuid(), 'review_value') # @UndefinedVariable - checkListObj.state = CheckListState.peer_review.name # @UndefinedVariable + request_data_mgr.get_cl_uuid(), 'review_value') + checkListObj.state = CheckListState.peer_review.name checkListObj.owner = checkListObj.engagement.peer_reviewer insert_to_recent_engagements( - owner=checkListObj.owner, action=RecentEngagementActionType.GOT_OWNERSHIP_OVER_ENGAGEMENT.name) # @UndefinedVariable + owner=checkListObj.owner, + action=RecentEngagementActionType.GOT_OWNERSHIP_OVER_ENGAGEMENT.name) checkListObj.update_time = timezone.now() @@ -377,17 +420,19 @@ def set_state_to_peer_review(): @auth(Permissions.peer_review_checklist, is_internal=True) def set_state_to_approval(): """ - This method is called when Peer Reviewer approves a review and moves a CL to approval state + This method is called when Peer Reviewer approves a + review and moves a CL to approval state """ checkListObj = retrieve_checklist_and_its_decisions( - request_data_mgr.get_cl_uuid(), 'peer_review_value') # @UndefinedVariable - checkListObj.state = CheckListState.approval.name # @UndefinedVariable - admin_role = Role.objects.get(name=Roles.admin.name) # @UndefinedVariable + request_data_mgr.get_cl_uuid(), 'peer_review_value') + checkListObj.state = CheckListState.approval.name + admin_role = Role.objects.get(name=Roles.admin.name) admin_list = IceUserProfile.objects.all().filter( - role=admin_role) # @UndefinedVariable + role=admin_role) if admin_list.count() < 1: - logger.error("Failed to save the new state of the Checklist to the DB") + logger.error("Failed to save the new state \ + of the Checklist to the DB") msg = "checklist state wasn't change due to server error" raise Exception(msg) @@ -397,7 +442,8 @@ def set_state_to_approval(): checkListObj.update_time = timezone.now() checkListObj.owner = admin insert_to_recent_engagements( - owner=checkListObj.owner, action=RecentEngagementActionType.GOT_OWNERSHIP_OVER_ENGAGEMENT.name) # @UndefinedVariable + owner=checkListObj.owner, + action=RecentEngagementActionType.GOT_OWNERSHIP_OVER_ENGAGEMENT.name) checkListObj.save() @@ -405,15 +451,17 @@ def set_state_to_approval(): @auth(Permissions.admin_approve_checklist) def set_state_to_handoff(): """ - This method is called when an admin approves a CL and moves it to a handoff state + This method is called when an admin approves + a CL and moves it to a handoff state """ checkListObj = retrieve_checklist_and_its_decisions( request_data_mgr.get_cl_uuid(), '') - checkListObj.state = CheckListState.handoff.name # @UndefinedVariable + checkListObj.state = CheckListState.handoff.name checkListObj.owner = checkListObj.creator insert_to_recent_engagements( - owner=checkListObj.owner, action=RecentEngagementActionType.GOT_OWNERSHIP_OVER_ENGAGEMENT.name) # @UndefinedVariable + owner=checkListObj.owner, + action=RecentEngagementActionType.GOT_OWNERSHIP_OVER_ENGAGEMENT.name) checkListObj.update_time = timezone.now() @@ -423,11 +471,12 @@ def set_state_to_handoff(): @auth(Permissions.handoff_checklist) def set_state_to_closed(): """ - This method is called when an EL approves the handoff and moves the CL to closed state + This method is called when an EL approves the handoff + and moves the CL to closed state """ checkListObj = retrieve_checklist_and_its_decisions( request_data_mgr.get_cl_uuid(), '') - checkListObj.state = CheckListState.closed.name # @UndefinedVariable + checkListObj.state = CheckListState.closed.name checkListObj.owner = checkListObj.creator checkListObj.update_time = timezone.now() update_eng_validation_details(checkListObj) diff --git a/django/engagementmanager/service/cms/__init__.py b/django/engagementmanager/service/cms/__init__.py index 1726c13..16f81cb 100644 --- a/django/engagementmanager/service/cms/__init__.py +++ b/django/engagementmanager/service/cms/__init__.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. diff --git a/django/engagementmanager/service/cms/base_cms.py b/django/engagementmanager/service/cms/base_cms.py index 8625d88..4f7cdd5 100644 --- a/django/engagementmanager/service/cms/base_cms.py +++ b/django/engagementmanager/service/cms/base_cms.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. diff --git a/django/engagementmanager/service/cms/pages_service.py b/django/engagementmanager/service/cms/pages_service.py index ab6fc96..9dbc44f 100644 --- a/django/engagementmanager/service/cms/pages_service.py +++ b/django/engagementmanager/service/cms/pages_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -55,10 +55,12 @@ class CMSPagesService(BaseCms): def getPage(self, id): page = cms_client.get_page(id) - # Handling static files address (like images) to get the full address of the CMS static file: + # Handling static files address (like images) to get the full + # address of the CMS static file: if 'content' in page and page['content']: cmsAddress = re.sub('\/api/$', '', cms_client.api_url) - page['content'] = page['content'].replace('src="/static/media/', 'src="%s/static/media/' % cmsAddress) + page['content'] = page['content'].replace( + 'src="/static/media/', 'src="%s/static/media/' % cmsAddress) return page diff --git a/django/engagementmanager/service/cms/posts_service.py b/django/engagementmanager/service/cms/posts_service.py index 720f766..3121202 100644 --- a/django/engagementmanager/service/cms/posts_service.py +++ b/django/engagementmanager/service/cms/posts_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -51,8 +51,10 @@ class CMSPostsService(BaseCms): from_last_days_param = "" if (fromLastDays is not None and fromLastDays != ""): - from_last_days_param = (datetime.now() - timedelta(days=int(fromLastDays))).strftime('%Y-%m-%d') + from_last_days_param = (datetime.now() - timedelta( + days=int(fromLastDays))).strftime('%Y-%m-%d') - posts = cms_client.get_posts(offset, limit, category, from_last_days_param) + posts = cms_client.get_posts( + offset, limit, category, from_last_days_param) return posts diff --git a/django/engagementmanager/service/deploment_target_service.py b/django/engagementmanager/service/deploment_target_service.py index 69c5e6f..d0ca514 100644 --- a/django/engagementmanager/service/deploment_target_service.py +++ b/django/engagementmanager/service/deploment_target_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. diff --git a/django/engagementmanager/service/ecomp_service.py b/django/engagementmanager/service/ecomp_service.py index d151ac0..190f613 100644 --- a/django/engagementmanager/service/ecomp_service.py +++ b/django/engagementmanager/service/ecomp_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. diff --git a/django/engagementmanager/service/engagement_service.py b/django/engagementmanager/service/engagement_service.py index 628bc57..48cc728 100644 --- a/django/engagementmanager/service/engagement_service.py +++ b/django/engagementmanager/service/engagement_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -50,8 +50,8 @@ from engagementmanager.bus.messages.activity_event_message import \ from engagementmanager.slack_client.api import SlackClient from engagementmanager.models import VF, Engagement, RecentEngagement, \ EngagementStatus, VFC, IceUserProfile, Checklist -from engagementmanager.serializers import SuperThinIceUserProfileModelSerializer, \ - VFModelSerializerForSignal +from engagementmanager.serializers import \ + SuperThinIceUserProfileModelSerializer, VFModelSerializerForSignal from engagementmanager.utils.constants import Roles, EngagementStage, \ ChecklistDefaultNames from engagementmanager.utils.dates import parse_date @@ -71,13 +71,15 @@ def update_engagement_status(user, description, eng_status_uuid, engagement): status.description = description status.update_time = timezone.now() status.save() - msg = "Status was successfully updated with a for engagement with uuid: " + \ + msg = "Status was successfully updated " +\ + "with a for engagement with uuid: " + \ engagement.uuid logger.debug(msg) except RecentEngagement.DoesNotExist: EngagementStatus.objects.create( creator=user, description=description) - msg = "Status was successfully created with a for engagement with uuid: " + \ + msg = "Status was successfully created with a " +\ + "for engagement with uuid: " + \ engagement.uuid logger.debug(msg) @@ -85,18 +87,19 @@ def update_engagement_status(user, description, eng_status_uuid, engagement): def insert_engagement_status(user, description, engagement): created_eng = EngagementStatus.objects.create( creator=user, description=description, engagement=engagement) - msg = "Status was successfully created with a for engagement with uuid: " + \ - engagement.uuid + msg = "Status was successfully created \ + with a for engagement with uuid: " + engagement.uuid logger.debug(msg) return created_eng -def update_or_insert_to_recent_engagements(original_user_uuid, vf, action_type): +def update_or_insert_to_recent_engagements( + original_user_uuid, vf, action_type): try: user_uuid = '' try: user_uuid = original_user_uuid.urn[9:] - except: + except BaseException: user_uuid = original_user_uuid recent_engs = RecentEngagement.objects.filter( user_uuid=user_uuid, vf=vf.uuid).order_by('-last_update') @@ -109,23 +112,28 @@ def update_or_insert_to_recent_engagements(original_user_uuid, vf, action_type): if (recent_eng.action_type != action_type): recent_eng.action_type = action_type recent_eng.last_update = timezone.now() - msg = "Recent engagement table was successfully updated the row for a user with uuid: " + \ + msg = "Recent engagement table was successfully updated " +\ + "the row for a user with uuid: " + \ user_uuid + " and vf uuid: " + vf.uuid + \ "with a new action type: " + action_type logger.debug(msg) recent_eng.save() else: recent_eng.last_update = timezone.now() - msg = "Recent engagement table was successfully updated the last_update row for a user with uuid: " + \ + msg = "Recent engagement table was successfully updated " +\ + "the last_update row for a user with uuid: " + \ user_uuid + " and vf uuid: " + vf.uuid logger.debug(msg) recent_eng.save() RecentEngagement.objects.filter( - last_update__lt=datetime.now() - timedelta(days=settings.RECENT_ENG_TTL)).delete() + last_update__lt=datetime.now() - + timedelta( + days=settings.RECENT_ENG_TTL)).delete() except RecentEngagement.DoesNotExist: RecentEngagement.objects.create( user_uuid=user_uuid, vf=vf, action_type=action_type) - msg = "Recent engagement table was successfully updated with a new row for a user with uuid: " + \ + msg = "Recent engagement table was successfully updated " +\ + "with a new row for a user with uuid: " + \ str(user_uuid) + " and vf uuid: " + str(vf.uuid) logger.debug(msg) @@ -135,13 +143,18 @@ def get_dashboard_expanded_engs(stage, keyword, offset, limit, user): Expecting: stage: one of the choices in the defined constants. keyword: string - offset: non-negative number to start the pull from them + 9 (Negative indexing (i.e. Entry.objects.all()[-1]) is not supported - according to Django 21.12.16). + offset: non-negative number to start the pull from them + 9 + (Negative indexing (i.e. Entry.objects.all()[-1]) is not + supported - according to Django 21.12.16). user: user object of the requesting client. Result: Query-set of engs that match the parameters provided (10 objects). """ - engStageList = [EngagementStage.Intake.name, EngagementStage.Active.name, - EngagementStage.Validated.name, EngagementStage.Completed.name] # @UndefinedVariable + engStageList = [ + EngagementStage.Intake.name, + EngagementStage.Active.name, + EngagementStage.Validated.name, + EngagementStage.Completed.name] # @UndefinedVariable q_object = Q() q_vfc_object = Q() @@ -160,14 +173,16 @@ def get_dashboard_expanded_engs(stage, keyword, offset, limit, user): q_vfc_object &= Q(vf__engagement__engagement_stage=stage) # @UndefinedVariable - if (user.role.name != Roles.admin.name and user.role.name != Roles.admin_ro.name): + if (user.role.name != Roles.admin.name and + user.role.name != Roles.admin_ro.name): q_object &= Q(engagement__engagement_team__uuid=user.uuid) q_vfc_object &= Q(vf__engagement__engagement_team__uuid=user.uuid) vf_list_uuids = VF.objects.filter(q_object).values_list( 'uuid', flat=True).order_by('engagement__target_completion_date') vfc_vflist_uuids = VFC.objects.filter(q_vfc_object).values_list( - 'vf__uuid', flat=True).order_by('vf__engagement__target_completion_date') + 'vf__uuid', flat=True).order_by( + 'vf__engagement__target_completion_date') vf_list_uuids = OrderedSet(vf_list_uuids) for current_vf in OrderedSet(vfc_vflist_uuids): @@ -175,33 +190,37 @@ def get_dashboard_expanded_engs(stage, keyword, offset, limit, user): num_of_objects = len(vf_list_uuids) vf_final_array = [] - vf_list = VF.objects.filter(uuid__in=vf_list_uuids)\ - .annotate(vf__name=F('name'), vendor__name=F('vendor__name'), - )\ - .values( - 'vf__name', - 'version', - 'deployment_target__version', - 'engagement__peer_reviewer__uuid', - 'ecomp_release__name', - 'engagement__engagement_stage', - 'engagement__engagement_manual_id', - 'engagement__uuid', - 'engagement__heat_validated_time', - 'engagement__image_scan_time', - 'engagement__aic_instantiation_time', - 'engagement__asdc_onboarding_time', - 'engagement__target_completion_date', - 'engagement__progress', - 'target_lab_entry_date', - 'engagement__started_state_time', - 'vendor__name', - 'engagement__validated_time', - 'engagement__completed_time', - 'uuid' - )\ - .annotate(vf_uuid_count=Count('uuid', distinct=True))\ - .order_by('engagement__target_completion_date')[int(offset):int(offset) + limit] + vf_list = VF.objects.filter( + uuid__in=vf_list_uuids) .annotate( + vf__name=F('name'), + vendor__name=F('vendor__name'), + ) .values( + 'vf__name', + 'version', + 'deployment_target__version', + 'engagement__peer_reviewer__uuid', + 'ecomp_release__name', + 'engagement__engagement_stage', + 'engagement__engagement_manual_id', + 'engagement__uuid', + 'engagement__heat_validated_time', + 'engagement__image_scan_time', + 'engagement__aic_instantiation_time', + 'engagement__asdc_onboarding_time', + 'engagement__target_completion_date', + 'engagement__progress', + 'target_lab_entry_date', + 'engagement__started_state_time', + 'vendor__name', + 'engagement__validated_time', + 'engagement__completed_time', + 'uuid') .annotate( + vf_uuid_count=Count( + 'uuid', + distinct=True)) .order_by( + 'engagement__target_completion_date')[ + int(offset):int(offset) + + limit] for current_vf in vf_list: eng = Engagement.objects.get(uuid=current_vf['engagement__uuid']) starred_users = eng.starred_engagement.all() @@ -257,7 +276,8 @@ def get_expanded_engs_for_export(stage, keyword, user): def is_eng_stage_eql_to_requested_one(engagement, requested_stage): if engagement.engagement_stage == requested_stage: - msg = "An attempt to change the Engagement's stage (uuid: " + engagement.uuid + \ + msg = "An attempt to change the Engagement's stage (uuid: " + \ + engagement.uuid + \ ") to the same stage it is current in(" + \ engagement.engagement_stage + ") was made." logger.debug(msg) @@ -275,6 +295,8 @@ def set_engagement_stage(eng_uuid, stage): engagement.engagement_stage = stage engagement.intake_time = timezone.now() engagement.save() + logger.debug("Engagement's stage was modified in DB to: %s" % stage) + logger.debug("firing an event to gitlab") vm_client.fire_event_in_bg('send_provision_new_vf_event', vfObj) msg = send_notifications_and_create_activity_after_eng_stage_update( engagement) @@ -286,22 +308,27 @@ def send_notifications_and_create_activity_after_eng_stage_update(engagement): res = get_engagement_manual_id_and_vf_name(engagement) slack_client = SlackClient() slack_client.update_for_change_of_the_engagement_stage( - res['engagement_manual_id'], res['vf_name'], engagement.engagement_stage) + res['engagement_manual_id'], res['vf_name'], + engagement.engagement_stage) - activity_data = ChangeEngagementStageActivityData(VF.objects.get(engagement=engagement), engagement.engagement_stage, - engagement) + activity_data = ChangeEngagementStageActivityData(VF.objects.get( + engagement=engagement), engagement.engagement_stage, engagement) from engagementmanager.apps import bus_service bus_service.send_message(ActivityEventMessage(activity_data)) - logger.debug("Engagement's stage (eng_uuid: " + engagement.uuid + ") was successfully changed to: " - + engagement.engagement_stage) + logger.debug( + "Engagement's stage (eng_uuid: " + + engagement.uuid + + ") was successfully changed to: " + + engagement.engagement_stage) return "OK" def set_progress_for_engagement(progress=None): prog = int(progress) if prog < 0 or prog > 100: - msg = 'set_progress_for_engagement failed: Progress value is invalid (out of bounds). Should be 0-100' + msg = 'set_progress_for_engagement failed: Progress ' +\ + 'value is invalid (out of bounds). Should be 0-100' logger.debug(msg) raise ValueError(msg) else: @@ -311,29 +338,35 @@ def set_progress_for_engagement(progress=None): def vf_retreiver(user, star=False, recent=False, eng_uuid=""): - engStageList = [EngagementStage.Intake.name, EngagementStage.Active.name, - EngagementStage.Validated.name, EngagementStage.Completed.name] # @UndefinedVariable + engStageList = [ + EngagementStage.Intake.name, + EngagementStage.Active.name, + EngagementStage.Validated.name, + EngagementStage.Completed.name] # @UndefinedVariable - if (user.role.name == Roles.admin.name or user.role.name == Roles.admin_ro.name): + if (user.role.name == Roles.admin.name or + user.role.name == Roles.admin_ro.name): if star: - vf_list = VF.objects.filter(engagement__engagement_stage__in=engStageList)\ - .filter(engagement__starred_engagement__uuid=user.uuid).distinct().order_by('engagement__engagement_manual_id')\ - .values( - 'uuid', - 'name', - 'is_service_provider_internal', - 'engagement__creator__uuid', - 'engagement__engagement_manual_id', - 'engagement__peer_reviewer__uuid', - 'engagement__peer_reviewer__email', - 'engagement__reviewer__uuid', - 'engagement__reviewer__email', - 'engagement__uuid' - ) + vf_list = VF.objects.filter( + engagement__engagement_stage__in=engStageList) .filter( + engagement__starred_engagement__uuid=user.uuid).\ + distinct().order_by( + 'engagement__engagement_manual_id') .values( + 'uuid', + 'name', + 'is_service_provider_internal', + 'engagement__creator__uuid', + 'engagement__engagement_manual_id', + 'engagement__peer_reviewer__uuid', + 'engagement__peer_reviewer__email', + 'engagement__reviewer__uuid', + 'engagement__reviewer__email', + 'engagement__uuid') for vf in vf_list: red_dot_activity = RecentEngagement.objects.filter( - vf=vf['uuid']).values('action_type').order_by('-last_update')[:1] + vf=vf['uuid']).values( + 'action_type').order_by('-last_update')[:1] if (red_dot_activity.count() > 0): vf['action_type'] = red_dot_activity[0]['action_type'] else: @@ -342,9 +375,10 @@ def vf_retreiver(user, star=False, recent=False, eng_uuid=""): return vf_list elif recent: - recent = RecentEngagement.objects.filter(vf__engagement__engagement_stage__in=engStageList)\ - .filter(user_uuid=user.uuid).distinct().order_by('-last_update')\ - .values( + recent = RecentEngagement.objects.filter( + vf__engagement__engagement_stage__in=engStageList) .filter( + user_uuid=user.uuid).distinct().order_by( + '-last_update') .values( 'vf__uuid', 'vf__name', 'vf__is_service_provider_internal', @@ -356,29 +390,31 @@ def vf_retreiver(user, star=False, recent=False, eng_uuid=""): 'vf__engagement__reviewer__email', 'vf__engagement__uuid', 'action_type', - 'last_update' - )[:20] + 'last_update')[ + :20] return recent else: if eng_uuid != "": - vf_list = VF.objects.filter(engagement__engagement_stage__in=engStageList)\ - .filter(engagement__uuid=eng_uuid).distinct().order_by('engagement__engagement_manual_id')\ - .values( - 'uuid', - 'name', - 'is_service_provider_internal', - 'engagement__creator__uuid', - 'engagement__engagement_manual_id', - 'engagement__peer_reviewer__uuid', - 'engagement__peer_reviewer__email', - 'engagement__reviewer__uuid', - 'engagement__reviewer__email', - 'engagement__uuid' - ) + vf_list = VF.objects.filter( + engagement__engagement_stage__in=engStageList) .filter( + engagement__uuid=eng_uuid).distinct().order_by( + 'engagement__engagement_manual_id') .values( + 'uuid', + 'name', + 'is_service_provider_internal', + 'engagement__creator__uuid', + 'engagement__engagement_manual_id', + 'engagement__peer_reviewer__uuid', + 'engagement__peer_reviewer__email', + 'engagement__reviewer__uuid', + 'engagement__reviewer__email', + 'engagement__uuid') else: - vf_list = VF.objects.filter(engagement__engagement_stage__in=engStageList)\ - .filter().distinct().order_by('engagement__engagement_manual_id')\ + vf_list = VF.objects.filter( + engagement__engagement_stage__in=engStageList)\ + .filter().distinct().order_by( + 'engagement__engagement_manual_id')\ .values( 'uuid', 'name', @@ -396,8 +432,15 @@ def vf_retreiver(user, star=False, recent=False, eng_uuid=""): else: if star: if eng_uuid != "": - vf_list = VF.objects.filter(engagement__engagement_stage__in=engStageList)\ - .filter(Q(engagement__uuid=eng_uuid, engagement__engagement_team__uuid=user.uuid, engagement__starred_engagement__uuid=user.uuid) | Q(engagement__uuid=eng_uuid, engagement__peer_reviewer=user, engagement__starred_engagement__uuid=user.uuid))\ + vf_list = VF.objects.filter( + engagement__engagement_stage__in=engStageList) .filter( + Q( + engagement__uuid=eng_uuid, + engagement__engagement_team__uuid=user.uuid, + engagement__starred_engagement__uuid=user.uuid) | Q( + engagement__uuid=eng_uuid, + engagement__peer_reviewer=user, + engagement__starred_engagement__uuid=user.uuid)) \ .values( 'uuid', 'name', @@ -408,12 +451,17 @@ def vf_retreiver(user, star=False, recent=False, eng_uuid=""): 'engagement__peer_reviewer__email', 'engagement__reviewer__uuid', 'engagement__reviewer__email', - 'engagement__uuid' - ) + 'engagement__uuid') else: - vf_list = VF.objects.filter(engagement__engagement_stage__in=engStageList)\ - .filter(Q(engagement__engagement_team__uuid=user.uuid, engagement__starred_engagement__uuid=user.uuid) | Q(engagement__peer_reviewer=user, engagement__starred_engagement__uuid=user.uuid)).distinct().order_by('engagement__engagement_manual_id')\ - .values( + vf_list = VF.objects.filter( + engagement__engagement_stage__in=engStageList) .filter( + Q( + engagement__engagement_team__uuid=user.uuid, + engagement__starred_engagement__uuid=user.uuid) | Q( + engagement__peer_reviewer=user, + engagement__starred_engagement__uuid=user.uuid)).\ + distinct().order_by( + 'engagement__engagement_manual_id') .values( 'uuid', 'name', 'is_service_provider_internal', @@ -423,11 +471,11 @@ def vf_retreiver(user, star=False, recent=False, eng_uuid=""): 'engagement__peer_reviewer__email', 'engagement__reviewer__uuid', 'engagement__reviewer__email', - 'engagement__uuid' - ) + 'engagement__uuid') for vf in vf_list: red_dot_activity = RecentEngagement.objects.filter( - vf=vf['uuid']).values('action_type').order_by('-last_update')[:1] + vf=vf['uuid']).values( + 'action_type').order_by('-last_update')[:1] if (red_dot_activity.count() > 0): vf['action_type'] = red_dot_activity[0]['action_type'] else: @@ -436,28 +484,38 @@ def vf_retreiver(user, star=False, recent=False, eng_uuid=""): return vf_list elif recent: - recent = RecentEngagement.objects.filter(vf__engagement__engagement_stage__in=engStageList)\ - .filter(Q(user_uuid=user.uuid, vf__engagement__engagement_team__uuid=user.uuid) | Q(user_uuid=user.uuid, vf__engagement__peer_reviewer=user)).distinct().order_by('-last_update')\ - .values( - 'vf__uuid', - 'vf__name', - 'vf__is_service_provider_internal', - 'vf__engagement__creator__uuid', - 'vf__engagement__engagement_manual_id', - 'vf__engagement__peer_reviewer__uuid', - 'vf__engagement__peer_reviewer__email', - 'vf__engagement__reviewer__uuid', - 'vf__engagement__reviewer__email', - 'vf__engagement__uuid', - 'action_type', - 'last_update' - )[:20] + recent = RecentEngagement.objects.filter( + vf__engagement__engagement_stage__in=engStageList) .filter( + Q( + user_uuid=user.uuid, + vf__engagement__engagement_team__uuid=user.uuid) | Q( + user_uuid=user.uuid, + vf__engagement__peer_reviewer=user)).distinct().order_by( + '-last_update') .values( + 'vf__uuid', + 'vf__name', + 'vf__is_service_provider_internal', + 'vf__engagement__creator__uuid', + 'vf__engagement__engagement_manual_id', + 'vf__engagement__peer_reviewer__uuid', + 'vf__engagement__peer_reviewer__email', + 'vf__engagement__reviewer__uuid', + 'vf__engagement__reviewer__email', + 'vf__engagement__uuid', + 'action_type', + 'last_update')[ + :20] return recent else: if eng_uuid != "": - vf_list = VF.objects.filter(engagement__engagement_stage__in=engStageList)\ - .filter(Q(engagement__uuid=eng_uuid, engagement__engagement_team__uuid=user.uuid) | Q(engagement__uuid=eng_uuid, engagement__peer_reviewer=user)).distinct().order_by('engagement__engagement_manual_id')\ - .values( + vf_list = VF.objects.filter( + engagement__engagement_stage__in=engStageList) .filter( + Q( + engagement__uuid=eng_uuid, + engagement__engagement_team__uuid=user.uuid) | Q( + engagement__uuid=eng_uuid, + engagement__peer_reviewer=user)).distinct().order_by( + 'engagement__engagement_manual_id') .values( 'uuid', 'name', 'is_service_provider_internal', @@ -467,12 +525,14 @@ def vf_retreiver(user, star=False, recent=False, eng_uuid=""): 'engagement__peer_reviewer__email', 'engagement__reviewer__uuid', 'engagement__reviewer__email', - 'engagement__uuid' - ) + 'engagement__uuid') else: - vf_list = VF.objects.filter(engagement__engagement_stage__in=engStageList)\ - .filter(Q(engagement__engagement_team__uuid=user.uuid) | Q(engagement__peer_reviewer=user)).distinct().order_by('engagement__engagement_manual_id')\ - .values( + vf_list = VF.objects.filter( + engagement__engagement_stage__in=engStageList) .filter( + Q( + engagement__engagement_team__uuid=user.uuid) | Q( + engagement__peer_reviewer=user)).distinct().order_by( + 'engagement__engagement_manual_id') .values( 'uuid', 'name', 'is_service_provider_internal', @@ -482,8 +542,7 @@ def vf_retreiver(user, star=False, recent=False, eng_uuid=""): 'engagement__peer_reviewer__email', 'engagement__reviewer__uuid', 'engagement__reviewer__email', - 'engagement__uuid' - ) + 'engagement__uuid') return vf_list @@ -557,7 +616,11 @@ def set_engagement_reviewer(eng_uuid, reviewer_uuid): res = get_engagement_manual_id_and_vf_name(engagement) slack_client = SlackClient() slack_client.update_reviewer_or_peer_reviewer( - res['engagement_manual_id'], res['vf_name'], reviewer, old_reviewer, 'reviewer') + res['engagement_manual_id'], + res['vf_name'], + reviewer, + old_reviewer, + 'reviewer') result = reviewer else: @@ -588,7 +651,11 @@ def set_engagement_peer_reviewer(eng_uuid, peer_reviewer_uuid): res = get_engagement_manual_id_and_vf_name(engagement) slack_client = SlackClient() slack_client.update_reviewer_or_peer_reviewer( - res['engagement_manual_id'], res['vf_name'], peer_reviewer, old_peer_reviewer, 'peer reviewer') + res['engagement_manual_id'], + res['vf_name'], + peer_reviewer, + old_peer_reviewer, + 'peer reviewer') result = peer_reviewer else: @@ -605,7 +672,8 @@ def switch_engagement_reviewers(eng_uuid, reviewer_uuid, peer_reviewer_uuid): old_reviewer = engagement.reviewer checklist_owners = Checklist.objects.filter( - Q(engagement__uuid=eng_uuid) & (Q(owner=old_reviewer) | Q(owner=old_peer_reviewer))) + Q(engagement__uuid=eng_uuid) & ( + Q(owner=old_reviewer) | Q(owner=old_peer_reviewer))) for checklist in checklist_owners: if checklist.owner == reviewer: @@ -622,9 +690,17 @@ def switch_engagement_reviewers(eng_uuid, reviewer_uuid, peer_reviewer_uuid): res = get_engagement_manual_id_and_vf_name(engagement) slack_client = SlackClient() slack_client.update_reviewer_or_peer_reviewer( - res['engagement_manual_id'], res['vf_name'], reviewer, old_reviewer, 'reviewer') + res['engagement_manual_id'], + res['vf_name'], + reviewer, + old_reviewer, + 'reviewer') slack_client.update_reviewer_or_peer_reviewer( - res['engagement_manual_id'], res['vf_name'], peer_reviewer, old_peer_reviewer, 'peer reviewer') + res['engagement_manual_id'], + res['vf_name'], + peer_reviewer, + old_peer_reviewer, + 'peer reviewer') return {"reviewer": reviewer_uuid, "peerreviewer": peer_reviewer_uuid} @@ -666,24 +742,32 @@ def update_engagement(engagement_dict): def remove_user_from_engagement_team(eng_uuid, user, removed_user_uuid): msg = "User was successfully removed from the engagement team" # @UndefinedVariable - if ((removed_user_uuid == user.uuid) or (removed_user_uuid != user.uuid and (user.role.name == Roles.admin.name or user.role.name == Roles.el.name))): + if ((removed_user_uuid == user.uuid) or + (removed_user_uuid != user.uuid and ( + user.role.name == Roles.admin.name or + user.role.name == Roles.el.name))): engagement = Engagement.objects.get(uuid=eng_uuid) requested_user = IceUserProfile.objects.get(uuid=removed_user_uuid) - if (engagement.peer_reviewer == requested_user or engagement.reviewer == requested_user - or engagement.creator == requested_user or engagement.contact_user == requested_user): - msg = "Reviewer/Peer Reviewer/Creator/Contact user cannot be removed from engagement team." + if (engagement.peer_reviewer == requested_user or + engagement.reviewer == requested_user + or engagement.creator == requested_user or + engagement.contact_user == requested_user): + msg = "Reviewer/Peer Reviewer/Creator/Contact " +\ + "user cannot be removed from engagement team." logger.error(msg) raise PermissionDenied engagement.engagement_team.remove(requested_user) engagement.save() logger.debug(msg) else: - msg = "removed user is not equal to conducting user or user is not an admin." + msg = "removed user is not equal to conducting " +\ + "user or user is not an admin." logger.error(msg) raise PermissionDenied def update_eng_validation_details(cl): setattr(cl.engagement, - ChecklistDefaultNames.VALIDATION_DATE_ARRAY[cl.name], timezone.now()) + ChecklistDefaultNames.VALIDATION_DATE_ARRAY[cl.name], + timezone.now()) cl.engagement.save() diff --git a/django/engagementmanager/service/invite_service.py b/django/engagementmanager/service/invite_service.py index c4780fd..b22a27d 100644 --- a/django/engagementmanager/service/invite_service.py +++ b/django/engagementmanager/service/invite_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -52,36 +52,46 @@ from engagementmanager.service.logging_service import LoggingServiceFactory logger = LoggingServiceFactory.get_logger() -def enforce_invitation_throttling(eng_uuid, invited_email, inviterUser, invitedUser): +def enforce_invitation_throttling(eng_uuid, invited_email, + inviterUser, invitedUser): assert eng_uuid is not None assert invited_email is not None - invitation = Invitation.objects.filter(engagement_uuid=eng_uuid, email=invited_email) + invitation = Invitation.objects.filter( + engagement_uuid=eng_uuid, email=invited_email) if len(invitation) > 0: - logger.warn("Oops, looks like an invitation with following details already exists: " + str(invitation)) + logger.warn( + "Oops, looks like an invitation with " + + "following details already exists: " + + str(invitation)) return False - if ((invitedUser != None and invitedUser.role.name != Roles.admin.name and - invitedUser.role.name != Roles.el.name) or invitedUser == None): - numOfInvitationinLast24H = Invitation.objects.filter(email=invited_email, - create_time__gte=datetime.now() - timedelta( - hours=24)).count() + if (not invitedUser or ( + not invitedUser and invitedUser.role.name != + Roles.admin.name and invitedUser.role.name != Roles.el.name)): + numOfInvitationinLast24H = Invitation.objects.filter( + email=invited_email, + create_time__gte=datetime.now() - timedelta( + hours=24)).count() if numOfInvitationinLast24H >= 5: logger.warn( - "Oops, looks like invited email (" + invited_email + ") which isn't EL nor admin has reached its " - "max invitations (5) in the last 24 hours") + "Oops, looks like invited email (" + invited_email + + ") which isn't EL nor admin has reached its " + "max invitations (5) in the last 24 hours") return False - if ((invitedUser != None and invitedUser.role.name == Roles.standard_user.name) or - (invitedUser != None and invitedUser.role.name == Roles.admin_ro.name) or - invitedUser == None): - numOfInvitationinLast24H = Invitation.objects.filter(invited_by_user_uuid=inviterUser.uuid, - create_time__gte=datetime.now() - timedelta( - hours=24)).count() + if ((invitedUser and invitedUser.role.name == Roles.standard_user.name) or + (invitedUser and invitedUser.role.name == Roles.admin_ro.name) or + invitedUser is None): + numOfInvitationinLast24H = Invitation.objects.filter( + invited_by_user_uuid=inviterUser.uuid, + create_time__gte=datetime.now() - timedelta( + hours=24)).count() if numOfInvitationinLast24H >= 25: logger.warn( "Oops, looks like a standard-user/admin-readonly inviter " - "(" + inviterUser.email + ") has reached its max invitations (25) in the last 24 hours") + "(" + inviterUser.email + ") has reached its max invitations" + + "(25) in the last 24 hours") return False return True @@ -92,27 +102,35 @@ def generateInviteMail(data, inviterUser, invitedUser, is_contact_user): data['vf_name'] = vf.name else: data['vf_name'] = "-" - logger.error("Couldn't fetch VF by engagement uuid=" + logEncoding(data['eng_uuid'])) + logger.error("Couldn't fetch VF by engagement uuid=" + + logEncoding(data['eng_uuid'])) body = get_template("{invite_template_dir}invite_mail_body.html".format( invite_template_dir=Constants.invite_template_dir)) - subject = get_template("{invite_template_dir}invite_mail_subject.html".format( - invite_template_dir=Constants.invite_template_dir)) + subject = get_template( + "{invite_template_dir}invite_mail_subject.html".format( + invite_template_dir=Constants.invite_template_dir)) data['dashboard_link'] = str(settings.DOMAIN) + "/#/dashboard/" - invitation = Invitation.objects.create(engagement_uuid=data['eng_uuid'], - invited_by_user_uuid=inviterUser.uuid, email=data['email'], - invitation_token=uuid4()) + invitation = Invitation.objects.create( + engagement_uuid=data['eng_uuid'], + invited_by_user_uuid=inviterUser.uuid, email=data['email'], + invitation_token=uuid4()) if invitedUser is not None: - data['invite_link'] = str(settings.DOMAIN) + "/#/login?invitation=" + str(invitation.invitation_token) - data['instruction'] = "To accept this invitation, please click this link:" - logger.debug("Invited Contact with email " + data['email'] + "already exist in the DB. Sending them an email " - "with link to login page. link=" + data[ + data['invite_link'] = str( + settings.DOMAIN) + "/#/login?invitation="\ + + str(invitation.invitation_token) + data['instruction'] = "To accept this invitation, \ + please click this link:" + logger.debug("Invited Contact with email " + data['email'] + + "already exist in the DB. Sending them an email " + "with link to login page. link=" + data[ 'invite_link']) if is_contact_user: logger.debug("Updating the Engagement with uuid=" + data[ - 'eng_uuid'] + " to have this contact user: " + invitedUser.full_name) + 'eng_uuid'] + " to have this contact user: " + + invitedUser.full_name) engObj = Engagement.objects.get(uuid=data['eng_uuid']) engObj.contact_user = invitedUser engObj.save() @@ -121,21 +139,27 @@ def generateInviteMail(data, inviterUser, invitedUser, is_contact_user): prefix = str(settings.DOMAIN) + "/#/signUp?invitation=" + \ str(invitation.invitation_token) + "&email=" + data['email'] suffix = "" - if 'full_name' in data and data['full_name'] and 'phone_number' in data and data['phone_number']: - suffix += "&full_name=" + data['full_name'] + "&phone_number=" + data['phone_number'] + if 'full_name' in data and data['full_name'] and \ + 'phone_number' in data and data['phone_number']: + suffix += "&full_name=" + \ + data['full_name'] + "&phone_number=" + data['phone_number'] if data.get('company'): suffix += "&company=" + data['company'] data['invite_link'] = prefix + suffix - data['instruction'] = "To create an account and accept this invitation, please click this link:" + data['instruction'] = "To create an account and accept this " +\ + "invitation, please click this link:" if is_contact_user: data['invite_link'] += "&is_contact_user=true" - logger.debug("The invite mail is sent to a contact person (VF Contact or " - + Constants.service_provider_company_name + " Sponsor)") + logger.debug("The invite mail is sent to a contact " + "person (VF Contact or " + + Constants.service_provider_company_name + + " Sponsor)") logger.debug( - "Invited Person doesn't exists, sending them an email with link to signup. link=" + data['invite_link']) + "Invited Person doesn't exists, sending them an email " + + "with link to signup. link=" + data['invite_link']) return body, subject, invitation @@ -151,23 +175,27 @@ def inviteUserToSignUpOrLogin(inviterUser, data, is_contact_user): if len(rs) > 0: invitedUser = IceUserProfile.objects.get(email=data['email']) - is_invite_ok = enforce_invitation_throttling(data['eng_uuid'], data['email'], inviterUser, invitedUser) + is_invite_ok = enforce_invitation_throttling( + data['eng_uuid'], data['email'], inviterUser, invitedUser) - if is_invite_ok == False: + if not is_invite_ok: msg = "Invite couldn't be created" logger.error(msg) raise VvpBadRequest(msg) - body, subject, invitation = generateInviteMail(data, inviterUser, invitedUser, is_contact_user) + body, subject, invitation = generateInviteMail( + data, inviterUser, invitedUser, is_contact_user) try: mail.sendMail(data['email'], data, body, subject) except Exception as e: logger.error(e) - msg = "Something went wrong while trying to send mail to " + data['email'] + " from " + inviterUser.email + msg = "Something went wrong while trying to send mail to " + \ + data['email'] + " from " + inviterUser.email logger.error(msg) if invitation: - logger.error("Rolling back the invitation (" + invitation + ") due to problems in sending its mail") + logger.error("Rolling back the invitation (" + + invitation + ") due to problems in sending its mail") invitation.delete() raise Exception(msg) diff --git a/django/engagementmanager/service/logging_service.py b/django/engagementmanager/service/logging_service.py index b90bdbf..7136774 100644 --- a/django/engagementmanager/service/logging_service.py +++ b/django/engagementmanager/service/logging_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. diff --git a/django/engagementmanager/service/login_service.py b/django/engagementmanager/service/login_service.py index 7216b56..6388e1e 100644 --- a/django/engagementmanager/service/login_service.py +++ b/django/engagementmanager/service/login_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -74,14 +74,19 @@ class LoginSvc(BaseSvc): raise PermissionDenied(msg) return user - def reset_password(self, reset_password_email, i_password, msg, user_profile): + def reset_password(self, reset_password_email, i_password, + msg, user_profile): token_user = self.get_user_by_email(reset_password_email) if user_profile.user.id != token_user.id: - msg = self.render_user_conflict_message(user_profile.user, token_user) + msg = self.render_user_conflict_message( + user_profile.user, token_user) temp_encrypted_password = user_profile.user.temp_password - is_temp_password_ok = check_password(i_password, temp_encrypted_password) + is_temp_password_ok = check_password( + i_password, temp_encrypted_password) if is_temp_password_ok: - self.logger.debug("Temporary Passwords match... Checking temporary password expiration") + self.logger.debug( + "Temporary Passwords match...\ + Checking temporary password expiration") else: msg = "User or Password does not match" self.logger.error(msg + " in Reset Password flow") @@ -90,7 +95,8 @@ class LoginSvc(BaseSvc): def render_user_conflict_message(self, user, user_from_token): msg = "User Conflict" - self.logger.error(msg + ". user uuid =" + user.id + ", user from token uuid=" + user_from_token.id) + self.logger.error(msg + ". user uuid =" + user.id + + ", user from token uuid=" + user_from_token.id) raise VvpConflict def render_user_not_active_message(self, i_email): @@ -106,25 +112,31 @@ class LoginSvc(BaseSvc): if reset_password_param is not None: is_reset_pwd_flow = True self.logger.debug( - "Reset Password flow is identified. Checking temporary password expiration. t=" + reset_password_param) + "Reset Password flow is identified.\ + Checking temporary password expiration. t=" + + reset_password_param) token_arr = reset_password_param.split("token") if len(token_arr) > 0: email = jwt_obj.decode_reset_password_token(str(token_arr[1])) else: - self.logger.error("token doesn't include token prefix: " + logEncoding(reset_password_param)) + self.logger.error( + "token doesn't include token prefix: " + + logEncoding(reset_password_param)) is_reset_pwd_flow = False return email, is_reset_pwd_flow def handle_invite_token(self, data, user_data, user_profile): data['invitation'] = data['invitation'].strip() - invitation = Invitation.objects.get(invitation_token=data['invitation']) + invitation = Invitation.objects.get( + invitation_token=data['invitation']) addUsersToEngTeam(invitation.engagement_uuid, [user_profile]) vf_obj = VF.objects.get(engagement__uuid=invitation.engagement_uuid) vm_client.fire_event_in_bg('send_provision_new_vf_event', vf_obj) user_data['eng_uuid'] = invitation.engagement_uuid markInvitationAsAccepted(data['invitation']) - def get_serialized_user_data(self, is_reset_pwd_flow, user_profile, jwt_obj, user): + def get_serialized_user_data(self, is_reset_pwd_flow, user_profile, + jwt_obj, user): user_data = ThinIceUserProfileModelSerializer(user_profile).data user_data['isResetPwdFlow'] = is_reset_pwd_flow user_data['token'] = jwt_obj.create_token(user) diff --git a/django/engagementmanager/service/nextstep_service.py b/django/engagementmanager/service/nextstep_service.py index 9fa8672..fe34f3a 100644 --- a/django/engagementmanager/service/nextstep_service.py +++ b/django/engagementmanager/service/nextstep_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -40,13 +40,19 @@ import json from django.db.models.query_utils import Q from django.utils import timezone from django.utils.timezone import timedelta -from engagementmanager.bus.messages.activity_event_message import ActivityEventMessage -from engagementmanager.models import Engagement, IceUserProfile, NextStep, VF -from engagementmanager.serializers import ThinNextStepModelSerializer, UserNextStepModelSerializer -from engagementmanager.utils.activities_data import UpdateNextStepsActivityData, AddNextStepsActivityData -from engagementmanager.service.engagement_service import update_or_insert_to_recent_engagements +from engagementmanager.bus.messages.activity_event_message import \ + ActivityEventMessage +from engagementmanager.models import Engagement, IceUserProfile, \ + NextStep, VF +from engagementmanager.serializers import ThinNextStepModelSerializer, \ + UserNextStepModelSerializer +from engagementmanager.utils.activities_data import \ + UpdateNextStepsActivityData, AddNextStepsActivityData +from engagementmanager.service.engagement_service import \ + update_or_insert_to_recent_engagements from engagementmanager.service.base_service import BaseSvc -from engagementmanager.utils.constants import Constants, NextStepType, NextStepState, RecentEngagementActionType +from engagementmanager.utils.constants import Constants, NextStepType,\ + NextStepState, RecentEngagementActionType from engagementmanager.utils.request_data_mgr import request_data_mgr from engagementmanager.apps import bus_service from engagementmanager.service.logging_service import LoggingServiceFactory @@ -59,37 +65,45 @@ class NextStepSvc(BaseSvc): { 'position': 2, 'stage': 'Intake', - 'text': 'Please work with your Engagement Lead (EL) to complete the necessary trial agreements.', + 'text': 'Please work with your Engagement Lead (EL) ' + + 'to complete the necessary trial agreements.', 'condition': lambda x, y: True, - 'type': NextStepType.trial_agreements.name # @UndefinedVariable + 'type': NextStepType.trial_agreements.name }, { 'position': 3, 'stage': 'Intake', - 'text': 'Please add your ' + Constants.service_provider_company_name + ' sponsor or vendor contact information.', - 'condition': lambda user, eng: False if (eng.contact_user) else True, - 'type': NextStepType.add_contact_person.name # @UndefinedVariable + 'text': 'Please add your ' + + Constants.service_provider_company_name + + ' sponsor or vendor contact information.', + 'condition': lambda user, eng: False if + (eng.contact_user) else True, + 'type': NextStepType.add_contact_person.name }, { 'position': 1, 'stage': 'Active', - 'text': 'Please submit the first version of the VF package. If you have any problems or questions, please contact your Engagement Lead (EL)', + 'text': 'Please submit the first version of the VF package. ' + + 'If you have any problems or questions, please ' + + 'contact your Engagement Lead (EL)', 'condition': lambda x, y: True, - 'type': NextStepType.submit_vf_package.name # @UndefinedVariable + 'type': NextStepType.submit_vf_package.name }, { 'position': 1, 'stage': 'Validated', - 'text': 'Please schedule a time with your Engagement Lead (EL) to complete the handoff.', + 'text': 'Please schedule a time with your Engagement Lead (EL) ' + + 'to complete the handoff.', 'condition': lambda x, y: True, - 'type': NextStepType.el_handoff.name # @UndefinedVariable + 'type': NextStepType.el_handoff.name } ] def get_user_next_steps(self, limit, state): user = request_data_mgr.get_user() - nextSteps = NextStep.objects.filter(Q(assignees=user) & Q(state=state)).order_by('due_date').distinct() + nextSteps = NextStep.objects.filter(Q(assignees=user) & Q( + state=state)).order_by('due_date').distinct() count = nextSteps.count() serializer = UserNextStepModelSerializer(nextSteps[:limit], many=True) return serializer, count @@ -98,16 +112,24 @@ class NextStepSvc(BaseSvc): user = request_data_mgr.get_user() eng_uuid = request_data_mgr.get_eng_uuid() - ers = NextStep.objects.filter(Q(engagement__uuid=eng_uuid, owner=None, engagement_stage=eng_stage) | Q( - owner=user, engagement_stage=eng_stage)).order_by('position') + ers = NextStep.objects.filter( + Q( + engagement__uuid=eng_uuid, + owner=None, + engagement_stage=eng_stage) | Q( + owner=user, + engagement_stage=eng_stage)).order_by('position') serializer = ThinNextStepModelSerializer(ers, many=True) for next_step in serializer.data: if next_step['files'] is not None: next_step['files'] = json.loads(next_step['files']) - if 'engagement' in next_step and next_step['engagement'] is not None and 'engagement_team' in next_step['engagement'] and next_step['engagement']['engagement_team'] is not None: + if 'engagement' in next_step and next_step['engagement'] \ + is not None and 'engagement_team' in next_step[ + 'engagement'] and \ + next_step['engagement']['engagement_team'] is not None: for user in next_step['engagement']['engagement_team']: - if (user['ssh_public_key'] != None): + if (user['ssh_public_key'] is not None): del user['ssh_public_key'] return serializer @@ -126,24 +148,27 @@ class NextStepSvc(BaseSvc): for data in dataList: try: - associated_files = json.dumps(data['files'], ensure_ascii=False) - except: + associated_files = json.dumps( + data['files'], ensure_ascii=False) + except BaseException: associated_files = "[]" try: due_date = data['duedate'] - except: + except BaseException: due_date = None - nextStepObj = NextStep.objects.create(creator=user, last_updater=user, engagement=engObj, position=NextStep.objects.count() + 1, - # @UndefinedVariable - description=data[ - 'description'], state=NextStepState.Incomplete.name, engagement_stage=engObj.engagement_stage, - files=associated_files, due_date=due_date) # @UndefinedVariable + nextStepObj = NextStep.objects.create( + creator=user, last_updater=user, engagement=engObj, + position=NextStep.objects.count() + 1, + description=data[ + 'description'], state=NextStepState.Incomplete.name, + engagement_stage=engObj.engagement_stage, + files=associated_files, due_date=due_date) try: data['assigneesUuids'] - except: + except BaseException: data['assigneesUuids'] = [] for assigneesUuid in data['assigneesUuids']: @@ -152,30 +177,39 @@ class NextStepSvc(BaseSvc): nextStepObj.assignees.add(assignee_user) nextStepObj.save() update_or_insert_to_recent_engagements( - assignee_user.uuid, vfObj, RecentEngagementActionType.NEXT_STEP_ASSIGNED.name) # @UndefinedVariable + assignee_user.uuid, + vfObj, + RecentEngagementActionType.NEXT_STEP_ASSIGNED.name) nextStepData.append(ThinNextStepModelSerializer(nextStepObj).data) - activity_data = AddNextStepsActivityData(VF.objects.get(engagement=engObj), user, engObj) + activity_data = AddNextStepsActivityData( + VF.objects.get(engagement=engObj), user, engObj) bus_service.send_message(ActivityEventMessage(activity_data)) - if checklist_uuid != None: - from engagementmanager.service.checklist_state_service import set_state - set_state(True, checklist_uuid, isMoveToAutomation=True, description=desc) - logger.debug("Successfully added a Next Step to engagement_uuid=" + - eng_uuid + " for checklist=" + checklist_uuid) + if checklist_uuid is not None: + from engagementmanager.service.checklist_state_service import \ + set_state + set_state(True, checklist_uuid, + isMoveToAutomation=True, description=desc) + logger.debug("Successfully added a \ + Next Step to engagement_uuid=" + + eng_uuid + " for checklist=" + checklist_uuid) return nextStepData ''' - This function shall return the update type in the next step (can be Completed or Denied) + This function shall return the update type in the next step + (can be Completed or Denied) ''' def validate_state_transition(self, user, current_state, next_state): update_type = next_state.name - logger.debug('validating step transition by %s from %s to %s', user.role.name, current_state, next_state) + logger.debug('validating step transition by %s from %s to %s', + user.role.name, current_state, next_state) - if (current_state == NextStepState.Completed and next_state == NextStepState.Incomplete): + if (current_state == NextStepState.Completed and next_state == + NextStepState.Incomplete): if (user.role.name == 'el'): update_type = 'Denied' else: @@ -184,7 +218,8 @@ class NextStepSvc(BaseSvc): return update_type def create_default_next_steps_for_user(self, user, el_user): - def cond(user): return False if (user.ssh_public_key and user.ssh_public_key != '') else True + def cond(user): return False if ( + user.ssh_public_key and user.ssh_public_key != '') else True if cond(user): desc = "Please add your SSH key to be able to contribute." @@ -198,12 +233,13 @@ class NextStepSvc(BaseSvc): engagement_stage='Intake', engagement=None, owner=user, - next_step_type=NextStepType.set_ssh.name, # @UndefinedVariable + next_step_type=NextStepType.set_ssh.name, due_date=timezone.now() + timedelta(days=1)) nextstep.save() ''' - This method is for non-personal default next step only since it doesn't have an owner + This method is for non-personal default next step only + since it doesn't have an owner ''' def create_default_next_steps(self, user, engagement, el_user): @@ -215,16 +251,30 @@ class NextStepSvc(BaseSvc): if (user.company == Constants.service_provider_company): desc = desc.replace('$Contact', 'Vendor Contact') else: - desc = desc.replace('$Contact', Constants.service_provider_company_name + ' Sponsor Contact') + desc = desc.replace( + '$Contact', + Constants.service_provider_company_name + + ' Sponsor Contact') logger.debug('Creating default next step : ' + desc) - nextstep = NextStep.objects.create(creator=el_user, last_updater=el_user, position=step['position'], description=desc, state='Incomplete', engagement_stage=step[ - 'stage'], engagement=engagement, next_step_type=ns_type, due_date=timezone.now() + timedelta(days=1)) + nextstep = NextStep.objects.create( + creator=el_user, + last_updater=el_user, + position=step['position'], + description=desc, + state='Incomplete', + engagement_stage=step['stage'], + engagement=engagement, + next_step_type=ns_type, + due_date=timezone.now() + + timedelta( + days=1)) nextstep.assignees.add(el_user) nextstep.save() else: - logger.debug('Skipping creation of default next step : ' + desc) + logger.debug( + 'Skipping creation of default next step : ' + desc) def update_next_steps_order(self, nextsteps): counter = 0 @@ -248,13 +298,17 @@ class NextStepSvc(BaseSvc): step.assignees.remove(user) for assigneesUuid in data['assigneesUuids']: assigned_user = IceUserProfile.objects.get(uuid=assigneesUuid) - eng_team = Engagement.objects.get(uuid=request_data_mgr.get_eng_uuid()).engagement_team.all() + eng_team = Engagement.objects.get( + uuid=request_data_mgr.get_eng_uuid()).\ + engagement_team.all() if (assigned_user in eng_team): step.assignees.add(assigned_user) step.save() else: logger.error( - "An attempt to edit a NS and assign a user who is not in the engagement team was conducted, user wasn't assigned!") + "An attempt to edit a NS and assign a user who is " + + "not in the engagement team was conducted, " + + "user wasn't assigned!") continue step.last_updater = request_data_mgr.get_user() @@ -268,7 +322,8 @@ class NextStepSvc(BaseSvc): if attr == 'state': update_type = self.validate_state_transition( - request_data_mgr.get_user(), NextStepState[step.state], NextStepState[state]) + request_data_mgr.get_user(), NextStepState[step.state], + NextStepState[state]) step.state = state step.last_updater = request_data_mgr.get_user() step.last_update_time = timezone.now() @@ -276,5 +331,6 @@ class NextStepSvc(BaseSvc): step.save() if step.engagement: activity_data = UpdateNextStepsActivityData( - step.last_update_type, request_data_mgr.get_user(), step.engagement) + step.last_update_type, + request_data_mgr.get_user(), step.engagement) bus_service.send_message(ActivityEventMessage(activity_data)) diff --git a/django/engagementmanager/service/user_service.py b/django/engagementmanager/service/user_service.py index 8d6317e..d8a99f1 100644 --- a/django/engagementmanager/service/user_service.py +++ b/django/engagementmanager/service/user_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -40,9 +40,11 @@ from django.contrib.auth import get_user_model from sshpubkeys import SSHKey from engagementmanager.apps import bus_service -from engagementmanager.bus.messages.activity_event_message import ActivityEventMessage +from engagementmanager.bus.messages.activity_event_message\ + import ActivityEventMessage from engagementmanager.models import IceUserProfile, Role, VF -from engagementmanager.serializers import SuperThinIceUserProfileModelSerializerForSignals +from engagementmanager.serializers import\ + SuperThinIceUserProfileModelSerializerForSignals from engagementmanager.service.base_service import BaseSvc from engagementmanager.utils.cryptography import CryptographyText from engagementmanager.utils.activities_data import SSHKeyAddedActivityData @@ -61,15 +63,15 @@ class UserService(BaseSvc): try: ssh.parse() except Exception as e: - msg = """ssh provided by the user is invalid, type of exception: """ + \ - str(e) + msg = """ssh provided by the user is invalid,""" +\ + """type of exception: """ + str(e) self.logger.error(msg) msg = "Updating SSH Key failed due to invalid key." raise VvpBadRequest(msg) # remove comment from ssh key # ssh.comment returns comment attached to key - if ssh.comment != None: + if ssh.comment is not None: striped_key = sshkey.replace(ssh.comment, '').strip() else: striped_key = sshkey.strip() @@ -85,7 +87,8 @@ class UserService(BaseSvc): raise Exception(msg) else: self.logger.debug( - "SSH key already taken by another user - uuid: %s", user_with_ssh.uuid) + "SSH key already taken by another user - uuid: %s", + user_with_ssh.uuid) msg = "Updating SSH Key failed due to invalid key." raise VvpBadRequest(msg) @@ -100,7 +103,8 @@ class UserService(BaseSvc): def get_el_list(self): el_role = Role.objects.get(name='el') engagement_leads_users = IceUserProfile.objects.filter(role=el_role) - return SuperThinIceUserProfileModelSerializerForSignals(engagement_leads_users, many=True).data + return SuperThinIceUserProfileModelSerializerForSignals( + engagement_leads_users, many=True).data def get_user_by_email(self, email): UserModel = get_user_model() diff --git a/django/engagementmanager/service/vf_service.py b/django/engagementmanager/service/vf_service.py index aa3a9d3..7399cd2 100644 --- a/django/engagementmanager/service/vf_service.py +++ b/django/engagementmanager/service/vf_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. diff --git a/django/engagementmanager/service/vfc_service.py b/django/engagementmanager/service/vfc_service.py index 341cfc1..807a8ea 100644 --- a/django/engagementmanager/service/vfc_service.py +++ b/django/engagementmanager/service/vfc_service.py @@ -1,5 +1,5 @@ -# -# ============LICENSE_START========================================== +# +# ============LICENSE_START========================================== # org.onap.vvp/engagementmgr # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. @@ -54,14 +54,19 @@ class VFCSvc(BaseSvc): duplicate = False many = True dict = {} - # Iterate through all the VFCs that are received from the user, if there's duplication -> check the VF, if it is the same ->duplicate = True - # If there's a duplication and the other VFCs trying to be created are not - # duplicated -> Many = True -> they would be successfully created any way + # Iterate through all the VFCs that are received from the user, + # if there's duplication -> check the VF, + # if it is the same ->duplicate = True + # If there's a duplication and the other + # VFCs trying to be created are not + # duplicated -> Many = True -> they would be successfully created any + # way for i in range(len(data['vfcs'])): dict.update(data['vfcs'][i]) # check if the VFC already exist (filter by name) try: - vfc = VFC.objects.filter(name=dict['name'], external_ref_id=dict['external_ref_id']) + vfc = VFC.objects.filter( + name=dict['name'], external_ref_id=dict['external_ref_id']) # if found VFC with same name and ref id if (vfc.count() > 0): for item in vfc: @@ -69,8 +74,10 @@ class VFCSvc(BaseSvc): if (not duplicate): duplicate = True duplicateNames.append(dict['name']) - # if found a similar VFC with name and ref_id, but VF is different ( - # cannot use else, and raise, since the for has to check all vfcs that + # if found a similar VFC with name and ref_id,\ + # but VF is different ( + # cannot use else, and raise, + # since the for has to check all vfcs that # match - for example, 2 VFs with same vfc) if not duplicate: raise VFC.DoesNotExist @@ -79,19 +86,26 @@ class VFCSvc(BaseSvc): raise VFC.DoesNotExist # If the VFC Does not exist, then continue as usual and create it. except VFC.DoesNotExist: - many = True # not used, unless there's a duplicate as well, just a helper + many = True + # not used, unless there's a duplicate as well, just a helper - user = IceUserProfile.objects.get(email=data['creator']['email']) + user = IceUserProfile.objects.get( + email=data['creator']['email']) vf = VF.objects.get(uuid=data['vf_uuid']) # Check if the company that the user entered already exist. try: company = Vendor.objects.get(name=dict['company']) except Vendor.DoesNotExist: - company = Vendor.objects.create(name=dict['company'], public=False) + company = Vendor.objects.create( + name=dict['company'], public=False) company.save() # create the VFC - vfc = VFC.objects.create(name=dict['name'], company=company, vf=vf, - creator=user, external_ref_id=dict['external_ref_id']) + vfc = VFC.objects.create( + name=dict['name'], + company=company, + vf=vf, + creator=user, + external_ref_id=dict['external_ref_id']) if 'ice_mandated' in dict: vfc.ice_mandated = dict['ice_mandated'] vfc.save() @@ -101,7 +115,8 @@ class VFCSvc(BaseSvc): num = 1 for vfc_name in duplicateNames: msg = msg + str(num) + ". The VFC " + vfc_name + \ - " already exist, the VF that it is related to is: " + item.vf.name + "\n" + " already exist, the VF that it is related to is: "\ + + item.vf.name + "\n" num += 1 msg = msg + "\nThe other VFCs were created succesfully\n" self.logger.error(msg) |