Esempio n. 1
0
def getFormObjAjax(request):
    '''
    load service_object's form_object
    return: json
    author: Arthur
    '''
    username = request.user.username
    postdata = getPostdata(request)
    result = {}

    if username:
        require_field = ['api_path']
        checker = DataChecker(postdata, require_field)
        if checker.get('status') == 'success':
            flow_uuid = FlowActiveGlobalObject.APIgetUUID(
                postdata.get('api_path'))
            thisQuery = list(
                FlowActive.objects.filter(flow_uuid=flow_uuid,
                                          undeploy_flag=False).values(
                                              'formobject', 'attachment'))
            if len(thisQuery):
                result = thisQuery[0]
                language = get_language()
                app_id = FlowActiveGlobalObject.UUIDSearch(
                    flow_uuid).flow_app_id
                formobject = Translator('formobject', 'active', language,
                                        app_id, None).Do(result['formobject'])
                result['formobject'] = json.dumps(formobject)
        return ResponseAjax(statusEnum.success, _('讀取成功。'),
                            result).returnJSON()
    else:
        error('%s get form_object with no permission' % username, request)
        return ResponseAjax(statusEnum.no_permission,
                            _('您沒有權限進行此操作。')).returnJSON()
Esempio n. 2
0
def saveServiceAjax(request):
    '''
    save manager's service setting
    input: request
    return: json
    author: Arthur
    '''
    #Server Side Rule Check
    username = request.user.username
    postdata = getPostdata(request)

    if username:
        require_field = ['content']
        checker = DataChecker(postdata, require_field)

        if checker.get('status') == 'success':

            #是否存入翻譯
            lan_package = postdata.get('lan_package', None)
            if lan_package:
                FlowActiveGlobalObject.setSysLanDict("service", None,
                                                     lan_package)

            #static variable
            box_object = json.loads(postdata.get('content', ''))
            OmServiceDesign.objects.create(
                content=json.dumps(box_object),
                language_package=json.dumps(
                    FlowActiveGlobalObject.getSysLanDict('service')))

            OmService.objects.all().delete()

            ServiceList = []
            for key in box_object["list"]:
                thisSer = box_object["list"][key]
                if thisSer["type"] == "service":
                    flow_uuid = FlowActiveGlobalObject.APIgetUUID(
                        thisSer['api_path'])
                    ser = OmService(service_id=thisSer['id'],
                                    flow_uuid=flow_uuid,
                                    role=thisSer['setting']['setRole'],
                                    default_value=json.dumps(
                                        thisSer['default_value']))
                    ServiceList.append(ser)

            OmService.objects.bulk_create(ServiceList)

            info('%s update Service success' % username, request)
            return ResponseAjax(statusEnum.success, _('儲存成功。')).returnJSON()
        else:
            info('%s update Service error' % username, request)
            return ResponseAjax(statusEnum.not_found, checker.get('message'),
                                checker).returnJSON()
    else:
        info('%s update Service with no permission' % username, request)
        return ResponseAjax(statusEnum.no_permission,
                            _('您沒有權限進行此操作。')).returnJSON()
Esempio n. 3
0
def getFormobjectListText(item_id, value, flow_uuid, formobject):
    item_id = item_id.upper()
    text = value
    lists = []
    if flow_uuid:
        fa = FlowActiveGlobalObject.UUIDSearch(flow_uuid)
        items = json.loads(fa.merge_formobject)
    else:
        if isinstance(formobject, str):
            formobject = json.loads(formobject)
        items = formobject['items']

    if isinstance(items, dict):
        item = items.get(item_id, {})
        lists = item.get('config', {}).get('lists', [])
    else:
        for item in items:
            if item['id'] == item_id:
                lists = item.get('config', {}).get('lists', [])
                break

    for l in lists:
        if l['value'] == value:
            text = l['text']
            break
    return text
Esempio n. 4
0
 def threadsubmit(self):
     while True:
         #get pool queue size
         pool_qsize = self.threadPool._work_queue.qsize()
         #get queue size
         queue_size = self.threadQueue.qsize()
         if pool_qsize == 0 and queue_size > 0 and self.Monitor_Start:
             #get json form queue
             jsonObj = self.threadQueue.get(block=True)
             flow_uuid = jsonObj['param'].get('flow_uuid', '')
             fa = None
             if flow_uuid:
                 fa = FlowActiveGlobalObject.UUIDSearch(flow_uuid)
             #import module
             try:
                 module_name = jsonObj['module_name']
                 l = module_name.split('.')
                 if l[0] == 'omformflow' and fa and self.name == 'FormFlow':
                     if l[-2] != fa.version:
                         module_name = 'omformflow.production.' + flow_uuid + '.' + str(
                             fa.version) + '.main'
                 module = import_module(module_name)
                 #submit threads
                 self.threadPool.submit(getattr(module, jsonObj['method']),
                                        jsonObj['param'])
             except Exception as e:
                 try:
                     if fa:
                         error(_('找不到main.py') + str(e))
                     else:
                         error(_('找不到流程') + str(e))
                 except:
                     pass
         sleep(0.00001)
