def generate_summary_file(): """ We need this function in order to test the real generate_summary_file function. Its name has been changed to __... :return: the time necessary to execute this function """ start_time = time() # Read configuration config = DITICConfig() # List of emails list_emails = set(config.get_email_to_user().keys()) # List of possible status list_status = config.get_list_status() # Let use system config list system = config.get_system() rt_object = RTApi(system['server'], system['username'], system['password']) summary = __generate_summary_file(rt_object, list_emails, list_status) # The summary of all files will be flushed to this file. try: with open( summary_filename(system['working_dir'], system['summary_file']), 'w') as file_handler: dump(summary, file_handler) except IOError as e: raise IOError('Error:' + str(e)) return '%0.2f seconds' % (time() - start_time)
def modifyTicket(ticketID): global emailGlobal dic = {"email": emailGlobal} lst = [] set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) try: response = resource.get(path='ticket/' + ticketID) for r in response.parsed: for t in r: logger.info(t) lst.append(t) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed) lst = dict(lst) return template("ticketDetails", lst=lst, ticketID=ticketID, dic=dic)
def logout(): set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) #create a ticket content = {'content': {}} try: response = resource.post( path='logout/', payload=content, ) logger.info(response.parsed) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed) redirect("/")
def generate_summary_file(): """ We need this function in order to test the real generate_summary_file function. Its name has been changed to __... :return: the time necessary to execute this function """ start_time = time() # Read configuration config = DITICConfig() # List of emails list_emails = set(config.get_email_to_user().keys()) # List of possible status list_status = config.get_list_status() # Let use system config list system = config.get_system() rt_object = RTApi(system['server'], system['username'], system['password']) summary = __generate_summary_file(rt_object, list_emails, list_status) # The summary of all files will be flushed to this file. try: with open(summary_filename(system['working_dir'], system['summary_file']), 'w') as file_handler: dump(summary, file_handler) except IOError as e: raise IOError('Error:' + str(e)) return '%0.2f seconds' % (time() - start_time)
def stats_update_json_file(number_of_days=1): """ Reads old json file, if it exists, get new information, update statistics, write back to file There is a known bug: the number_of_days MUST not overlap a month If it does, there will be a problem ;) :param number_of_days: Number of days to analyze :return: time took to execute """ # TODO: guarantee that the data is written in the correct filename, if number_of_days overlap a month start_time = time() config = DITICConfig() system = config.get_system() rt_object = RTApi(system['server'], system['username'], system['password']) # result = read_statistics_file(config) for this_day in range(0, number_of_days): current_date = get_date(this_day) current_year_month = current_date[:7] result = stats_read_json_file(current_year_month[:4], current_year_month[5:7]) result[get_date(this_day)] = full_list_of_tickets_on_a_date( rt_object, config, current_date) write_statistics_file(config, result, current_year_month[:4], current_year_month[5:7]) return '%0.2f seconds' % (time() - start_time)
def user_get_resolved_tickets(rt_object, email): config = DITICConfig() # Check if user is known... if not config.check_if_email_exist(email): raise ValueError("Unknown email/user:"******"%s" AND Queue = "general" AND Status = "resolved"' % (email) # Get the information from the server. try: response = get_list_of_tickets(rt_object, query) except NameError as e: raise ValueError("Error: " + str(e)) number_tickets_per_status = {email: len(response)} for line in response: try: auxiliary_date = strptime(line["lastupdated"]) auxiliary_date = "%02d/%02d" % (auxiliary_date.tm_mon, auxiliary_date.tm_mday) except ValueError: auxiliary_date = 0 line["auxiliary_date"] = auxiliary_date create_ticket_possible_actions(config, line, email, number_tickets_per_status) result = group_result_by(response, "auxiliary_date") email_limit = config.get_email_limits(email) return {"tickets": result}
def test_check_if_user_exist_unknown_user(): test_config = DITICConfig() test_config.email_to_user = { '*****@*****.**': 'Vapi', '*****@*****.**': 'Alex', } response = test_config.check_if_user_exist('Gina') assert response == False
def test_check_if_email_exist_known_email(): test_config = DITICConfig() test_config.email_to_user = { '*****@*****.**': 'Vapi', '*****@*****.**': 'Alex', } response = test_config.check_if_email_exist('*****@*****.**') assert response == False
def test_get_email_from_user(): test_config = DITICConfig() test_config.email_to_user = { '*****@*****.**': 'Vapi', '*****@*****.**': 'Alex', } response = test_config.get_email_from_user('Vapi') assert response == '*****@*****.**'
def test_users_list(): test_config = DITICConfig() test_config.email_to_user = { '*****@*****.**': 'Vapi', '*****@*****.**': 'Alex', } response = test_config.get_users_list() assert response == ['Vapi', 'Alex']
def search_tickets(rt_object, search): """ Search for tickets that match those criteria. The search will focus on those fields: - Requestors.EmailAddress - Subject - cf{servico} - cc - admincc - Requestor.Name - Requestor.RealName The tickets must be under the following restrictions: - Belongs to Queue General - Must have "CF.{IS - Informatica e Sistemas}" equal to DIR or DIR-INBOX - Must be created or updated on the last 90 days :param rt_object: RTApi object :param search: the search criteria :return: """ config = DITICConfig() # Search last 30 days. previous_date = (date.today() - timedelta(90)).isoformat() # The search string query = ( 'Queue = "General" AND ( "CF.{IS - Informatica e Sistemas}" = "DIR" ' 'OR "CF.{IS - Informatica e Sistemas}" = "DIR-INBOX" ) AND ' '( Lastupdated > "' + previous_date + '" OR Created > "' + previous_date + '") ' 'AND ( Requestor.EmailAddress LIKE "%' + search + '%" ' ) for query_items in ["Subject", "cf.{servico}", "cc", "admincc", "Requestor.Name", "Requestor.RealName"]: query += ' OR %s LIKE "%%%s%%" ' % (query_items, search) query += ")" # Get the information from the server. try: response = get_list_of_tickets(rt_object, query) except NameError as e: raise ValueError("Error: " + str(e)) except ValueError: return {"no_result": True, "number_tickets": "No results...", "tickets": {}} number_tickets = len(response) for line in response: try: auxiliary_date = strptime(line["lastupdated"]) auxiliary_date = "%02d/%02d" % (auxiliary_date.tm_mon, auxiliary_date.tm_mday) except ValueError: auxiliary_date = 0 line["auxiliary_date"] = auxiliary_date result = group_result_by(response, "auxiliary_date") email_limit = config.get_email_limits(search) return {"no_result": False, "tickets": result, "number_tickets": number_tickets, "email_limit": email_limit}
def __init__(self): self.config = DITICConfig() self.ids = { # Only used for tests... # u'10': { # 'email': '*****@*****.**', # 'rt_object': RTApi('server_address', 'username', 'password'), # } }
def test_get_list_status(): test_config = DITICConfig() test_config.list_status = [ 'new', 'open', ] response = test_config.get_list_status() assert response == [ 'new', 'open', ]
def test_get_system(): test_config = DITICConfig() test_config.system = { 'server': 'server_address', 'username': '******', } response = test_config.get_system() assert response == { 'server': 'server_address', 'username': '******', }
def create_default_result(): # Default header configuration result = {"title": "Still testing..."} # Summary information result.update({"summary": get_summary_info()}) # Mapping email do uer alias config = DITICConfig() result.update({"alias": config.get_email_to_user()}) return result
def createTicket(): global emailGlobal priority = '' priority = int(request.forms.get('priority')) if priority >= 200: setUrgent = 'yes' else: setUrgent = '' set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) #create a ticket content = { 'content': { 'Queue': request.forms.get( "queue" ), #General - unassigned is the name of the desired queue 'Requestors': emailGlobal, 'Subject': request.forms.get("subject"), #text to go into subject field 'Text': request.forms.get("content"), 'Priority': request.forms.get('priority'), 'CF.{servico}': request.forms.get("servico"), 'CF.{IS - Informatica e Sistemas}': request.forms.get("inforsistemas"), 'CF.{DITIC - Interrupted}': '', 'CF.{DITIC - Urgent}': setUrgent, } } try: response = resource.post( path='ticket/new', payload=content, ) logger.info(response.parsed) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
def create_default_result(): # Default header configuration result = { 'title': 'Still testing...' } # Summary information result.update({'summary': get_summary_info()}) # Mapping email do uer alias config = DITICConfig() result.update({'alias': config.get_email_to_user()}) return result
def create_default_result(): # Default header configuration result = {'title': 'Dashboard'} call(['update_statistics']) call(["generate_summary_file"]) # Summary information result.update({'summary': get_summary_info()}) # Mapping email do uer alias config = DITICConfig() result.update({'alias': config.get_email_to_user()}) return result
def test_get_email_limits_unknown_email(): test_config = DITICConfig() test_config.email_to_user = { '*****@*****.**': 'Vapi', '*****@*****.**': 'Alex', } test_config.email_limits = { '*****@*****.**': { 'new': 7, 'open': 1, 'rejected': 7, } } response = test_config.get_email_limits('*****@*****.**') assert response == {}
def user_closed_tickets(rt_object, email): """ Get the closed tickets on the last X days. (X = 60) :param rt_object: RTApi object :param email: the user email (it must exist in the config) :return: """ config = DITICConfig() # Check if user is known... if not config.check_if_email_exist(email): raise ValueError('Unknown email/user:'******'Owner = "%s" AND Queue = "general" AND Status = "resolved" AND LastUpdated > "%s"' % ( email, previous_date) # Get the information from the server. try: response = get_list_of_tickets(rt_object, query) except NameError as e: raise ValueError('Error: ' + str(e)) number_tickets_per_status = {email: len(response)} for line in response: try: auxiliary_date = strptime(line['lastupdated']) auxiliary_date = '%02d/%02d' % (auxiliary_date.tm_mon, auxiliary_date.tm_mday) except ValueError: auxiliary_date = 0 line['auxiliary_date'] = auxiliary_date create_ticket_possible_actions(config, line, email, number_tickets_per_status) result = group_result_by(response, 'auxiliary_date') email_limit = config.get_email_limits(email) return { 'tickets': result, 'number_tickets_per_status': number_tickets_per_status, 'email_limit': email_limit, }
def user_closed_tickets(rt_object, email): """ Get the closed tickets on the last X days. (X = 60) :param rt_object: RTApi object :param email: the user email (it must exist in the config) :return: """ config = DITICConfig() # Check if user is known... if not config.check_if_email_exist(email): raise ValueError('Unknown email/user:'******'Owner = "%s" AND Queue = "general" AND Status = "resolved" AND LastUpdated > "%s"' % (email, previous_date) # Get the information from the server. try: response = get_list_of_tickets(rt_object, query) except NameError as e: raise ValueError('Error: '+str(e)) number_tickets_per_status = {email: len(response)} for line in response: try: auxiliary_date = strptime(line['lastupdated']) auxiliary_date = '%02d/%02d' % (auxiliary_date.tm_mon, auxiliary_date.tm_mday) except ValueError: auxiliary_date = 0 line['auxiliary_date'] = auxiliary_date create_ticket_possible_actions(config, line, email, number_tickets_per_status) result = group_result_by(response, 'auxiliary_date') email_limit = config.get_email_limits(email) return { 'tickets': result, 'number_tickets_per_status': number_tickets_per_status, 'email_limit': email_limit, }
def get_summary_info(): """ returns a dictionary with the following format { 'email': { 'status': 'value', ... } ... } :return: """ #generate_summary_file() #retirar o comando generate_summary_file #stats_update_json_file() # retirar o comando update_statistics # Read configuration config = DITICConfig() # List of known emails list_emails = config.get_email_to_user().keys() # List of known status list_status = config.get_list_status() # Let use system config list system = config.get_system() # Get the file information try: with open( summary_filename(system['working_dir'], system['summary_file']), 'r') as file_handler: summary = load(file_handler) except IOError: # If there is an error, then return everything zeroed summary = { email: {status: 0 for status in list_status} for email in list_emails } summary['dir'] = {status: 0 for status in list_status} summary['dir-inbox'] = {status: 0 for status in list_status} summary['unknown'] = {status: 0 for status in list_status} return summary
def create_default_result(): # Default header configuration result = { 'title': 'Dashboard' } call(['update_statistics']) call(["generate_summary_file"]) # Summary information result.update({'summary': get_summary_info()}) # Mapping email do uer alias config = DITICConfig() result.update({'alias': config.get_email_to_user()}) return result
def test_user_closed_tickets_unknown_email(): rt_object = RTApiMock() rt_object.set_return([ u'id: ticket/887677', u'owner: [email protected]', u'subject: create rt dashboard', u'status: open', u'priority: 26', u'cf.{servico}: csc-gsiic', u'cf.{is - informatica e sistemas}: dir-inbox', ]) test_config = DITICConfig() test_config.email_to_user = { '*****@*****.**': 'Vapi', '*****@*****.**': 'Alex', } with pytest.raises(ValueError) as value_error: user_closed_tickets(rt_object, '*****@*****.**') assert 'Unknown email/user:' in str(value_error)
def get_summary_info(): """ returns a dictionary with the following format { 'email': { 'status': 'value', ... } ... } :return: """ #generate_summary_file() #retirar o comando generate_summary_file #stats_update_json_file() # retirar o comando update_statistics # Read configuration config = DITICConfig() # List of known emails list_emails = config.get_email_to_user().keys() # List of known status list_status = config.get_list_status() # Let use system config list system = config.get_system() # Get the file information try: with open(summary_filename(system['working_dir'], system['summary_file']), 'r') as file_handler: summary = load(file_handler) except IOError: # If there is an error, then return everything zeroed summary = {email: {status: 0 for status in list_status} for email in list_emails} summary['dir'] = {status: 0 for status in list_status} summary['dir-inbox'] = {status: 0 for status in list_status} summary['unknown'] = {status: 0 for status in list_status} return summary
def updateTicket(ticketID): global emailGlobal priority = int(request.forms.get('priority')) if priority > 255: priority = 255 if priority >= 200: setUrgent = 'yes' else: setUrgent = '' set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) #create a ticket content = { 'content': { 'Priority': str(priority), 'cf.{ditic - urgent}': setUrgent, } } try: response = resource.post( path='ticket/' + ticketID, payload=content, ) logger.info(response.parsed) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
def stats_update_json_file(number_of_days=1): """ Reads old json file, if it exists, get new information, update statistics, write back to file There is a known bug: the number_of_days MUST not overlap a month If it does, there will be a problem ;) :param number_of_days: Number of days to analyze :return: time took to execute """ # TODO: guarantee that the data is written in the correct filename, if number_of_days overlap a month start_time = time() config = DITICConfig() system = config.get_system() rt_object = RTApi(system['server'], system['username'], system['password']) # result = read_statistics_file(config) for this_day in range(0, number_of_days): current_date = get_date(this_day) current_year_month = current_date[:7] result = stats_read_json_file(current_year_month[:4], current_year_month[5:7]) result[get_date(this_day)] = full_list_of_tickets_on_a_date(rt_object, config, current_date) write_statistics_file(config, result, current_year_month[:4], current_year_month[5:7]) return '%0.2f seconds' % (time() - start_time)
def addComment(ticketID): set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) try: params = { 'content': { 'Action': 'comment', 'Text': request.forms.get("content"), }, } params2 = { 'content': { 'status': 'resolved', } } response = resource.post( path='ticket/' + ticketID + '/comment', payload=params, ) response = resource.post(path='ticket/' + ticketID, payload=params2) for r in response.parsed: for t in r: logger.info(t) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
def stats_read_json_file(desired_year, desired_month): """ Just read the JSON file for the request year and month. It will return everything on this file. :param desired_month: :return: """ system = DITICConfig().get_system() filename = '%s/%s%s-%s' % (system['working_dir'], desired_year, desired_month, system['statistics_file']) # Get the file information try: with open(filename, 'r') as file_handler: return load(file_handler) except IOError: return {} except ValueError: return {}
def user_tickets_details(rt_object, email): query = 'Owner = "' + email + '" AND Queue = "general" ' config = DITICConfig() # If the user is dir, then build the search if email == 'dir': query = 'Queue = "general" AND "CF.{IS - Informatica e Sistemas}" = "DIR" AND Owner = "Nobody" AND ' \ 'Status != "deleted" ' # If the user is dir-inbox, then search for it elif email == 'dir-inbox': query = 'Queue = "general" AND "CF.{IS - Informatica e Sistemas}" = "DIR-INBOX" AND Owner = "Nobody" AND ' \ 'Status != "deleted" ' # If the user is unknown, then search all users but those that we already know elif email == 'unknown': query = 'Queue = "general" AND "CF.{IS - Informatica e Sistemas}" LIKE "DIR%" AND ' \ 'Status != "deleted" ' for user in config.get_email_to_user().keys(): query += 'AND Owner != "' + user + '" ' query += 'AND Owner != "Nobody"' # Otherwise, check if user is not known... elif not config.check_if_email_exist(email): raise ValueError('Unknown email/user:'******' AND Status != "deleted" ' # Get the information from the server. try: response = get_list_of_tickets(rt_object, query) except ValueError as e: response = [] if email == 'dir' or email == 'dir-inbox' or email == 'unknown': number_tickets_per_status = {email: len(response)} result = group_result_by(response, 'priority') for priority in result: for line in result[priority]: create_ticket_possible_actions(config, line, email, number_tickets_per_status) else: # Get some statistics response_grouped_by_status = group_result_by(response, 'status') number_tickets_per_status = {} for status in response_grouped_by_status: number_tickets_per_status[status] = len( response_grouped_by_status[status]) result = {} for status in response_grouped_by_status: grouped_by_priority = group_result_by( response_grouped_by_status[status], 'priority') result[status] = grouped_by_priority for priority in grouped_by_priority: for line in grouped_by_priority[priority]: create_ticket_possible_actions(config, line, email, number_tickets_per_status) # The user limits... email_limit = config.get_email_limits(email) return { 'tickets': result, 'number_tickets_per_status': number_tickets_per_status, 'email_limit': email_limit, }
def search_tickets(rt_object, search): """ Search for tickets that match those criteria. The search will focus on those fields: - Requestors.EmailAddress - Subject - cf{servico} - cc - admincc - Requestor.Name - Requestor.RealName The tickets must be under the following restrictions: - Belongs to Queue General - Must have "CF.{IS - Informatica e Sistemas}" equal to DIR or DIR-INBOX - Must be created or updated on the last 90 days :param rt_object: RTApi object :param search: the search criteria :return: """ config = DITICConfig() # Search last 30 days. previous_date = (date.today() - timedelta(90)).isoformat() # The search string query = 'Queue = "General" AND ( "CF.{IS - Informatica e Sistemas}" = "DIR" ' \ 'OR "CF.{IS - Informatica e Sistemas}" = "DIR-INBOX" ) AND ' \ '( Lastupdated > "'+previous_date+'" OR Created > "'+previous_date+'") ' \ 'AND ( Requestor.EmailAddress LIKE "%'+search+'%" ' for query_items in [ 'Subject', 'cf.{servico}', 'cc', 'admincc', 'Requestor.Name', 'Requestor.RealName' ]: query += ' OR %s LIKE "%%%s%%" ' % (query_items, search) query += ')' # Get the information from the server. try: response = get_list_of_tickets(rt_object, query) except NameError as e: raise ValueError('Error: ' + str(e)) except ValueError: return { 'no_result': True, 'number_tickets': 'No results...', 'tickets': {}, } number_tickets = len(response) for line in response: try: auxiliary_date = strptime(line['lastupdated']) auxiliary_date = '%02d/%02d' % (auxiliary_date.tm_mon, auxiliary_date.tm_mday) except ValueError: auxiliary_date = 0 line['auxiliary_date'] = auxiliary_date result = group_result_by(response, 'auxiliary_date') email_limit = config.get_email_limits(search) return { 'no_result': False, 'tickets': result, 'number_tickets': number_tickets, 'email_limit': email_limit, }
#!/usr/bin/env python from pprint import pprint from ditic_kanban.config import DITICConfig from ditic_kanban.rt_api import RTApi #from ditic_kanban.statistics import stats_read_json_file #from ditic_kanban.statistics import get_statistics #from ditic_kanban.statistics import full_list_of_tickets_on_a_date from ditic_kanban.rt_projects import get_project_tree from ditic_kanban.rt_projects import ManageProjectElements config = DITICConfig() system = config.get_system() rt_object = RTApi(system['server'], system['username'], system['password']) #for aux in range(0, 30): # print get_date(aux), # print stats_number_of_tickets_of_an_user(rt_object, '*****@*****.**', get_date(aux)) #print stats_update_json_file(28) #result = stats_read_json_file('2015', '07') #for day in sorted(result): # print day, # print 'Created:', result[day]['created_tickets'], # print 'Resolved:', result[day]['team']['resolved'], # print 'Open:', result[day]['team']['open'] # print 'Mean time: %0.2f' % result[day]['team']['mean_time_to_resolve'] #pprint(get_statistics('2015-05-01', '2015-07-30')) #result = full_list_of_tickets_on_a_date(rt_object, config, '2015-07-25') #pprint(result) # Project examples:
from ditic_kanban.tools import user_get_resolved_tickets from ditic_kanban.tools import archive_tickets from ditic_kanban.rt_api import RTApi from ditic_kanban.rt_api import get_list_of_tickets from ditic_kanban.rt_api import modify_ticket from ditic_kanban.statistics import get_date from ditic_kanban.statistics import get_statistics from subprocess import call emailGlobal = '' # My first global variable... user_auth = UserAuth() # Only used by the URGENT tickets search my_config = DITICConfig() system = my_config.get_system() rt_object = RTApi(system['server'], system['username'], system['password']) # This part is necessary in order to get access to sound files # Static dir is in the parent directory STATIC_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../static")) print STATIC_PATH @get('/static/<filename>') def fileget(filename): return static_file(filename, root='views') @route('/getUrgentNumber') def get_urgent_number():
#!/usr/bin/env python from ditic_kanban.config import DITICConfig from ditic_kanban.rt_api import get_list_of_tickets from ditic_kanban.rt_api import RTApi myconfig = DITICConfig() system = myconfig.get_system() email_rt_api = RTApi(system['server'], system['username'], system['password']) #query = 'Owner = "*****@*****.**" and Status = "rejected"' query = '"cf.{is - informatica e sistemas}" not like "dir" and "cf.{is - informatica e sistemas}" not like "dir-inbox"' response = get_list_of_tickets(email_rt_api, query) print response print len(response)
class UserAuth: def __init__(self): self.config = DITICConfig() self.ids = { # Only used for tests... # u'10': { # 'email': '*****@*****.**', # 'rt_object': RTApi('server_address', 'username', 'password'), # } } def __get_new_id(self): while True: new_id = unicode(randint(0, 1000)) if new_id not in self.ids: return new_id # noinspection PyTypeChecker def get_email_id(self, email): if email not in self.config.get_email_to_user().keys(): raise ValueError('Unknown email') for uid in self.ids: if email == self.ids[uid]['email']: return uid raise ValueError('Unknown error! This should not be like this...') # noinspection PyTypeChecker def get_email_from_id(self, uid): if 'email' not in self.ids[uid]: raise ValueError('Unauthenticated user') return self.ids[uid]['email'] # noinspection PyTypeChecker,PyTypeChecker def get_rt_object_from_email(self, email): if email not in self.config.get_email_to_user().keys(): raise ValueError('Unknown email') for uid in self.ids: if email == self.ids[uid]['email']: return self.ids[uid]['rt_object'] raise ValueError('Unknown error! This should not be like this...') def check_id(self, uid): """ This function will check if id exists. It is important to say that id MUST be a unicode value! :param uid: unicode with id value :return: True or False, depending if ID exists or not """ if uid in self.ids: return True return False def check_password(self, email, pwd): if email not in self.config.get_email_to_user().keys(): raise ValueError('Unknown email') # Get system configurations system = self.config.get_system() # To check the password, we will try to check if user has any new ticket email_rt_api = RTApi(system['server'], email, pwd) data_dict = {'query': 'Owner = "%s" and Status = "new"' % email} response = email_rt_api.get_data_from_rest('/search/ticket', data_dict) if 'your username or password is incorrect' in response: raise ValueError('Password is incorrect') self.ids[self.__get_new_id()] = { 'email': email, 'rt_object': email_rt_api, } return True
def search_tickets(rt_object, search): """ Search for tickets that match those criteria. The search will focus on those fields: - Requestors.EmailAddress - Subject - cf{servico} - cc - admincc - Requestor.Name - Requestor.RealName The tickets must be under the following restrictions: - Belongs to Queue General - Must have "CF.{IS - Informatica e Sistemas}" equal to DIR or DIR-INBOX - Must be created or updated on the last 90 days :param rt_object: RTApi object :param search: the search criteria :return: """ config = DITICConfig() # Search last 30 days. previous_date = (date.today() - timedelta(90)).isoformat() # The search string query = 'Queue = "General" AND ( "CF.{IS - Informatica e Sistemas}" = "DIR" ' \ 'OR "CF.{IS - Informatica e Sistemas}" = "DIR-INBOX" ) AND ' \ '( Lastupdated > "'+previous_date+'" OR Created > "'+previous_date+'") ' \ 'AND ( Requestor.EmailAddress LIKE "%'+search+'%" ' for query_items in ['Subject', 'cf.{servico}', 'cc', 'admincc', 'Requestor.Name', 'Requestor.RealName']: query += ' OR %s LIKE "%%%s%%" ' % (query_items, search) query += ')' # Get the information from the server. try: response = get_list_of_tickets(rt_object, query) except NameError as e: raise ValueError('Error: '+str(e)) except ValueError: return { 'no_result': True, 'number_tickets': 'No results...', 'tickets': {}, } number_tickets = len(response) for line in response: try: auxiliary_date = strptime(line['lastupdated']) auxiliary_date = '%02d/%02d' % (auxiliary_date.tm_mon, auxiliary_date.tm_mday) except ValueError: auxiliary_date = 0 line['auxiliary_date'] = auxiliary_date result = group_result_by(response, 'auxiliary_date') email_limit = config.get_email_limits(search) return { 'no_result': False, 'tickets': result, 'number_tickets': number_tickets, 'email_limit': email_limit, }
def __generate_summary_file(rt_object, list_emails, list_status): """ This function will search all tickets and generate a summary to be used by the summary report. :param rt_object: the rt_object for accessing get_list_of_tickets :param list_emails: A set with the known emails. It is a set to optimize the search :param list_status: A list of available status :return: summary (TODO: how it is done!) """ # Get the date from which we start searching tickets. previous_date = (date.today() - timedelta(0)).isoformat() # First step: search for all tickets of known emails known_email_query = '' for email in DITICConfig().get_email_to_user().keys(): if known_email_query: known_email_query += ' OR ' known_email_query += ' Owner = "%s" ' % email email_query = ' AND (' + known_email_query + ') ' # Get the information from the server. try: response = get_list_of_tickets( rt_object, r'Queue = "general" AND ( Resolved > "%s" ' r'OR ( Status != "resolved" ' r'AND Status != "deleted" ) ) %s' % (previous_date, email_query)) except ValueError as e: raise ValueError('Error1:' + str(e)) # Second step: search for all tickets of DIR and DIR-INBOX try: response += get_list_of_tickets( rt_object, r'Queue = "general" AND ( "CF.{IS - Informatica e Sistemas}" = "INBOX"' r'OR "CF.{IS - Informatica e Sistemas}" = "INBOX" )' r'AND Owner = "nobody" AND Status != "resolved" ' r'AND Status != "deleted" ') except ValueError as e: #raise ValueError('Error:2' + str(e)) pass # Third step: search for all tickets of unknown emails known_email_query = '' for email in DITICConfig().get_email_to_user().keys(): known_email_query += ' AND Owner != "%s" ' % email email_query = known_email_query + ' AND Owner != "nobody" ' # Get the information from the server. try: response += get_list_of_tickets( rt_object, ''' Queue = "general" AND Status != "resolved" AND Status != "deleted" AND ( "CF.{IS - Informatica e Sistemas}" = "INBOX"' OR "CF.{IS - Informatica e Sistemas}" = "INBOX" ) %s ''' % email_query) except ValueError as e: if str(e) != 'no matching results.': raise ValueError('Error:3' + str(e)) # Lets create summary dictionary summary = dict() summary['unknown'] = {status: 0 for status in list_status} summary['inbox'] = {status: 0 for status in list_status} #summary['dir-inbox'] = {status: 0 for status in list_status} group_by_email = group_result_by(response, 'owner') for email in sorted(group_by_email.keys()): group_by_status = group_result_by(group_by_email[email], 'status') # If this email is known, then identify it # If user is nobody, then it can be DIR or DIR-INBOX # Otherwise, it is unknown! if email in list_emails: summary[email] = {status: 0 for status in list_status} elif email == 'nobody': pass else: email = 'unknown' # Count the number of tickets in every status for this email for status in sorted(group_by_status.keys()): if email == 'nobody': group_by_cf = group_result_by( group_by_status[status], 'cf.{is - informatica e sistemas}') #summary['dir'][status] += len(group_by_cf.get('dir', '')) summary['inbox'][status] += len(group_by_cf.get('inbox', '')) else: summary[email][status] += len(group_by_status[status]) return summary
def user_tickets_details(rt_object, email): query = 'Owner = "'+email+'" AND Queue = "general" ' config = DITICConfig() # If the user is dir, then build the search if email == 'dir': query = 'Queue = "general" AND "CF.{IS - Informatica e Sistemas}" = "DIR" AND Owner = "Nobody" AND ' \ 'Status != "deleted" ' # If the user is dir-inbox, then search for it elif email == 'dir-inbox': query = 'Queue = "general" AND "CF.{IS - Informatica e Sistemas}" = "DIR-INBOX" AND Owner = "Nobody" AND ' \ 'Status != "deleted" ' # If the user is unknown, then search all users but those that we already know elif email == 'unknown': query = 'Queue = "general" AND "CF.{IS - Informatica e Sistemas}" LIKE "DIR%" AND ' \ 'Status != "deleted" ' for user in config.get_email_to_user().keys(): query += 'AND Owner != "'+user+'" ' query += 'AND Owner != "Nobody"' # Otherwise, check if user is not known... elif not config.check_if_email_exist(email): raise ValueError('Unknown email/user:'******' AND Status != "deleted" ' # Get the information from the server. try: response = get_list_of_tickets(rt_object, query) except ValueError as e: response = [] if email == 'dir' or email == 'dir-inbox' or email == 'unknown': number_tickets_per_status = {email: len(response)} result = group_result_by(response, 'priority') for priority in result: for line in result[priority]: create_ticket_possible_actions(config, line, email, number_tickets_per_status) else: # Get some statistics response_grouped_by_status = group_result_by(response, 'status') number_tickets_per_status = {} for status in response_grouped_by_status: number_tickets_per_status[status] = len(response_grouped_by_status[status]) result = {} for status in response_grouped_by_status: grouped_by_priority = group_result_by(response_grouped_by_status[status], 'priority') result[status] = grouped_by_priority for priority in grouped_by_priority: for line in grouped_by_priority[priority]: create_ticket_possible_actions(config, line, email, number_tickets_per_status) # The user limits... email_limit = config.get_email_limits(email) return { 'tickets': result, 'number_tickets_per_status': number_tickets_per_status, 'email_limit': email_limit, }