Esempio n. 1
0
    def get_defaults(self):
        # TODO: autogenerate code

        defaults = {
            "login": Environment.get_user_name()
        }
        return defaults
Esempio n. 2
0
    def get_by_key(cls, key, user=None, project_code=None, use_cache=True):
      
        if not user:
            user = Environment.get_user_name()

        # ignore the project_code column for now
        dict_key = '%s:%s:%s' %(cls.SEARCH_TYPE, project_code, user) 
        if use_cache:
            settings_dict = Container.get(dict_key)
        else:
            settings_dict = None

        # explicit check for None
        if settings_dict == None:
            settings_dict = {}

            if use_cache:
                Container.put(dict_key, settings_dict)

            search = Search(cls.SEARCH_TYPE)
            search.add_filter("login", user)
            if project_code:
                search.add_filter("project_code", project_code)
            else:
                search.add_null_filter("project_code")
            # don't filter with the key in order to build a dict
            pref_settings = search.get_sobjects()
            for setting in pref_settings:
                settings_dict[setting.get_value('key')] = setting

        pref_setting = settings_dict.get(key)

        return pref_setting
Esempio n. 3
0
    def create(cls, sobject, process, description="", assigned="", supervisor="",\
            status=None, depend_id=None, project_code=None, pipeline_code='', \
            start_date=None, end_date=None, context='', bid_duration=8):


        task = SearchType.create( cls.SEARCH_TYPE )
        task.set_parent(sobject)

        task.set_value("process", process )
        if description:
            task.set_value("description", description )
        if assigned != None:
            task.set_value("assigned", assigned)

        if supervisor != None:
            task.set_value("supervisor", supervisor)

        if not project_code:
            project_code = sobject.get_project_code()
        task.set_value("project_code", project_code )
        task.set_value("pipeline_code", pipeline_code) 

        if not status:
            pipeline = task.get_pipeline()
            process_names = pipeline.get_process_names()
            if process_names:
                status = process_names[0]

        if status:
            task.set_value("status", status)

        if bid_duration:
            task.set_value("bid_duration", bid_duration)


        if start_date:
            task.set_value("bid_start_date", start_date)
        if end_date:
            task.set_value("bid_end_date", end_date)
        # auto map context as process as the default
        #if not context:
        #    context = process
        # let get_defaults() set the context properly instead of auto-map
        if context:
            task.set_value("context", context)

        # DEPRECATED
        if depend_id:
            task.set_value("depend_id", depend_id)

        # created by 
        if task.has_value('login'):
            user = Environment.get_user_name()
            task.set_value('login', user)

        task.commit(triggers=True)
        # log the status creation event
        StatusLog.create(task, status)

        return task
Esempio n. 4
0
    def get_by_key(cls, key, user=None, project_code=None, use_cache=True):

        if not user:
            user = Environment.get_user_name()

        # ignore the project_code column for now
        dict_key = '%s:%s:%s' % (cls.SEARCH_TYPE, project_code, user)
        if use_cache:
            settings_dict = Container.get(dict_key)
        else:
            settings_dict = None

        # explicit check for None
        if settings_dict == None:
            settings_dict = {}

            if use_cache:
                Container.put(dict_key, settings_dict)

            search = Search(cls.SEARCH_TYPE)
            search.add_filter("login", user)
            if project_code:
                search.add_filter("project_code", project_code)
            else:
                search.add_null_filter("project_code")
            # don't filter with the key in order to build a dict
            pref_settings = search.get_sobjects()
            for setting in pref_settings:
                settings_dict[setting.get_value('key')] = setting

        pref_setting = settings_dict.get(key)

        return pref_setting
Esempio n. 5
0
 def get_display(self):
     search = Search(Login)
     self.set_search_for_options(search, 'login', 'login')
     self.set_option("extra_values", "admin")
     if self.kwargs.get('default_user') == 'true':
         self.set_option('default', Environment.get_user_name())
     return super(UserSelectWdg, self).get_display()
    def get_side_bar_cache(my, left_nav_wdg):
        project = Project.get()
        project_code = project.get_code()

        # do it with sobject
        #key = "%s_side_bar" % project.get_code()
        #cache = Search.get("sthpw/widget_cache")
        #cache.add_filter("key", key)
        #sobject = cache.get_sobject()
        #value = sobject.get_value("cache")

        login = Environment.get_user_name()
        tmp_dir = "%s/cache/side_bar" % Environment.get_tmp_dir()

        filename = "%s__%s.html" % (project_code, login)
        path = "%s/%s" % (tmp_dir, filename)

        # use files
        import os
        if os.path.exists(path):
            f = open(path, "r")
            html = f.read()
            f.close()
        else:            
            dirname = os.path.dirname(path)
            if not os.path.exists(dirname):
                os.makedirs(dirname)
            f = open(path, "w")
            html = left_nav_wdg.get_buffer_display()
            f.write(html)
            f.close()

        return html
Esempio n. 7
0
    def add(command, kwargs, queue_type, priority, description, message_code=None):

        queue = SearchType.create("sthpw/queue")
        queue.set_value("project_code", Project.get_project_code())
        #queue.set_sobject_value(sobject)

        if not queue_type:
            queue_type = "default"
        queue.set_value("queue", queue_type)

        queue.set_value("state", "pending")

        queue.set_value("login", Environment.get_user_name())

        queue.set_value("command", command)
        data = jsondumps(kwargs)
        queue.set_value("data", data)

        if message_code:
            queue.set_value("message_code", message_code)


        if not priority:
            priority = 9999
        queue.set_value("priority", priority)

        if description:
            queue.set_value("description", description)

        queue.set_user()
        queue.commit()

        return queue
Esempio n. 8
0
    def create(sobject, value, prev_value=None):
        if prev_value == value:
            return

        # if this is successful, the store it in the status_log
        #search_type = sobject.get_search_type()
        #search_id = sobject.get_id()
        #search_code = sobject.get_value("code")

        status_log = SearchType.create("sthpw/status_log")
        status_log.set_value("login", Environment.get_user_name() )

        status_log.set_sobject_value(sobject)
        #status_log.set_value("search_type", search_type)
        #status_log.set_value("search_code", search_id, no_exception=True)
        #status_log.set_value("search_id", search_code, no_exception=True)

        if prev_value:
            status_log.set_value("from_status", prev_value)

        status_log.set_value("to_status", value)

        project_code = Project.get_project_name()
        status_log.set_value("project_code", project_code)

        status_log.commit(cache=False)

        return status_log
Esempio n. 9
0
 def get_display(my):
     search = Search(Login)
     my.set_search_for_options(search, 'login','login')
     my.set_option("extra_values", "admin")
     if my.kwargs.get('default_user') =='true':
         my.set_option('default', Environment.get_user_name())
     return super(UserSelectWdg, my).get_display() 
Esempio n. 10
0
    def get_defaults(self):
        '''specifies the defaults for this sobject'''
        project_code = Project.get_project_code()
        me = Environment.get_user_name()
        defaults = {"project_code": project_code, "login": me}

        return defaults
Esempio n. 11
0
    def execute(my):
        sobject = my.get_caller()
        search_type = sobject.get_base_search_type()

        all_logins = False
        if search_type == 'config/widget_config':
            category = sobject.get_value("category")
            if not category:
                category = sobject.get_value("search_type")

            if category != 'SideBarWdg':
                return
            user = sobject.get_value('login')
            user = user.strip()
            if not user:
                all_logins = True

        from pyasm.biz import Project
        project = Project.get()
        project_code = project.get_code()

        login = Environment.get_user_name()
        tmp_dir = "%s/cache/side_bar" % Environment.get_tmp_dir()
        project_check = True
        if search_type == 'sthpw/login_group':
            login_objs = sobject.get_logins()
            logins = [x.get_value('login') for x in login_objs]
            project_check = False
        else:
            if all_logins:
                expr = '@GET(sthpw/login.login)'
                logins = Search.eval(expr)
            else:
                logins = [login]

        filenames = []
        if not os.path.exists(tmp_dir):
            os.makedirs(tmp_dir)
            return
        search = Search('sthpw/project')
        projects = search.get_sobjects()
        project_codes = [x.get_value('code') for x in projects]
        for login in logins:
            if project_check:
                filename = "%s__%s.html" % (project_code, login)
                filenames.append(filename)
            else:
                for project_code in project_codes:
                    filename = "%s__%s.html" % (project_code, login)
                    filenames.append(filename)

            #filenames = os.listdir(tmp_dir)
        for filename in filenames:
            #if not filename.startswith("%s__" % project_code):
            #    print "skip filename ", filename

            path = "%s/%s" % (tmp_dir, filename)
            if os.path.exists(path):
                print "Deleting: ", path
                os.unlink(path)