Esempio n. 5
0
def importTranslationAjax(request):
    '''
    import service language package
    input: request
    return: json
    author: Arthur
    '''
    #function variable
    require_field = ['language']
    #server side rule check
    postdata = getPostdata(request)
    language_str = postdata.get('language_list', '')
    language = postdata.get('language', '')
    checker = DataChecker(postdata, require_field)
    if checker.get('status') == 'success':
        #wa = WorkspaceApplication.objects.get(id=app_id)
        #language_dict = json.loads(wa.language_package)
        max = OmServiceDesign.objects.all().aggregate(Max('id')).get('id__max')
        this_service = OmServiceDesign.objects.get(id=max)
        language_dict = json.loads(this_service.language_package)

        temp_dict = {}
        language_list = language_str.split('\r\n')
        for line in language_list:
            if line:
                sp_index = line.find(':')
                if line[:sp_index] == 'original':
                    key = line[sp_index + 1:]
                else:
                    temp_dict[key] = line[sp_index + 1:]
        language_dict[language] = temp_dict
        language_str = json.dumps(language_dict)
        this_service.language_package = language_str
        this_service.save()
        #set global
        FlowActiveGlobalObject.setSysLanDict("service", language, temp_dict)
        info('%s import language package success.' % request.user.username,
             request)
        return ResponseAjax(statusEnum.success, _('匯入成功。')).returnJSON()
    else:
        info(
            '%s missing some require variable or the variable type error.' %
            request.user.username, request)
        return ResponseAjax(statusEnum.not_found, checker.get('message', ''),
                            checker).returnJSON()
Esempio n. 6
0
 def datatable_multi_app(self, content):
     if isinstance(content, dict):
         for key in content:
             line = content[key]
             for s_k in line:
                 if isinstance(line[s_k], str):
                     if line.get('flow_uuid', None):
                         fa = FlowActiveGlobalObject.UUIDSearch(
                             line.get('flow_uuid', None))
                         if fa:
                             app_id = fa.flow_app_id
                         else:
                             app_id = None
                         app_name = None
                     else:
                         app_id = line.get('id', None)
                         app_name = line.get('app_name', None)
                     lan = FlowActiveGlobalObject.getAppLanDict(
                         self.trans_type, app_id,
                         app_name).get(self.language, {})
                     line[s_k] = self.fun(lan.get(line[s_k], line[s_k]),
                                          line[s_k])
     elif isinstance(content, list):
         for line in content:
             for s_k in line:
                 if isinstance(line[s_k], str):
                     if line.get('flow_uuid', None):
                         fa = FlowActiveGlobalObject.UUIDSearch(
                             line.get('flow_uuid', None))
                         if fa:
                             app_id = fa.flow_app_id
                         else:
                             app_id = None
                         app_name = None
                     else:
                         app_id = line.get('id', None)
                         app_name = line.get('app_name', None)
                     lan = FlowActiveGlobalObject.getAppLanDict(
                         self.trans_type, app_id,
                         app_name).get(self.language, {})
                     line[s_k] = self.fun(lan.get(line[s_k], line[s_k]),
                                          line[s_k])
     return content
Esempio n. 7
0
 def flowobject(self, content):
     full_language_package = FlowActiveGlobalObject.getAppLanDict(
         self.trans_type, self.app_id, self.app_name)
     lan = full_language_package.get(self.language, {})
     if isinstance(content, str):
         content = json.loads(content)
     items = content['items']
     for i in items:
         item_type = i['type']
         if item_type != 'line':
             #置換元件名稱
             i['text'] = self.fun(lan.get(i['text'], i['text']), i['text'])
     return content
Esempio n. 8
0
def requestAjax(request):
    '''
    send user's service request
    return: json
    author: Arthur
    '''
    username = request.user.username
    postdata = request.POST.copy()
    files = request.FILES.getlist('files', '')
    result = {}
    #print(postdata)
    if username:
        require_field = ['api_path', 'service_id', 'formdata']
        checker = DataChecker(postdata, require_field)
        if checker.get('status') == 'success':
            #判斷權限
            postdata['flow_uuid'] = FlowActiveGlobalObject.APIgetUUID(
                postdata.get('api_path'))
            thisQuery = list(
                OmService.objects.filter(
                    service_id=postdata.get('service_id')))
            if len(thisQuery):
                service_obj = thisQuery[0]
                #print(service_obj.default_value)
                service_obj = json.loads(service_obj.default_value)

                postdata["formdata"] = json.loads(postdata["formdata"])
                for default_col in service_obj:
                    postdata["formdata"].append(default_col)

                postdata["formdata"] = json.dumps(postdata["formdata"])
            else:
                info('%s update Service error' % username, request)
                return ResponseAjax(statusEnum.error, _('查無此服務。')).returnJSON()

            result = createOmData(postdata, request.user.username, files)
            if result['status']:
                return ResponseAjax(statusEnum.success,
                                    result['message']).returnJSON()
            else:
                return ResponseAjax(statusEnum.not_found,
                                    result['message']).returnJSON()
        else:
            return ResponseAjax(statusEnum.not_found,
                                _('缺少必填欄位。')).returnJSON()
    else:
        error('%s request_service with no permission' % username, request)
        return ResponseAjax(statusEnum.no_permission,
                            _('您沒有權限進行此操作。')).returnJSON()
Esempio n. 9
0
def exportServcieAjax(request):
    if OmServiceDesign.objects.all().count() > 0:
        max = OmServiceDesign.objects.all().aggregate(Max('id')).get('id__max')
        box_object = list(
            OmServiceDesign.objects.filter(id=max).values('content'))
        box_object = json.loads(box_object[0]["content"])

        #翻譯語言
        lan_package = FlowActiveGlobalObject.getSysLanDict('service')
        result = {"box_object": box_object, "lan_package": lan_package}

        info(request,
             '%s export language package success.' % request.user.username)
        return ResponseAjax(statusEnum.success, _('匯出成功。'),
                            result).returnJSON()
