示例#1
0
def main(server=None, input=None):
    """
    The main function of the custom script. The entire script was copied
    and pasted into the body of the try statement in order to add some
    error handling. It's all legacy code, so edit with caution.

    :param server: the TacticServerStub object
    :param input: a dict with data like like search_key, search_type, sobject, and update_data
    :return: None
    """
    if not input:
        input = {}

    try:
        # CUSTOM_SCRIPT00063
        # Matthew Tyler Misenhimer
        # This was made to handle new snapshot insertions (uploads) and notify relevant people via email about the new upload
        
        # Do Not send external if location is internal
        def make_right_code_ending(sid):
            ending = str(sid)
            ending_len = len(ending)
            if ending_len < 5:
                zeros = 5 - ending_len
                for num in range (0, zeros):
                    ending = '0%s' % ending
            return ending
        
        def make_note_code_ending(sid):
            ending = str(sid)
            ending_len = len(ending)
            if ending_len < 8:
                zeros = 8 - ending_len
                for num in range (0, zeros):
                    ending = '0%s' % ending
            return ending
        
        def make_timestamp():
            import datetime
            now = datetime.datetime.now()
            return now.strftime("%Y-%m-%d %H:%M:%S")
        
        def get_time_date_dict(str_time):
            pre_split = str_time.split('.')[0]
            first_split = pre_split.split(' ')
            date = first_split[0]
            time = first_split[1]
            date_split = date.split('-')
            dt = {}
            dt['year'] = int(date_split[0])
            dt['month'] = int(date_split[1])
            dt['day'] = int(date_split[2])
            dt['date'] = date
            dt['time'] = time
            time_split = time.split(':')
            dt['hour'] = int(time_split[0])
            dt['minute'] = int(time_split[1])
            dt['second'] = int(time_split[2])
            dt['big_time'] = float((dt['hour'] * 3600) + (dt['minute'] * 60) + dt['second'])
            return dt
        
        def compare_dt_dicts(dt1, dt2):
            # This is rough. Don't use it for anything else. Should work for this though.
            difference = 0
            newest = -1
            dt1_bignum = float(float((dt1['year'] - 2000) * 365 * 24 * 3600) + float((dt1['month'] - 1) * 31 * 24 * 3600) + float((dt1['day'] - 1) * 24 * 3600) + dt1['big_time'])    
            dt2_bignum = float(float((dt2['year'] - 2000) * 365 * 24 * 3600) + float((dt2['month'] - 1) * 31 * 24 * 3600) + float((dt2['day'] - 1) * 24 * 3600) + dt2['big_time'])    
            difference = dt2_bignum - dt1_bignum
            if difference < 0:
                newest = 0
            else:
                newest = 1
            return [difference, newest]
        
        def fix_date(date):
            #This is needed due to the way Tactic deals with dates (using timezone info), post v4.0
            from pyasm.common import SPTDate
            return_date = ''
            date_obj = SPTDate.convert_to_local(date)
            if date_obj not in [None,'']:
                return_date = date_obj.strftime("%Y-%m-%d  %H:%M")
            return return_date
        
        def fix_note_chars(note):
            if isinstance(note, bool):
                note2 = 'False'
                if note:
                    note2 = 'True'
                note = note2
            else:
                import sys
                from json import dumps as jsondumps
                if note not in [None,'']:
                    if sys.stdout.encoding:
                        note = note.decode(sys.stdout.encoding)
                note = jsondumps(note)
                note = note.replace('||t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\"','"')
                note = note.replace('\"','"')
                note = note.replace('||n','<br/>')
                note = note.replace('\\\\n','<br/>')
                note = note.replace('\\\n','<br/>')
                note = note.replace('\\n','<br/>')
                note = note.replace('\n','<br/>')
            return note
        
        import os
        from pyasm.common import Environment
        allow_client_emails = True
        sobject = input.get('sobject')
        update_data = input.get('update_data')
        parent_type_solid = update_data.get('search_type')
        parent_type = update_data.get('search_type').split('?')[0]
        find_str = parent_type.split('/')[1].upper().split('?')[0]
        is_latest = sobject.get('is_latest')
        process = sobject.get('process')
        id = sobject.get('id')
        search_id = sobject.get('search_id')
        code = sobject.get('code')
        version = sobject.get('version')
        snap_timestamp = sobject.get('timestamp')
        
        sea_t = update_data.get('search_type').split('?')[0]
        upper_st = sea_t.split('/')[1].upper()
        srch_id = update_data.get('search_id')
        full_ending = make_right_code_ending(srch_id)
        parent_code = '%s%s' % (upper_st, full_ending)
        parent_sk = server.build_search_key(sea_t, parent_code)
        
        parent_type = parent_sk.split('?')[0]
        internal_template_file = '/opt/spt/custom/formatted_emailer/internal_email_template.html'
        external_template_file = '/opt/spt/custom/formatted_emailer/external_email_template.html'
        if is_latest and find_str == 'ORDER':
            # If this is the newest file, and it was uploaded to an order...
            order_code = parent_code
            if version not in [-1,'-1']:
                if process == 'PO':
                    # ... notify people about the upload if it was a new PO file
                    parent = server.eval("@SOBJECT(%s['code','%s'])" % (parent_type, parent_code))[0]
                    parent_timestamp = parent.get('timestamp')
                    snap_tdict = get_time_date_dict(snap_timestamp)
                    parent_tdict = get_time_date_dict(parent_timestamp)
                    #If the snapshot was made after the order, then we can search for the files
                    rez = compare_dt_dicts(parent_tdict, snap_tdict)
                    if rez[1] == 1:
                        # If the order has been there for at least 15 milliseconds before the snapshot, then you'll be able to find the file objects
                        if rez[0] > 15:
                            filez = server.eval("@SOBJECT(sthpw/file['search_id','%s']['search_type','%s'])" % (search_id, parent_type_solid))
                            file_name = ''
                            if filez:
                                for fi in filez:
                                    if fi.get('type') == 'main': 
                                        sp = fi.get('source_path').split('/')
                                        lsp = sp[len(sp) - 1].split('\\')
                                        file_name = lsp[len(lsp) - 1]
                            #Then send an email
                            from formatted_emailer import EmailDirections
                            ed = EmailDirections(order_code=order_code)
                            int_data = ed.get_internal_data()
                            subject = '2G-FILE-UPLOAD %s Order: "%s" PO#: %s' % (file_name, int_data['order_name'], int_data['po_number']) 
                            if int_data['client_email'] == '' and int_data['location'] == 'external':
                                subject = 'NOT SENT TO CLIENT!? %s' % subject
                            subject_see = subject
                            subject = subject.replace(' ','..') # Spaces are no good when sending to php as a parameter
                            message = '%s has uploaded a new PO File.' % int_data['from_name'].replace('.',' ')
                            message = '%s<br/>Uploaded PO File: %s' % (message, file_name) 
                            message = fix_note_chars(message)
                            #Fill the internal template file to create a file you can email
                            template = open(internal_template_file, 'r')
                            filled = ''
                            for line in template:
                                line = line.replace('[ORDER_CODE]', int_data['order_code'])
                                line = line.replace('[PO_NUMBER]', int_data['po_number'])
                                line = line.replace('[CLIENT_EMAIL]', int_data['client_email'])
                                line = line.replace('[EMAIL_CC_LIST]', int_data['ccs'])
                                line = line.replace('[SCHEDULER_EMAIL]', int_data['scheduler_email'])
                                line = line.replace('[SUBJECT]', subject_see)
                                line = line.replace('[MESSAGE]', message)
                                line = line.replace('[CLIENT]', int_data['client_name'])
                                line = line.replace('[CLIENT_LOGIN]', int_data['client_login'])
                                line = line.replace('[ORDER_NAME]', int_data.get('order_hyperlink', int_data['order_name']))
                                line = line.replace('[START_DATE]', fix_date(int_data['start_date']))
                                line = line.replace('[DUE_DATE]', fix_date(int_data['due_date']))
                                line = line.replace('[TITLE_ROW]', '')
                                line = line.replace('[PROJ_ROW]', '')
                                filled = '%s%s' % (filled, line)
                            template.close()
                            filled_in_email = '/var/www/html/formatted_emails/int_snap_inserted_%s.html' % code
                            filler = open(filled_in_email, 'w')
                            filler.write(filled)
                            filler.close()
                            #Send the internal email
                            the_command = "php /opt/spt/custom/formatted_emailer/inserted_order_email.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, int_data['to_email'], int_data['from_email'], int_data['from_name'], subject, int_data['ccs'].replace(';','#Xs*'))
                            os.system(the_command)
                            if int_data['location'] == 'external' and allow_client_emails:
                                ext_data = ed.get_external_data()
                                #Fill the external template file to create a file you can email
                                template = open(external_template_file, 'r')
                                filled = ''
                                for line in template:
                                    line = line.replace('[ORDER_CODE]', ext_data['order_code'])
                                    line = line.replace('[PO_NUMBER]', ext_data['po_number'])
                                    line = line.replace('[CLIENT_EMAIL]', ext_data['client_email'])
                                    line = line.replace('[EMAIL_CC_LIST]', ext_data['ccs'])
                                    line = line.replace('[SCHEDULER_EMAIL]', ext_data['scheduler_email'])
                                    line = line.replace('[SUBJECT]', subject_see)
                                    line = line.replace('[MESSAGE]', message)
                                    line = line.replace('[CLIENT]', ext_data['client_name'])
                                    line = line.replace('[CLIENT_LOGIN]', ext_data['client_login'])
                                    line = line.replace('[ORDER_NAME]', ext_data['order_name'])
                                    line = line.replace('[START_DATE]', fix_date(ext_data['start_date']))
                                    line = line.replace('[DUE_DATE]', fix_date(ext_data['due_date']))
                                    filled = '%s%s' % (filled, line)
                                template.close()
                                filled_in_email = '/var/www/html/formatted_emails/ext_snap_inserted_%s.html' % code
                                filler = open(filled_in_email, 'w')
                                filler.write(filled)
                                filler.close()
                                #Send the external email
                                os.system("php /opt/spt/custom/formatted_emailer/inserted_order_email.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, ext_data['to_email'], ext_data['from_email'], ext_data['from_name'], subject, ext_data['ccs'].replace(';','#Xs*')))
                    else:
                        print "THIS MAKES NO SENSE. THE SNAPSHOT WAS CREATED BEFORE THE ORDER?"
        elif find_str == 'NOTE':
            #If the upload was made to a note
            #Get the correct 
            #full_ending = make_note_code_ending(srch_id) #This was for Tactic v3.9
            #parent_code = 'NOTE%s' % (full_ending) #This was for Tactic v3.9
            #parent_sk = server.build_search_key('sthpw/note', parent_code) #This was for Tactic v3.9
            #note_obj = server.eval("@SOBJECT(sthpw/note['code','%s'])" % parent_code)[0] #This was for Tactic v3.9
            note_obj = server.eval("@SOBJECT(sthpw/note['id','%s'])" % srch_id)[0]
            parent_sk = note_obj.get('__search_key__')
            parent_code = note_obj.get('code') 
            note = note_obj.get('note')
            #Need to wait until all files have been checked in to Tactic
            if 'HASATTACHEDFILES:' in note:
                prenote = note.split('HASATTACHEDFILES')[0]
                count = int(note.split('HASATTACHEDFILES:')[1].split('MTMCOUNT')[0])
                new_count = count - 1
                if count == 1 or count == 0:
                    #Get all the files that have been checked in so far and send them along with the note in an email
                    #MAKE SURE TO REMOVE THE HASATTACHEDFILES section from the note before sending it, also update it in the db
                    server.update(parent_sk, {'note': prenote}, triggers=False)
                    search_id = note_obj.get('search_id') 
                    login = note_obj.get('login')
                    process = note_obj.get('process')
                    note = prenote
                    #Have to make the note work in html format
                    note = note.replace('\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                    note = note.replace('\n','<br/>')
                    note = note.replace('  ', '&nbsp;&nbsp;')
                    note = fix_note_chars(note)
                    note_id = note_obj.get('id')
                    timestamp = note_obj.get('timestamp').split('.')[0]
                    #time.sleep(60)
                    addressed_to = note_obj.get('addressed_to')
                    search_type = note_obj.get('search_type').split('?')[0]
                    parent_tall_str = search_type.split('/')[1].upper()
                    groups = Environment.get_group_names()
                    order = None
                    title = None
                    proj = None
                    work_order = None
                    order_code = ''
                    display_ccs = ''
                    subject_see = ''
                    message = ''
                    title_row = ''
                    proj_row = ''
                    if parent_tall_str in ['ORDER','TITLE','PROJ','WORK_ORDER']: # and 'compression' not in groups and 'compression supervisor' not in groups:
                        from formatted_emailer import EmailDirections
                        right_ending = make_right_code_ending(search_id)
                        parent_code = '%s%s' % (parent_tall_str, right_ending)
                        parent = server.eval("@SOBJECT(%s['code','%s'])" % (search_type, parent_code))
                        if parent:
                            parent = parent[0]
                        ident_str = ''
                        going_to_client = False
                        if parent_tall_str == 'WORK_ORDER':
                            proj = server.eval("@SOBJECT(twog/work_order['code','%s'].twog/proj)" % parent_code)[0]
                            title = server.eval("@SOBJECT(twog/work_order['code','%s'].twog/proj.twog/title)" % parent_code)[0] 
                            order = server.eval("@SOBJECT(twog/order['code','%s'])" % title.get('order_code'))[0]
                        elif parent_tall_str == 'PROJ':
                            proj = parent
                            title = server.eval("@SOBJECT(twog/proj['code','%s'].twog/title)" % parent_code)[0] 
                            order = server.eval("@SOBJECT(twog/order['code','%s'])" % title.get('order_code'))[0]
                        elif parent_tall_str == 'TITLE':
                            title = parent
                            order = server.eval("@SOBJECT(twog/order['code','%s'])" % title.get('order_code'))[0]
                        elif parent_tall_str == 'ORDER':
                            order = server.eval("@SOBJECT(twog/order['code','%s'])" % parent_code)[0]
                        if parent_tall_str == 'ORDER' and process == 'client':
                            order = parent 
                            going_to_client = True
                        elif parent_tall_str == 'TITLE' and process == 'client':
                            going_to_client = True
                        display_heirarchy = ''
                    
                        ed = EmailDirections(order_code=order.get('code'))
                        int_data = ed.get_internal_data()
                        ext_data = ed.get_external_data()
                    
                        if title:
                            title_display = title.get('title')
                            if title.get('episode') not in [None,'']:
                                title_display = '%s: %s' % (title_display, title.get('episode'))
                            display_heirarchy = '"%s" in %s' % (title_display, display_heirarchy)
                        ident_str = ''
                        if parent_tall_str in ['ORDER','TITLE']:
                            ident_str = '%s PO#: %s' % (display_heirarchy, ext_data['po_number'])
                        else:
                            ident_str = '%s (%s)' % (parent_code, ext_data['po_number'])
                        subject = '2G-NOTE FOR %s' % (ident_str)
                        if ext_data['to_email'] == '' and ext_data['ext_ccs'] == '' and ext_data['location'] == 'external':
                            subject = 'NOT SENT TO CLIENT!? %s' % subject
                        subject_see = subject
                        subject = subject.replace(' ','..')
                        message = '<br/>%s has added a new note for %s:<br/><br/>Note:<br/>%s<br/>%s' % (ext_data['from_name'], ident_str, note, timestamp)
                        message = fix_note_chars(message)
                        if going_to_client and allow_client_emails:
                            ext_template = open(external_template_file, 'r')
                            filled = ''
                            for line in ext_template:
                                line = line.replace('[ORDER_CODE]', ext_data['order_code'])
                                line = line.replace('[PO_NUMBER]', ext_data['po_number'])
                                line = line.replace('[CLIENT_EMAIL]', ext_data['client_email'])
                                line = line.replace('[EMAIL_CC_LIST]', ext_data['ext_ccs'])
                                line = line.replace('[SCHEDULER_EMAIL]', ext_data['scheduler_email'])
                                line = line.replace('[SUBJECT]', subject_see)
                                line = line.replace('[MESSAGE]', message)
                                line = line.replace('[CLIENT]', ext_data['client_name'])
                                line = line.replace('[CLIENT_LOGIN]', ext_data['client_login'])
                                line = line.replace('[ORDER_NAME]', ext_data['order_name'])
                                line = line.replace('[START_DATE]', fix_date(ext_data['start_date']))
                                line = line.replace('[DUE_DATE]', fix_date(ext_data['due_date']))
                                filled = '%s%s' % (filled, line)
                            snaps_expr = "@SOBJECT(sthpw/snapshot['search_type','sthpw/note']['search_id','%s'])" % note_id
                            snaps = server.eval(snaps_expr)
                            for snap in snaps:
                                if snap.get('is_current') in [True,'T','true','t']:
                                    #files_expr = "@SOBJECT(sthpw/file['snapshot_code','%s'])" % snap.get('code')
                                    files_expr = "@SOBJECT(sthpw/file['search_type','sthpw/note']['search_id','%s'])" % note_obj.get('id')
                                    files = server.eval(files_expr)
                                    for file in files:
                                        if file.get('type') == 'main' and file.get('snapshot_code') == snap.get('code'):
                                            file_path = '%s/%s' % (file.get('checkin_dir'), file.get('file_name'))
                                            filled = '%s\nMATTACHMENT:%s' % (filled, file_path) 
                            ext_template.close()
                            filled_in_email = '/var/www/html/formatted_emails/ext_note_inserted_%s.html' % note_id
                            filler = open(filled_in_email, 'w')
                            filler.write(filled)
                            filler.close()
                            if addressed_to not in [None,'']:
                                adt = addressed_to.split(',')
                                for adta in adt:
                                    if '@2gdigital' not in adta and adta not in ext_data['ext_ccs']:
                                        if ext_data['ext_ccs'] == '':
                                            ext_data['ext_ccs'] = adta
                                        else:
                                            ext_data['ext_ccs'] = '%s;%s' % (ext_data['ext_ccs'], adta)
                            the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, ext_data['to_email'], ext_data['from_email'], ext_data['from_name'], subject, ext_data['ext_ccs'].replace(';','#Xs*'))
                            if ext_data['to_email'] not in [None,''] and ext_data['ext_ccs'] not in [None,'',';']:
                                os.system(the_command)
                        #Now do internal email
                        if title:
                            full_title = title.get('title')
                            if title.get('episode') not in [None,'']:
                                full_title = '%s: %s' % (full_title, title.get('episode'))
                            title_row = "<div id='pagesubTitle3'>Title: <strong>%s</strong> | Title Code: <strong>%s</strong></div>" % (full_title, title.get('code')) 
                        if proj:
                            proj_row = "<div id='pagesubTitle3'>Project: <strong>%s</strong> | Project Code: <strong>%s</strong></div>" % (proj.get('process'), proj.get('code'))
                        int_template = open(internal_template_file, 'r')
                        filled = ''
                        for line in int_template:
                            line = line.replace('[ORDER_CODE]', int_data['order_code'])
                            line = line.replace('[PO_NUMBER]', int_data['po_number'])
                            line = line.replace('[CLIENT_EMAIL]', int_data['client_email'])
                            line = line.replace('[EMAIL_CC_LIST]', int_data['int_ccs'])
                            line = line.replace('[SCHEDULER_EMAIL]', int_data['scheduler_email'])
                            line = line.replace('[SUBJECT]', subject_see)
                            line = line.replace('[MESSAGE]', message)
                            line = line.replace('[CLIENT]', int_data['client_name'])
                            line = line.replace('[CLIENT_LOGIN]', int_data['client_login'])
                            line = line.replace('[ORDER_NAME]', int_data.get('order_hyperlink', int_data['order_name']))
                            line = line.replace('[START_DATE]', fix_date(int_data['start_date']))
                            line = line.replace('[DUE_DATE]', fix_date(int_data['due_date']))
                            line = line.replace('[TITLE_ROW]', title_row)
                            line = line.replace('[PROJ_ROW]', proj_row)
                            filled = '%s%s' % (filled, line)
                        snaps_expr = "@SOBJECT(sthpw/snapshot['search_type','sthpw/note']['search_id','%s'])" % note_id
                        snaps = server.eval(snaps_expr)
                        for snap in snaps:
                            if snap.get('is_current') in [True,'T','true','t']:
                                #files_expr = "@SOBJECT(sthpw/file['snapshot_code','%s'])" % snap.get('code')
                                files_expr = "@SOBJECT(sthpw/file['search_type','sthpw/note']['search_id','%s'])" % note_obj.get('id')
                                files = server.eval(files_expr)
                                for file in files:
                                    if file.get('type') == 'main' and file.get('snapshot_code') == snap.get('code'):
                                        file_path = '%s/%s' % (file.get('checkin_dir'), file.get('file_name'))
                                        filled = '%s\nMATTACHMENT:%s' % (filled, file_path) 
                        int_template.close()
                        filled_in_email = '/var/www/html/formatted_emails/int_note_inserted_%s.html' % note_id
                        filler = open(filled_in_email, 'w')
                        filler.write(filled)
                        filler.close()
                        if addressed_to not in [None,'']:
                            adt = addressed_to.split(',')
                            for adta in adt:
                                if '@2gdigital' in adta and adta not in int_data['int_ccs']:
                                    if int_data['int_ccs'] == '':
                                        int_data['int_ccs'] = adta
                                    else:
                                        int_data['int_ccs'] = '%s;%s' % (int_data['int_ccs'], adta)
                        login_email = server.eval("@GET(sthpw/login['login','%s'].email)" % login)
                        if login_email:
                            int_data['from_email'] = login_email[0] 
                        the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, int_data['to_email'], int_data['from_email'], int_data['from_name'], subject, int_data['int_ccs'].replace(';','#Xs*'))
                        if int_data['to_email'] not in [None,''] and int_data['int_ccs'] not in [None,'',';']:
                            os.system(the_command)
                else:
                    #Keep going until all uploads have been accounted for
                    new_note = '%s\nHASATTACHEDFILES:%sMTMCOUNT' % (prenote, new_count) 
                    server.update(parent_sk, {'note': new_note})
    except AttributeError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the server object does not exist.'
        raise e
    except KeyError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the input dictionary does not exist.'
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e
示例#2
0
def main(server=None, input=None):
    """
    The main function of the custom script. The entire script was copied
    and pasted into the body of the try statement in order to add some
    error handling. It's all legacy code, so edit with caution.

    :param server: the TacticServerStub object
    :param input: a dict with data like like search_key, search_type, sobject, and update_data
    :return: None
    """
    if not input:
        input = {}

    try:
        # CUSTOM_SCRIPT00059
        # Matthew Tyler Misenhimer
        # Do not send external if location is internal
        # This was made to send info about an order after the order sobject has been edited
        def make_timestamp():
            import datetime
            now = datetime.datetime.now()
            return now.strftime("%Y-%m-%d %H:%M:%S")
        
        def get_time_date_dict(str_time):
            pre_split = str_time.split('.')[0]
            first_split = pre_split.split(' ')
            date = first_split[0]
            time = first_split[1]
            date_split = date.split('-')
            dt = {}
            dt['year'] = int(date_split[0])
            dt['month'] = int(date_split[1])
            dt['day'] = int(date_split[2])
            dt['date'] = date
            dt['time'] = time
            time_split = time.split(':')
            dt['hour'] = int(time_split[0])
            dt['minute'] = int(time_split[1])
            dt['second'] = int(time_split[2])
            dt['big_time'] = float((dt['hour'] * 3600) + (dt['minute'] * 60) + dt['second'])
            return dt
        
        def compare_dt_dicts(dt1, dt2):
            # This is rough. Don't use it for anything else. Should work for this though.
            difference = 0
            newest = -1
            dt1_bignum = float(float((dt1['year'] - 2000) * 365 * 24 * 3600) + float((dt1['month'] - 1) * 31 * 24 * 3600) + float((dt1['day'] - 1) * 24 * 3600) + dt1['big_time'])    
            dt2_bignum = float(float((dt2['year'] - 2000) * 365 * 24 * 3600) + float((dt2['month'] - 1) * 31 * 24 * 3600) + float((dt2['day'] - 1) * 24 * 3600) + dt2['big_time'])    
            difference = dt2_bignum - dt1_bignum
            if difference < 0:
                newest = 0
            else:
                newest = 1
            return [difference, newest]
        
        def fix_date(date):
            #This is needed due to the way Tactic deals with dates (using timezone info), post v4.0
            from pyasm.common import SPTDate
            return_date = ''
            date_obj = SPTDate.convert_to_local(date)
            if date_obj not in [None,'']:
                return_date = date_obj.strftime("%Y-%m-%d  %H:%M")
            return return_date
        
        def fix_note_chars(note):
            if isinstance(note, bool):
                note2 = 'False'
                if note:
                    note2 = 'True'
                note = note2
            else:
                import sys
                from json import dumps as jsondumps
                if note not in [None,'']:
                    if sys.stdout.encoding:
                        note = note.decode(sys.stdout.encoding)
                note = jsondumps(note)
                note = note.replace('||t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\"','"')
                note = note.replace('\"','"')
                note = note.replace('||n','<br/>')
                note = note.replace('\\\\n','<br/>')
                note = note.replace('\\\n','<br/>')
                note = note.replace('\\n','<br/>')
                note = note.replace('\n','<br/>')
            return note
        
        
        allow_client_emails = True
        #print "In Order Edited"
        order = input.get('sobject')
        client_code = order.get('client_code')
        update_data = input.get('update_data')
        prev_data = input.get('prev_data')
        sob_timestamp = order.get('timestamp')
        now_time = make_timestamp()
        dt1 = get_time_date_dict(sob_timestamp)
        dt2 = get_time_date_dict(now_time)
        rez = compare_dt_dicts(dt1, dt2)
        go_or_no = True
        good_count = 0
        for key, val in update_data.iteritems():
            #We don't care about changes to the following fields
            if key in ['login','initial_po_upload_list','actual_cost','classification','completion_date','invoiced_date','closed','expected_price','client_email_list','expected_cost','keywords','seen_by','prev_seen_by']:
                go_or_no = False
            else:
                good_count = good_count + 1
        if client_code in [None,'']:
            go_or_no = False
        if good_count > 0:
            go_or_no = True
        if go_or_no:
            if rez[1] == 1:
                if rez[0] > 5:
                    # If more than 5 seconds have passed since the time of this order's creation, then it is ok to send the email notification
                    import os
                    from pyasm.common import Environment
                    from formatted_emailer import EmailDirections
                    external_template_file = '/opt/spt/custom/formatted_emailer/external_email_template.html'
                    internal_template_file = '/opt/spt/custom/formatted_emailer/internal_email_template.html'
                    order_code = order.get('code')
                    ed = EmailDirections(order_code=order_code)
                    int_data = ed.get_internal_data()
                    ext_data = ed.get_external_data()
                    subject = '2G-ORDER-EDIT-"%s" PO#: %s' % (int_data['order_name'], int_data['po_number'])
                    if ext_data['client_email'] == '' and ext_data['location'] == 'external':
                        subject = 'NOT SENT TO CLIENT!? %s' % subject
                    subject_see = subject
                    subject = subject.replace(' ','..')
                    initial_po_upload_list = order.get('initial_po_upload_list')
                    message = '%s has edited an order. Order Name = "%s"  PO Number = "%s".' % (int_data['from_name'].replace('.',' '), int_data['order_name'], int_data['po_number'])
                    message = '%s<br/>Edits Made:' % message
                    
                    added_update = False
                    for key, val in update_data.iteritems():
                        # Report the change of previous value to new value - if it isnt one of these fields
                        if str(prev_data[key]) != str(val) and key not in ['login','initial_po_upload_list','actual_cost','classification','completion_date','invoiced_date','closed','expected_price','client_email_list','expected_cost','keywords','seen_by','prev_seen_by']:
                            message = '%s<br/>%s: "%s"  --- Used to be "%s"' % (message, key, val, prev_data[key])  
                            added_update = True
        
                    message = fix_note_chars(message)
                    if added_update:
                        template = open(internal_template_file, 'r')
                        filled = ''
                        for line in template:
                            line = line.replace('[ORDER_CODE]', int_data['order_code'])
                            line = line.replace('[PO_NUMBER]', int_data['po_number'])
                            line = line.replace('[CLIENT_EMAIL]', int_data['client_email'])
                            line = line.replace('[EMAIL_CC_LIST]', int_data['ccs'])
                            line = line.replace('[SCHEDULER_EMAIL]', int_data['scheduler_email'])
                            line = line.replace('[SUBJECT]', subject_see)
                            line = line.replace('[MESSAGE]', message)
                            line = line.replace('[CLIENT]', int_data['client_name'])
                            line = line.replace('[CLIENT_LOGIN]', int_data['client_login'])
                            line = line.replace('[ORDER_NAME]', int_data.get('order_hyperlink', int_data['order_name']))
                            line = line.replace('[START_DATE]', fix_date(int_data['start_date']))
                            line = line.replace('[DUE_DATE]', fix_date(int_data['due_date']))
                            line = line.replace('[TITLE_ROW]', '')
                            line = line.replace('[PROJ_ROW]', '')
                            filled = '%s%s' % (filled, line)
                        template.close()
                        filled_in_email = '/var/www/html/formatted_emails/int_order_edited_%s.html' % order_code
                        filler = open(filled_in_email, 'w')
                        filler.write(filled)
                        filler.close()
                        #Send the internal email
                        the_command = "php /opt/spt/custom/formatted_emailer/inserted_order_email.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, int_data['to_email'], int_data['from_email'], int_data['from_name'], subject, int_data['ccs'].replace(';','#Xs*'))
                        os.system(the_command)
                        if ext_data['location'] == 'external' and allow_client_emails:
                            template = open(external_template_file, 'r')
                            filled = ''
                            for line in template:
                                line = line.replace('[ORDER_CODE]', ext_data['order_code'])
                                line = line.replace('[PO_NUMBER]', ext_data['po_number'])
                                line = line.replace('[CLIENT_EMAIL]', ext_data['client_email'])
                                line = line.replace('[EMAIL_CC_LIST]', ext_data['ccs'])
                                line = line.replace('[SCHEDULER_EMAIL]', ext_data['scheduler_email'])
                                line = line.replace('[SUBJECT]', subject_see)
                                line = line.replace('[MESSAGE]', message)
                                line = line.replace('[CLIENT]', ext_data['client_name'])
                                line = line.replace('[CLIENT_LOGIN]', ext_data['client_login'])
                                line = line.replace('[ORDER_NAME]', ext_data['order_name'])
                                line = line.replace('[START_DATE]', fix_date(ext_data['start_date']))
                                line = line.replace('[DUE_DATE]', fix_date(ext_data['due_date']))
                                filled = '%s%s' % (filled, line)
                            template.close()
                            filled_in_email = '/var/www/html/formatted_emails/ext_order_edited_%s.html' % order_code
                            filler = open(filled_in_email, 'w')
                            filler.write(filled)
                            filler.close()
                            #Send the external email
                            the_command = "php /opt/spt/custom/formatted_emailer/inserted_order_email.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, ext_data['to_email'], ext_data['from_email'], ext_data['from_name'], subject, ext_data['ccs'].replace(';','#Xs*'))
                            os.system(the_command)
            else:
                print "THIS MAKES NO SENSE. SOB TIME IS GREATER THAN NOW TIME"
    except AttributeError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the server object does not exist.'
        raise e
    except KeyError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the input dictionary does not exist.'
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e
示例#3
0
def main(server=None, input=None):
    """
    The main function of the custom script. The entire script was copied
    and pasted into the body of the try statement in order to add some
    error handling. It's all legacy code, so edit with caution.

    :param server: the TacticServerStub object
    :param input: a dict with data like like search_key, search_type, sobject, and update_data
    :return: None
    """
    if not input:
        input = {}

    try:
        # CUSTOM_SCRIPT00060
        # Matthew Tyler Misenhimer
        # This was made to report by email that a new order has been inserted
        # Do not send external if location is internal
        
        def fix_date(date):
            #This is needed due to the way Tactic deals with dates (using timezone info), post v4.0
            from pyasm.common import SPTDate
            return_date = ''
            date_obj = SPTDate.convert_to_local(date)
            if date_obj not in [None,'']:
                return_date = date_obj.strftime("%Y-%m-%d  %H:%M")
            return return_date
        
        def fix_note_chars(note):
            if isinstance(note, bool):
                note2 = 'False'
                if note:
                    note2 = 'True'
                note = note2
            else:
                import sys
                from json import dumps as jsondumps
                if note not in [None,'']:
                    if sys.stdout.encoding:
                        note = note.decode(sys.stdout.encoding)
                note = jsondumps(note)
                note = note.replace('||t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\"','"')
                note = note.replace('\"','"')
                note = note.replace('||n','<br/>')
                note = note.replace('\\\\n','<br/>')
                note = note.replace('\\\n','<br/>')
                note = note.replace('\\n','<br/>')
                note = note.replace('\n','<br/>')
            return note
        
        import os
        from pyasm.common import Environment
        from pyasm.common import SPTDate
        from formatted_emailer import EmailDirections
        allow_client_emails = True
        internal_template_file = '/opt/spt/custom/formatted_emailer/internal_email_template.html'
        external_template_file = '/opt/spt/custom/formatted_emailer/external_email_template.html'
        #print "In Order Inserted"
        order = input.get('sobject')
        order_code = order.get('code')
        client = order.get('client_code')
        if client not in [None,'']:
            #Get the valid recipients for this work, both internal and external
            ed = EmailDirections(order_code=order_code)
            int_data = ed.get_internal_data()
            subject = '2G-ORDER-CREATED-"%s" PO#: %s' % (int_data['order_name'], int_data['po_number'])
            subject_see = subject
            subject = subject.replace(' ','..')
            initial_po_upload_list = order.get('initial_po_upload_list')
            message = '%s has uploaded a new PO.' % int_data['from_name'].replace('.',' ')
            #The initial po upload list was created to handle uploads by clients, as the files will not exist for querying until after this trigger has been run.
            #These are the files the client uploaded to the order, inserted into the initial_po_upload_list after being selected by the client
            if initial_po_upload_list not in [None,'']:
                message = '%s<br/>Uploaded PO File: %s' % (message, initial_po_upload_list) 
            message = fix_note_chars(message) 
            #Open the internal template file and create a new file to send as email
            template = open(internal_template_file, 'r')
            filled = ''
            for line in template:
                line = line.replace('[ORDER_CODE]', int_data['order_code'])
                line = line.replace('[PO_NUMBER]', int_data['po_number'])
                line = line.replace('[CLIENT_EMAIL]', int_data['client_email'])
                line = line.replace('[EMAIL_CC_LIST]', int_data['int_ccs'])
                line = line.replace('[SCHEDULER_EMAIL]', int_data['scheduler_email'])
                line = line.replace('[SUBJECT]', subject_see)
                line = line.replace('[MESSAGE]', message)
                line = line.replace('[CLIENT]', int_data['client_name'])
                line = line.replace('[CLIENT_LOGIN]', int_data['client_login'])
                line = line.replace('[ORDER_NAME]', int_data.get('order_hyperlink', int_data['order_name']))
                line = line.replace('[START_DATE]', fix_date(int_data['start_date']))
                line = line.replace('[DUE_DATE]', fix_date(int_data['due_date']))
                line = line.replace('[TITLE_ROW]', '')
                line = line.replace('[PROJ_ROW]', '')
                filled = '%s%s' % (filled, line)
            template.close()
            filled_in_email = '/var/www/html/formatted_emails/int_order_inserted_%s.html' % order_code
            filler = open(filled_in_email, 'w')
            filler.write(filled)
            filler.close()
            #Send the internal Email
            the_command = "php /opt/spt/custom/formatted_emailer/inserted_order_email.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, int_data['to_email'], int_data['from_email'], int_data['from_name'], subject, int_data['ccs'].replace(';','#Xs*'))
            os.system(the_command)
            ext_data = ed.get_external_data()
            if int_data['location'] == 'external' and allow_client_emails:
                ext_data = ed.get_external_data()
                #Open the external template file and create a new file to send as email
                template = open(external_template_file, 'r')
                filled = ''
                for line in template:
                    line = line.replace('[ORDER_CODE]', ext_data['order_code'])
                    line = line.replace('[PO_NUMBER]', ext_data['po_number'])
                    line = line.replace('[CLIENT_EMAIL]', ext_data['client_email'])
                    line = line.replace('[EMAIL_CC_LIST]', ext_data['ext_ccs'])
                    line = line.replace('[SCHEDULER_EMAIL]', ext_data['scheduler_email'])
                    line = line.replace('[SUBJECT]', subject_see)
                    line = line.replace('[MESSAGE]', message)
                    line = line.replace('[CLIENT]', ext_data['client_name'])
                    line = line.replace('[CLIENT_LOGIN]', ext_data['client_login'])
                    line = line.replace('[ORDER_NAME]', ext_data['order_name'])
                    line = line.replace('[START_DATE]', fix_date(ext_data['start_date']))
                    line = line.replace('[DUE_DATE]', fix_date(ext_data['due_date']))
                    filled = '%s%s' % (filled, line)
                template.close()
                filled_in_email = '/var/www/html/formatted_emails/ext_order_inserted_%s.html' % order_code
                filler = open(filled_in_email, 'w')
                filler.write(filled)
                filler.close()
                #Send the External Email
                the_command = "php /opt/spt/custom/formatted_emailer/inserted_order_email.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, ext_data['to_email'], ext_data['from_email'], ext_data['from_name'], subject, ext_data['ccs'].replace(';','#Xs*'))
                os.system(the_command)
    except AttributeError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the server object does not exist.'
        raise e
    except KeyError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the input dictionary does not exist.'
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e
def main(server=None, input=None):
    """
    The main function of the custom script. The entire script was copied
    and pasted into the body of the try statement in order to add some
    error handling. It's all legacy code, so edit with caution.

    :param server: the TacticServerStub object
    :param input: a dict with data like like search_key, search_type, sobject, and update_data
    :return: None
    """
    if not input:
        input = {}

    try:
        # CUSTOM_SCRIPT00103
        # Matthew Tyler Misenhimer
        # Sends an email when a External Rejection is updated
        
        def fix_note_chars(note):
            if isinstance(note, bool):
                note2 = 'False'
                if note:
                    note2 = 'True'
                note = note2
            else:
                import sys
                from json import dumps as jsondumps
                if note not in [None,'']:
                    if sys.stdout.encoding:
                        note = note.decode(sys.stdout.encoding)
                note = jsondumps(note)
                note = note.replace('||t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                note = note.replace('\\"','"')
                note = note.replace('\"','"')
                note = note.replace('||n','<br/>')
                note = note.replace('\\\\n','<br/>')
                note = note.replace('\\\n','<br/>')
                note = note.replace('\\n','<br/>')
                note = note.replace('\n','<br/>')
            return note
        
        import os, time
        from pyasm.common import Environment
        import common_tools.utils as ctu
        internal_template_file = '/opt/spt/custom/formatted_emailer/internal_general_fillin_template.html'
        trigger_sobject = input.get('trigger_sobject')
        event = trigger_sobject.get('event')
        is_insert = False
        if 'insert' in event:
            is_insert = True
        if not is_insert:
            er_dict = input.get('sobject')
            login = er_dict.get('login')
            order_code = er_dict.get('order_code')
            title_code = er_dict.get('title_code')
        
            reported_issue = er_dict.get('reported_issue')
            if reported_issue not in [None,'']:
                reported_issue = reported_issue.replace('\n','<br/>').replace(' ','&nbsp;')
            reported_issue = fix_note_chars(reported_issue)
            
            rcnq = "@SOBJECT(sthpw/note['search_id','%s']['process','Root Cause']['search_type','twog/external_rejection?project=twog'])" % (er_dict.get('id'))
            root_cause_notes = server.eval(rcnq)
            root_cause = ''
            for rc in root_cause_notes:
                root_cause = '%s\n%s -- %s\n<b>Note: %s</b>\n' % (root_cause, rc.get('login'), rc.get('timestamp').split('.')[0], rc.get('note'))
            if root_cause not in [None,'']:
                root_cause = root_cause.replace('\n','<br/>').replace(' ','&nbsp;')
            root_cause = fix_note_chars(root_cause)
        
            corrective_action_notes = server.eval("@SOBJECT(sthpw/note['search_id','%s']['process','Corrective Action']['search_type','twog/external_rejection?project=twog'])" % (er_dict.get('id')))
            corrective_action = ''
            for ca in corrective_action_notes:
                corrective_action = '%s\n%s -- %s\n<b>Note:%s</b>\n' % (corrective_action, ca.get('login'), ca.get('timestamp').split('.')[0], ca.get('note'))
            if corrective_action not in [None,'']:
                corrective_action = corrective_action.replace('\n','<br/>').replace(' ','&nbsp;')
            corrective_action = fix_note_chars(corrective_action)

            title = er_dict.get('title')
            episode = er_dict.get('episode')
            po_number = er_dict.get('po_number')
            assigned = er_dict.get('assigned')
            status = er_dict.get('status')
            root_cause_type = er_dict.get('root_cause_type')
            corrective_action_assigned = er_dict.get('corrective_action_assigned')
            email_list = er_dict.get('email_list')
            addressed_to = email_list
            sources = er_dict.get('sources')
            replacement_order_code = er_dict.get('replacement_order_code')
            replacement_title_code = er_dict.get('replacement_title_code')
            
            reasons = ['video_cropping_reason','video_digihits_reason','video_dropped_frames_reason','video_dropout_reason','video_duplicate_frames_reason','video_interlacing_progressive_reason','video_motion_lag_reason','video_missing_elements_reason','video_corrupt_file_reason','video_bad_aspect_ratio_reason','video_bad_resolution_reason','video_bad_pixel_aspect_ratio_reason','video_bad_specifications_reason','video_bad_head_tail_reason','video_other_reason','audio_bad_mapping_reason','audio_missing_audio_channel_reason','audio_crackle_reason','audio_distortion_reason','audio_dropouts_reason','audio_sync_reason','audio_missing_elements_reason','audio_corrupt_missing_file_reason','audio_bad_specifications_reason','audio_other_reason','metadata_missing_info_reason','metadata_bad_info_reason','metadata_bad_formatting_reason','metadata_other_reason','subtitle_interlacing_reason','subtitle_bad_subtitles_reason','subtitle_sync_issue_reason','subtitle_overlapping_reason','subtitle_other_reason','cc_sync_issue_reason','cc_bad_cc_reason','cc_overlapping_reason','cc_other_reason']
            
            order_obj = server.eval("@SOBJECT(twog/order['code','%s'])" % order_code)
            order_name = ''
            client_name = ''
            scheduler = ''
            if order_obj:
                order_obj = order_obj[0]
                order_name = order_obj.get('name')
                client_name = order_obj.get('client_name')
                scheduler = order_obj.get('login')

            order_builder_url = ctu.get_order_builder_url(order_code, server)
            href = '<a href="{0}">{1}</a>'
            order_hyperlink = href.format(order_builder_url, order_name)

            title_obj = server.eval("@SOBJECT(twog/title['code','%s'])" % title_code)
            title_due_date = ''
            title_expected_delivery = ''
            title_full_name = title
            if episode not in [None,'']:
                title_full_name = '%s: %s' % (title, episode)
            if title_obj:
                title_obj = title_obj[0]
                title_due_date = title_obj.get('due_date')
                title_expected_delivery = title_obj.get('expected_delivery_date')
                if client_name in [None,'']:
                    client_name = title_obj.get('client_name')
                if scheduler in [None,'']:
                    scheduler = order_obj.get('login')
                
            update_data = None
            main_message = ''
            head_message = ''
            head_detail = ''
            is_an_update = False
            if 'update_data' in input.keys():
                update_data = input.get('update_data')
                prev_data = input.get('prev_data')
                if prev_data not in [None,{},'']:
                    ukeys = update_data.keys()
                    if len(ukeys) > 0:
                        is_an_update = True
                        head_message = 'Update for External Rejection on %s (%s) [%s PO#: %s]:' % (title_full_name, title_code, order_code, po_number)
                        if 'status' in ukeys and update_data['status'] == 'Closed':
                            head_message += '<br/><br/>THIS EXTERNAL REJECTION IS NOW CLOSED'
                        else:
                            return
                    main_message = '<table style="font-size: 14px;"><tr><td colspan="2"><br/><hr></td><td> </td></tr>'
                    main_message += '<tr><td valign="top"><b><u>Reported Issue:</u></b></td><td valign="top">{0}</td></tr>'.format(reported_issue)
                    main_message += '<tr><td valign="top"><b><u>Root Cause:</u></b></td><td valign="top">{0}</td></tr>'.format(root_cause)
                    main_message += '<tr><td valign="top"><b><u>Corrective Action:</u></b></td><td valign="top">{0}</td></tr>'.format(corrective_action)
                    main_message += '</table>'

            if is_an_update:
                subject_int = 'NEW - URGENT External Rejection Closed for %s (%s) - Status: %s Scheduler: %s PO#: %s' % (title_full_name, title_code, status, scheduler, po_number)
            else:
                return
            
            head_detail = '<tr><td align="left" style="font-size: 16px;">Replacement Order Code: <strong>%s</strong></td></tr><tr><td align="left" style="font-size: 16px;">Replacement Title Code: <strong>%s</strong></td></tr>' % (replacement_order_code, replacement_title_code)
            
            from formatted_emailer import EmailDirections
            
            ed = EmailDirections(order_code=order_code)
            int_data = ed.get_internal_data()
            
            int_template = open(internal_template_file, 'r')
            filled = ''
            for line in int_template:
                line = line.replace('[ORDER_CODE]', order_code)
                line = line.replace('[ORDER_NAME]', order_hyperlink)
                line = line.replace('[PO_NUMBER]', po_number)
                line = line.replace('[MAIN_MESSAGE]', main_message)
                line = line.replace('[TOP_MESSAGE]', head_message)
                line = line.replace('[EXTRA_HEAD_DETAIL]', head_detail)
                line = line.replace('[CLIENT_NAME]', client_name)
                line = line.replace('[TITLE_CODE]', title_code)
                line = line.replace('[TITLE_FULL_NAME]', title_full_name)
                line = line.replace('[TITLE_DUE_DATE]', title_due_date)
                line = line.replace('[TITLE_EXPECTED_DELIVERY]', title_expected_delivery)
                filled = '%s%s' % (filled, line)
            int_template.close()
            filled_in_email = '/var/www/html/formatted_emails/int_note_inserted_%s.html' % er_dict.get('code')
            filler = open(filled_in_email, 'w')
            filler.write(filled)
            filler.close()
            if addressed_to not in [None,'']:
                adt = addressed_to.split(',')
                for adta in adt:
                    if '@2gdigital' in adta and adta not in int_data['int_ccs']:
                        if int_data['int_ccs'] == '':
                            int_data['int_ccs'] = adta
                        else:
                            int_data['int_ccs'] = '%s;%s' % (int_data['int_ccs'], adta)
            if int_data['int_ccs'] in [None,'']:
                int_data['int_ccs'] = '[email protected];[email protected]'
            else:
                int_data['int_ccs'] = '%s;[email protected];[email protected]' % int_data['int_ccs']
            int_data['int_ccs'] = '%s;[email protected]' % (int_data['int_ccs']) 
            login_email = server.eval("@GET(sthpw/login['login','%s'].email)" % login)
            if login_email:
                int_data['from_email'] = login_email[0] 
            #NEW WAY TO SET THE FROM FOR THE EMAIL
            login_obj = Environment.get_login()
            sender_email = login_obj.get_value('email')
            sender_name = '%s %s' % (login_obj.get_value('first_name'), login_obj.get_value('last_name'))
            subject_int = subject_int.replace(' ','..')
            #the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, int_data['to_email'], int_data['from_email'], int_data['from_name'], subject_int, int_data['int_ccs'].replace(';','#Xs*'))
            the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, int_data['to_email'], sender_email, sender_name, subject_int, int_data['int_ccs'].replace(';','#Xs*'))
            if int_data['to_email'] not in [None,''] and int_data['int_ccs'] not in [None,'',';']:
                os.system(the_command)
    except AttributeError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the server object does not exist.'
        raise e
    except KeyError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the input dictionary does not exist.'
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e
示例#5
0
def main(server=None, input=None):
    """
    The main function of the custom script. The entire script was copied
    and pasted into the body of the try statement in order to add some
    error handling. It's all legacy code, so edit with caution.

    :param server: the TacticServerStub object
    :param input: a dict with data like like search_key, search_type, sobject, and update_data
    :return: None
    """
    if not input:
        input = {}

    try:
        # CUSTOM_SCRIPT00060
        # Matthew Tyler Misenhimer
        # This was made to report by email that a new order has been inserted
        # Do not send external if location is internal

        import os
        from pyasm.common import Environment
        from pyasm.common import SPTDate
        from formatted_emailer import EmailDirections, email_sender
        allow_client_emails = True
        internal_template_file = '/opt/spt/custom/formatted_emailer/order_inserted_email_template.html'
        external_template_file = '/opt/spt/custom/formatted_emailer/external_email_template.html'
        order = input.get('sobject')
        order_code = order.get('code')
        client = order.get('client_code')
        if client not in [None, '']:
            # Get the valid recipients for this work, both internal and external
            ed = EmailDirections(order_code=order_code)
            int_data = ed.get_internal_data()
            subject = '2G-ORDER-CREATED-"%s" PO#: %s' % (int_data['order_name'], int_data['po_number'])
            subject_see = subject
            subject = subject.replace(' ', '..')
            initial_po_upload_list = order.get('initial_po_upload_list')
            message = '%s has uploaded a new PO.' % int_data['from_name'].replace('.', ' ')
            # The initial po upload list was created to handle uploads by clients,
            # as the files will not exist for querying until after this trigger has been run.
            # These are the files the client uploaded to the order,
            # inserted into the initial_po_upload_list after being selected by the client
            if initial_po_upload_list not in [None, '']:
                message = '%s<br/>Uploaded PO File: %s' % (message, initial_po_upload_list)
            message = ctu.fix_message_characters(message)

            int_data['subject'] = subject
            int_data['message'] = message
            int_data['start_date'] = ctu.fix_date(int_data['start_date'])
            int_data['due_date'] = ctu.fix_date(int_data['due_date'])

            email_sender.send_email(template=internal_template_file, email_data=int_data,
                                    email_file_name='int_order_inserted_{0}.html'.format(order_code), server=server)

            if int_data['location'] == 'external' and allow_client_emails:
                ext_data = ed.get_external_data()
                # Open the external template file and create a new file to send as email
                template = open(external_template_file, 'r')
                filled = ''
                for line in template:
                    line = line.replace('[ORDER_CODE]', ext_data['order_code'])
                    line = line.replace('[PO_NUMBER]', ext_data['po_number'])
                    line = line.replace('[CLIENT_EMAIL]', ext_data['client_email'])
                    line = line.replace('[EMAIL_CC_LIST]', ext_data['ext_ccs'])
                    line = line.replace('[SCHEDULER_EMAIL]', ext_data['scheduler_email'])
                    line = line.replace('[SUBJECT]', subject_see)
                    line = line.replace('[MESSAGE]', message)
                    line = line.replace('[CLIENT]', ext_data['client_name'])
                    line = line.replace('[CLIENT_LOGIN]', ext_data['client_login'])
                    line = line.replace('[ORDER_NAME]', ext_data['order_name'])
                    line = line.replace('[START_DATE]', ctu.fix_date(ext_data['start_date']))
                    line = line.replace('[DUE_DATE]', ctu.fix_date(ext_data['due_date']))
                    filled = '%s%s' % (filled, line)
                template.close()
                filled_in_email = '/var/www/html/formatted_emails/ext_order_inserted_%s.html' % order_code
                filler = open(filled_in_email, 'w')
                filler.write(filled)
                filler.close()
                # Send the External Email
                the_command = "php /opt/spt/custom/formatted_emailer/inserted_order_email.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, ext_data['to_email'], ext_data['from_email'], ext_data['from_name'], subject, ext_data['ccs'].replace(';','#Xs*'))
                os.system(the_command)
    except AttributeError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the server object does not exist.'
        raise e
    except KeyError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the input dictionary does not exist.'
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e
def main(server=None, event_data=None):
    """
    The main function of the custom script.

    :param server: the TacticServerStub object
    :param event_data: a dict with data like search_key, search_type, sobject, and update_data
    :return: None
    """
    if not event_data:
        event_data = {}

    try:
        # CUSTOM_SCRIPT00107
        work_order, task = get_sobjects(server, event_data)
        if not task or task.get('status') == 'Pending':
            # They don't care about updates if the work order is not ready yet
            return

        assigned_group = work_order.get('work_group')
        if assigned_group and get_notification_setting(assigned_group, server):
            from formatted_emailer import EmailDirections, email_sender
            ed = EmailDirections(order_code=work_order.get('order_code'))
            internal_data = ed.get_internal_data()
            title = server.query('twog/title', filters=[('code', work_order.get('title_code'))])
            title = title[0] if title else {}

            # to_email should be the department distribution group
            # TODO: get the actual department distribution email address
            internal_data['to_email'] = '{0}@2gdigital.com'.format(assigned_group)
            if get_is_insert(event_data.get('update_data')):
                subject = 'Work Order "{0}" assigned to "{1}"'.format(work_order.get('process'), assigned_group)
                message = work_order.get('instructions')
                internal_data['message_type'] = 'INSTRUCTIONS:'
            else:
                subject = 'Work Order "{0}" has been updated'.format(work_order.get('process'))
                message = get_update_message(event_data.get('prev_data'), event_data.get('update_data'))
                internal_data['message_type'] = 'UPDATES:'

            internal_data['subject'] = subject
            internal_data['message'] = message
            internal_data['work_order_code'] = work_order.get('code')
            internal_data['work_order_name'] = work_order.get('process')
            internal_data['title_code'] = title.get('code')
            internal_data['title_name'] = title.get('title')
            title_hyperlink = ctu.get_edit_wdg_hyperlink('twog/title', title.get('code'),
                                                         sobject_name=title.get('title'), server=server)
            internal_data['title_hyperlink'] = title_hyperlink
            internal_data['start_date'] = ctu.fix_date(internal_data.get('start_date'))
            internal_data['due_date'] = ctu.fix_date(internal_data.get('due_date'))

            # TODO: generalize this and make it a prod setting
            if 'tactic03' in server.server_name or 'tactic04' in server.server_name:
                internal_data['to_email'] = '*****@*****.**'
                internal_data['ccs'] = ''

            email_template = '/opt/spt/custom/formatted_emailer/work_order_email_template.html'
            email_file_name = 'work_order_inserted/work_order_{0}.html'.format(work_order.get('code'))
            email_sender.send_email(template=email_template, email_data=internal_data, email_file_name=email_file_name)

    except AttributeError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the server object does not exist.'
        raise e
    except KeyError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the event dictionary does not exist.'
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e
示例#7
0
def main(server=None, input=None):
    """
    The main function of the custom script. The entire script was copied
    and pasted into the body of the try statement in order to add some
    error handling. It's all legacy code, so edit with caution.

    :param server: the TacticServerStub object
    :param input: a dict with data like like search_key, search_type, sobject, and update_data
    :return: None
    """
    if not input:
        input = {}

    try:
        # CUSTOM_SCRIPT00061
        # Matthew Tyler Misenhimer
        # This code is run when a note is inserted
        # It emails the note to the groups or individuals associated with the objects the note is attached to
        def make_right_code_ending(sid):
            ending = str(sid)
            ending_len = len(ending)
            if ending_len < 5:
                zeros = 5 - ending_len
                for num in range(0, zeros):
                    ending = '0%s' % ending
            return ending

        import os, time, sys
        from pyasm.common import Environment
        allow_client_emails = True
        external_template_file = '/opt/spt/custom/formatted_emailer/external_email_template.html'
        internal_template_file = '/opt/spt/custom/formatted_emailer/note_inserted_email_template.html'
        note_dict = input.get('sobject')
        search_type = note_dict.get('search_type').split('?')[0]
        search_id = note_dict.get('search_id')
        login = note_dict.get('login')
        process = note_dict.get('process')
        note = note_dict.get('note')

        if 'Corrective Action' in process or 'Root Cause' in process or 'Cloned WO:' in process:
            return

        # If there are no attached files, then send the note
        # If there are attached files, the file insertion trigger will email the note
        if 'HASATTACHEDFILES' not in note and process not in ['Billing', 'Closed']:
            note = note.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
            note = note.replace('\n', '<br/>')
            note = note.replace('  ', '&nbsp;&nbsp;')
            note_id = note_dict.get('id')
            timestamp = note_dict.get('timestamp').split('.')[0]
            addressed_to = note_dict.get('addressed_to')
            parent_tall_str = search_type.split('/')[1].upper()
            order = None
            title = None
            proj = None
            title_row = ''
            proj_row = ''
            is_external_rejection = False
            if parent_tall_str in ['ORDER', 'TITLE', 'PROJ', 'WORK_ORDER']:
                from formatted_emailer import EmailDirections, email_sender
                right_ending = make_right_code_ending(search_id)
                parent_code = '%s%s' % (parent_tall_str, right_ending)
                parent = server.eval("@SOBJECT(%s['code','%s'])" % (search_type, parent_code))
                if parent:
                    parent = parent[0]
                going_to_client = False
                if parent_tall_str == 'WORK_ORDER':
                    proj = server.eval("@SOBJECT(twog/work_order['code','%s'].twog/proj)" % parent_code)[0]
                    title = server.eval("@SOBJECT(twog/work_order['code','%s'].twog/proj.twog/title)" % parent_code)[0]
                    order = server.eval("@SOBJECT(twog/order['code','%s'])" % title.get('order_code'))[0]
                elif parent_tall_str == 'PROJ':
                    proj = parent
                    title = server.eval("@SOBJECT(twog/proj['code','%s'].twog/title)" % parent_code)[0]
                    order = server.eval("@SOBJECT(twog/order['code','%s'])" % title.get('order_code'))[0]
                elif parent_tall_str == 'TITLE':
                    title = parent
                    order = server.eval("@SOBJECT(twog/order['code','%s'])" % title.get('order_code'))[0]
                elif parent_tall_str == 'ORDER':
                    order = server.eval("@SOBJECT(twog/order['code','%s'])" % parent_code)[0]
                if parent_tall_str == 'ORDER' and process == 'client':
                    order = parent
                    going_to_client = True
                elif parent_tall_str == 'TITLE' and process == 'client':
                    going_to_client = True
                display_heirarchy = ''

                ed = EmailDirections(order_code=order.get('code'))
                int_data = ed.get_internal_data()
                int_data['info_text_color'] = '#06C'
                ext_data = ed.get_external_data()

                if title:
                    title_display = title.get('title')
                    if title.get('episode') not in [None, '']:
                        title_display = '%s: %s' % (title_display, title.get('episode'))
                    display_heirarchy = '"%s" in %s' % (title_display, display_heirarchy)
                if parent_tall_str in ['ORDER', 'TITLE']:
                    ident_str = '%s PO# %s' % (display_heirarchy, ext_data['po_number'])
                else:
                    ident_str = '%s (%s)' % (parent_code, ext_data['po_number'])
                subject = '2G-NOTE FOR %s' % ident_str
                if 'External Rejection' in process:
                    # Then it is a Title, for sure
                    is_external_rejection = True
                    title_name = parent.get('title')
                    if parent.get('episode') not in [None, '']:
                        title_name = '%s: %s' % (title_name, parent.get('episode'))
                    subject = '%s on %s' % (process, title_name)
                if 'MTMSUBJECT' in note:
                    snote = note.split('MTMSUBJECT')
                    subject = snote[0]
                    note = snote[1]
                subject_int = subject
                if title:
                    if title.get('login') not in [None, '']:
                        subject_int = '%s Scheduler: %s' % (subject_int, title.get('login'))
                else:
                    if order.get('login') not in [None, '']:
                        subject_int = '%s Scheduler: %s' % (subject_int, order.get('login'))

                if ext_data['to_email'] == '' and ext_data['ext_ccs'] == '' and ext_data['location'] == 'external':
                    subject = 'NOT SENT TO CLIENT!? %s' % subject
                    subject_int = 'NOT SENT TO CLIENT!? %s' % subject_int
                subject_see = subject
                subject = subject.replace(' ', '..')
                subject_int = subject_int.replace(' ', '..')
                note = ctu.fix_message_characters(note)
                message = '%s has added a new note for %s:<br/><br/><p style="font-size: 16px;"><b>Note:</b><i><br/>%s<br/>%s</i></p>' % (ext_data['from_name'], ident_str, note, timestamp)
                if going_to_client and allow_client_emails:
                    ext_template = open(external_template_file, 'r')
                    filled = ''
                    for line in ext_template:
                        line = line.replace('[ORDER_CODE]', ext_data['order_code'])
                        line = line.replace('[PO_NUMBER]', ext_data['po_number'])
                        line = line.replace('[CLIENT_EMAIL]', ext_data['client_email'])
                        line = line.replace('[EMAIL_CC_LIST]', ext_data['ext_ccs'])
                        line = line.replace('[SCHEDULER_EMAIL]', ext_data['scheduler_email'])
                        line = line.replace('[SUBJECT]', subject_see)
                        line = line.replace('[MESSAGE]', message)
                        line = line.replace('[CLIENT]', ext_data['client_name'])
                        line = line.replace('[CLIENT_LOGIN]', ext_data['client_login'])
                        line = line.replace('[ORDER_NAME]', ext_data['order_name'])
                        line = line.replace('[START_DATE]', ctu.fix_date(ext_data['start_date']))
                        line = line.replace('[DUE_DATE]', ctu.fix_date(ext_data['due_date']))
                        filled = '%s%s' % (filled, line)
                    ext_template.close()
                    filled_in_email = '/var/www/html/formatted_emails/ext_note_inserted_%s.html' % note_id
                    filler = open(filled_in_email, 'w')
                    filler.write(filled)
                    filler.close()
                    if addressed_to not in [None, '']:
                        adt = addressed_to.split(',')
                        for adta in adt:
                            if '@2gdigital' not in adta and adta not in ext_data['ext_ccs']:
                                if ext_data['ext_ccs'] == '':
                                    ext_data['ext_ccs'] = adta
                                else:
                                    ext_data['ext_ccs'] = '%s;%s' % (ext_data['ext_ccs'], adta)
                    the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, ext_data['to_email'], ext_data['from_email'], ext_data['from_name'], subject, ext_data['ext_ccs'].replace(';','#Xs*'))
                    if ext_data['to_email'] not in [None, ''] and ext_data['ext_ccs'] not in [None, '', ';']:
                        os.system(the_command)

                # Now do internal email
                details = order.get('details', '')
                if details:
                    int_data['order_hyperlink'] += ' - ' + details
                if title:
                    full_title = title.get('title')
                    if title.get('episode') not in [None, '']:
                        full_title = '%s: %s' % (full_title, title.get('episode'))
                    title_row = "<tr><td align='left' style='color: #06C; font-size: 16px;'>Title: <strong>%s</strong> | Title Code: <strong>%s</strong></td></tr>" % (full_title, title.get('code'))
                if proj:
                    proj_row = "<tr><td align='left' style='color: #06C; font-size: 16px;'>Project: <strong>%s</strong> | Project Code: <strong>%s</strong></td></tr>" % (proj.get('process'), proj.get('code'))
                if is_external_rejection:
                    int_data['info_text_color'] = '#FF0000'
                    title_row = title_row.replace('#06C', '#FF0000')
                    proj_row = proj_row.replace('#06C', '#FF0000')

                int_data['subject'] = subject_int
                int_data['message'] = message
                int_data['title_row'] = title_row
                int_data['proj_row'] = proj_row
                int_data['start_date'] = ctu.fix_date(int_data['start_date'])
                int_data['due_date'] = ctu.fix_date(int_data['due_date'])

                cc_addresses = int_data['int_ccs'].split(';')
                if addressed_to:
                    cc_addresses.extend([x for x in addressed_to.split(',') if '@2gdigital' in x])
                if is_external_rejection:
                    cc_addresses.append('*****@*****.**')
                cc_addresses.append('*****@*****.**')
                int_data['ccs'] = ';'.join(set(cc_addresses))

                login_email = server.eval("@GET(sthpw/login['login','{0}'].email)".format(login))
                if login_email:
                    int_data['from_email'] = login_email[0]

                if int_data['to_email']:
                    email_sender.send_email(template=internal_template_file, email_data=int_data,
                                            email_file_name='int_note_inserted_{0}.html'.format(note_id), server=server)

            elif 'WHATS_NEW' in parent_tall_str:
                subject = 'Updates have been made to Tactic'
                subject_int = subject.replace(' ', '..')
                message = 'Changes have been made to Tactic. Please see the "Whats New" section in Tactic to see what has changed.'
                internal_template_file = '/opt/spt/custom/formatted_emailer/whats_new_email.html'
                int_template = open(internal_template_file, 'r')
                filled = ''
                for line in int_template:
                    line = line.replace('[MESSAGE]', message)
                    filled = '%s%s' % (filled, line)
                int_template.close()
                filled_in_email = '/var/www/html/formatted_emails/whats_new_email_%s.html' % search_id
                filler = open(filled_in_email, 'w')
                filler.write(filled)
                filler.close()
                addressed_to = '*****@*****.**'
                from_email = '*****@*****.**'
                the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, addressed_to, from_email, 'Admin', subject_int, '*****@*****.**')
                os.system(the_command)
            elif 'CLIENT' in parent_tall_str:
                subject = 'A client has been put on a billing hold'
                subject_int = subject.replace(' ', '..')
                note = ctu.fix_message_characters(note)
                message = '%s' % note
                internal_template_file = '/opt/spt/custom/formatted_emailer/whats_new_email.html'
                int_template = open(internal_template_file, 'r')
                filled = ''
                for line in int_template:
                    line = line.replace('[MESSAGE]', message)
                    filled = '%s%s' % (filled, line)
                int_template.close()
                filled_in_email = '/var/www/html/formatted_emails/whats_new_email_%s.html' % search_id
                filler = open(filled_in_email, 'w')
                filler.write(filled)
                filler.close()
                addressed_to = note_dict.get('addressed_to')
                from_email = '*****@*****.**'
                the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, addressed_to, from_email, 'Accounting', subject_int, '*****@*****.**')
                os.system(the_command)
            elif 'EXTERNAL_REJECTION' in parent_tall_str:
                note = ctu.fix_message_characters(note)
                right_ending = make_right_code_ending(search_id)
                parent_code = '%s%s' % (parent_tall_str, right_ending)
                parent = server.eval("@SOBJECT(%s['code','%s'])" % (search_type, parent_code))[0]
                if process == 'Root Cause':
                    server.update(parent.get('__search_key__'), {'root_cause': note})
                elif process == 'Corrective Action':
                    server.update(parent.get('__search_key__'), {'corrective_action': note})
                else:
                    email_list = parent.get('email_list')
                    server.update(parent.get('__search_key__'), {'email_list': email_list})

    except AttributeError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the server object does not exist.'
        raise e
    except KeyError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the input dictionary does not exist.'
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e
示例#8
0
def main(server=None, input=None):
    """
    The main function of the custom script. The entire script was copied
    and pasted into the body of the try statement in order to add some
    error handling. It's all legacy code, so edit with caution.

    :param server: the TacticServerStub object
    :param input: a dict with data like like search_key, search_type, sobject, and update_data
    :return: None
    """
    if not input:
        input = {}

    try:
        # CUSTOM_SCRIPT00074
        # Matthew Tyler Misenhimer
        # This is run when a new file is uploaded to an object or a note (notes handled differently)
        
        # Do Not send external if location is internal
        def make_right_code_ending(sid):
            ending = str(sid)
            ending_len = len(ending)
            if ending_len < 5:
                zeros = 5 - ending_len
                for num in range (0, zeros):
                    ending = '0%s' % ending
            return ending
        
        def make_note_code_ending(sid):
            ending = str(sid)
            ending_len = len(ending)
            if ending_len < 8:
                zeros = 8 - ending_len
                for num in range (0, zeros):
                    ending = '0%s' % ending
            return ending
        
        def make_timestamp():
            import datetime
            now = datetime.datetime.now()
            return now.strftime("%Y-%m-%d %H:%M:%S")
        
        def get_time_date_dict(str_time):
            pre_split = str_time.split('.')[0]
            first_split = pre_split.split(' ')
            date = first_split[0]
            time = first_split[1]
            date_split = date.split('-')
            dt = {}
            dt['year'] = int(date_split[0])
            dt['month'] = int(date_split[1])
            dt['day'] = int(date_split[2])
            dt['date'] = date
            dt['time'] = time
            time_split = time.split(':')
            dt['hour'] = int(time_split[0])
            dt['minute'] = int(time_split[1])
            dt['second'] = int(time_split[2])
            dt['big_time'] = float((dt['hour'] * 3600) + (dt['minute'] * 60) + dt['second'])
            return dt
        
        def compare_dt_dicts(dt1, dt2):
            # This is rough. Don't use it for anything else. Should work for this though.
            # This is to see the difference in seconds between two special date&time dicts. 
            # Result in first position in return array will be 1 if the first passed in variable is older, 0 if it is newer than the second passed in
            difference = 0
            newest = -1
            dt1_bignum = float(float((dt1['year'] - 2000) * 365 * 24 * 3600) + float((dt1['month'] - 1) * 31 * 24 * 3600) + float((dt1['day'] - 1) * 24 * 3600) + dt1['big_time'])    
            dt2_bignum = float(float((dt2['year'] - 2000) * 365 * 24 * 3600) + float((dt2['month'] - 1) * 31 * 24 * 3600) + float((dt2['day'] - 1) * 24 * 3600) + dt2['big_time'])    
            difference = dt2_bignum - dt1_bignum
            if difference < 0:
                newest = 0
            else:
                newest = 1
            return [difference, newest]
        
        def fix_date(date):
            #This is needed due to the way Tactic deals with dates (using timezone info), post v4.0
            from pyasm.common import SPTDate
            return_date = ''
            date_obj = SPTDate.convert_to_local(date)
            if date_obj not in [None,'']:
                return_date = date_obj.strftime("%Y-%m-%d  %H:%M")
            return return_date
        
        def fix_note_chars(note):
            import sys
            from json import dumps as jsondumps
            if sys.stdout.encoding:
                note = note.decode(sys.stdout.encoding)
            note = jsondumps(note)
            note = note.replace('||t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
            note = note.replace('\\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
            note = note.replace('\\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
            note = note.replace('\\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
            note = note.replace('\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
            note = note.replace('\\"','"')
            note = note.replace('\"','"')
            note = note.replace('||n','<br/>')
            note = note.replace('\\\\n','<br/>')
            note = note.replace('\\\n','<br/>')
            note = note.replace('\\n','<br/>')
            note = note.replace('\n','<br/>')
            return note
        
        
        
        import os
        from pyasm.common import Environment
        allow_client_emails = True
        sobject = input.get('sobject')
        parent_type_solid = sobject.get('search_type')
        parent_type = sobject.get('search_type').split('?')[0]
        find_str = parent_type.split('/')[1].upper().split('?')[0]
        file_name = sobject.get('file_name') #.replace(' ','_')
        #This only handles files that were attached to notes or orders
        
        
        
        
        
        
        
        if '_web.' not in file_name and '_icon.' not in file_name and 'icon' not in sobject.get('checkin_dir'):
            #see if the file was attached to a note, if not, see if it was connected to an order 
            note_expr = "@SOBJECT(sthpw/snapshot['search_id','%s']['search_type','sthpw/note']['@ORDER_BY','timestamp asc'])" % sobject.get('search_id')
            snapshots = server.eval(note_expr)
            if len(snapshots) == 0:
                order_expr = "@SOBJECT(sthpw/snapshot['search_id','%s']['search_type','twog/order?project=twog'])" % sobject.get('search_id')
                snapshots = server.eval(order_expr)
            if len(snapshots) > 0:
                #Get the most recent snapshot that the file could have been attached to
                snapshot = snapshots[len(snapshots) - 1]    
                is_latest = snapshot.get('is_latest')
                description = snapshot.get('description')
                process = snapshot.get('process')
                id = snapshot.get('id')
                search_id = snapshot.get('search_id')
                code = snapshot.get('code')
                snap_timestamp = snapshot.get('timestamp')
                sea_t = sobject.get('search_type').split('?')[0]
                upper_st = sea_t.split('/')[1].upper()
                srch_id = sobject.get('search_id')
                full_ending = make_right_code_ending(srch_id)
                parent_code = '%s%s' % (upper_st, full_ending)
                parent_sk = server.build_search_key(sea_t, parent_code)
                parent_type = parent_sk.split('?')[0]
                version = int(snapshot.get('version'))
                #There's a template for the internal emails, and one for those that go out to our clients
                internal_template_file = '/opt/spt/custom/formatted_emailer/internal_email_template.html'
                external_template_file = '/opt/spt/custom/formatted_emailer/external_email_template.html'
                if is_latest and find_str == 'ORDER':
                    #Handle the case in which it was attached to an order
                    order_code = parent_code
                    if version not in [-1,'-1']:
                        #The only process we care about sending alerts out for is the "PO"
                        if process == 'PO':
                            parent = server.eval("@SOBJECT(%s['code','%s'])" % (parent_type, parent_code))[0]
                            sched = parent.get('login')
                            sched_email = server.eval("@GET(sthpw/login['login','%s'].email)" % sched)
                            if sched_email:
                                sched_email = sched_email[0]
                            else:
                                sched_email = 'imakestringnothinghappn'
                            parent_timestamp = parent.get('timestamp')
                            snap_tdict = get_time_date_dict(snap_timestamp)
                            parent_tdict = get_time_date_dict(parent_timestamp)
                            rez = compare_dt_dicts(parent_tdict, snap_tdict)
                            #If the result is 1, the parent is older than the snapshot
                            #If the snapshot is older than the order, the result will be 0, which means there is a problem
                            if rez[1] == 1:
                                #If the difference in seconds between the object creation is greater than 15 seconds, there will probably be no problems with the following queries (Had to put it in, because it was creating errors occasionally)
                                if rez[0] > 15:
                                    #Get all the files associated with the file upload (there could be others attached to the same snapshot)
                                    #Then send an email, using the internal template
                                    from formatted_emailer import EmailDirections
                                    ed = EmailDirections(order_code=order_code)
                                    int_data = ed.get_internal_data()
                                    subject = '2G-PO-FILE-UPLOAD %s Order: "%s" PO#: %s' % (file_name, int_data['order_name'], int_data['po_number']) 
                                    if int_data['client_email'] == '' and int_data['location'] == 'external':
                                        subject = 'NOT SENT TO CLIENT!? %s' % subject
                                    subject_see = subject
                                    subject = subject.replace(' ','..')
                                    message = '%s has uploaded a new PO File.' % int_data['from_name'].replace('.',' ')
                                    message = '%s<br/>Uploaded PO File: %s' % (message, file_name)
                                    if parent_type == 'twog/order':
                                        sales_repper = parent.get('sales_rep')
                                        sales_rep_email = server.eval("@GET(sthpw/login['login','%s']['location','internal'].email)" % sales_repper)
                                        if sales_rep_email not in [None,'',[]]:
                                            sales_rep_email = sales_rep_email[0]
                                            if int_data['ccs'] not in [None,'']:
                                                int_data['ccs'] = '%s;%s' % (int_data['ccs'], sales_rep_email)
                                            else:
                                                int_data['ccs'] = '%s' % sales_rep_email
                                    int_data['ccs'] = int_data['ccs'].replace(';%s' % sched_email, '').replace('%s;' % sched_email, '')
                                    template = open(internal_template_file, 'r')
                                    filled = ''
                                    for line in template:
                                        line = line.replace('[ORDER_CODE]', int_data['order_code'])
                                        line = line.replace('[PO_NUMBER]', int_data['po_number'])
                                        line = line.replace('[CLIENT_EMAIL]', int_data['client_email'])
                                        line = line.replace('[EMAIL_CC_LIST]', int_data['ccs'])
                                        line = line.replace('[SCHEDULER_EMAIL]', int_data['scheduler_email'])
                                        line = line.replace('[SUBJECT]', subject_see)
                                        line = line.replace('[MESSAGE]', message)
                                        line = line.replace('[CLIENT]', int_data['client_name'])
                                        line = line.replace('[CLIENT_LOGIN]', int_data['client_login'])
                                        line = line.replace('[ORDER_NAME]', int_data.get('order_hyperlink', int_data['order_name']))
                                        line = line.replace('[START_DATE]', fix_date(int_data['start_date']))
                                        line = line.replace('[DUE_DATE]', fix_date(int_data['due_date']))
                                        line = line.replace('[TITLE_ROW]', '')
                                        line = line.replace('[PROJ_ROW]', '')
                                        filled = '%s%s' % (filled, line)
                                    transaction_ticket = server.get_transaction_ticket()
                                    upload_dir = Environment.get_upload_dir(transaction_ticket)
                                    filled = '%s\nMATTACHMENT:%s/%s' % (filled, upload_dir, file_name)
                                    template.close()
                                    filled_in_email = '/var/www/html/formatted_emails/int_snap_inserted_%s.html' % code
                                    filler = open(filled_in_email, 'w')
                                    filler.write(filled)
                                    filler.close()
                                    the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, int_data['to_email'], int_data['from_email'], int_data['from_name'], subject, int_data['ccs'].replace(';','#Xs*'))
                                    os.system(the_command)
                                    #If the location of the user is external, and we allow this client to receive emails, then send them an email as well
                                    if int_data['location'] == 'external' and allow_client_emails:
                                        ext_data = ed.get_external_data()
                                        template = open(external_template_file, 'r')
                                        filled = ''
                                        for line in template:
                                            line = line.replace('[ORDER_CODE]', ext_data['order_code'])
                                            line = line.replace('[PO_NUMBER]', ext_data['po_number'])
                                            line = line.replace('[CLIENT_EMAIL]', ext_data['client_email'])
                                            line = line.replace('[EMAIL_CC_LIST]', ext_data['ccs'])
                                            line = line.replace('[SCHEDULER_EMAIL]', ext_data['scheduler_email'])
                                            line = line.replace('[SUBJECT]', subject_see)
                                            line = line.replace('[MESSAGE]', message)
                                            line = line.replace('[CLIENT]', ext_data['client_name'])
                                            line = line.replace('[CLIENT_LOGIN]', ext_data['client_login'])
                                            line = line.replace('[ORDER_NAME]', ext_data['order_name'])
                                            line = line.replace('[START_DATE]', fix_date(ext_data['start_date']))
                                            line = line.replace('[DUE_DATE]', fix_date(ext_data['due_date']))
                                            filled = '%s%s' % (filled, line)
                                        filled = '%s\nMATTACHMENT:%s/%s' % (filled, upload_dir, file_name)
                                        template.close()
                                        filled_in_email = '/var/www/html/formatted_emails/ext_snap_inserted_%s.html' % code
                                        filler = open(filled_in_email, 'w')
                                        filler.write(filled)
                                        filler.close()
                                        os.system("php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, ext_data['to_email'], ext_data['from_email'], ext_data['from_name'], subject, ext_data['ccs'].replace(';','#Xs*')))
                            else:
                                print "THIS MAKES NO SENSE. THE SNAPSHOT WAS CREATED BEFORE THE ORDER?"
                elif find_str == 'NOTE':
                    #So it was attached to a note
                    #Need to make a code with the search id, as there's different ways the order and note deal with their snapshots
                    full_ending = make_note_code_ending(srch_id)
                    parent_code = 'NOTE%s' % (full_ending)
                    parent_sk = server.build_search_key('sthpw/note', parent_code)
                    #Get the note sobject
                    #note_obj = server.eval("@SOBJECT(sthpw/note['code','%s'])" % parent_code)[0]
                    note_obj = server.eval("@SOBJECT(sthpw/note['id','%s'])" % srch_id)[0]
                    note = note_obj.get('note')
                    #Need to wait until all files have been checked in to Tactic
                    if process == 'note_attachment':
                        timestamp = note_obj.get('timestamp').split('.')[0]
                        search_id = note_obj.get('search_id') 
                        login = note_obj.get('login')
                        process = note_obj.get('process')
                        note_id = note_obj.get('id')
                        addressed_to = note_obj.get('addressed_to')
                        override_compression = True
                        #if addressed_to not in [None,'']:
                        #    override_compression = True
                        search_type = note_obj.get('search_type').split('?')[0]
                        parent_tall_str = search_type.split('/')[1].upper()
                        groups = Environment.get_group_names()
                        note = note_obj.get('note')
                        note = note.replace('\t','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                        note = note.replace('\n','<br/>')
                        note = note.replace('  ', '&nbsp;&nbsp;')
                        note = fix_note_chars(note)
                        order = None
                        title = None
                        proj = None
                        work_order = None
                        order_code = ''
                        display_ccs = ''
                        subject_see = ''
                        message = ''
                        title_row = ''
                        proj_row = ''
                        #If the note was attached to an order, title, proj or work_order, and compression didn't write the note, then send it. If compression intended to send it, then go ahead and send. 
                        if parent_tall_str in ['ORDER','TITLE','PROJ','WORK_ORDER']: # and (('compression' not in groups and 'compression supervisor' not in groups) or override_compression):
                            from formatted_emailer import EmailDirections
                            #create the note parent's code from search_id
                            right_ending = make_right_code_ending(search_id)
                            parent_code = '%s%s' % (parent_tall_str, right_ending)
                            parent = server.eval("@SOBJECT(%s['code','%s'])" % (search_type, parent_code))
                            if parent:
                                parent = parent[0]
                            ident_str = ''
                            going_to_client = False
                            #Get info from the related elements, going up the chain
                            if parent_tall_str == 'WORK_ORDER':
                                proj = server.eval("@SOBJECT(twog/work_order['code','%s'].twog/proj)" % parent_code)[0]
                                title = server.eval("@SOBJECT(twog/work_order['code','%s'].twog/proj.twog/title)" % parent_code)[0] 
                                order = server.eval("@SOBJECT(twog/order['code','%s'])" % title.get('order_code'))[0]
                            elif parent_tall_str == 'PROJ':
                                proj = parent
                                title = server.eval("@SOBJECT(twog/proj['code','%s'].twog/title)" % parent_code)[0] 
                                order = server.eval("@SOBJECT(twog/order['code','%s'])" % title.get('order_code'))[0]
                            elif parent_tall_str == 'TITLE':
                                title = parent
                                order = server.eval("@SOBJECT(twog/order['code','%s'])" % title.get('order_code'))[0]
                            elif parent_tall_str == 'ORDER':
                                order = server.eval("@SOBJECT(twog/order['code','%s'])" % parent_code)[0]
                            #If the note was attached to an order or a title, go ahead and send it to the client (as long as we allow emailing to that client), otherwise it will remain internal 
                            if parent_tall_str == 'ORDER' and process == 'client':
                                order = parent 
                                going_to_client = True
                            elif parent_tall_str == 'TITLE' and process == 'client':
                                going_to_client = True
                            display_heirarchy = ''
                        
                            #Get the different message elements and mail_to lists for internal and external emails
                            ed = EmailDirections(order_code=order.get('code'))
                            int_data = ed.get_internal_data()
                            ext_data = ed.get_external_data()
                        
                            
                            if title:
                                title_display = title.get('title')
                                if title.get('episode') not in [None,'']:
                                    title_display = '%s: %s' % (title_display, title.get('episode'))
                                display_heirarchy = '"%s" in %s' % (title_display, display_heirarchy)
                            ident_str = ''
                            if parent_tall_str in ['ORDER','TITLE']:
                                ident_str = '%s PO#: %s' % (display_heirarchy, ext_data['po_number'])
                            else:
                                ident_str = '%s (%s)' % (parent_code, ext_data['po_number'])
                            subject = '2G-NOTE ATTACHMENT FOR %s (%s)' % (ident_str, file_name)
                            #If it's not going to the client because we don't have their email, at least tell the people internally that it didn't go out to the client
                            if ext_data['to_email'] == '' and ext_data['ext_ccs'] == '' and ext_data['location'] == 'external':
                                subject = 'NOT SENT TO CLIENT!? %s' % subject
                            subject_see = subject
                            subject = subject.replace(' ','..')
                            message = '<br/>%s has added a new note for %s:<br/><br/>Note:<br/>%s<br/>%s' % (ext_data['from_name'], ident_str, note, timestamp)
                            if going_to_client and allow_client_emails:
                                ext_template = open(external_template_file, 'r')
                                filled = ''
                                for line in ext_template:
                                    line = line.replace('[ORDER_CODE]', ext_data['order_code'])
                                    line = line.replace('[PO_NUMBER]', ext_data['po_number'])
                                    line = line.replace('[CLIENT_EMAIL]', ext_data['client_email'])
                                    line = line.replace('[EMAIL_CC_LIST]', ext_data['ext_ccs'])
                                    line = line.replace('[SCHEDULER_EMAIL]', ext_data['scheduler_email'])
                                    line = line.replace('[SUBJECT]', subject_see)
                                    line = line.replace('[MESSAGE]', message)
                                    line = line.replace('[CLIENT]', ext_data['client_name'])
                                    line = line.replace('[CLIENT_LOGIN]', ext_data['client_login'])
                                    line = line.replace('[ORDER_NAME]', ext_data['order_name'])
                                    line = line.replace('[START_DATE]', fix_date(ext_data['start_date']))
                                    line = line.replace('[DUE_DATE]', fix_date(ext_data['due_date']))
                                    filled = '%s%s' % (filled, line)
                                #If there were files attached (which there should be), show what they are in the email 
                                transaction_ticket = server.get_transaction_ticket()
                                upload_dir = Environment.get_upload_dir(transaction_ticket)
                                filled = '%s\nMATTACHMENT:%s/%s' % (filled, upload_dir, file_name)
                                ext_template.close()
                                filled_in_email = '/var/www/html/formatted_emails/ext_note_inserted_%s.html' % note_id
                                filler = open(filled_in_email, 'w')
                                filler.write(filled)
                                filler.close()
                                if addressed_to not in [None,'']:
                                    adt = addressed_to.split(',')
                                    for adta in adt:
                                        if '@2gdigital' not in adta and adta not in ext_data['ext_ccs']:
                                            if ext_data['ext_ccs'] == '':
                                                ext_data['ext_ccs'] = adta
                                            else:
                                                ext_data['ext_ccs'] = '%s;%s' % (ext_data['ext_ccs'], adta)
                                the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, ext_data['to_email'], ext_data['from_email'], ext_data['from_name'], subject, ext_data['ext_ccs'].replace(';','#Xs*'))
                                if ext_data['to_email'] not in [None,''] and ext_data['ext_ccs'] not in [None,'',';']:
                                    os.system(the_command)
                            #Now do internal email
                            if title:
                                full_title = title.get('title')
                                if title.get('episode') not in [None,'']:
                                    full_title = '%s: %s' % (full_title, title.get('episode'))
                                title_row = "<div id='pagesubTitle3'>Title: <strong>%s</strong> | Title Code: <strong>%s</strong></div>" % (full_title, title.get('code')) 
                            if proj:
                                proj_row = "<div id='pagesubTitle3'>Project: <strong>%s</strong> | Project Code: <strong>%s</strong></div>" % (proj.get('process'), proj.get('code'))
                            int_template = open(internal_template_file, 'r')
                            filled = ''
                            for line in int_template:
                                line = line.replace('[ORDER_CODE]', int_data['order_code'])
                                line = line.replace('[PO_NUMBER]', int_data['po_number'])
                                line = line.replace('[CLIENT_EMAIL]', int_data['client_email'])
                                line = line.replace('[EMAIL_CC_LIST]', int_data['int_ccs'])
                                line = line.replace('[SCHEDULER_EMAIL]', int_data['scheduler_email'])
                                line = line.replace('[SUBJECT]', subject_see)
                                line = line.replace('[MESSAGE]', message)
                                line = line.replace('[CLIENT]', int_data['client_name'])
                                line = line.replace('[CLIENT_LOGIN]', int_data['client_login'])
                                line = line.replace('[ORDER_NAME]', int_data.get('order_hyperlink', int_data['order_name']))
                                line = line.replace('[START_DATE]', fix_date(int_data['start_date']))
                                line = line.replace('[DUE_DATE]', fix_date(int_data['due_date']))
                                line = line.replace('[TITLE_ROW]', title_row)
                                line = line.replace('[PROJ_ROW]', proj_row)
                                filled = '%s%s' % (filled, line)
                            #If there were files attached (which there should be), show what they are in the email 
                            transaction_ticket = server.get_transaction_ticket()
                            upload_dir = Environment.get_upload_dir(transaction_ticket)
                            filled = '%s\nMATTACHMENT:%s/%s' % (filled, upload_dir, file_name)
                            int_template.close()
                            filled_in_email = '/var/www/html/formatted_emails/int_note_inserted_%s.html' % note_id
                            filler = open(filled_in_email, 'w')
                            filler.write(filled)
                            filler.close()
                            if addressed_to not in [None,'']:
                                adt = addressed_to.split(',')
                                for adta in adt:
                                    if '@2gdigital' in adta and adta not in int_data['int_ccs']:
                                        if int_data['int_ccs'] == '':
                                            int_data['int_ccs'] = adta
                                        else:
                                            int_data['int_ccs'] = '%s;%s' % (int_data['int_ccs'], adta)
                            login_email = server.eval("@GET(sthpw/login['login','%s'].email)" % login)
                            if login_email:
                                int_data['from_email'] = login_email[0]
                            the_command = "php /opt/spt/custom/formatted_emailer/trusty_emailer.php '''%s''' '''%s''' '''%s''' '''%s''' '''%s''' '''%s'''" % (filled_in_email, int_data['to_email'], int_data['from_email'], int_data['from_name'], subject, int_data['int_ccs'].replace(';','#Xs*'))
                            if int_data['to_email'] not in [None,''] and int_data['int_ccs'] not in [None,'',';']:
                                #Do it. Send the email
                                os.system(the_command)
        elif '_icon' in file_name:
            snapshot_code = sobject.get('snapshot_code')
            extension = 'jpg' #I don't know why I can't get the actual info on this file right now. Kinda tarded. We just have to assume that it will end up being a jpg
            fsplit = file_name.split('.')
            sexpr = "@SOBJECT(sthpw/snapshot['code','%s'])" % snapshot_code
            snapshot = server.eval(sexpr)[0]
            version = int(snapshot.get('version'))
            if version > 9:
                version = 'v0%s' % version
            elif version > 99:
                version = 'v%s' % version
            else:
                version = 'v00%s' % version
            parent_type = snapshot.get('search_type').split('?')[0]
            find_str = parent_type.split('/')[1].upper().split('?')[0]
            process = snapshot.get('process')
            if process == 'icon':
                id = snapshot.get('id')
                search_id = snapshot.get('search_id')
                sea_t = snapshot.get('search_type').split('?')[0]
                upper_st = sea_t.split('/')[1].upper()
                srch_id = snapshot.get('search_id')
                full_ending = make_right_code_ending(srch_id)
                parent_code = '%s%s' % (upper_st, full_ending)
                parent_sk = server.build_search_key(sea_t, parent_code)
                parent_type = parent_sk.split('?')[0]
                #This is to set the icon for orders
                if find_str == 'ORDER':
                    preview_path = server.get_path_from_snapshot(snapshot.get('code'), mode="web")
                    preview_path_i = preview_path.split('/')
                    fn2 = preview_path_i[len(preview_path_i) - 1]
                    fn3_s = fn2.split('.')
                    fn3 = '%s_icon_%s.%s' % (fn3_s[0], version, extension)
                    preview_path = preview_path.replace(fn2, fn3)
                    server.update(parent_sk, {'icon_path': preview_path})
    except AttributeError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the server object does not exist.'
        raise e
    except KeyError as e:
        traceback.print_exc()
        print str(e) + '\nMost likely the input dictionary does not exist.'
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e