Esempio n. 12
0
    def get_subscriptions(my, category, mode="new"):

        search = Search("sthpw/subscription")
        search.add_user_filter()
        if category:
            search.add_filter("category", category)



        if mode == "new":
            search.add_op("begin")
            search.add_filter("last_cleared", '"message"."timestamp"', quoted=False, op="<")
            search.add_filter("last_cleared", "NULL", quoted=False, op="is")
            search.add_op("or")


            #project_code = Project.get_project_code()
            #search.add_filter("project_code", project_code )

            # use an inner join because if there are no messages, we don't
            # want the subscription
            search.add_order_by("message.timestamp", direction="desc", join="INNER")

            # don't show user message except when category is certain values
            user = Environment.get_user_name()
            search.add_op("begin")
            search.add_filter("login", user, op="!=", table="message")
            search.add_filters("category", ["script","default","sobject"], table="message")
            search.add_op("or")
        else:
            search.add_order_by("message.timestamp", direction="desc")

        subscriptions = search.get_sobjects()

        return subscriptions
Esempio n. 13
0
    def get_subscriptions(self, category, mode="new"):

        search = Search("sthpw/subscription")
        search.add_user_filter()
        if category:
            search.add_filter("category", category)



        if mode == "new":
            search.add_op("begin")
            search.add_filter("last_cleared", '"message"."timestamp"', quoted=False, op="<")
            search.add_filter("last_cleared", "NULL", quoted=False, op="is")
            search.add_op("or")


            #project_code = Project.get_project_code()
            #search.add_filter("project_code", project_code )

            # use an inner join because if there are no messages, we don't
            # want the subscription
            search.add_order_by("message.timestamp", direction="desc", join="INNER")

            # don't show user message except when category is certain values
            user = Environment.get_user_name()
            search.add_op("begin")
            search.add_filter("login", user, op="!=", table="message")
            search.add_filters("category", ["script","default","sobject","progress"], table="message")
            search.add_op("or")
        else:
            search.add_order_by("message.timestamp", direction="desc")

        subscriptions = search.get_sobjects()
        return subscriptions
Esempio n. 14
0
    def get_side_bar_cache(self, left_nav_wdg):
        project = Project.get()
        project_code = project.get_code()

        # do it with sobject
        #key = "%s_side_bar" % project.get_code()
        #cache = Search.get("sthpw/widget_cache")
        #cache.add_filter("key", key)
        #sobject = cache.get_sobject()
        #value = sobject.get_value("cache")

        login = Environment.get_user_name()
        tmp_dir = "%s/cache/side_bar" % Environment.get_tmp_dir()

        filename = "%s__%s.html" % (project_code, login)
        path = "%s/%s" % (tmp_dir, filename)

        # use files
        import os
        if os.path.exists(path):
            f = open(path, "r")
            html = f.read()
            f.close()
        else:
            dirname = os.path.dirname(path)
            if not os.path.exists(dirname):
                os.makedirs(dirname)
            f = open(path, "w")
            html = left_nav_wdg.get_buffer_display()
            f.write(html)
            f.close()

        return html
Esempio n. 15
0
    def add(command,
            kwargs,
            queue_type,
            priority,
            description,
            message_code=None):

        queue = SearchType.create("sthpw/queue")
        queue.set_value("project_code", Project.get_project_code())
        #queue.set_sobject_value(sobject)
        queue.set_value("queue", queue_type)
        queue.set_value("state", "pending")

        queue.set_value("login", Environment.get_user_name())

        queue.set_value("command", command)
        data = jsondumps(kwargs)
        queue.set_value("data", data)

        if message_code:
            queue.set_value("message_code", message_code)

        queue.set_value("priority", priority)
        queue.set_value("description", description)

        queue.set_user()
        queue.commit()

        return queue
Esempio n. 16
0
    def create(sobject, value, prev_value=None):
        if prev_value == value:
            return

        # if this is successful, the store it in the status_log
        #search_type = sobject.get_search_type()
        #search_id = sobject.get_id()
        #search_code = sobject.get_value("code")

        status_log = SearchType.create("sthpw/status_log")
        status_log.set_value("login", Environment.get_user_name())

        status_log.set_sobject_value(sobject)
        #status_log.set_value("search_type", search_type)
        #status_log.set_value("search_code", search_id, no_exception=True)
        #status_log.set_value("search_id", search_code, no_exception=True)

        if prev_value:
            status_log.set_value("from_status", prev_value)

        status_log.set_value("to_status", value)

        project_code = Project.get_project_name()
        status_log.set_value("project_code", project_code)

        status_log.commit(cache=False)

        return status_log
Esempio n. 17
0
    def create(cls, sobject, process, description="", assigned="", supervisor="",\
            status=None, depend_id=None, project_code=None, pipeline_code='', \
            start_date=None, end_date=None, context='', bid_duration=8):

        task = SearchType.create(cls.SEARCH_TYPE)
        task.set_parent(sobject)

        task.set_value("process", process)
        if description:
            task.set_value("description", description)
        if assigned != None:
            task.set_value("assigned", assigned)

        if supervisor != None:
            task.set_value("supervisor", supervisor)

        if not project_code:
            project_code = sobject.get_project_code()
        task.set_value("project_code", project_code)
        task.set_value("pipeline_code", pipeline_code)

        if not status:
            pipeline = task.get_pipeline()
            process_names = pipeline.get_process_names()
            if process_names:
                status = process_names[0]

        if status:
            task.set_value("status", status)

        if bid_duration:
            task.set_value("bid_duration", bid_duration)

        if start_date:
            task.set_value("bid_start_date", start_date)
        if end_date:
            task.set_value("bid_end_date", end_date)
        # auto map context as process as the default
        #if not context:
        #    context = process
        # let get_defaults() set the context properly instead of auto-map
        if context:
            task.set_value("context", context)

        # DEPRECATED
        if depend_id:
            task.set_value("depend_id", depend_id)

        # created by
        if task.has_value('login'):
            user = Environment.get_user_name()
            task.set_value('login', user)

        task.commit(triggers=True)
        # log the status creation event
        StatusLog.create(task, status)

        return task
Esempio n. 18
0
    def execute(my):
        my.search_type = my.kwargs.get("search_type")
        my.element_name = my.kwargs.get("element_name")
        assert my.search_type
        assert my.element_name

        interval = my.kwargs.get('interval')
        if not interval:
            interval = 120

        data_type = my.kwargs.get('data_type')
        if not data_type:
            data_type = 'float'

        class_name = 'tactic.ui.app.aggregate_wdg.AggregateCmd'
        priority = None

        user = Environment.get_user_name()

        # these interval jobs need to have a specific code
        code = "aggregate|%s|%s" % (my.search_type, my.element_name)

        # check to see if the job exists
        job = Search.get_by_code("sthpw/queue", code)
        if not job:
            job = SearchType.create("sthpw/queue")
            job.set_value("code", code)

            job.set_value("project_code", Project.get_project_code() )
            job.set_value("class_name", class_name)
            job.set_value("command", class_name)
            job.set_value("login", user) 
            job.set_value("queue", 'interval')

            # this is meaningless
            job.set_value("priority", 9999)

            # not sure what to do here if it already exists
            job.set_value("state", 'pending')



            # add a column to the table
            from pyasm.command import ColumnAddCmd
            from pyasm.search import AlterTable
            column_name = my.element_name
            cmd = ColumnAddCmd(my.search_type, column_name, data_type)
            cmd.execute()

            # modify the table
            #alter = AlterTable(my.search_type)
            #alter.modify(my.search_type, data_type)
            #print alter.get_statements()


        job.set_value("serialized", str(my.kwargs) )
        job.set_value("interval", interval)
        job.commit()