Esempio n. 10
0
 def datatable_single_app(self, content):
     full_language_package = FlowActiveGlobalObject.getAppLanDict(
         self.trans_type, self.app_id, self.app_name)
     lan = full_language_package.get(self.language, {})
     if isinstance(content, dict):
         for key in content:
             line = content[key]
             for s_k in line:
                 if isinstance(line[s_k], str):
                     line[s_k] = self.fun(lan.get(line[s_k], line[s_k]),
                                          line[s_k])
     elif isinstance(content, list):
         for line in content:
             for s_k in line:
                 if isinstance(line[s_k], str):
                     line[s_k] = self.fun(lan.get(line[s_k], line[s_k]),
                                          line[s_k])
     return content
Esempio n. 11
0
 def single_app(self, content):
     full_language_package = FlowActiveGlobalObject.getAppLanDict(
         self.trans_type, self.app_id, self.app_name)
     lan = full_language_package.get(self.language, {})
     if isinstance(content, str):
         result = self.fun(lan.get(content, content), content)
     elif isinstance(content, list):
         result = []
         for i in content:
             result.append(self.fun(lan.get(i, i), i))
     elif isinstance(content, dict):
         result = {}
         for key in content:
             result[key] = self.fun(lan.get(content[key], content[key]),
                                    content[key])
     else:
         result = None
     return result
Esempio n. 12
0
    def formobject(self, content):
        full_language_package = FlowActiveGlobalObject.getAppLanDict(
            self.trans_type, self.app_id, self.app_name)
        lan = full_language_package.get(self.language, {})
        if isinstance(content, str):
            content = json.loads(content)
        items = content['items']
        for i in items:
            item_type = i['type']
            config = i['config']

            if item_type in ['box12', 'box6', 'areabox']:
                config['title'] = self.fun(
                    lan.get(config['title'], config['title']), config['title'])

            elif item_type in [
                    'h_title', 'inputbox', 'date', 'datetime', 'subquery'
            ]:
                config['title'] = self.fun(
                    lan.get(config['title'], config['title']), config['title'])
                config['placeholder'] = self.fun(
                    lan.get(config['placeholder'], config['placeholder']),
                    config['placeholder'])

            elif item_type == 'h_group':
                config['group_title'] = self.fun(
                    lan.get(config['group_title'], config['group_title']),
                    config['group_title'])
                config['user_title'] = self.fun(
                    lan.get(config['user_title'], config['user_title']),
                    config['user_title'])

            elif item_type in ['h_level', 'h_status', 'list', 'checkbox']:
                config['title'] = self.fun(
                    lan.get(config['title'], config['title']), config['title'])
                lists = config['lists']
                for l in lists:
                    l['text'] = self.fun(lan.get(l['text'], l['text']),
                                         l['text'])
        return content
Esempio n. 13
0
def myformpage(request, url):
    '''
    system config page
    input:request
    return: system.html
    author:Jia Liu
    '''
    url_list = url.split('/')
    flow_uuid = url_list[0]
    data_no = url_list[1]
    try:
        fa = FlowActiveGlobalObject.UUIDSearch(flow_uuid)
        if fa:
            app_id = fa.flow_app_id
        if len(url_list) == 2:
            model = getModel('omformmodel', 'Omdata_' + flow_uuid)
            omdata = model.objects.filter(data_no=data_no, history=False)[0]
            data_id = omdata.id
        else:
            data_id = url_list[2]
    except:
        pass
    return render(request, "myform.html", locals())
Esempio n. 14
0
    mail_info = get_email(num, conn)
    mail_from = mail_info["From"]
    mail_subject = mail_info["Subject"]
    mail_content = mail_info["Body"]
    unseen_mails.append(mail_info)
#         print(mail_from)
#         print(mail_subject)
#         print(mail_content)
conn.close()
conn.logout()

#-----------------------------------------Submit Ticket--------------------------------------------#
from omformflow.views import createOmData
from omflow.global_obj import FlowActiveGlobalObject
try:
    fa = FlowActiveGlobalObject.NameSearch("事故管理", None, "服務管理")
    event_uuid = fa.flow_uuid.hex
    para_list = receive_keyword.split(',')
    for mail_info in unseen_mails:
        param = {}
        mail_from = mail_info["From"]
        mail_subject = mail_info["Subject"]
        mail_content = mail_info["Body"]
        #如果type = ['h_group','h_title','h_status','h_level']
        #{"id":"title","value":mail_subject,"type":"titile"}
        #{"id":"status","value":<text>,"type":"status"}
        #---------------------------------------------------
        #{"id":"FORMITM_4","value":0,"type":"h_status"},\
        #{"id":"status","value":'new',"type":"status"},\
        if [item for item in para_list if item in mail_subject
            ] and not ("Re:" in mail_subject or "RE:" in mail_subject):
