Esempio n. 1
0
 def init(my):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     my.server = TacticServerStub.get()
     my.login = Environment.get_login()
     my.user = my.login.get_login()
     my.movement_code = my.kwargs.get('movement_code')
Esempio n. 2
0
    def set_project(cls, project_code):
        '''This is kept here because everybody is used to using this'''

        security = Environment.get_security()
        # FIXME:
        # Because it is possible to call this before one is 
        # logged in.  This is required to see the login screen.
        from pyasm.security import get_security_version
        security_version = get_security_version()
        if security_version != 1 and not project_code == 'admin':
            key = { 'code': project_code }
            key2 = { 'code': "*" }
            keys = [key, key2]
            if not security.check_access("project", keys, access="allow", default="deny"):
                user = Environment.get_login()
                if user:
                    user = user.get_value("login")
                    raise SecurityException("User [%s] is not permitted to view project [%s]" % (user, project_code))
                else:
                    raise SecurityException("User is not permitted to view project [%s]" % (project_code))

        from pyasm.security import Site
        site = Site.get_site()
        PROJECT_KEY = "Project:global:%s:" % site
        Container.put(PROJECT_KEY, project_code)
Esempio n. 3
0
 def get_display(my):
     sobject = my.get_current_sobject()
     sk = sobject.get_search_key()
     widget = DivWdg()
     sts_to_perm = {'twog/qc_report_vars': 'compression|qc supervisor|edeliveries'}
     if '-1' not in sk:
         table = Table()
         table.add_attr('width', '50px')
         login = Environment.get_login()
         user_name = login.get_login()
         groups = Environment.get_group_names()
         st = sk.split('?')[0]; 
         perms = sts_to_perm[st] 
         allow = False
         for g in groups:
             if g in perms:
                 allow = True
         if user_name == 'admin':
             allow = True
         if allow:
             table.add_row()
             cell1 =  table.add_cell(my.x_butt)
             cell1.add_attr('id','sp_del_%s' % sk)
             launch_behavior = my.get_delete_behavior(sk)
             cell1.add_style('cursor: pointer;')
             cell1.add_behavior(launch_behavior)
             widget.add(table)
     return widget
Esempio n. 4
0
    def init(my):
        from pyasm.common import Environment
        from pyasm.search import Search
        my.login = Environment.get_login()
        my.user = my.login.get_login()

        my.sk = ''
        my.seen_groups = []
        my.bigdict = {}
        my.indi_pct = 0.0
        my.stat_colors = {'Pending':'#d7d7d7','In Progress':'#f5f3a4','In_Progress':'#f5f3a4','On Hold':'#e8b2b8','On_Hold':'#e8b2b8','Client Response': '#ddd5b8', 'Completed':'#b7e0a5','Need Buddy Check':'#e3701a','Ready':'#b2cee8','Internal Rejection':'#ff0000','External Rejection':'#ff0000','Fix Needed':'#c466a1','Failed QC':'#ff0000','Rejected': '#ff0000','DR In_Progress': '#d6e0a4', 'DR In Progress': '#d6e0a4','Amberfin01_In_Progress':'#D8F1A8', 'Amberfin01 In Progress':'#D8F1A8','Amberfin02_In_Progress':'#F3D291', 'Amberfin02 In Progress':'#F3D291','BATON In_Progress': '#c6e0a4', 'BATON In Progress': '#c6e0a4','Export In_Progress': '#796999','Export In Progress': '#796999', 'Buddy Check In_Progress': '#1aade3','Buddy Check In Progress': '#1aade3'}
        my.stat_relevance = {'Pending': 0,'In Progress': 4,'In_Progress': 4,'On Hold': 1,'On_Hold': 1,'Client Response': 2, 'Completed': -1,'Need Buddy Check': 10, 'Buddy Check In_Progress': 11, 'Buddy Check In Progress': 11, 'Ready': 3,'Internal Rejection': 12,'External Rejection': 13,'Failed QC': 14,'Fix Needed': 16,'Rejected': 15,'DR In_Progress': 5, 'DR In Progress': 5,'BATON In_Progress': 8, 'BATON In Progress': 8,'Export In_Progress': 9, 'Export In Progress': 9,'Amberfin01_In_Progress': 6, 'Amberfin01 In Progress': 6, 'Amberfin02_In_Progress':7, 'Amberfin02 In Progress':7 }
        my.timestamp = my.make_timestamp()
        my.date = my.timestamp.split(' ')[0]
        my.real_date = datetime.datetime.strptime(my.date, '%Y-%m-%d')
        my.all_groups = []
        my.big_user = False
        users_s = Search('sthpw/login')
        users_s.add_filter('location','internal')
        users = users_s.get_sobjects()
        my.username_lookup = {'': '', None: '', 'NOTHING': ''}
        for user in users: 
            login_name = user.get_value('login')
            fname = user.get_value('first_name')
            lname = user.get_value('last_name')
            my.username_lookup[login_name] = '%s %s' % (fname, lname)
    def get_display(my):
        sobject = None
        code = ''
        show_checks = False
        if 'source_code' in my.kwargs.keys():
            code = str(my.kwargs.get('source_code'))    
        else:
            sobject = my.get_current_sobject()
            code = sobject.get_code()
        if sobject.get_value('high_security') in [True,'T','t','1']:
            show_checks = True
        widget = DivWdg()
        table = Table()
        table.add_attr('width', '50px')
        if show_checks:
            table.add_style('background-color: #ff0000;')
            login = Environment.get_login()
            user_name = login.get_login()
            table.add_row()
            cell1 =  table.add_cell('<img border="0" style="vertical-align: middle" title="Security Checklist" name="Security Checklist" src="/context/icons/32x32/lock_32_01.png">')
            cell1.add_attr('user', user_name)
            launch_behavior = my.get_launch_behavior(code,user_name)
            cell1.add_style('cursor: pointer;')
            cell1.add_behavior(launch_behavior)
        widget.add(table)

        return widget