Esempio n. 19
0
    def alter_search(self, search):

        user = Environment.get_user_name()
        from pyasm.security import Login
        user = Login.get_by_login(user)
        search.add_filter("login", user.get_value("login"))

        import datetime
        from dateutil import parser
        filter_data = FilterData.get()
        values = filter_data.get_values_by_index("week", 0)
        date_string = values.get("calendar")
        if date_string:
            date = parser.parse(date_string)
        else:
            date = datetime.datetime.now()

        from tactic.ui.report import MMSUtility
        #start_wday, end_wday = self.get_week_range(date_string)
        start_wday, end_wday = MMSUtility.get_week_range(date)

        one_day = datetime.timedelta(days=1)

        column = "work_performed_date"

        # KEEP it simple for now
        search.add_op("begin")
        search.add_filter(column, start_wday, op='>=')
        search.add_filter(column, end_wday, op='<=')
        search.add_op("and")
        '''
        search.add_op("begin")
        search.add_filter(column, start_wday + one_day, op='>=')
        search.add_filter(column, end_wday - one_day, op='<=')
        search.add_op("and")

        search.add_op("begin")
        search.add_filter(column, start_wday, op='>=')
        search.add_filter(column, start_wday+one_day, op='<=')
        search.add_filter("shift", "pm", op='=')
        search.add_op("and")

        # FIXME: have to add this extra "or" because we don't support multiple
        # begins??
        search.add_op("or")
 
        search.add_op("begin")
        search.add_filter(column, end_wday, op='>=')
        search.add_filter(column, end_wday+one_day, op='<=')
        search.add_filter("shift", "am", op='=')
        search.add_op("and")
 
        search.add_op("or")
        '''

        search.add_order_by(column)
        search.add_order_by("work_start_time")
        search.add_order_by("shift")
Esempio n. 20
0
    def _process_task(my, task, mode):
        project = Project.get_project_code()
        if not task.kwargs.get("user"):
            user = Environment.get_user_name()
        if not task.kwargs.get("project"):
            project_code = Project.get_project_code()
            task.kwargs['project'] = project_code

        task.kwargs['mode'] = mode
Esempio n. 21
0
    def _process_task(my, task, mode):
        project = Project.get_project_code()
        if not task.kwargs.get("user"):
            user = Environment.get_user_name()
        if not task.kwargs.get("project"):
            project_code = Project.get_project_code()
            task.kwargs['project'] = project_code

        task.kwargs['mode'] = mode
Esempio n. 22
0
    def get_results(my):
        code = my.kwargs.get("code")
        script_path = my.kwargs.get("script_path")
        file_path = my.kwargs.get("file_path")


        # if a script path is specified, then get it from the custom_script
        # table
        if script_path:

            folder = os.path.dirname(script_path)
            title = os.path.basename(script_path)

            search = Search("config/custom_script")
            search.add_filter("folder", folder)
            search.add_filter("title", title)
            custom_script = search.get_sobject()
            if not custom_script:
                raise TacticException("Custom script with path [%s/%s] does not exist" % (folder, title) )
            code = custom_script.get_value("script")

        elif file_path:
            f = open(file_path)
            code = f.read()
            f.close()


        server = TacticServerStub.get(protocol='local')
        server.login = Environment.get_user_name()
        spt_mako_results = {}

        #kwargs = {
        #    'server': server,
        #    'spt_mako_results': spt_mako_results
        #}

        code = '''
<%%def name='spt_run_code()'>
<%%
%s
%%>
</%%def>

<%%
spt_mako_results['spt_ret_val'] = spt_run_code()
%%>
''' % code
        

        #template = Template(code, output_encoding='utf-8', input_encoding='utf-8')
        try:
            template = Template(code)
            template.render(server=server,spt_mako_results=spt_mako_results, kwargs=my.kwargs,**my.kwargs)
        except Exception, e:
            print "Error in Mako code: "
            print code
            raise
Esempio n. 23
0
    def get_defaults(self):
        '''specifies the defaults for this sobject'''
        project_code = Project.get_project_code()
        me = Environment.get_user_name()
        defaults = {
            "project_code": project_code,
            "login": me
        }

        return defaults
Esempio n. 24
0
    def execute(self):
        self.search_type = self.kwargs.get("search_type")
        self.element_name = self.kwargs.get("element_name")
        assert self.search_type
        assert self.element_name

        interval = self.kwargs.get('interval')
        if not interval:
            interval = 120

        data_type = self.kwargs.get('data_type')
        if not data_type:
            data_type = 'float'

        class_name = 'tactic.ui.app.aggregate_wdg.AggregateCmd'
        priority = None

        user = Environment.get_user_name()

        # these interval jobs need to have a specific code
        code = "aggregate|%s|%s" % (self.search_type, self.element_name)

        # check to see if the job exists
        job = Search.get_by_code("sthpw/queue", code)
        if not job:
            job = SearchType.create("sthpw/queue")
            job.set_value("code", code)

            job.set_value("project_code", Project.get_project_code())
            job.set_value("class_name", class_name)
            job.set_value("command", class_name)
            job.set_value("login", user)
            job.set_value("queue", 'interval')

            # this is meaningless
            job.set_value("priority", 9999)

            # not sure what to do here if it already exists
            job.set_value("state", 'pending')

            # add a column to the table
            from pyasm.command import ColumnAddCmd
            from pyasm.search import AlterTable
            column_name = self.element_name
            cmd = ColumnAddCmd(self.search_type, column_name, data_type)
            cmd.execute()

            # modify the table
            #alter = AlterTable(self.search_type)
            #alter.modify(self.search_type, data_type)
            #print alter.get_statements()

        job.set_value("serialized", str(self.kwargs))
        job.set_value("interval", interval)
        job.commit()
Esempio n. 25
0
    def create(cls, key, value):
        setting = cls.get_by_key(key)
        if not setting:
            setting = PrefSetting.create_new()
            setting.set_value("key", key)
            user = Environment.get_user_name()
            setting.set_value("login", user)

        setting.set_value("value", value)
        setting.commit()

        return setting
Esempio n. 26
0
    def init(self):
        self.task_code = self.kwargs.get('task_code', '')
        self.task_pipelines = ''
        self.parent_sk = self.kwargs.get('parent_sk', '')
        self.parent_pyclass = ''
        self.order_sk = self.kwargs.get('order_sk', '')
        self.groups = Environment.get_group_names()

        if 'user' in self.kwargs.keys():
            self.user = str(self.kwargs.get('user'))
        else:
            self.user = Environment.get_user_name()
Esempio n. 27
0
    def execute(my):
        assert my.snapshot
        assert my.sobject

        # add some additional options
        my.set_option("snapshot_code", my.snapshot.get_code() )
        my.set_option("render_dir", my.get_render_dir() )

        input_path = my.get_input_path()
        my.set_option("input_path", input_path)

        # handle the policy if it exists
        policy = my.render_package.get_policy()
        if policy:
            width = policy.get_value("width")
            height = policy.get_value("height")
            frame_by = policy.get_value("frame_by")
            extra_settings = policy.get_value("extra_settings")

            my.set_option("resolution", "%sx%s" % (width, height))

            my.set_option("width", width)
            my.set_option("height", height)
            my.set_option("frame_by", frame_by)
            my.set_option("extra_settings", extra_settings)
            





        # get some information from the render context
        search_type = my.sobject.get_search_type_obj()
        description = "Render %s: %s" % (search_type.get_title(),my.sobject.get_code())

        # create queue in tactic related to this submission
        if not my.queue:
            my.queue = Queue.create(my.sobject, "render", "9999", description)
        else:
            my.queue.set_sobject_value(my.sobject)
            my.queue.set_value('login', Environment.get_user_name())
            # have to make sure it is committed to get a queue_id
            if my.queue.get_id() == -1:
                my.queue.commit()


        # submit the job to the dispatcher
        dispatcher_id = my.submit()

        # store the dispatcher id in the queue object
        my.queue.set_value("dispatcher_id", dispatcher_id)
        my.queue.commit()
Esempio n. 28
0
    def _test_security_pass(self):

        fail = False
        try:
            self.security.login_user(self.user, self.password)
        except SecurityException as e:
            fail = True

        # set this user as admin
        self.security.set_admin(True)

        self.assertEquals('unittest_guy', Environment.get_user_name())
        self.assertEquals(False, fail)