Esempio n. 15
0
def getColumnListAjax(request):
    '''
    get model column-list with permission
    input: request
    return: json
    author: Arthur
    '''
    username = request.user.username
    postdata = getPostdata(request)

    if username:
        require_field = ['model']
        checker = DataChecker(postdata, require_field)
        if checker.get('status') == 'success':
            permission = "Omdata_" + postdata.get('model', '') + "_View"
            this_model = list(
                filter(
                    lambda x: x.__name__ == re.findall("^(.+)_View",
                                                       permission)[0],
                    apps.get_models()))
            result = {}

            #isPolicy = False
            from omflow.syscom.common import License
            version_type = License().getVersionType()
            if version_type != 'C':
                from ommonitor.models import MonitorFlow
                if len(this_model) == 0 and request.user.has_perm(
                        "OmMonitor_Manage"):
                    policy_model = list(
                        filter(
                            lambda x: x.__name__ == postdata.get('model', ''),
                            apps.get_models()))
                    if len(policy_model):
                        this_table_id = re.findall("OmPolicy_(.+)",
                                                   postdata.get('model',
                                                                ''))[0]
                        fa = list(
                            MonitorFlow.objects.filter(
                                table_id=this_table_id).values('flowobject'))
                        if len(fa):
                            fa = json.loads(fa[0]['flowobject'])
                            result["collector_id"] = "收集器ID"
                            for item in fa['items']:
                                if item['type'] == "end":
                                    for output in item['config']['output']:
                                        field_name = re.findall(
                                            '\$\((.+)\)', output['name'])[0]
                                        result[field_name] = output['des']

            if len(this_model) and request.user.has_perm(
                    str(this_model[0]._meta.app_label) + "." + permission):
                if re.match('Omdata_.+_View', permission):
                    flow_uuid = re.findall("Omdata_(.+)_View", permission)[
                        0]  #Omdata_5d3c2cbdcf4145c3a05affaf4a74345b_View
                    fa = FlowActiveGlobalObject.UUIDSearch(
                        flow_uuid).merge_formobject
                    if len(fa):
                        fa = json.loads(fa)
                        for field in this_model[0]._meta.fields:
                            if 'formitm' in field.verbose_name:
                                if field.name.upper() in fa:
                                    if fa[field.name.upper(
                                    )]["type"] == 'h_group':
                                        #result[field.name] = fa[field.name.upper]
                                        result[
                                            field.name] = fa[field.name.upper(
                                            )]["config"]["group_title"]
                                    else:
                                        result[
                                            field.name] = fa[field.name.upper(
                                            )]["config"]["title"]
                            else:
                                result[field.name] = field.verbose_name

                    lang = get_language()
                    app_id = FlowActiveGlobalObject.UUIDSearch(
                        flow_uuid).flow_app_id
                    result = Translator('single_app', 'active', lang, app_id,
                                        None).Do(result)

            if result != {}:
                info('%s get Column-List success' % username, request)
                return ResponseAjax(statusEnum.success, _('讀取成功。'),
                                    result).returnJSON()
            else:
                info('%s get Column-List with no permission' % username,
                     request)
                return ResponseAjax(statusEnum.no_permission,
                                    _('您沒有權限進行此操作。')).returnJSON()
        else:
            info('%s get Column-List error' % username, request)
            return ResponseAjax(statusEnum.not_found, checker.get('message'),
                                checker).returnJSON()
    else:
        info('%s get Column-List with no permission' % username, request)
        return ResponseAjax(statusEnum.no_permission,
                            _('您沒有權限進行此操作。')).returnJSON()
Esempio n. 16
0
def loadServiceAjax(request):
    '''
    load manager's service setting
    return: json
    author: Arthur
    '''

    #Server Side Rule Check
    username = request.user.username
    postdata = getPostdata(request)
    result = {}
    if username:
        #static variable
        #         result['structure'] = OmServiceDesign.objects.all()
        #         if request.user.has_perm('omservice.OmServiceDesign_Manager'):
        #             result['objects'] = OmService.objects.all()
        #         else:
        #             #等待修改
        #             user_role_list = list(request.user.groups.all().values_list('id', flat=True))
        #             for service_obj in OmService.objects.all():
        #                 service_role_list = json.loads(service_obj.get('role','[]'))
        #                 if len(set(user_role_list) & set(service_role_list)):
        #                     result['objects'].append(service_obj)
        #print(OmServiceDesign.objects.all().count())
        if OmServiceDesign.objects.all().count() > 0:
            max = OmServiceDesign.objects.all().aggregate(
                Max('id')).get('id__max')
            result = list(
                OmServiceDesign.objects.filter(id=max).values('content'))

            box_object = json.loads(result[0]["content"])

            #檢查權限
            if request.user.has_perm('omservice.OmServiceDesign_Manage'):
                pass
            else:
                Service_List = list(OmService.objects.all())
                Group_List = list(request.user.groups.all().values_list(
                    'id', flat=True))
                if len(Group_List):
                    Group_List.append(-1)
                else:
                    Group_List = [-1]
                for thisSer in Service_List:
                    if len(set(json.loads(thisSer.role))
                           & set(Group_List)) == 0:
                        del box_object["list"][str(thisSer.service_id)]

            #檢查是否過期
            this_activeList = list(
                FlowActive.objects.filter(
                    undeploy_flag=0,
                    parent_uuid__isnull=True).values_list('flow_uuid',
                                                          flat=True))
            this_activeList = [o.hex for o in this_activeList]
            for idx in box_object["list"]:
                #print(box_object["list"][idx])
                if box_object["list"][idx]["type"] == "service":
                    if 'api_path' in box_object["list"][idx]:
                        flow_uuid = FlowActiveGlobalObject.APIgetUUID(
                            box_object["list"][idx]["api_path"])
                    else:
                        flow_uuid = box_object["list"][idx]["flow_uuid"]
                        box_object["list"][idx][
                            "api_path"] = FlowActiveGlobalObject.UUIDgetAPI(
                                flow_uuid)

                    if flow_uuid in this_activeList:
                        box_object["list"][idx]["available"] = 1
                    else:
                        box_object["list"][idx]["available"] = 0

            #翻譯語言
            if postdata.get('type') != "source":
                language_type = get_language()
                #print(FlowActiveGlobalObject.getSysLanDict('service'))
                lan_package = FlowActiveGlobalObject.getSysLanDict(
                    'service').get(language_type, None)

                if lan_package:
                    for idx in box_object["list"]:
                        this_service = box_object["list"][idx]
                        if this_service["setting"]["setTitle"]:
                            this_service["setting"]["setTitle"] = lan_package[
                                this_service["setting"]
                                ["setTitle"]] if checkJsonKey(
                                    lan_package,
                                    this_service["setting"]["setTitle"]
                                ) else this_service["setting"]["setTitle"]

                        if this_service["type"] == "service":
                            if this_service["setting"]["setTip"]:
                                this_service["setting"]["setTip"] = lan_package[
                                    this_service["setting"]
                                    ["setTip"]] if checkJsonKey(
                                        lan_package,
                                        this_service["setting"]["setTip"]
                                    ) else this_service["setting"]["setTip"]
                            for sup_idx in this_service["service"]["list"]:
                                this_step = this_service["service"]["list"][
                                    sup_idx]
                                if this_step["name"]:
                                    this_step["name"] = lan_package[
                                        this_step["name"]] if checkJsonKey(
                                            lan_package, this_step["name"]
                                        ) else this_step["name"]
                                if this_step["tip"]:
                                    this_step["tip"] = lan_package[
                                        this_step["tip"]] if checkJsonKey(
                                            lan_package, this_step["tip"]
                                        ) else this_step["tip"]

            #print(result[0]["content"])
            result[0]["content"] = json.dumps(box_object)

        return ResponseAjax(statusEnum.success, _('讀取成功。'),
                            result).returnJSON()
    else:
        error('%s load Service with no permission' % username, request)
        return ResponseAjax(statusEnum.no_permission,
                            _('您沒有權限進行此操作。')).returnJSON()