Esempio n. 6
0
    def set_project(cls, project_code):
        '''This is kept here because everybody is used to using this'''

        security = Environment.get_security()
        # FIXME:
        # Because it is possible to call this before one is
        # logged in.  This is required to see the login screen.
        from pyasm.security import get_security_version
        security_version = get_security_version()
        if security_version != 1 and not project_code == 'admin':
            key = {'code': project_code}
            key2 = {'code': "*"}
            keys = [key, key2]
            if not security.check_access(
                    "project", keys, access="allow", default="deny"):
                user = Environment.get_login()
                if user:
                    user = user.get_value("login")
                    raise SecurityException(
                        "User [%s] is not permitted to view project [%s]" %
                        (user, project_code))
                else:
                    raise SecurityException(
                        "Not permitted to view project [%s]" % (project_code))

        from pyasm.security import Site
        site = Site.get_site()
        PROJECT_KEY = "Project:global:%s:" % site
        Container.put(PROJECT_KEY, project_code)
Esempio n. 7
0
    def init(my):
        from client.tactic_client_lib import TacticServerStub

        my.server = TacticServerStub.get()
        my.login = Environment.get_login()
        my.user = my.login.get_login()
        my.work_order_code = ""
Esempio n. 8
0
    def get_to(my):
        from tactic_client_lib import TacticServerStub
        from pyasm.common import Environment
        recipients = set()
        to = '*****@*****.**'
        login_obj = Environment.get_login()
        login = login_obj.get_login()
        server = TacticServerStub.get()
        eq = my.sobject
        wo_code = eq.get_value('work_order_code')
        
        if wo_code not in [None,'']:
            wo = server.eval("@SOBJECT(twog/work_order['code','%s'])" % wo_code)
            if wo:
                wo = wo[0]
                if wo.get('login') != login:
                    the_obj = Login.get_by_code(wo.get('login'))
                    if the_obj:
                        recipients.add(the_obj)
#                    creator_login_obj = server.eval("@SOBJECT(sthpw/login['login','%s'])" % wo.get('login'))
#                    if creator_login_obj:
#                        creator_login_obj = creator_login_obj[0]
#                        #to = creator_login_obj.get('email')
#                        to = creator_login_obj
        print "RETURN Recipients: %s" % recipients        
        return recipients
Esempio n. 9
0
 def init(my):
     from client.tactic_client_lib import TacticServerStub
     my.login_obj = Environment.get_login()
     my.login = my.login_obj.get_login()
     my.server = TacticServerStub.get()
     my.login_obj = my.server.eval("@SOBJECT(sthpw/login['login','%s'])" % my.login)[0]
     my.key_dict = {'highlight_notes': 'Highlight Notes - Record What I Have Seen (Slower)]:', 'show_note_counts': 'Show Top Section of Notes, Showing Count Breakdown:'}
Esempio n. 10
0
    def get_display(my):
        from tactic_client_lib import TacticServerStub

        sobject = None
        code = ""
        if "source_code" in my.kwargs.keys():
            code = str(my.kwargs.get("source_code"))
        else:
            sobject = my.get_current_sobject()
            code = sobject.get_code()
        widget = DivWdg()
        table = Table()
        table.add_attr("width", "50px")
        login = Environment.get_login()
        user_name = login.get_login()
        table.add_row()
        cell1 = table.add_cell(
            '<img border="0" style="vertical-align: middle" title="Clone Source" name="Clone Source" src="/context/icons/silk/star.png">'
        )
        cell1.add_attr("user", user_name)
        launch_behavior = my.get_launch_behavior(code, user_name)
        cell1.add_style("cursor: pointer;")
        cell1.add_behavior(launch_behavior)
        widget.add(table)

        return widget
Esempio n. 11
0
    def get_display(my):
        sobject = None
        if 'order_code' in my.kwargs.keys():
            my.order_code = my.kwargs.get('order_code')
        else:
            sobject = my.get_current_sobject()
            my.order_code = sobject.get_code()
        sobject = my.server.eval("@SOBJECT(twog/order['code','%s'])" % my.order_code)[0]
        my.order_name = sobject.get('name')
        widget = DivWdg()
        table = Table()
        table.add_attr('width', '50px')
        login = Environment.get_login()
        user_name = login.get_login()
        table.add_row()
        cell1 = table.add_cell('<b><u>Calculate Costs</u></b>')
        cell1.add_attr('order_code', my.order_code)
        cell1.add_attr('user', user_name)
        cell1.add_attr('order_name', my.order_name)
        cell1.add_attr('nowrap','nowrap')
        launch_behavior = my.get_launch_behavior()
        cell1.add_style('cursor: pointer;')
        cell1.add_behavior(launch_behavior)
        widget.add(table)

        return widget
Esempio n. 12
0
 def init(my):
     from client.tactic_client_lib import TacticServerStub
     my.server = TacticServerStub.get()
     my.login = Environment.get_login()
     my.user = my.login.get_login()
     my.task_code = ''
     my.task_codes = ''
     my.code = ''
Esempio n. 13
0
 def __init__(my, **kwargs):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     super(ClipboardEmptySearchTypeCmd, my).__init__(**kwargs)
     my.login = Environment.get_login()
     my.user_name = my.login.get_login() 
     my.server = TacticServerStub.get()
     my.search_type = str(kwargs.get('search_type'))