Esempio n. 29
0
    def _test_security_pass(self):

        fail = False
        try:
            self.security.login_user(self.user,self.password)
        except SecurityException as e:
            fail = True

        # set this user as admin
        self.security.set_admin(True)

        self.assertEquals('unittest_guy',  Environment.get_user_name())
        self.assertEquals( False, fail )
Esempio n. 30
0
    def create(cls, key, value):
        setting = cls.get_by_key(key)
        if not setting:
            setting = PrefSetting.create_new()
            setting.set_value("key", key)
            user = Environment.get_user_name()
            setting.set_value("login", user)

        setting.set_value("value", value)
        setting.commit()


        return setting
Esempio n. 31
0
    def execute(self):

        web = WebContainer.get_web()

        # get the input names
        input_names = web.get_form_value(
            SerialStatusWdg.STATUS_CMD_INPUT).split('|')

        values = []
        for input_name in input_names:
            value = web.get_form_value(input_name)
            if value:
                values.append(web.get_form_value(input_name))

        # FIXME: HARDCODED Value for status column!!!!
        column = "status"

        for value in values:
            # get the sobject to be updated
            search_type, id, status = value.split("|")
            search = Search(search_type)
            search.add_id_filter(id)
            self.sobject = search.get_sobject()

            status_attr = self.sobject.get_attr(column)

            cur_status = status_attr.get_current_process()
            if cur_status == status:
                continue

            status_attr.set_status(status)

            update_column = 'time_update'
            if update_column in self.sobject.get_attr_names():
                self.sobject.set_value(update_column,
                                       Sql.get_timestamp_now(),
                                       quoted=False)
            self.sobject.commit()

            # if this is successful, the store it in the status_log
            status_log = SObjectFactory.create("sthpw/status_log")
            status_log.set_value("login", Environment.get_user_name())
            status_log.set_value("search_type", search_type)
            status_log.set_value("search_id", id)
            #status_log.set_value("status", "%s to %s" % (cur_status, status) )
            status_log.commit()
            status_log.set_value("from_status", cur_status)
            status_log.set_value("to_status", status)

            # Call the finaled trigger
            Trigger.call(self, status)
Esempio n. 32
0
    def execute(my):

        web = WebContainer.get_web()
        
        # get the input names
        input_names = web.get_form_value(SerialStatusWdg.STATUS_CMD_INPUT).split('|')
        
        values = []
        for input_name in input_names:
            value = web.get_form_value(input_name)
            if value:
                values.append(web.get_form_value(input_name))
            
       
        # FIXME: HARDCODED Value for status column!!!!
        column = "status"

        for value in values:
            # get the sobject to be updated
            search_type,id,status = value.split("|")
            search = Search(search_type)
            search.add_id_filter(id)
            my.sobject = search.get_sobject()
            
            status_attr = my.sobject.get_attr(column)

            cur_status = status_attr.get_current_process()
            if cur_status == status:
                continue

            status_attr.set_status(status)
           
            update_column = 'time_update'
            if update_column in my.sobject.get_attr_names():
                my.sobject.set_value(update_column, Sql.get_timestamp_now(), quoted=False)
            my.sobject.commit()

           
            # if this is successful, the store it in the status_log
            status_log = SObjectFactory.create("sthpw/status_log")
            status_log.set_value("login", Environment.get_user_name() )
            status_log.set_value("search_type", search_type)
            status_log.set_value("search_id", id)
            #status_log.set_value("status", "%s to %s" % (cur_status, status) )
            status_log.commit()
            status_log.set_value("from_status", cur_status)
            status_log.set_value("to_status", status)

            # Call the finaled trigger
            Trigger.call(my, status)
Esempio n. 33
0
    def __init__(self):
        self.security = Environment.get_security()

        # if not already logged in, login as a safe user (guest)
        if not self.security.is_logged_in():
            #self.security.login_as_guest()
            pass

        self.access_manager = self.security.get_access_manager()
        login = Environment.get_user_name()
        self.was_admin = self.access_manager.was_admin
        if self.was_admin == None:
            self.access_manager.set_up()
            self.was_admin = self.access_manager.was_admin
     
        self.access_manager.set_admin(True)
Esempio n. 34
0
    def __init__(my):
        my.security = Environment.get_security()

        # if not already logged in, login as a safe user (guest)
        if not my.security.is_logged_in():
            #my.security.login_as_guest()
            pass

        my.access_manager = my.security.get_access_manager()
        login = Environment.get_user_name()
        my.was_admin = my.access_manager.was_admin
        if my.was_admin == None:
            my.access_manager.set_up()
            my.was_admin = my.access_manager.was_admin

        my.access_manager.set_admin(True)
Esempio n. 35
0
    def __init__(my):
        my.security = Environment.get_security()

        # if not already logged in, login as a safe user (guest)
        if not my.security.is_logged_in():
            #my.security.login_as_guest()
            pass

        my.access_manager = my.security.get_access_manager()
        login = Environment.get_user_name()
        my.was_admin = my.access_manager.was_admin
        if my.was_admin == None:
            my.access_manager.set_up()
            my.was_admin = my.access_manager.was_admin
     
        my.access_manager.set_admin(True)
Esempio n. 36
0
    def execute(my):
        assert my.snapshot
        assert my.sobject

        # add some additional options
        my.set_option("snapshot_code", my.snapshot.get_code())
        my.set_option("render_dir", my.get_render_dir())

        input_path = my.get_input_path()
        my.set_option("input_path", input_path)

        # handle the policy if it exists
        policy = my.render_package.get_policy()
        if policy:
            width = policy.get_value("width")
            height = policy.get_value("height")
            frame_by = policy.get_value("frame_by")
            extra_settings = policy.get_value("extra_settings")

            my.set_option("resolution", "%sx%s" % (width, height))

            my.set_option("width", width)
            my.set_option("height", height)
            my.set_option("frame_by", frame_by)
            my.set_option("extra_settings", extra_settings)

        # get some information from the render context
        search_type = my.sobject.get_search_type_obj()
        description = "Render %s: %s" % (search_type.get_title(),
                                         my.sobject.get_code())

        # create queue in tactic related to this submission
        if not my.queue:
            my.queue = Queue.create(my.sobject, "render", "9999", description)
        else:
            my.queue.set_sobject_value(my.sobject)
            my.queue.set_value('login', Environment.get_user_name())
            # have to make sure it is committed to get a queue_id
            if my.queue.get_id() == -1:
                my.queue.commit()

        # submit the job to the dispatcher
        dispatcher_id = my.submit()

        # store the dispatcher id in the queue object
        my.queue.set_value("dispatcher_id", dispatcher_id)
        my.queue.commit()
Esempio n. 37
0
 def alter_search(search):
     # always restrict access from others
     security = Environment.get_security()
     if security.check_access("builtin", "view_private_notes", 'view', default='deny'):
         return
     
     user = Environment.get_user_name() 
     search.add_op('begin')
     search.add_op('begin')
     search.add_filter("access", "private", op='=')
     search.add_user_filter()
     search.add_op("and")
     search.add_op('begin')
     search.add_filter("access", "private", op='!=')
     search.add_filter("access", None)
     search.add_op("or")
     search.add_op("or")
Esempio n. 38
0
 def init(my):
     my.title = 'Equipment Used'
     my.sk = ''
     my.code = ''
     my.user = Environment.get_user_name()
     my.parent_sk = ''
     my.order_sk = ''
     my.order_sid = ''
     my.client_code = ''
     my.formats = ['Electronic/File', 'HDCAM SR', 'NTSC', 'PAL']
     my.frame_rates = ProdSetting.get_seq_by_key('frame_rates')
     my.aspect_ratios = ['16x9 1.33', '16x9 1.33 Pan & Scan', '16x9 1.78 Anamorphic', '16x9 1.78 Full Frame',
                         '16x9 1.85 Letterbox', '16x9 1.85 Matted', '16x9 1.85 Matted Anamorphic', '16x9 2.20',
                         '16x9 2.20 Letterbox', '16x9 2.35 Anamorphic', '16x9 2.35 Letterbox', '16x9 2.39 Letterbox',
                         '16x9 2.40 Letterbox', '16x9 2.55 Letterbox', '4x3 1.33 Full Frame', '4x3 1.78 Letterbox',
                         '4x3 1.85 Letterbox', '4x3 2.35 Letterbox', '4x3 2.40 Letterbox']
     my.standards = ['625', '525', '720', '1080 (4:4:4)', '1080', 'PAL', 'NTSC']