Esempio n. 17
0
def SubQueryDataAjax(request):
    '''
    load omdata.
    input: request
    return: json
    author: Kolin Hsu
    '''
    #function variable
    require_field = ['app_name', 'flow_name', 'data_id']
    #server side rule check
    postdata = getPostdata(request)
    checker = DataChecker(postdata, require_field)
    #get post data
    app_name = postdata.get('app_name', '')
    flow_name = postdata.get('flow_name', '')
    data_id = postdata.get('data_id', '')
    field_list = postdata.get('fields', [])
    service_id = postdata.get('service_id', [])

    if True:
        if checker.get('status') == 'success':
            #get model
            fa = FlowActiveGlobalObject.NameSearch(flow_name, None, app_name)
            omdata_model = getModel('omformmodel',
                                    'Omdata_' + fa.flow_uuid.hex)
            #整理欄位
            new_field_list = []
            group_user = []
            group_user_id = None
            for f in field_list:
                if re.match(r'formitm_[0-9]+-.+', f):
                    group_user_id = re.findall(r'(.+)-.+', f)[0]
                    group_user.append(f)
                    new_field_list.append(group_user_id)
                else:
                    new_field_list.append(f)

            #取得資料
            omdata = list(
                omdata_model.objects.filterformat(*new_field_list, id=data_id))

            if omdata:
                result = omdata[0]
                if group_user_id:
                    group_user_dict = json.loads(result.pop(group_user_id))
                    for g_u in group_user:
                        key = re.findall(r'.+-(.+)', g_u)[0]
                        result[g_u] = group_user_dict.get(key, '')
            else:
                result = {}

            info('%s load OmData success.' % request.user.username, request)
            return ResponseAjax(statusEnum.success, _('讀取成功。'),
                                result).returnJSON()
        else:
            info(
                '%s missing some require variable or the variable type error.'
                % request.user.username, request)
            return ResponseAjax(statusEnum.not_found, checker.get('message'),
                                checker).returnJSON()
    else:
        info('%s has no permission.' % request.user.username, request)
        return ResponseAjax(statusEnum.no_permission,
                            _('您沒有權限進行此操作。')).returnJSON()
Esempio n. 18
0
def SubQueryHeaderAjax(request):
    '''
    list omdata for subquery.
    input: request
    return: json
    author: Kolin Hsu
    '''
    #function variable
    display_field_list = [
        'id', 'data_no', 'stop_uuid', 'stop_chart_text', 'error',
        'error_message', 'closed', 'running'
    ]
    #get post data
    postdata = getPostdata(request)
    app_name = postdata.get('app_name', '')
    flow_name = postdata.get('flow_name', '')
    condition = postdata.get('condition', [])
    service_id = postdata.get('service_id', [])
    flowactive = FlowActiveGlobalObject.NameSearch(flow_name, None, app_name)
    flow_uuid = flowactive.flow_uuid.hex

    if True:
        #get field setting
        display_field_dict = json.loads(flowactive.display_field)
        for key in display_field_dict:
            if '-' in key:
                key = 'group'
            if key == 'create_user_id' or key == 'create_user':
                key = 'create_user_id__nick_name'
            elif key == 'update_user_id' or key == 'update_user':
                key = 'update_user_id__nick_name'
            display_field_list.append(key)
        search_field_list = display_field_list.copy()
        #暫時先使用display_field當作search_field
        field_list = list(
            map(lambda search_field: search_field + '__icontains',
                search_field_list))

        #sp conditions
        search_conditions = [{
            'column': 'history',
            'condition': '=',
            'value': False
        }]
        exclude_conditions = []
        for con in condition:
            if con['condition'] == '!=':
                con['condition'] = '='
                exclude_conditions.append(con)
            elif con['condition'] == 'exclude':
                con['condition'] = 'contains'
                exclude_conditions.append(con)
            else:
                search_conditions.append(con)

        sc = searchConditionBuilder(search_conditions)
        ec = searchConditionBuilder(exclude_conditions)
        #get model
        omdata_model = getModel('omformmodel', 'Omdata_' + flow_uuid)
        if ec:
            query = omdata_model.objects.filter(
                reduce(operator.and_,
                       sc)).exclude(reduce(operator.and_,
                                           ec)).values(*display_field_list)
        else:
            query = omdata_model.objects.filter(reduce(
                operator.and_, sc)).values(*display_field_list)

        result = DatatableBuilder(request, query, field_list)

        #轉換字與值
        result['data'] = datatableValueToText(result['data'], flow_uuid)

        #載入語言包
        language = get_language()
        result['data'] = Translator('datatable_single_app', 'active', language,
                                    flowactive.flow_app_id,
                                    None).Do(result['data'])

        info(request, '%s list OmData success.' % request.user.username)
        return JsonResponse(result)
    else:
        info('%s has no permission.' % request.user.username, request)
        return ResponseAjax(statusEnum.no_permission,
                            _('您沒有權限進行此操作。')).returnJSON()