Esempio n. 14
0
 def __init__(my, **kwargs):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     super(ClipboardMovementMakerCmd, my).__init__(**kwargs)
     my.login = Environment.get_login()
     my.user_name = my.login.get_login() 
     my.server = TacticServerStub.get()
     my.movement_code = str(kwargs.get('movement_code'))
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_SCRIPT00075
        from pyasm.common import Environment

        update_data = input.get("update_data")
        prev_data = input.get("prev_data")
        sobject = input.get("sobject")
        login = Environment.get_login()
        user_name = login.get_login()
        name = ""
        if "TITLE" in sobject.get("code"):
            name = sobject.get("title")
            if sobject.get("episode") not in [None, ""]:
                name = "%s: %s" % (name, sobject.get("episode"))
        else:
            title = server.eval("@SOBJECT(twog/title['code','%s'])" % sobject.get("title_code"))[0]
            name = title.get("title")
            if title.get("episode") not in [None, ""]:
                name = "%s: %s" % (name, title.get("episode"))
            name = "%s -> %s" % (name, sobject.get("process"))
        from_priority = prev_data.get("priority")
        if from_priority in [None, ""]:
            from_priority = 100
        server.insert(
            "twog/priority_log",
            {
                "to_priority": update_data.get("priority"),
                "from_priority": from_priority,
                "login": user_name,
                "lookup_code": sobject.get("code"),
                "name": 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 input dictionary does not exist."
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e
Esempio n. 16
0
 def init(my):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     my.server = TacticServerStub.get()
     my.login = Environment.get_login()
     my.user = my.login.get_login()
     my.code = ''
     my.types = ['Full_Work_Order']
     my.template_files = {'Full_Work_Order': '/var/www/html/source_labels/work_order.html'}
Esempio n. 17
0
 def __init__(my, **kwargs):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     super(ClipboardAddCmd, my).__init__(**kwargs)
     my.code = str(kwargs.get('code'))
     my.st = str(kwargs.get('st')).split('?')[0]
     my.login = Environment.get_login()
     my.user_name = my.login.get_login() 
     my.server = TacticServerStub.get()
Esempio n. 18
0
 def __init__(my, **kwargs):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     super(NormalPipeToHackPipeCmd, my).__init__(**kwargs)
     my.login = Environment.get_login()
     my.user_name = my.login.get_login() 
     my.server = TacticServerStub.get()
     my.sob_sk = kwargs.get('sob_sk')
     my.new_pipe = kwargs.get('new_pipe')
     my.sob_code = my.sob_sk.split('code=')[1]
Esempio n. 19
0
def main(server=None, input_data=None):
    if not input_data:
        return

    sobject_input = input_data.get('sobject')

    login = Environment.get_login()
    user_name = login.get_value("login")

    server.update(sobject_input.get('__search_key__'), {'login': user_name})
Esempio n. 20
0
 def __init__(my, **kwargs):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     super(CreateTitlesCmd, my).__init__(**kwargs)
     my.login = Environment.get_login()
     my.user_name = my.login.get_login() 
     my.server = TacticServerStub.get()
     my.data = kwargs.get('data')
     # There has to be at least one episode for some reason, even if it's empty
     my.episodes = kwargs.get('episodes', [''])
Esempio n. 21
0
 def init(my):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     my.server = TacticServerStub.get()
     my.number = 0
     my.code = ''
     my.login = Environment.get_login()
     my.user = my.login.get_login()
     my.width = '1000px'
     my.height = '300px'
Esempio n. 22
0
 def __init__(my, **kwargs):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     super(WorkOrderPrintExecutePages, my).__init__(**kwargs)
     my.server = TacticServerStub.get()
     my.login = Environment.get_login()
     my.user = my.login.get_login()
     my.codes = str(kwargs.get('codes'))
     my.types = ['Full_Work_Order']
     my.template_files = {'Full_Work_Order': '/var/www/html/source_labels/work_order.html'}
     my.transaction = None
Esempio n. 23
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_SCRIPT00105
        def make_timestamp():
            from pyasm.common import SPTDate

            # Makes a Timestamp for postgres
            import datetime

            now = SPTDate.convert_to_local(datetime.datetime.now())
            now = datetime.datetime.now()
            return now

        from pyasm.common import Environment

        if "update_data" in input.keys():
            from pyasm.common import SPTDate

            login = Environment.get_login()
            user_name = login.get_login()
            update_data = input.get("update_data")
            ukeys = update_data.keys()
            sobject = input.get("sobject")
            history = sobject.get("history_log")
            line = "[???[x^LOGIN: %s^x][x^TIMESTAMP: %s^x]" % (user_name, make_timestamp())
            for u in ukeys:
                line = "%s[^x%s: %sx^]" % (line, u.upper(), update_data.get(u))
            line = "%s???]" % line
            history = "%s%s" % (history, line)
            server.update(input.get("search_key"), {"history_log": history}, triggers=False)
    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
Esempio n. 24
0
 def init(my):
     nothing = 'true'
     my.server = None
     my.login = Environment.get_login()
     my.groups_arr = Environment.get_group_names()
     my.groups_str = ''
     for guy in my.groups_arr:
         if my.groups_str == '':
             my.groups_str = guy
         else:
             my.groups_str = '%s,%s' % (my.groups_str, guy)
     my.user_name = my.login.get_login()
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_SCRIPT00082
        def make_timestamp():
            #Makes a Timestamp for postgres
            import datetime
            now = datetime.datetime.now()
            return now.strftime("%Y-%m-%d %H:%M:%S")
        
        from pyasm.common import Environment
        login = Environment.get_login()
        user_name = login.get_login()
        update_data = input.get('update_data')
        sobject = input.get('sobject')
        client_billing = update_data.get('billing_status')
        client_code = sobject.get('code')
        new_task_str = ''
        if client_billing == 'On Hold - Do Not Book':
            new_task_str = 'nobook'
        if client_billing == 'On Hold - Do Not Ship':
            new_task_str = 'noship'

        server.execute_cmd('manual_updaters.commander.ClientBillingTaskVisibilityCmd', {'client_code': client_code, 'new_task_str': new_task_str})
        client_sk = server.build_search_key('twog/client', client_code)
        timestamp = make_timestamp()
        note = "%s has been set to '%s' by %s on %s" % (sobject.get('name'), client_billing, user_name, timestamp)
        note_ccs = '[email protected];[email protected]'
        server.execute_cmd('operator_view.MakeNoteWdg', {'obj_sk': client_sk, 'header': client_billing + ' ' + timestamp, 'note': note, 'note_ccs': note_ccs})
    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
Esempio n. 26
0
 def init(my):
     my.group_list = Environment.get_group_names()
     login = Environment.get_login()
     my.user = login.get_login()
     my.server = TacticServerStub.get()
     my.sk = ''
     my.code = ''
     my.st = ''
     my.is_scheduler = False
     for gname in my.group_list:
         if 'scheduling' in gname:
             my.is_scheduler = True
     if my.user == 'admin':
         my.is_scheduler = True
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_SCRIPT00076
        from pyasm.common import Environment
        update_data = input.get('update_data')
        prev_data = input.get('prev_data')
        sobject = input.get('sobject')
        login = Environment.get_login()
        user_name = login.get_login()
        name = sobject.get('title')
        season = sobject.get('season')
        if season not in [None,'']:
            name = '%s, SEASON: %s' % (name, season)
        episode = sobject.get('episode')
        if episode not in [None,'']:
            name = '%s, EPISODE: %s' % (name, episode)
        code = sobject.get('code')
        prevkeys = prev_data.keys()
        update_str = ''
        for key in prevkeys:
            if update_str == '':
                update_str = '[%s from:%s, to:%s]' % (key, prev_data[key], update_data[key])
            else:
                update_str = '%s[%s from:%s, to:%s]' % (update_str, key, prev_data[key], update_data[key])
        server.insert('twog/source_log', {'name': name, 'updates': update_str, 'login': user_name, 'source_code': code})
    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
Esempio n. 28
0
 def init(my):
     from client.tactic_client_lib import TacticServerStub
     from pyasm.common import Environment
     my.group_list = Environment.get_group_names()
     login = Environment.get_login()
     my.user = login.get_login()
     my.server = TacticServerStub.get()
     my.sk = ''
     my.code = ''
     my.st = ''
     my.is_scheduler = False
     for gname in my.group_list:
         if 'scheduling' in gname:
             my.is_scheduler = True
     if my.user == 'admin':
         my.is_scheduler = True
Esempio n. 29
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_SCRIPT00081
        from pyasm.common import TacticException, Environment
        login = Environment.get_login()
        user_name = login.get_login()
        update_data = input.get('update_data') 
        sobject = input.get('sobject')
        title_code = sobject.get('code')
        if 'bigboard' in update_data.keys():
            bigboard = update_data.get('bigboard')
            if bigboard not in [True,'True','true','t','T',1,'1']:
                server.insert('twog/bigboard_record', {'title_code': title_code, 'bigboard_value': 'False', 'login': user_name})
                #cmnd = "update task set bigboard = False where title_code = '%s'" % title_code
                #server.execute_cmd('manual_updaters.commander.DBDirectCmd', {'cmnd': cmnd, 'which_db': 'sthpw'})
                task_expr = "@SOBJECT(sthpw/task['title_code','%s']['bigboard','in','True|true|t|1'])" % title_code
                tasks = server.eval(task_expr)
                for task in tasks:
                    if task.get('bigboard'):
                        server.update(task.get('__search_key__'), {'bigboard': False});       
            else:
                server.insert('twog/bigboard_record', {'title_code': title_code, 'bigboard_value': 'True', 'login': user_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 input dictionary does not exist.'
        raise e
    except Exception as e:
        traceback.print_exc()
        print str(e)
        raise e
Esempio n. 30
0
    def get_display(my):
        from tactic_client_lib import TacticServerStub
        server = TacticServerStub.get()
        source_code = ''
        source_id = ''
        source_sk = ''
        user_name = ''
        if 'source_code' in my.kwargs.keys():
            source_code = str(my.kwargs.get('source_code'))    
        if 'source_id' in my.kwargs.keys():
            source_id = str(my.kwargs.get('source_id'))
        if 'source_sk' in my.kwargs.keys():
            source_sk = str(my.kwargs.get('source_sk'))
        if 'user_name' in my.kwargs.keys():
            user_name = my.kwargs.get('user_name')
        else:
            login = Environment.get_login()
            user_name = login.get_login()

        source = None
        if source_sk not in [None,'']:
            source = server.get_by_search_key(source_sk)
            source_code = source.get('code')
            #source = server.eval("@SOBJECT(twog/source['code','%s'])" % source_code)[0]
        elif source_id not in [None,'']:
            source = server.eval("@SOBJECT(twog/source['id','%s'])" % source_id)[0]
        elif source_code not in [None,'']:
            source = server.eval("@SOBJECT(twog/source['code','%s'])" % source_code)[0]
        widget = DivWdg()
        table = Table()
        if source.get('high_security'):
            table.add_row()
            table.add_cell('<font color=#ff0000">!!!HIGH SECURITY!!! Make sure you are following the following requirements!</font>')
            table.add_row()
            securitywdg = SourceSecurityWdg(user_name=user_name, source_code=source_code)
            table.add_cell(securitywdg)
            table.add_row()
            table.add_cell('<font color="#ff0000">End Security Requirements</font>') 
        table.add_row()
        editwdg = EditWdg(element_name='general', mode='edit', search_type='twog/source', code=source_code, title='Edit Source', view='edit', widget_key='edit_layout')
        table.add_cell(editwdg)
        widget.add(table)

        return widget
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_SCRIPT00058
        #THIS IS WAS JUST USED FOR TESTING. UNIMPORTANT.
        def make_timestamp():
            import datetime
            now = datetime.datetime.now()
            return now.strftime("%Y-%m-%d %H:%M:%S")
        from pyasm.common import Environment
        login = Environment.get_login()
        user_name = login.get_login()
        #print "IN DELETE OR RETIRE PIPELINE"
        now_timestamp = make_timestamp() 
        #print "DEL/RET PIPE TIME = %s" % now_timestamp
        #print "DEL/RET PIPE LOGIN = %s" % user_name
        #print "DEL/RET PIPELINE = %s" % input
    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
Esempio n. 32
0
    def get_display(my):

        web = WebContainer.get_web()

        widget = Widget()
        html = HtmlElement("html")

        is_xhtml = False
        if is_xhtml:
            web.set_content_type("application/xhtml+xml")
            widget.add('''<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html 
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
            ''')
            html.add_attr("xmlns", "http://www.w3.org/1999/xhtml")
            #html.add_attr("xmlns:svg", "http://www.w3.org/2000/svg")

        # add the copyright
        widget.add(my.get_copyright_wdg())
        widget.add(html)

        # create the header
        head = HtmlElement("head")
        html.add(head)

        head.add(
            '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>\n'
        )
        head.add('<meta http-equiv="X-UA-Compatible" content="IE=edge"/>\n')

        # Add the tactic favicon
        head.add(
            '<link rel="shortcut icon" href="/context/favicon.ico" type="image/x-icon"/>'
        )

        # add the css styling
        head.add(my.get_css_wdg())

        # add the title in the header
        project = Project.get()
        project_code = project.get_code()
        project_title = project.get_value("title")

        if web.is_admin_page():
            is_admin = " - Admin"
        else:
            is_admin = ""

        if project_code == 'admin':
            head.add("<title>TACTIC Site Admin</title>\n")
        else:
            head.add("<title>%s%s</title>\n" % (project_title, is_admin))

        # add the javascript libraries
        head.add(JavascriptImportWdg())

        # add the body
        body = my.body
        html.add(body)
        body.add_event('onload', 'spt.onload_startup(this)')

        top = my.top

        # Add a NOSCRIPT tag block here to provide a warning message on browsers where 'Enable JavaScript'
        # is not checked ... TODO: clean up and re-style to make look nicer
        top.add("""
        <NOSCRIPT>
        <div style="border: 2px solid black; background-color: #FFFF99; color: black; width: 600px; height: 70px; padding: 20px;">
        <img src="%s" style="border: none;" /> <b>Javascript is not enabled on your browser!</b>
        <p>This TACTIC powered, web-based application requires JavaScript to be enabled in order to function. In your browser's options/preferences, please make sure that the 'Enable JavaScript' option is checked on, click OK to accept the settings change, and then refresh this web page.</p>
        </div>
        </NOSCRIPT>
        """ % (IconWdg.get_icon_path("ERROR")))

        # add the content
        content_div = DivWdg()
        top.add(content_div)
        Container.put("TopWdg::content", content_div)

        # add a dummy button for global behaviors
        from tactic.ui.widget import ButtonNewWdg, IconButtonWdg
        ButtonNewWdg(title="DUMMY", icon=IconWdg.FILM)
        IconButtonWdg(title="DUMMY", icon=IconWdg.FILM)
        # NOTE: it does not need to be in the DOM.  Just needs to be
        # instantiated
        #content_div.add(button)

        if my.widgets:
            content_wdg = my.get_widget('content')
        else:
            content_wdg = Widget()
            my.add(content_wdg)

        content_div.add(content_wdg)

        # add a calendar wdg

        from tactic.ui.widget import CalendarWdg
        cal_wdg = CalendarWdg(css_class='spt_calendar_template_top')
        cal_wdg.top.add_style('display: none')
        content_div.add(cal_wdg)

        if web.is_admin_page():
            from tactic_branding_wdg import TacticCopyrightNoticeWdg
            branding = TacticCopyrightNoticeWdg(show_license_info=True)
            top.add(branding)

        # add the admin bar
        security = Environment.get_security()
        if not web.is_admin_page() and security.check_access(
                "builtin", "view_site_admin", "allow"):

            div = DivWdg()
            top.add(div)
            top.add_style("padding-top: 21px")

            div.add_class("spt_admin_bar")

            div.add_style("height: 15px")
            div.add_style("padding: 3px 0px 3px 15px")
            #div.add_style("margin-bottom: -5px")
            div.add_style("position: fixed")
            div.add_style("top: 0px")
            div.add_style("left: 0px")
            div.add_style("opacity: 0.7")
            div.add_style("width: 100%")
            #div.add_gradient("background", "background2", 20, 10)
            div.add_style("background-color", "#000")
            div.add_style("color", "#FFF")
            div.add_style("z-index", "1000")
            div.add_class("hand")
            div.set_box_shadow("0px 5px 5px")

            # remove
            icon_div = DivWdg()
            div.add(icon_div)
            icon_div.add_style("float: right")
            icon_div.add_style("margin-right: 10px")
            icon_div.add_style("margin-top: -3px")
            icon_button = IconButtonWdg(title="Remove Admin Bar",
                                        icon=IconWdg.G_CLOSE)
            icon_div.add(icon_button)
            icon_button.add_behavior({
                'type':
                'click_up',
                'cbjs_action':
                '''
                var parent = bvr.src_el.getParent(".spt_admin_bar");
                bvr.src_el.getParent(".spt_top").setStyle("padding-top", "0px");
                spt.behavior.destroy_element(parent);
                '''
            })

            div.add("<b>ADMIN >></b>")

            div.add_behavior({
                'type':
                'listen',
                'event_name':
                'close_admin_bar',
                'cbjs_action':
                '''
                bvr.src_el.getParent(".spt_top").setStyle("padding-top", "0px");
                spt.behavior.destroy_element(bvr.src_el);
                '''
            })

            div.add_behavior({
                'type':
                'mouseover',
                'cbjs_action':
                '''
                bvr.src_el.setStyle("opacity", 0.85)
                //new Fx.Tween(bvr.src_el).start('height', "30px");
                '''
            })
            div.add_behavior({
                'type':
                'mouseout',
                'cbjs_action':
                '''
                bvr.src_el.setStyle("opacity", 0.7)
                //new Fx.Tween(bvr.src_el).start('height', "15px");
                '''
            })
            project_code = Project.get_project_code()
            div.add_behavior({
                'type':
                'click_up',
                'cbjs_action':
                '''
                var url = "/tactic/%s/admin/link/_startup";
                window.open(url);

                ''' % project_code
            })

        # Add the script editor listener
        load_div = DivWdg()
        top.add(load_div)
        load_div.add_behavior({
            'type':
            'listen',
            'event_name':
            'show_script_editor',
            'cbjs_action':
            '''
        var js_popup_id = "TACTIC Script Editor";
        var js_popup = $(js_popup_id);
        if( js_popup ) {
            spt.popup.toggle_display( js_popup_id, false );
        }
        else {
            spt.panel.load_popup(js_popup_id, "tactic.ui.app.ShelfEditWdg", {}, {"load_once": true} );
        }
        '''
        })

        # deal with the palette defined in /index which can override the palette
        if my.kwargs.get("hash") == ():
            key = "index"
            search = Search("config/url")
            search.add_filter("url", "/%s/%%" % key, "like")
            search.add_filter("url", "/%s" % key)
            search.add_where("or")
            url = search.get_sobject()
            if url:
                xml = url.get_xml_value("widget")
                palette_key = xml.get_value("element/@palette")

                # look up palette the expression for index
                from pyasm.web import Palette
                palette = Palette.get()

                palette.set_palette(palette_key)
                colors = palette.get_colors()
                colors = jsondumps(colors)

                script = HtmlElement.script('''
                    var env = spt.Environment.get();
                    env.set_colors(%s);
                    env.set_palette('%s');
                    ''' % (colors, palette_key))
                top.add(script)

        env = Environment.get()
        client_handoff_dir = env.get_client_handoff_dir(include_ticket=False,
                                                        no_exception=True)
        client_asset_dir = env.get_client_repo_dir()

        login = Environment.get_login()
        user_name = login.get_value("login")
        user_id = login.get_id()
        login_groups = Environment.get_group_names()

        # add environment information
        script = HtmlElement.script('''
        var env = spt.Environment.get();
        env.set_project('%s');
        env.set_user('%s');
        env.set_user_id('%s');
        var login_groups = '%s'.split('|');
        env.set_login_groups(login_groups);
        env.set_client_handoff_dir('%s');
        env.set_client_repo_dir('%s');

        ''' % (Project.get_project_code(), user_name, user_id,
               '|'.join(login_groups), client_handoff_dir, client_asset_dir))
        top.add(script)

        # add a global container for commonly used widgets
        div = DivWdg()
        top.add(div)
        div.set_id("global_container")

        # add in the app busy widget
        # find out if there is an override for this
        search = Search("config/url")
        search.add_filter("url", "/app_busy")
        url = search.get_sobject()
        if url:
            busy_div = DivWdg()
            div.add(busy_div)

            busy_div.add_class("SPT_PUW")
            busy_div.add_styles(
                "display: none; position: absolute; z-index: 1000")

            busy_div.add_class("app_busy_msg_block")
            busy_div.add_style("width: 300px")
            busy_div.add_style("height: 100px")
            busy_div.add_style("padding: 20px")
            busy_div.add_color("background", "background3")
            busy_div.add_border()
            busy_div.set_box_shadow()
            busy_div.set_round_corners(20)
            busy_div.set_attr("id", "app_busy_msg_block")

            # put the custom url here

            title_wdg = DivWdg()
            busy_div.add(title_wdg)
            title_wdg.add_style("font-size: 20px")
            title_wdg.add_class("spt_app_busy_title")
            busy_div.add("<hr/>")
            msg_div = DivWdg()
            busy_div.add(msg_div)
            msg_div.add_class("spt_app_busy_msg")

        else:
            from page_header_wdg import AppBusyWdg
            div.add(AppBusyWdg())

        # popup parent
        popup = DivWdg()
        popup.set_id("popup")
        div.add(popup)

        # create another general popup
        popup_div = DivWdg()
        popup_div.set_id("popup_container")
        popup_div.add_class("spt_panel")
        popup = PopupWdg(id="popup_template", destroy_on_close=True)
        popup_div.add(popup)
        div.add(popup_div)

        inner_html_div = DivWdg()
        inner_html_div.set_id("inner_html")
        div.add(inner_html_div)

        # add in a global color
        from tactic.ui.input import ColorWdg
        color = ColorWdg()
        div.add(color)

        # add in a global notify wdg
        from notify_wdg import NotifyWdg
        widget.add(NotifyWdg())

        return widget
Esempio n. 33
0
    def handle_td(self, td):
        sobject = self.get_current_sobject()

        edit_scope = self.get_option("edit_scope")
        if edit_scope == "assigned":
            login = Environment.get_user_name()
            user = Environment.get_login()
            security = Environment.get_security()
            if not security.is_admin() and login != sobject.get_value("assigned"):
                td.add_class("spt_cell_no_edit")

 
        # find the pipeline code of the task
        pipeline_code = sobject.get_value('pipeline_code', no_exception=True)
        parent_pipeline_code = ''
        if self.parent:
            parent_pipeline_code = self.parent.get_value('pipeline_code', no_exception=True)

        if sobject.get_base_search_type() == "sthpw/snapshot":
            pipeline_code = "snapshot"

        # if not find the pipeline of the parent and match the process
        if not pipeline_code:
            task_process = sobject.get_value("process")
            if task_process:

                parent = self.parent
                if parent:
                    parent_pipeline_code = parent.get_value('pipeline_code', no_exception=True)
                    pipeline = Pipeline.get_by_code(parent_pipeline_code)
                    if pipeline:
                        attributes = pipeline.get_process_attrs(task_process)
                        pipeline_code = attributes.get('task_pipeline')


        value = self.get_value()
        color = Task.get_default_color(value)
        
        # If task status  pipeline is chosen, 
        # use color attribute from status (process)
        if pipeline_code:
            td.set_attr("spt_pipeline_code", pipeline_code)

            pipeline = Pipeline.get_by_code(pipeline_code)
            
            if pipeline:
                #attributes = pipeline.get_process_attrs(value)
                #color = attributes.get("color")
                process = pipeline.get_process(value)
                if process:
                    color = process.get_color()
                    if not color: 
                        process_sobject = pipeline.get_process_sobject(value)
                        if process_sobject:
                            color = process_sobject.get_value("color") 

        if color:
           td.add_style("background-color: %s" % color)


        if parent_pipeline_code:
            td.set_attr("spt_parent_pipeline_code", parent_pipeline_code)
        super(TaskStatusElementWdg, self).handle_td(td)
Esempio n. 34
0
    def naming_to_file(my, template, sobject, snapshot, file=None, ext=None, file_type=None):
        '''
        # chr001_model_v004_00001.ext
        '''


        version_padding = Config.get_value("checkin", "version_padding")
        if version_padding:
            version_padding = int(version_padding)
        else:
            version_padding = 3
        version_expr = "%%0.%dd" % version_padding


        # the main sobject
        project = sobject.get_project()

        # parse the pattern string
        expression = re.compile(r'{(.*?)}')
        #expression = re.compile(r'{([\w|\.|\#]+\[?\d?\]?)}')
        temp_list = expression.findall(template)

        result = template
        from pyasm.biz import ExpressionParser
        xp = ExpressionParser()
        # if nothing is found, then just return parse through an expression
        '''
        if not temp_list:
            #return template
            # put in the ability to add expressions
            env_sobjects = {
                'snapshot': snapshot,
                'file': file
            }

            
            file_name = file.get_value("file_name")
            base_type = file.get_value("base_type")
            if base_type =='directory':
                base = file_name
                ext = None
            else:
                base, ext = os.path.splitext(file_name)
            if not ext:
                value = None
            else:
                # external ext starts with a .
                ext = ext.lstrip(".")
                value = ext
            vars = {'EXT': value, 'BASEFILE': base}
            
            result = xp.eval(template, sobject, mode='string', env_sobjects=env_sobjects, vars=vars)
            test = template
            test = test.replace("{", "")
            test = test.replace("}", "")
            # don't allow / in filename
            test = test.replace("/", "_")
            if test != result:
               return result
        '''
       
        base = None

        if file:
            file_name = file.get_value("file_name")
            base_type = file.get_value("base_type")
            if base_type =='directory':
                base = file_name
                ext = None
            else:
                base, file_ext = os.path.splitext(file_name)
                # passed in ext takes prescedence
                if not ext:
                    ext = file_ext

        if not ext:
            value = None
        else:
            # external ext starts with a .
            ext = ext.lstrip(".")
            value = ext

        vars = {'EXT': value, 'BASEFILE': base}


        for part in temp_list:
            index = -1
            if part.startswith(("@","$")):
                env_sobjects = {
                    'snapshot': snapshot,
                    'file': file
                }
                value = xp.eval("{%s}" % part, sobject, env_sobjects=env_sobjects, vars=vars, single=True)
            elif part.find(".") != -1:
                # explict declarations
                object, attr = part.split(".")
                
                if attr.endswith(']'):
                    # ugly, but it works
                    attr, index = attr.split("[")
                    index = int(index.rstrip("]"))

                if object == "sobject":
                    value = sobject.get_value(attr)
                elif object == "snapshot":
                    if not snapshot:
                        continue
                    value = snapshot.get_value(attr)
                    if attr in ['version', 'revision']:
                        if value:
                            value = version_expr % int(value)
                        else:
                            value = "0"*version_padding
                    #value = snapshot.get_value(attr)
                elif object == "file":
                    if attr == 'file_type':
                        if file_type:
                            value = file_type
                        else:
                            value = 'main'
                    else:
                        value = file.get_value(attr)

                elif object == "parent":
                    parent = sobject.get_parent()
                    if not parent:
                        value = "NO_PARENT"
                    else:
                        value = parent.get_value(attr)
                elif object in ["login","user"]:
                    login = Environment.get_login()
                    value = login.get_value(attr)
                elif object == "project":
                    project = Project.get()
                    value = project.get_value(attr)
                else:
                    raise NamingException("Can't parse part [%s] in template" % part)

            else:
                # use implicit declarations
                attr = part

                
                if attr.endswith(']'):
                    # ugly, but it works
                    attr, index = attr.split("[")
                    index = int(index.rstrip("]"))    

                if attr in ["context","process","snapshot_type"]:
                    value = snapshot.get_value(attr)
                elif attr == "version":
                    value = snapshot.get_value(attr)
                    if value:
                        value = version_expr % int(value)
                    else:
                        value = "0"*version_padding
                elif attr == "revision":
                    value = snapshot.get_value(attr)
                    if value:
                        value = version_expr % int(value)
                    else:
                        value = "0"*version_padding

                elif attr.startswith("#"):
                    if not snapshot:
                        continue
                    value = snapshot.get_value("version")

                    expr = "%%0.%sd" % len(attr)
                    if value:
                        value = expr % int(value)
                    else:
                        value = "0" * len(attr)

                elif attr == "basefile":
                    file_name = file.get_value("file_name")
                    base_type = file.get_value("base_type")
                    if base_type =='directory':
                        value = file_name
                    else:
                        base, ext = os.path.splitext(file_name)
                        value = base
                elif attr == "ext":
                    if not ext:
                        file_name = file.get_value("file_name")
                        base_type = file.get_value("base_type")
                        if base_type =='directory':
                            value = ''
                        else:
                            base, ext = os.path.splitext(file_name)
                            value = ext.lstrip(".")
                    else:
                        # external ext starts with a .
                        ext = ext.lstrip(".")
                        value = ext
                elif attr in ["login","user"]:
                    login = Environment.get_login()
                    value = login.get_value("login")

                elif attr == "file_type":
                    if file_type:
                        value = file_type
                    else:
                        value = 'main'

                elif attr.startswith('date'):
                    # {date,%Y-%m-%d_%H-%M-%S]}
                    import time
                    parts = attr.split(",", 1)
                    if len(parts) == 2:
                        format = parts[1]
                    else:
                        format = "%Y%m%d"
                    value = time.strftime(format, time.localtime())


                else:
                    value = sobject.get_value(attr)

            # tbis applies to context for now
            if index != -1:
                value = re.split("[/]", value)
                if len(value) <= index:
                    value = '!'
                else:
                    value = value[index]


            #if not value:
            #    raise NamingException("Value for part [%s] is empty" % part)
            if isinstance(value, int):
                value = str(value)
            elif value is None:
                value = ""
            
            result = result.replace("{%s}" % part, value)

        # don't allow / in filename, 
        # FIXME: it's not put in get_filesystem_name since it
        # is used for directory name also, need to modify that
        result = result.replace("/", "_")

        # remove trailing . if any
        if result and result[-1] == '.':
            result = result[:-1]
        # post process result so that it looks good
        result = Common.get_filesystem_name(result)

        return result
Esempio n. 35
0
    def naming_to_dir(my, template, sobject, snapshot, file=None, file_type=None):
        '''
        # shot/SEQ001/shot_001
        '''

        # the main sobject
        project = sobject.get_project()

        # parse the pattern string
        expression = re.compile(r'{(.*?)}')
        temp_list = expression.findall(template)


        from pyasm.biz import ExpressionParser
        xp = ExpressionParser()
        ''' 
        # if nothing is found, then just return parse through an expression
        if not temp_list:
            #return template

            # put in the ability to add expressions
            env_sobjects = {
                'snapshot': snapshot,
                'file': file
            }
            result = xp.eval(template, sobject, mode='string', env_sobjects=env_sobjects)
            test = template
            test = test.replace("{", "")
            test = test.replace("}", "")
            if test != result:
                return result
        '''

        # version padding defaults
        version_padding = Config.get_value("checkin", "version_padding")
        if version_padding:
            version_padding = int(version_padding)
        else:
            version_padding = 3
        version_expr = "%%0.%dd" % version_padding



        # use simplified expressions
        result = template

        for part in temp_list:
             
            index = -1

            if part.startswith(("@","$")):
                env_sobjects = {
                    'snapshot': snapshot,
                    'file': file
                }
                value = xp.eval("{%s}" % part, sobject, env_sobjects=env_sobjects, single=True)
            
            elif part.find(".") != -1:
                # explict declarasions
                object, attr = part.split(".")
                
                if attr.endswith(']'):
                    # ugly, but it works
                    attr, index = attr.split("[")
                    index = int(index.rstrip("]"))
                if object == "sobject":
                    if attr == "timestamp":
                        value = my._get_timestamp(sobject)
                    else:
                        value = sobject.get_value(attr)
                elif object == "snapshot":
                    if not snapshot:
                        continue
                    if attr == "timestamp":
                        value = my._get_timestamp(snapshot)
                    else:
                        value = snapshot.get_value(attr)
                    if attr in ['version', 'revision']:
                        if value:
                            value = version_expr % int(value)
                        else:
                            value = "0"*version_padding
                elif object == "search_type":
                    search_type_obj = sobject.get_search_type_obj()
                    value = search_type_obj.get_value(attr)
                elif object == "parent":
                    parent = sobject.get_parent()
                    if not parent:
                        value = "NO_PARENT"
                    else:
                        if attr == 'timestamp':
                            value = my._get_timestamp(parent)
                        else:
                            value = parent.get_value(attr)
                elif object == "project":
                    project = Project.get()
                    value = project.get_value(attr)
                elif object in ["login","user"]:
                    login = Environment.get_login()
                    value = login.get_value(attr)
                elif object == "file":
                    if attr == 'file_type':
                        if file_type:
                            value = file_type
                        else:
                            value = 'main'
                    else:
                        value = file.get_value(attr)

                else:
                    raise NamingException("Can't parse part [%s] in template" % part)

            else:
                # use implicit declarations
                attr = part
                if attr.endswith(']'):
                    # ugly, but it works
                    attr, index = attr.split("[")
                    index = int(index.rstrip("]"))
                
                if attr in ['context','process','snapshot_type','version','revision'] \
                    and not snapshot:
                    continue
                if attr in ["context","process","snapshot_type"]:
                    value = snapshot.get_value(attr)
                elif attr == "version":
                    value = snapshot.get_value(attr)
                    if value:
                        value = version_expr % int(value)
                    else:
                        value = "0"*version_padding
                elif attr == "revision":
                    value = snapshot.get_value(attr)
                    if value:
                        value = version_expr % int(value)
                    else:
                        value = "0"*version_padding

                elif attr.startswith("#"):
                    if not snapshot:
                        continue
                    value = snapshot.get_value("version")
                    expr = "%%0.%sd" % len(attr)
                    if value:
                        value = expr % int(value)
                    else:
                        value = "0" * len(attr)

                elif attr.startswith("id"):
                    value = "%0.5d" % sobject.get_id()

                elif attr in ["login","user"]:
                    login = Environment.get_login()
                    value = login.get_value("login")

                elif attr == "file_type":
                    if file_type:
                        value = file_type
                    else:
                        value = 'main'
                else:
                    if attr == "timestamp":
                        value = my._get_timestamp(sobject)
                    else:
                        value = sobject.get_value(attr)

            if index != -1:
                value = re.split("[/]", value)
                if len(value) <= index:
                    value = '!'
                else:
                    try:
                        value = value[index]
                    except IndexError, e:
                        value = ""



            if not sobject.is_insert() and not value:
                value = ""
                #raise NamingException("Naming convention error: Value for part [%s] is empty" % part)

          
            if isinstance(value, int):
                value = str(value)
            result = result.replace("{%s}" % part, value)
Esempio n. 36
0
    def get_display(self):
        top = DivWdg()
        top.add_class("ad_input_top")

        name = self.get_name()
        text = TextWdg(self.get_input_name())

        # get the login
        sobject = self.get_current_sobject()
        client = sobject.get_value("contact_name")
        print "client: ", client
        if client:
            login_sobj = Login.get_by_code(client)
        else:
            login_sobj = Environment.get_login()

        # build the display_name
        login = login_sobj.get_value("login")
        display_name = login_sobj.get_value("display_name")
        if not display_name:
            display_name = "%s %s" % (user.get('first_name'),
                                      user.get('last_name'))
        display_name = display_name.replace('"', "'")

        print "login: "******"spt_ad_input")
        if login:
            hidden.set_value(login)
        top.add(hidden)

        # copy over some options
        #text.set_options( self.options.copy() )
        if login:
            text.set_value(display_name)
        text.set_option("read_only", "true")
        text.add_class("spt_ad_display")
        top.add(text)

        top.add("&nbsp;&nbsp;")

        groups_str = self.get_option("groups_allowed_to_search")
        if groups_str:
            stmt = 'groups_list = %s' % groups_str
            exec stmt
        else:
            groups_list = None

        allow_search = True

        if groups_list:
            allow_search = False
            login_in_group_list = Search.eval(
                "@SOBJECT(sthpw/login_in_group['login','=','%s'])" % login)
            for login_in_group in login_in_group_list:
                group = login_in_group.get_value("login_group")
                if group in groups_list:
                    allow_search = True
                    break

        if login == 'admin':
            allow_search = True

        if allow_search:
            button = IconButtonWdg('Search for User', IconWdg.USER)
            #button = ButtonWdg()
            button.add_behavior({
                'type':
                'click_up',
                'cbjs_action':
                '''
                var top = bvr.src_el.getParent('.ad_input_top');
                var content = top.getElement('.ad_input_content');
                spt.toggle_show_hide(content);
                '''
            })
            top.add(button)

        ad_top = DivWdg()
        ad_top.add_class("ad_input_content")
        ad_top.add_style("display: none")
        ad_top.add_style("position: absolute")
        ad_top.add_style("background: #222")
        ad_top.add_style("min-width: 300px")
        ad_top.add_style("border: solid 1px #000")
        ad_top.add_style("padding: 20px")

        cbjs_action = '''
        var value = bvr.src_el.getAttribute('spt_input_value');
        var display_value = bvr.src_el.getAttribute('spt_display_value');
        var phone_number = bvr.src_el.getAttribute('spt_phone_number');
        var email = bvr.src_el.getAttribute('spt_mail');

        var top = bvr.src_el.getParent('.ad_input_top');
        var content = top.getElement('.ad_input_content');
        var input = top.getElement('.spt_ad_input');
        var display = top.getElement('.spt_ad_display');
        input.value = value;
        display.value = display_value;

        server = TacticServerStub.get()
        server.execute_cmd("tactic.active_directory.ADCacheUserCbk", {login: value})

        spt.toggle_show_hide(content);

        '''
        ad_search_wdg = ADSearchWdg(cbjs_action=cbjs_action)
        ad_top.add(ad_search_wdg)

        top.add(ad_top)

        return top