Esempio n. 39
0
    def execute(my):

        login = Environment.get_user_name()
        users = my.kwargs.get("users")

        everyone = [login]
        everyone.extend(users)

        # find out if there already is a subscription between this user
        # and others
        search = Search("sthpw/subscription")
        search.add_filter("login", login)
        search.add_filter("category", "chat")
        login_subscriptions = search.get_sobjects()
        keys = [x.get_value("message_code") for x in login_subscriptions]

        create = True

        # find the subscriptions for each user with the same keys
        for user in users:
            search = Search("sthpw/subscription")
            search.add_filters("message_code", keys)
            search.add_filter("login", user)
            user_subscriptions = search.get_sobjects()
            if user_subscriptions:
                create = False


        # create a new subscription
        if create:
            key = Common.generate_random_key()
            message = SearchType.create("sthpw/message")
            message.set_value("code", key)
            message.set_value("login", login)
            message.set_value("category", "chat")
            message.set_value("message", "Welcome!!!")
            message.commit()

            # create a subscription for each person
            for person in everyone:
                subscription = SearchType.create("sthpw/subscription")
                subscription.set_value("message_code", key)
                subscription.set_value("login", person)
                subscription.set_value("category", "chat")
                subscription.commit()
Esempio n. 40
0
    def execute(self):

        login = Environment.get_user_name()
        users = self.kwargs.get("users")

        everyone = [login]
        everyone.extend(users)

        # find out if there already is a subscription between this user
        # and others
        search = Search("sthpw/subscription")
        search.add_filter("login", login)
        search.add_filter("category", "chat")
        login_subscriptions = search.get_sobjects()
        keys = [x.get_value("message_code") for x in login_subscriptions]

        create = True

        # find the subscriptions for each user with the same keys
        for user in users:
            search = Search("sthpw/subscription")
            search.add_filters("message_code", keys)
            search.add_filter("login", user)
            user_subscriptions = search.get_sobjects()
            if user_subscriptions:
                create = False


        # create a new subscription
        if create:
            key = Common.generate_random_key()
            message = SearchType.create("sthpw/message")
            message.set_value("code", key)
            message.set_value("login", login)
            message.set_value("category", "chat")
            message.set_value("message", "Welcome!!!")
            message.commit()

            # create a subscription for each person
            for person in everyone:
                subscription = SearchType.create("sthpw/subscription")
                subscription.set_value("message_code", key)
                subscription.set_value("login", person)
                subscription.set_value("category", "chat")
                subscription.commit()
Esempio n. 41
0
    def get_display(my):

        print "NotifyPollCmd"

        user = Environment.get_user_name()
        print "user: "******"sthpw/message")
        #search.add_filter("login", user)



        search = Search("sthpw/login")
        sobjects = search.get_sobjects()

        codes = [x.get_code() for x in sobjects]
        codes = ", ".join(codes)

        div = DivWdg()
        div.add_behavior( {
            'type': 'click_up',
            'cbjs_action': '''
            spt.tab.set_main_body_tab();
            var class_name = 'tactic.ui.panel.ViewPanelWdg';
            var search_type = "sthpw/login";
            var view = 'table';
            var kwargs = {
                'search_type': search_type,
                'view': view
            }
            spt.tab.add_new("Login", "Login", class_name, kwargs);
            '''
        } )
        div.add("cow")
        div.add_class("handle")


        #my.info = {
        #    'msg': div.get_buffer_display()
        #}

        return div
Esempio n. 42
0
    def get_display(my):

        print "NotifyPollCmd"

        user = Environment.get_user_name()
        print "user: "******"sthpw/message")
        #search.add_filter("login", user)

        search = Search("sthpw/login")
        sobjects = search.get_sobjects()

        codes = [x.get_code() for x in sobjects]
        codes = ", ".join(codes)

        div = DivWdg()
        div.add_behavior({
            'type':
            'click_up',
            'cbjs_action':
            '''
            spt.tab.set_main_body_tab();
            var class_name = 'tactic.ui.panel.ViewPanelWdg';
            var search_type = "sthpw/login";
            var view = 'table';
            var kwargs = {
                'search_type': search_type,
                'view': view
            }
            spt.tab.add_new("Login", "Login", class_name, kwargs);
            '''
        })
        div.add("cow")
        div.add_class("handle")

        #my.info = {
        #    'msg': div.get_buffer_display()
        #}

        return div
Esempio n. 43
0
    def create(cls, key, value, user=None, project_code=None):

        if not user:
            user = Environment.get_user_name()

        setting = cls.get_by_key(key, user, project_code, use_cache=False)
        if not setting:
            setting = PrefSetting.create_new()
            setting.set_value("key", key)
            setting.set_value("login", user)
            if project_code:
                setting.set_value("project_code", project_code)

        setting.set_value("value", value)
        setting.commit()

        dict_key = '%s:%s:%s' % (cls.SEARCH_TYPE, project_code, user)
        settings_dict = Container.put(dict_key, None)

        return setting
Esempio n. 44
0
    def alter_search(search):
        # always restrict access from others
        security = Environment.get_security()
        if security.check_access("builtin",
                                 "view_private_notes",
                                 'view',
                                 default='deny'):
            return

        user = Environment.get_user_name()
        search.add_op('begin')
        search.add_op('begin')
        search.add_filter("access", "private", op='=')
        search.add_user_filter()
        search.add_op("and")
        search.add_op('begin')
        search.add_filter("access", "private", op='!=')
        search.add_filter("access", None)
        search.add_op("or")
        search.add_op("or")
Esempio n. 45
0
    def create(sobject, queue_type, priority, description, command=None):

        queue = SObjectFactory.create("sthpw/queue")
        queue.set_value("project_code", Project.get_project_name())
        queue.set_sobject_value(sobject)
        queue.set_value("queue", queue_type)
        queue.set_value("state", "pending")

        queue.set_value("login", Environment.get_user_name())
        if command:
            pickled = pickle.dumps(command)
            queue.set_value("command", command.__class__.__name__)
            queue.set_value("serialized", pickled)

        queue.set_value("priority", priority)
        queue.set_value("description", description)

        queue.set_user()
        queue.commit()

        return queue
Esempio n. 46
0
    def create(sobject, queue_type, priority, description, command=None):

        queue = SObjectFactory.create("sthpw/queue")
        queue.set_value("project_code", Project.get_project_name())
        queue.set_sobject_value(sobject)
        queue.set_value("queue", queue_type)
        queue.set_value("state", "pending")

        queue.set_value("login", Environment.get_user_name())
        if command:
            pickled = pickle.dumps(command)
            queue.set_value("command", command.__class__.__name__)
            queue.set_value("serialized", pickled)

        queue.set_value("priority", priority)
        queue.set_value("description", description)

        queue.set_user()
        queue.commit()

        return queue
Esempio n. 47
0
    def create(cls, key, value, user=None, project_code=None):

        if not user:
            user = Environment.get_user_name()


        setting = cls.get_by_key(key, user, project_code, use_cache=False)
        if not setting:
            setting = PrefSetting.create_new()
            setting.set_value("key", key)
            setting.set_value("login", user)
            if project_code:
                setting.set_value("project_code", project_code)

        setting.set_value("value", value)
        setting.commit()

        dict_key = '%s:%s:%s' %(cls.SEARCH_TYPE, project_code, user) 
        settings_dict = Container.put(dict_key, None)

        return setting
Esempio n. 48
0
    def get(cls, search_key, week, year, desc=None, login=None, project=None):

        search = Search(cls.SEARCH_TYPE)
        if search_key:
            search_type, search_id = search_key.split("|")
            search.add_filter('search_type',search_type)
            search.add_filter('search_id',search_id)
        if desc: # some general timecards are for minor stuff
            search.add_filter('description', desc)

        if week:
            search.add_filter('week', week)
        if year:
            search.add_filter('year', year)
        # get the current user if not specified    
        if not login:
            login = Environment.get_user_name()
        search.add_filter('login', login)

        if not project:
            project = Project.get_project_name()
        search.add_filter('project_code', project)
  
        # try getting from cache
        key = '||'.join([Timecard._get_key(search_key), str(Timecard._get_key(year)),\
            str(Timecard._get_key(week)),\
            Timecard._get_key(login), Timecard._get_key(project)])

        cached = cls.get_cached_obj(key)
        if cached != None:
            return cached
        
        sobjs = search.get_sobjects()
        
        dict = cls.get_cache_dict()

        dict[key] = sobjs
        
        return sobjs