Esempio n. 19
0
def exportTranslationAjax(request):
    '''
    export workspace application language package
    '''
    #function variable
    require_field = ['language']
    #get postdata
    postdata = getPostdata(request)
    language_type = postdata.get('language', '')
    #server side rule check
    checker = DataChecker(postdata, require_field)
    if checker.get('status') == 'success':
        export = ''
        export_list = []
        if OmServiceDesign.objects.all().count() > 0:
            max = OmServiceDesign.objects.all().aggregate(
                Max('id')).get('id__max')
            result = list(
                OmServiceDesign.objects.filter(id=max).values('content'))

            box_object = json.loads(result[0]["content"])

            #翻譯語言
            #language_type = get_language()
            lan_package = FlowActiveGlobalObject.getSysLanDict('service').get(
                language_type, {})

            #翻譯「全部」
            #export = check2addExport('全部',export,export_list,lan_package,language_type)
            for idx in box_object["list"]:
                this_service = box_object["list"][idx]
                #翻譯「服務名稱」
                export = check2addExport(this_service["setting"]["setTitle"],
                                         export, export_list, lan_package,
                                         language_type)

                if this_service["type"] == "service":
                    #翻譯「服務說明」
                    export = check2addExport(this_service["setting"]["setTip"],
                                             export, export_list, lan_package,
                                             language_type)
                    for sup_idx in this_service["service"]["list"]:
                        this_step = this_service["service"]["list"][sup_idx]
                        #翻譯「服務步驟名稱」
                        export = check2addExport(this_step["name"], export,
                                                 export_list, lan_package,
                                                 language_type)
                        #翻譯「服務步驟說明」
                        export = check2addExport(this_step["tip"], export,
                                                 export_list, lan_package,
                                                 language_type)

        info('%s export language package success.' % request.user.username,
             request)
        return ResponseAjax(statusEnum.success, _('匯出成功。'),
                            export).returnJSON()
    else:
        info(
            '%s missing some require variable or the variable type error.' %
            request.user.username, request)
        return ResponseAjax(statusEnum.not_found, checker.get('message', ''),
                            checker).returnJSON()
Esempio n. 20
0
def doPreProcessing():
    '''
    server建立schedule檢查node回報狀態
    node建立schedule向server回報狀態
    '''
    try:
        from omflow.syscom.common import License
        version_type = License().getVersionType()
        if version_type != 'C':
            if settings.OMFLOW_TYPE == 'server':
                method_name = 'checkNodeStatus'
            elif settings.OMFLOW_TYPE == 'collector':
                method_name = 'registerToServer'
            from omflow.models import Scheduler
            input_param = {
                'module_name': 'ommonitor.views',
                'method_name': method_name,
                'param': None
            }
            input_param_str = json.dumps(input_param)
            sch = Scheduler.objects.filter(
                input_param=input_param_str).exists()
            if not sch:
                from omflow.syscom.schedule_monitor import schedule_Execute
                exec_time = datetime.now()
                every = '3'
                cycle = 'Minutely'
                cycle_date = '[]'
                exec_fun = {
                    'module_name': 'omflow.syscom.schedule_monitor',
                    'method_name': 'put_flow_job'
                }
                exec_fun_str = json.dumps(exec_fun)
                scheduler = Scheduler.objects.create(
                    exec_time=exec_time,
                    every=every,
                    cycle=cycle,
                    cycle_date=cycle_date,
                    exec_fun=exec_fun_str,
                    input_param=input_param_str,
                    flowactive_id=None)
                schedule_Execute(scheduler)
            #SLA
            if settings.OMFLOW_TYPE == 'server':
                method_name = 'checkSLAData'
                input_param = {
                    'module_name': 'omformflow.views',
                    'method_name': method_name,
                    'param': None
                }
                input_param_str = json.dumps(input_param)
                sch = Scheduler.objects.filter(
                    input_param=input_param_str).exists()
                if not sch:
                    from omflow.syscom.schedule_monitor import schedule_Execute
                    exec_time = datetime.now()
                    every = '1'
                    cycle = 'Minutely'
                    cycle_date = '[]'
                    exec_fun = {
                        'module_name': 'omflow.syscom.schedule_monitor',
                        'method_name': 'put_flow_job'
                    }
                    exec_fun_str = json.dumps(exec_fun)
                    scheduler = Scheduler.objects.create(
                        exec_time=exec_time,
                        every=every,
                        cycle=cycle,
                        cycle_date=cycle_date,
                        exec_fun=exec_fun_str,
                        input_param=input_param_str,
                        flowactive_id=None)
                    schedule_Execute(scheduler)
            #檢查是否有更新暫存檔
            temp_path = os.path.join(settings.BASE_DIR, "tmp.py")
            if os.path.isfile(temp_path):
                from omflow.global_obj import FlowActiveGlobalObject
                with open(temp_path, 'r', encoding='UTF-8') as f:
                    temp_file = f.read()
                    exec(temp_file)
                os.remove(temp_path)
                FlowActiveGlobalObject.ServerStart()
    except:
        pass
Esempio n. 21
0
    def ready(self):
        import sys
        if (not 'makemigrations' in sys.argv) and (not 'migrate' in sys.argv):
            #set sidebar design to global object
            from omflow.global_obj import GlobalObject, FlowActiveGlobalObject
            from omflow.syscom.q_monitor import FormFlowMonitor, LoadBalanceMonitor
            from omflow.models import SystemSetting, QueueData
            from omflow.syscom.schedule_monitor import scheduleThread
            import threading

            starttime = str(datetime.now())
            GlobalObject.__statusObj__['server_start_time'] = datetime.now()
            #開發環境runserver的主線程功能只會監控子線程運作,以子線程為主要運行,子線程環境變數為True。
            if (os.environ.get('RUN_MAIN') == 'true'
                ) or "mod_wsgi" in sys.argv or "--noreload" in sys.argv:
                t1 = threading.Thread(target=FormFlowMonitor.setRunning)
                t1.start()
                t2 = threading.Thread(target=scheduleThread)
                t2.start()

            #確認是否為第一次啟動server
            systemsetting = SystemSetting.objects.all()
            if systemsetting:
                FlowActiveGlobalObject.ServerStart()
                if (os.environ.get('RUN_MAIN') == 'true'
                    ) or "mod_wsgi" in sys.argv or "--noreload" in sys.argv:
                    #將未完成的單放入form flow monitor
                    q_l = list(QueueData.objects.all().values(
                        'module_name', 'method_name', 'input_param'))
                    for q in q_l:
                        FormFlowMonitor.putQueue(q['module_name'],
                                                 q['method_name'],
                                                 json.loads(q['input_param']))
                    from omflow.syscom.common import check_app
                    if settings.OMFLOW_TYPE == 'collector' and check_app(
                            'ommonitor'):
                        from ommonitor.models import LoadBalanceQueueData
                        #將未完成的python放入load balance monitor
                        q_l = list(LoadBalanceQueueData.objects.all().values(
                            'module_name', 'method_name', 'input_param'))
                        for q in q_l:
                            LoadBalanceMonitor.putQueue(
                                q['module_name'], q['method_name'],
                                json.loads(q['input_param']))
                sidebar_design_str = SystemSetting.objects.get(
                    name='sidebar_design').value
                sidebar_design = json.loads(sidebar_design_str)
                GlobalObject.__sidebarDesignObj__[
                    'sidebar_design'] = sidebar_design
                GlobalObject.__sidebarDesignObj__[
                    'design_updatetime'] = starttime
                GlobalObject.__sidebarDesignObj__[
                    'permission_updatetime'] = starttime
                #ThreadPoolExecutor max workers
                POOL_MAX_WORKER = int(
                    SystemSetting.objects.get(name='pool_max_worker').value)
                ldap_str = SystemSetting.objects.get(name='ldap_config').value
                ldap_json = json.loads(ldap_str)
            else:
                #create system user when first time run server
                from omuser.models import OmUser
                import uuid
                sysuser = OmUser.objects.create_user(username='******',
                                                     nick_name='system',
                                                     password=uuid.uuid4().hex,
                                                     email='*****@*****.**',
                                                     is_superuser=True)
                #create sidebar design when first time run server
                app_list = settings.INSTALLED_APPS
                sidebar_design = []
                #check which app has been installed
                if 'omformflow' in app_list:
                    mymission = {
                        "id": "mymission",
                        "name": "我的任務",
                        "p_id": "",
                        "flow_uuid": "default",
                        "icon": "commenting"
                    }
                    service = {
                        "id": "service",
                        "name": "服務請求",
                        "p_id": "",
                        "flow_uuid": "default",
                        "icon": "shopping-cart"
                    }
                    customflow = {
                        "id": "custom_1",
                        "name": "Apps",
                        "p_id": "",
                        "flow_uuid": "custom",
                        "icon": "folder"
                    }
                    servermanage = {
                        "id": "servermanage",
                        "name": "資料收集",
                        "p_id": "",
                        "flow_uuid": "default",
                        "icon": "server"
                    }
                    flowmgmt = {
                        "id": "flowmgmt",
                        "name": "應用管理",
                        "p_id": "",
                        "flow_uuid": "default",
                        "icon": "cubes"
                    }
                    sidebar_design.append(mymission)
                    sidebar_design.append(service)
                    sidebar_design.append(servermanage)
                    sidebar_design.append(flowmgmt)
                    sidebar_design.append(customflow)
                staffmgmt = {
                    "id": "staffmgmt",
                    "name": "人員管理",
                    "p_id": "",
                    "flow_uuid": "default",
                    "icon": "user"
                }
                syssetting = {
                    "id": "syssetting",
                    "name": "系統設定",
                    "p_id": "",
                    "flow_uuid": "default",
                    "icon": "gear"
                }
                sidebar_design.append(staffmgmt)
                sidebar_design.append(syssetting)
                sidebar_design_str = json.dumps(sidebar_design)
                SystemSetting.objects.create(
                    name='sidebar_design',
                    description='side bar design json',
                    value=sidebar_design_str)
                GlobalObject.__sidebarDesignObj__[
                    'sidebar_design'] = sidebar_design
                GlobalObject.__sidebarDesignObj__[
                    'design_updatetime'] = starttime
                GlobalObject.__sidebarDesignObj__[
                    'permission_updatetime'] = starttime
                #ThreadPoolExecutor max workers
                POOL_MAX_WORKER = 10
                SystemSetting.objects.create(
                    name='pool_max_worker',
                    description='formflow thread pool max worker',
                    value=POOL_MAX_WORKER)
                #ldap config
                ldpadata_json = {
                    'ldap_client_server': '',
                    'ldap_client_server_port': '',
                    'ldap_base_dn': '',
                    'ldap_bind_user': '',
                    'ldap_bind_user_password': '',
                    'ldap_client_domain': ''
                }
                ldpadata_str = json.dumps(ldpadata_json)
                SystemSetting.objects.create(
                    name='ldap_config',
                    description='ldap connect setting',
                    value=ldpadata_str)
                #使用條款
                SystemSetting.objects.create(
                    name='PI_agree',
                    description='personal_information_agree',
                    value=personal_information_agree)
                SystemSetting.objects.create(name='SU_agree',
                                             description='software_use_agree',
                                             value=software_use_agree)
                #node default group
                from ommonitor.models import CollectorGroup
                CollectorGroup.objects.create(name='未分類')
                CollectorGroup.objects.create(name='分散處理')
                #首次啟動匯入default流程
                firstrunImport(sysuser)
            #server, node啟動的事前準備
            if (os.environ.get('RUN_MAIN') == 'true'
                ) or "mod_wsgi" in sys.argv or "--noreload" in sys.argv:
                doPreProcessing()
            #設定global
            from omformflow.models import OmParameter
            op = list(
                OmParameter.objects.filter(group_id=None).values(
                    'name', 'value'))
            for i in op:
                GlobalObject.__OmParameter__[i['name']] = i['value']
            ldap_json = {}
            GlobalObject.__ldapObj__['ldap_client_server'] = ldap_json.get(
                'ldap_client_server', '')
            GlobalObject.__ldapObj__[
                'ldap_client_server_port'] = ldap_json.get(
                    'ldap_client_server_port', '')
            GlobalObject.__ldapObj__['ldap_client_domain'] = ldap_json.get(
                'ldap_client_domain', '')