Esempio n. 49
0
    def get(cls, search_key, week, year, desc=None, login=None, project=None):

        search = Search(cls.SEARCH_TYPE)
        if search_key:
            search_type, search_id = search_key.split("|")
            search.add_filter('search_type',search_type)
            search.add_filter('search_id',search_id)
        if desc: # some general timecards are for minor stuff
            search.add_filter('description', desc)

        if week:
            search.add_filter('week', week)
        if year:
            search.add_filter('year', year)
        # get the current user if not specified    
        if not login:
            login = Environment.get_user_name()
        search.add_filter('login', login)

        if not project:
            project = Project.get_project_name()
        search.add_filter('project_code', project)
  
        # try getting from cache
        key = '||'.join([Timecard._get_key(search_key), str(Timecard._get_key(year)),\
            str(Timecard._get_key(week)),\
            Timecard._get_key(login), Timecard._get_key(project)])

        cached = cls.get_cached_obj(key)
        if cached != None:
            return cached
        
        sobjs = search.get_sobjects()
        
        dict = cls.get_cache_dict()

        dict[key] = sobjs
        
        return sobjs
Esempio n. 50
0
    def get_display(my):
        
        login = Environment.get_user_name()
        sobject = my.get_current_sobject()
        seen_by = sobject.get_value('seen_by')
        code = sobject.get_code()
        txt = my.unseen_txt
        seen_intstr = '0'
        if login in seen_by:
            txt = my.seen_txt
            seen_intstr = '1'
        widget = DivWdg()
        table = Table()
        table.add_attr('width', '50px')
        table.add_row()
        cell1 = table.add_cell(txt)
        indicate_behavior = my.get_indicate_behavior(login, code)
        cell1.add_attr('seen',seen_intstr)
        cell1.add_style('cursor: pointer;')
        cell1.add_behavior(indicate_behavior)
        widget.add(table)

        return widget
Esempio n. 51
0
    def get_display(my):

        login = Environment.get_user_name()
        sobject = my.get_current_sobject()
        seen_by = sobject.get_value("seen_by")
        code = sobject.get_code()
        txt = my.unseen_txt
        seen_intstr = "0"
        if login in seen_by:
            txt = my.seen_txt
            seen_intstr = "1"
        widget = DivWdg()
        table = Table()
        table.add_attr("width", "50px")
        table.add_row()
        cell1 = table.add_cell(txt)
        indicate_behavior = my.get_indicate_behavior(login, code)
        cell1.add_attr("seen", seen_intstr)
        cell1.add_style("cursor: pointer;")
        cell1.add_behavior(indicate_behavior)
        widget.add(table)

        return widget
Esempio n. 52
0
    def get_remote_repo(my):
        # remote repo does not make sense in batch mode
        if Environment.get_app_server() == 'batch':
            return

        remote_repos = Container.get("remote_repos")
        if remote_repos == None:
            search = Search("sthpw/remote_repo")
            remote_repos = search.get_sobjects()
            Container.put("remote_repos", remote_repos)

        # TODO: Get this function out of this class
        # THIS function requires the web
        from pyasm.web import WebContainer
        web = WebContainer.get_web()
        if not web:
            return None

        # if a login name is found, use that instead of doing the more 
        # stringent IP match
        current_user = Environment.get_user_name()
        simple_remote_repo = RemoteRepo.get_by_login(current_user)
        if simple_remote_repo:
            return simple_remote_repo

        src_ip = web.get_request_host()
        if not src_ip:
            return

        for remote_repo in remote_repos:
            tgt_ip  = remote_repo.get_value("ip_address")
            mask = remote_repo.get_value("ip_mask")

            if Common.match_ip(src_ip, tgt_ip, mask):
                return remote_repo

        return None
Esempio n. 53
0
    def get_remote_repo(self):
        # remote repo does not make sense in batch mode
        if Environment.get_app_server() == 'batch':
            return

        remote_repos = Container.get("remote_repos")
        if remote_repos == None:
            search = Search("sthpw/remote_repo")
            remote_repos = search.get_sobjects()
            Container.put("remote_repos", remote_repos)

        # TODO: Get this function out of this class
        # THIS function requires the web
        from pyasm.web import WebContainer
        web = WebContainer.get_web()
        if not web:
            return None

        # if a login name is found, use that instead of doing the more 
        # stringent IP match
        current_user = Environment.get_user_name()
        simple_remote_repo = RemoteRepo.get_by_login(current_user)
        if simple_remote_repo:
            return simple_remote_repo

        src_ip = web.get_request_host()
        if not src_ip:
            return

        for remote_repo in remote_repos:
            tgt_ip  = remote_repo.get_value("ip_address")
            mask = remote_repo.get_value("ip_mask")

            if Common.match_ip(src_ip, tgt_ip, mask):
                return remote_repo

        return None
Esempio n. 54
0
    def log(cls, level, message, category="default"):
        assert level in ("critical", "error", "warning", "info", "debug")

        # record the exception
        user_name = Environment.get_user_name()
        if not user_name:
            user_name = "UNKNOWN"

        # put the debug in a completely separate transaction from the main
        # transaction
        transaction = Transaction.get(force=True)
        transaction.set_record(False)

        debug_log = SObjectFactory.create("sthpw/debug_log")
        debug_log.set_value("login", user_name)
        debug_log.set_value("level", level)
        debug_log.set_value("category", category)
        debug_log.set_value("message", message)
        debug_log.commit()

        transaction.commit()
        transaction.remove_from_stack()

        return debug_log
Esempio n. 55
0
    def log(cls, level, message, category="default"):
        assert level in ("critical", "error", "warning", "info", "debug")

        # record the exception
        user_name = Environment.get_user_name()
        if not user_name:
            user_name = "UNKNOWN"

        # put the debug in a completely separate transaction from the main
        # transaction
        transaction = Transaction.get(force=True)
        transaction.set_record(False)

        debug_log = SObjectFactory.create("sthpw/debug_log")
        debug_log.set_value("login", user_name)
        debug_log.set_value("level", level)
        debug_log.set_value("category", category)
        debug_log.set_value("message", message )
        debug_log.commit()

        transaction.commit()
        transaction.remove_from_stack()

        return debug_log