Esempio n. 22
0
def listMyMissionAjax(request):
    '''
    list my missions.
    input: request
    return: json
    author: Kolin Hsu
    '''
    #get post data
    postdata = getPostdata(request)
    omflow_restapi = postdata.get('omflow_restapi', '')
    if not omflow_restapi:
        ticket_createtime = postdata.get('ticket_createtime', '')
        ticket_createtime = ticket_createtime.split(',')
        field_list = [
            'title__icontains', 'flow_name__icontains', 'status__icontains',
            'create_user_id__nick_name__icontains'
        ]
        display_field = [
            'flow_name', 'flow_uuid', 'level', 'status', 'title',
            'create_user_id__nick_name', 'assign_group_id__display_name',
            'assignee_id__nick_name', 'ticket_createtime', 'data_id',
            'data_no', 'action', 'attachment'
        ]
        group_id_list = list(request.user.groups.all().values_list('id',
                                                                   flat=True))
        query = Missions.objects.filter(
            (Q(assignee_id=request.user.id)
             | (Q(assign_group_id__in=group_id_list) & Q(assignee_id=None)))
            & Q(history=False) & Q(ticket_createtime__range=ticket_createtime)
            & Q(is_active=True) & Q(deploy_flag=True)).values(*display_field)
        result = DatatableBuilder(request, query, field_list)

        #載入語言包
        language = get_language()
        data = result['data']
        if isinstance(data, str):
            pass
        elif isinstance(data, list) or isinstance(data, dict):
            for key_or_line in data:
                if isinstance(data, list):
                    line = key_or_line
                else:
                    line = data[key_or_line]
                fa = FlowActiveGlobalObject.UUIDSearch(line['flow_uuid'])
                if fa:
                    app_id = fa.flow_app_id
                    for key in line:
                        if key in ['flow_name', 'level', 'status']:
                            line[key] = Translator('single_app', 'active',
                                                   language, app_id,
                                                   None).Do(line[key])
                        elif key == 'action':
                            action = line[key]
                            if action:
                                action1 = action.split(',')[0]
                                action2 = action.split(',')[1]
                                trans_a1 = Translator('single_app', 'active',
                                                      language, app_id,
                                                      None).Do(action1)
                                trans_a2 = Translator('single_app', 'active',
                                                      language, app_id,
                                                      None).Do(action2)
                                line[key] = trans_a1 + ',' + trans_a2


#         result['data'] = Translator('datatable_multi_app', 'active', language, None, None).Do(result['data'])

        info('%s list Mission success.' % request.user.username, request)
        return JsonResponse(result)
    else:
        #api使用
        group_id_list = list(request.user.groups.all().values_list('id',
                                                                   flat=True))
        query = Missions.objects.filter((Q(assignee_id=request.user.id) | (
            Q(assign_group_id__in=group_id_list) & Q(assignee_id=None)))
                                        & Q(history=False) & Q(is_active=True)
                                        & Q(deploy_flag=True))
        result = listQueryBuilder(None, postdata, query)
        if result['status']:
            info('%s list Mission success.' % request.user.username, request)
            return ResponseAjax(statusEnum.success, result['message'],
                                result['result']).returnJSON()
        else:
            info('%s list Mission error.' % request.user.username, request)
            return ResponseAjax(statusEnum.not_found,
                                result['message']).returnJSON()