Esempio n. 56
0
    def get_buttons(my):
        button_div = DivWdg()


        button_row = ButtonRowWdg()
        button_div.add(button_row)
        button_row.add_style("float: right")
        button_row.add_style("padding-top: 5px")
        button_row.add_style("padding-bottom: 3px")
        button_row.add_style("padding-right: 5px")

        button = ButtonNewWdg(title="Refresh", icon=IconWdg.REFRESH)
        button_row.add(button)
        button.add_behavior( {
            'type': 'click_up',
            'cbjs_action': '''
            spt.app_busy.show("Refreshing");
            var top = bvr.src_el.getParent(".spt_undo_log_top");
            spt.panel.refresh(top)
            spt.app_busy.hide();
            '''
        } )


        button = ButtonNewWdg(title="Undo the last transaction", icon=IconWdg.UNDO)
        button_row.add(button)
        button.add_behavior( {
            'type': 'click_up',
            'cbjs_action': '''
            spt.undo_cbk(evt, bvr);
            spt.panel.refresh('UndoLogWdg');
            '''
        } )



        button = ButtonNewWdg(title="Redo the last transaction", icon=IconWdg.REDO)
        button_row.add(button)
        button.add_behavior( {
            'type': 'click_up',
            'cbjs_action': '''
            spt.redo_cbk(evt, bvr);
            spt.panel.refresh('UndoLogWdg');
            '''
        } )


        # concept of a work session, which holds transaction codes
        session = {}

        # how should this session be stored?  Timestamp based?
        now = datetime.datetime.now()
        today = now.strftime("%Y-%m-%d")
        now = now.strftime("%Y-%m-%d %H:%M:%S")


        location = Config.get_value("install", "server")
        login = Environment.get_user_name()
        project_code = Project.get_project_code()


        """
        button = ButtonNewWdg(title="Save Selected Transactions", icon=IconWdg.SAVE)
        button_row.add(button)
        button.add_behavior( {
            'type': 'click_up',
            'login': login,
            'project_code': project_code,
            'session': session,
            'cbjs_action': '''


            var top = bvr.src_el.getParent(".spt_undo_log_top");
            var table = top.getElement(".spt_table");

            var search_keys = spt.dg_table.get_selected_search_keys(table);
            if (search_keys.length == 0) {
                spt.error("No transactions selected");
                return;
            }

            spt.app_busy.show("Saving Selected Transactions")
            bvr.session['search_keys'] = search_keys.join("|");

            var server = TacticServerStub.get();
            var kwargs = {
                login: bvr.login,
                project_code: bvr.project_code,
                session: bvr.session
            }

            var class_name = 'tactic.command.TransactionPluginCreateCmd';
            server.execute_cmd(class_name, kwargs);

            spt.panel.refresh('UndoLogWdg');

            spt.app_busy.hide();

            '''
        } )


        #button.add_arrow_behavior( {
        #    'type': 'click_up',
        #    'cbjs_action': '''alert('cow')'''
        #} )
        button.set_show_arrow_menu(True)

        from tactic.ui.container import SmartMenu, Menu, MenuItem
        menu = Menu(width=180)
        menu_item = MenuItem(type='title', label='Actions')
        menu.add(menu_item)
        menu_item = MenuItem(type='action', label='Save Today\'s Transactions')
        menu.add(menu_item)

        session['start_time'] =  "%s 00:00:00" % today
        session['end_time'] =  now

        menu_item.add_behavior( {
            'type': 'click_up',
            'login': login,
            'project_code': project_code,
            'session': session,
            'cbjs_action': '''

            spt.app_busy.show("Saving Today's Transactions")

            var server = TacticServerStub.get();
            var kwargs = {
                login: bvr.login,
                project_code: bvr.project_code,
                session: bvr.session
            }

            var class_name = 'tactic.command.TransactionPluginCreateCmd';
            server.execute_cmd(class_name, kwargs);

            spt.panel.refresh('UndoLogWdg');

            spt.app_busy.hide();

            '''
        } )


        SmartMenu.add_smart_menu_set( button.get_arrow_wdg(), { 'BUTTON_MENU': menu } )
        SmartMenu.assign_as_local_activator( button.get_arrow_wdg(), "BUTTON_MENU", True )





        button = ButtonNewWdg(title="Upload Transaction Session", icon=IconWdg.UPLOAD)
        button_row.add(button)
        button.add_behavior( {
            'type': 'click_up',
            'cbjs_action': '''

            spt.app_busy.show("Select Transaction File");

            var applet = spt.Applet.get();
            var files = applet.open_file_browser();
            if (files.length == 0) {
                spt.alert("No files selected");
                spt.app_busy.hide();
                return;
            }

            var path = files[0];

            spt.app_busy.show("Installing Transaction File");

            var server = TacticServerStub.get();
            server.upload_file(path);

            var class_name = 'tactic.command.TransactionPluginInstallCmd';
            var kwargs = {
                path: path
            }

            try {
                var info = server.execute_cmd(class_name, kwargs);
            }
            catch(e) {
                spt.alert(e);
            }

            spt.panel.refresh('UndoLogWdg');

            spt.app_busy.hide();
            '''
        } )
        """



        return button_div
Esempio n. 57
0
    def _get_predefined_url(cls, key, hash):

        # only allow people with site admin
        security = Environment.get_security()
        is_admin = security.is_admin()
        if not is_admin and key == "admin":
            return None
 
 
        # make some predefined fake urls
        if key in ["link", "tab", "admin"]:
            # this is called by PageNav
            if key == "admin":
                expression = "/admin/link/{link}"
            else:
                expression = "/%s/{link}" % key
            options = Common.extract_dict(hash, expression)
            link = options.get("link")
            
            if not link:
                return None


            from tactic.ui.panel import SideBarBookmarkMenuWdg
            personal = False
            if '.' in link:

                # put in a check to ensure this is a user
                parts = link.split(".")

                user = Environment.get_user_name()
                
                def is_personal(user, parts):
                    '''See if parts contains period
                       seperated form of username.'''
                    acc = ""
                    for part in parts:
                        if acc == "":
                            acc = part
                        else:
                            acc = "%s.%s" % (acc, part)
                        if user == acc:
                            return True
                    return False

                personal = is_personal(user, parts) 
                
            # test link security
            project_code = Project.get_project_code()
            security = Environment.get_security()
            keys = [
                    { "element": link },
                    { "element": "*" },
                    { "element": link, "project": project_code },
                    { "element": "*", "project": project_code }
            ]
            if not personal and not security.check_access("link", keys, "allow", default="deny"):
                print "Not allowed"
                return None


            # This is used to find a sub menu (?)
            #view = link
            view = "definition"
            config = SideBarBookmarkMenuWdg.get_config("SideBarWdg", view, personal=personal)

            view = config.get_element_attribute(link, 'view')
            if view:
                options['widget_key'] = 'custom_layout'
                options['view'] = view
                class_name = None
            else:
                options = config.get_display_options(link)
                class_name = config.get_display_handler(link)


            if not options:

                from pyasm.biz import Schema
                config_xml = []
                config_xml.append( '''
                <config>
                ''')
         
                config_schema = Schema.get_predefined_schema('config')
                SideBarBookmarkMenuWdg.get_schema_snippet("_config_schema", config_schema, config_xml)
                schema = Schema.get_admin_schema()
                SideBarBookmarkMenuWdg.get_schema_snippet("_admin_schema", schema, config_xml)

                config_xml.append( '''
                </config>
                ''')

                xml = "".join(config_xml)

                from pyasm.widget import WidgetConfig
                schema_config = WidgetConfig.get(view="_admin_schema", xml=xml)
                options = schema_config.get_display_options(link)
                if not options:
                    schema_config.set_view("_config_schema")
                    options = schema_config.get_display_options(link)

                if not options:
                    return None


            if not class_name or class_name == "LinkWdg":
                class_name = options.get("class_name")

            widget_key = options.get("widget_key")


            if widget_key:
                class_name = WidgetClassHandler().get_display_handler(widget_key)
            elif not class_name:
                class_name = 'tactic.ui.panel.ViewPanelWdg'


            if key in ["admin", "tab"]:
                use_index = "false"
            else:
                use_index = "true"

            if key in ['admin']:
                use_admin = "true"
            else:
                use_admin = "false"


            xml = []
            xml.append('''<element admin="%s" index="%s">''' % (use_admin, use_index))
            xml.append('''  <display class="%s">''' % class_name)
            for name, value in options.items():
                xml.append("<%s>%s</%s>" % (name, value, name) )
            xml.append('''  </display>''')
            xml.append('''</element>''')

            xml = "\n".join(xml)

            sobject = SearchType.create("config/url")
            sobject.set_value("url", "/%s/{value}" % key)
            sobject.set_value("widget", xml )

            return sobject


        elif key == "rest":

            xml = '''<element widget='true'>
  <display class='tactic.protocol.APIRestHandler'>
  </display>
</element>'''

            sobject = SearchType.create("config/url")
            sobject.set_value("url", "/rest")
            sobject.set_value("widget", xml )

            return sobject


        else:
            return None
Esempio n. 58
0
    def get_display(self):

        top = self.top
        login = self.kwargs.get("login")
        if not login or login == "$LOGIN":
            login = Environment.get_user_name()

        login_sobj = Login.get_by_code(login)

        #top.add_style("margin-top: -2px")
        #top.add_style("margin-left: -2px")

        thumb_div = DivWdg()
        thumb_div.add_style("float: left")
        thumb_div.add_style("margin-right: 5px")
        thumb_div.add_style("margin-bottom: 5px")
        thumb_div.add_style("padding-top: 1px")
        thumb = ThumbWdg()
        thumb.set_sobject(login_sobj)
        thumb_div.add(thumb)
        thumb.set_icon_size(90)
        thumb.set_aspect("height")

        full_name = login_sobj.get_full_name()

        info_wdg = DivWdg()
        top.add(info_wdg)

        name_wdg = DivWdg()
        info_wdg.add(thumb_div)
        info_wdg.add(name_wdg)
        name_wdg.add("&nbsp;" * 3)
        name_wdg.add(full_name)
        name_wdg.add_style("font-size: 1.5em")
        name_wdg.add_style("font-weight: bold")
        name_wdg.add_style("padding: 5px")
        #name_wdg.add_style("margin-left: -10px")
        name_wdg.add_color("background", "background3")
        name_wdg.add_style("height: 20px")
        name_wdg.add_style("margin-bottom: 0px")
        name_wdg.add_border()

        info_wdg.add("<br/>")

        from tactic.ui.container import TabWdg

        # return if the supplied tab view has a config xml
        if self.tab_view:
            search = Search("config/widget_config")
            search.add_filter("category", "TabWdg")
            search.add_filter("view", self.tab_view)
            config_sobj = search.get_sobject()
            if config_sobj:

                config_xml = config_sobj.get_value('config')
                # replace the variable $login with the login clicked
                if login:
                    config_xml = config_xml.replace('$login', login)

                tab = TabWdg(config_xml=config_xml,
                             view=self.tab_view,
                             show_add=False,
                             show_remove=False)
                top.add(tab)
                return top

        config_xml = []
        config_xml.append('<config>')
        config_xml.append('<tab>')

        config_xml.append('''
        <element name='schedule'>
          <display class='tactic.ui.widget.TaskCalendarWdg'>
            <assigned>%s</assigned>
            <sobject_display_expr>%s</sobject_display_expr>
            <show_header>true</show_header>
            <show_border>false</show_border>
          </display>
        </element> 
        ''' % (login, self.sobject_display_expr))

        config_xml.append('''
        <element name='activity'>
          <display class='tactic.ui.widget.ActivityCalendarWdg'>
            <login>%s</login>
            <cell_width>100px</cell_width>
            <cell_height>50px</cell_height>
            <show_header>true</show_header>
            <show_border>false</show_border>
          </display>
        </element> 
        ''' % login)

        config_xml.append('''
        <element name='tasks'>
          <display class='tactic.ui.panel.FastTableLayoutWdg'>
            <search_type>sthpw/task</search_type>
            <view>table</view>
            <expression>@SOBJECT(sthpw/task['assigned','%s']['@ORDER_BY', 'bid_start_date desc'])</expression>
            <mode>simple</mode>
          </display>
        </element> 
        ''' % login)

        config_xml.append('''
        <element name='work_hours'>
          <display class='tactic.ui.widget.SObjectCalendarWdg'>
            <login>%s</login>
            <!--
            <cell_width>100px</cell_width>
            -->
            <cell_height>50px</cell_height>
            <show_header>true</show_header>
            <show_border>false</show_border>
            <search_type>sthpw/work_hour</search_type>
            <handler>tactic.ui.widget.WorkHourCalendarDayWdg</handler>
            <start_date_col>day</start_date_col>
            <end_date_col>day</end_date_col>
          </display>
        </element> 
        ''' % login)

        config_xml.append('''
         <element name='recent transactions'>
          <display class='tactic.ui.panel.FastTableLayoutWdg'>
            <search_type>sthpw/transaction_log</search_type>
            <view>table</view>
            <expression>@SOBJECT(sthpw/transaction_log['login','%s']['@ORDER_BY','timestamp desc']['@LIMIT','30'])</expression>
            <element_names>code,timestamp,namespace,description,transaction_log_hidden</element_names>
            <show_shelf>false</show_shelf>
            <show_select>false</show_select>
          </display>
        </element> 
        ''' % login)

        config_xml.append('</tab>')
        config_xml.append('</config>')
        config_xml = "".join(config_xml)

        tab = TabWdg(config_xml=config_xml,
                     view='tab',
                     show_add=False,
                     show_remove=False)
        top.add(tab)
        tab.add_style("margin-left: -2px")
        tab.add_style("margin-right: -2px")

        return top
Esempio n. 59
0
    def execute(my):

        value = my.get_value()
        if value:
            data = jsonloads(value)
        else:
            data = {}

        task = my.sobject
        parent = task.get_parent()

        my.unit = my.get_option("unit")
        if not my.unit:
            my.unit = "hour"

        my.use_straight_time = my.get_option("use_straight_time")
        #my.use_straight_time = 'false'
        if my.use_straight_time == 'false':
            my.use_straight_time = False
        else:
            my.use_straight_time = True

        # Do this for now. EXIT if the parent of task can't be found..
        if not parent:
            return

        # TODO: make it work if my.sobject is not an instance of a Task
        use_task_code = True

        # match assigned to avoid deleting work hours entries made on the same task by other users
        user = Environment.get_user_name()
        entries = parent.get_related_sobjects("sthpw/work_hour")

        # filter out just for this task
        if use_task_code:
            entries = [
                x for x in entries
                if x.get_value('task_code') == task.get_code()
                and x.get_value('login') == user
            ]

        entry_dict = {}
        for key, value in data.items():
            if my.use_straight_time:
                if not (key.startswith("day_") or key.startswith("otday_")):
                    continue
            else:
                if not (key.startswith("day_") or key.startswith("sttday_")
                        or key.startswith("entday_")):
                    continue
                start_value = data

            tmp, year, month, day = key.split("_")
            date = "%s-%s-%s 00:00:00" % (year, month, day)
            #OVER_TIME_TYPE = 'ot'

            exists = False
            # TODO: we should allow multiple entiries per task per day and just
            # have a special UI to edit individual entries post creation.
            for entry in entries:
                entry_day = entry.get_value("day")
                if entry_day == date:
                    if my.use_straight_time:

                        if key.startswith("day_"):
                            if entry.get_value("category") in [
                                    '', WorkHoursElementWdg.ST
                            ]:
                                exists = True
                                break
                        if key.startswith("otday_"):
                            if WorkHoursElementWdg.OT == entry.get_value(
                                    "category"):
                                exists = True
                                break
                    else:
                        # only supports regular hours for start and end time
                        if key.startswith("sttday_"):
                            if entry.get_value("category") in [
                                    '', WorkHoursElementWdg.ST
                            ]:
                                exists = True
                                break
                        elif key.startswith("entday_"):
                            if entry.get_value("category") in [
                                    '', WorkHoursElementWdg.ST
                            ]:
                                exists = True
                                break

            if not exists:
                entry = entry_dict.get(date)
                if not entry:
                    # create a new one
                    entry = SearchType.create("sthpw/work_hour")
                    if parent:
                        entry.set_parent(parent)
                    entry.set_value("task_code", task.get_code())
                    entry.set_value("process", task.get_value('process'))
                    entry.set_value("day", date)
                    entry.set_user()
                    entry.set_project()

            if not my.use_straight_time:
                # only enter standard time for now
                entry.set_value("project_code", task.get_value('project_code'))
                entry.set_value("category", WorkHoursElementWdg.ST)
                if not value:
                    continue

                date_part = ''
                if key.startswith("entday_"):
                    date_part = key.replace('entday_', '')
                    date_part = date_part.replace('_', '-')
                    value = value.zfill(4)
                    time = parser.parse('%s %s' % (date_part, value))
                    entry.set_value("end_time", time)

                elif key.startswith("sttday_"):
                    date_part = key.replace('sttday_', '')
                    date_part = date_part.replace('_', '-')
                    value = value.zfill(4)
                    time = parser.parse('%s %s' % (date_part, value))
                    entry.set_value("start_time", time)

                entry_dict[date] = entry

                #entry.commit()

            else:
                if value == '' or value == '0':
                    if exists:
                        entry.delete()

                elif value == '%s' % entry.get_value('straight_time'):
                    # prevent commit the same value again
                    continue
                else:
                    #
                    entry.set_value("straight_time", value)
                    entry.set_value("project_code",
                                    task.get_value('project_code'))

                    if key.startswith("otday_"):
                        entry.set_value("category", WorkHoursElementWdg.OT)
                    else:
                        entry.set_value("category", WorkHoursElementWdg.ST)

                    entry.commit()

            for key, entry in entry_dict.items():

                # set the straight_time as well
                st_time = str(entry.get_value('start_time'))
                end_time = str(entry.get_value('end_time'))
                if st_time and end_time:
                    st_time_obj = parser.parse(st_time)
                    end_time_obj = parser.parse(end_time)

                    delta = (end_time_obj - st_time_obj
                             ).seconds / WorkHoursElementWdg.UNIT_DICT[my.unit]
                    entry.set_value("straight_time", delta)

                entry.commit()