Esempio n. 1
0
 def evalKey(fieldname, **params):
     if fieldname in FezAlarmFaxChecker().fields:
         _str = FezAlarmFaxChecker().fields[fieldname][0]
     else:  # key not found
         FezAlarmFaxChecker().fields[fieldname] = (u'----', 0)
         raise
     if _str == '':
         FezAlarmFaxChecker().fields[fieldname] = (_str, 0)
         return
     keys = {k.key: k.id for k in Alarmkey.getAlarmkeys()}
     try:
         repl = difflib.get_close_matches(_str.strip(),
                                          keys.keys(),
                                          1,
                                          cutoff=0.8)  # default cutoff 0.6
         if len(repl) == 0:
             repl = difflib.get_close_matches(_str.strip(), keys.keys(),
                                              1)  # try with default cutoff
         if len(repl) > 0:
             k = Alarmkey.getAlarmkeys(int(keys[repl[0]]))
             FezAlarmFaxChecker().fields[fieldname] = (u'{}: {}'.format(
                 k.category, k.key), k.id)
             FezAlarmFaxChecker().logger.debug(
                 u'key: found "{}: {}"'.format(k.category, k.key))
             return
         FezAlarmFaxChecker().logger.info(
             u'key: "{}" not found in alarmkeys'.format(_str))
         FezAlarmFaxChecker().fields[fieldname] = (_str, 0)
     except:
         FezAlarmFaxChecker().logger.error(u'key: error in key evaluation')
     finally:
         return
Esempio n. 2
0
 def evalKey(fieldname, **params):
     if fieldname in FezAlarmFaxChecker().fields:
         _str = FezAlarmFaxChecker().fields[fieldname][0]
     else:  # key not found
         FezAlarmFaxChecker().fields[fieldname] = (u'----', 0)
         raise
     if _str == '':
         FezAlarmFaxChecker().fields[fieldname] = (_str, 0)
         return
     keys = {k.key: k.id for k in Alarmkey.getAlarmkeys()}
     try:
         repl = difflib.get_close_matches(_str.strip(), keys.keys(), 1, cutoff=0.8)  # default cutoff 0.6
         if len(repl) == 0:
             repl = difflib.get_close_matches(_str.strip(), keys.keys(), 1)  # try with default cutoff
         if len(repl) > 0:
             k = Alarmkey.getAlarmkeys(int(keys[repl[0]]))
             FezAlarmFaxChecker().fields[fieldname] = (u'{}: {}'.format(k.category, k.key), k.id)
             FezAlarmFaxChecker().logger.debug(u'key: found "{}: {}"'.format(k.category, k.key))
             return
         FezAlarmFaxChecker().logger.info(u'key: "{}" not found in alarmkeys'.format(_str))
         FezAlarmFaxChecker().fields[fieldname] = (_str, 0)
     except:
         FezAlarmFaxChecker().logger.error(u'key: error in key evaluation')
     finally:
         return
Esempio n. 3
0
    def evalKey(field, **params):
        if field.value[0] == '':
            return

        keys = {k.key: k.id for k in Alarmkey.getAlarmkeys()}
        try:
            repl = difflib.get_close_matches(field.value[0].strip(),
                                             keys.keys(),
                                             1,
                                             cutoff=0.8)  # default cutoff 0.6
            if len(repl) == 0:
                repl = difflib.get_close_matches(field.value[0].strip(),
                                                 keys.keys(),
                                                 1)  # try with default cutoff
            if len(repl) > 0:
                k = Alarmkey.getAlarmkeys(int(keys[repl[0]]))
                field.value = (u'{}: {}'.format(k.category, k.key), k.id)
                GenericAlarmFaxChecker().fields[field.key] = field.value
                GenericAlarmFaxChecker().logger.debug(
                    u'key: found "{}: {}"'.format(k.category, k.key))
                return
            GenericAlarmFaxChecker().logger.info(
                u'key: "{}" not found in alarmkeys'.format(field.value[0]))
        except:
            GenericAlarmFaxChecker().logger.error(
                u'key: error in key evaluation')
        finally:
            return
def buildDownloadFile(department, dtype=0):
    """
    Create XLSX file with definition of given department and store file in tmp directory with filename *aao.xlsx*

    :param department: department object
    :param dtype: 0|1: add default definition if no material definition found for keyword
    :return: filename of created file, on error ''
    """
    alarmkeys = Alarmkey.getAlarmkeys()
    
    header = ['dbid', 'category', 'key', 'key internal']
    _maxcars1 = 1
    _maxcars2 = 1
    _maxmaterial = 1

    counted_keys = AlarmkeyCars.query.from_statement("select kid, dept, (LENGTH(cars1)-LENGTH(REPLACE(cars1, ';', '')))as cars1, (LENGTH(cars2)-LENGTH(REPLACE(cars2, ';', ''))) as cars2, (LENGTH(material)-LENGTH(REPLACE(material, ';', ''))) as material from alarmkeycars where dept='1';")
    
    for c_k in counted_keys:
        if _maxcars1 < c_k._cars1: _maxcars1 = c_k._cars1
        if _maxcars2 < c_k._cars2: _maxcars2 = c_k._cars2
        if _maxmaterial < c_k._material: _maxmaterial = c_k._material
        
    header += ['p_%s' % i for i in range(0, _maxcars1 + 1)]
    header += ['s_%s' % i for i in range(0, _maxcars2 + 1)]
    header += ['m_%s' % i for i in range(0, _maxmaterial + 1)]
    header += ['remark']
        
    # Create an new Excel file and add a worksheet.
    workbook = xlsxwriter.Workbook('%s/aao.xlsx' % current_app.config.get('PATH_TMP'))
    worksheet = workbook.add_worksheet('aao')
    bold = workbook.add_format({'bold': 1})

    worksheet.write_row(0, 0, header, bold)

    _w = 0
    for alarmkey in alarmkeys:
        if dtype == '1' and not alarmkey.hasDefinition(department):
            continue
        _w += 1
        data = [alarmkey.id, alarmkey.category, alarmkey.key, alarmkey.key_internal]
        _c1 = alarmkey.getCars1(department)
        data += [c1.name for c1 in _c1]
        data += ['' for i in range(0, _maxcars1 - len(_c1) + 1)]
        _c2 = alarmkey.getCars2(department)
        data += [c2.name for c2 in _c2]
        data += ['' for i in range(0, _maxcars2 - len(_c2) + 1)]
        _c3 = alarmkey.getMaterial(department)
        data += [c3.name for c3 in _c3]
        data += ['' for i in range(0, _maxmaterial - len(_c3) + 1)]
        data += [alarmkey.remark]
        
        worksheet.write_row(list(alarmkeys).index(alarmkey) + 1, 0, data)

    workbook.close()
    
    if _w == 0:  # no data written
        return ''
    else:
        return 'aao.xlsx'
Esempio n. 5
0
def getFrontendData(self, params={}):
    """
    Deliver frontend content of module alarmkeys

    :param params: given parameters of current request
    :return: data of alarmkeys
    """
    if request.args.get(u'action') == u'keyslookup':
        keys = {}

        for k in Alarmkey.getAlarmkeys():
            keys[u"{}".format(k.id)] = u'{}: {}'.format(k.category, k.key)
        return keys

    elif request.args.get(u'action') == u'categorylookup':
        key = Alarmkey.getAlarmkeys(id=request.args.get(u'keyid'))
        return {u'id': key.id, u'category': key.category}

    elif request.args.get(u'action') == u'carslookup':
        ret = {u'cars1': [], u'cars2': [], u'material': []}
        try:
            city = City.getCities(id=request.args.get(u'cityid'))
        except ValueError:
            city = None
        key = Alarmkey.getAlarmkeys(id=request.args.get(u'keyid'))
        if request.args.get(
                u'objectid') != u'0':  # use alarmobject and test for aao
            aobject = AlarmObject.getAlarmObjects(
                id=request.args.get(u'objectid'))
            if aobject.hasOwnAAO():
                return {
                    u'cars1': [c.id for c in aobject.getCars1()],
                    u'cars2': [c.id for c in aobject.getCars2()],
                    u'material': [m.id for m in aobject.getMaterial()]
                }
        if key and city:
            ret = {
                u'cars1': [c.id for c in key.getCars1(city.dept)],
                u'cars2': [c.id for c in key.getCars2(city.dept)],
                u'material': [m.id for m in key.getMaterial(city.dept)]
            }
        return ret

    return u""
Esempio n. 6
0
    def evalKey(field, **params):
        if field.value[0] == '':
            return

        keys = {k.key: k.id for k in Alarmkey.getAlarmkeys()}
        try:
            repl = difflib.get_close_matches(field.value[0].strip(), keys.keys(), 1, cutoff=0.8)  # default cutoff 0.6
            if len(repl) == 0:
                repl = difflib.get_close_matches(field.value[0].strip(), keys.keys(), 1)  # try with default cutoff
            if len(repl) > 0:
                k = Alarmkey.getAlarmkeys(int(keys[repl[0]]))
                field.value = (u'{}: {}'.format(k.category, k.key), k.id)
                GenericAlarmFaxChecker().fields[field.key] = field.value
                GenericAlarmFaxChecker().logger.debug(u'key: found "{}: {}"'.format(k.category, k.key))
                return
            GenericAlarmFaxChecker().logger.info(u'key: "{}" not found in alarmkeys'.format(field.value[0]))
        except:
            GenericAlarmFaxChecker().logger.error(u'key: error in key evaluation')
        finally:
            return
def getFrontendData(self, params={}):
    """
    Deliver frontend content of module alarmkeys

    :param params: given parameters of current request
    :return: data of alarmkeys
    """
    if request.args.get(u'action') == u'keyslookup':
        keys = {}

        for k in Alarmkey.getAlarmkeys():
            keys[u"{}".format(k.id)] = u'{}: {}'.format(k.category, k.key)
        return keys

    elif request.args.get(u'action') == u'categorylookup':
        key = Alarmkey.getAlarmkeys(id=request.args.get(u'keyid'))
        return {u'id': key.id, u'category': key.category}

    elif request.args.get(u'action') == u'carslookup':
        ret = {u'cars1': [], u'cars2': [], u'material': []}
        try:
            city = City.getCities(id=request.args.get(u'cityid'))
        except ValueError:
            city = None
        key = Alarmkey.getAlarmkeys(id=request.args.get(u'keyid'))
        if request.args.get(u'objectid') != u'0':  # use alarmobject and test for aao
            aobject = AlarmObject.getAlarmObjects(id=request.args.get(u'objectid'))
            if aobject.hasOwnAAO():
                return {u'cars1': [c.id for c in aobject.getCars1()], u'cars2': [c.id for c in aobject.getCars2()],
                        u'material': [m.id for m in aobject.getMaterial()]}
        if key and city:
            ret = {u'cars1': [c.id for c in key.getCars1(city.dept)], u'cars2': [c.id for c in key.getCars2(city.dept)],
                   u'material': [m.id for m in key.getMaterial(city.dept)]}
        return ret

    return u""
Esempio n. 8
0
def getAdminData(self):
    """
    Deliver admin content of module alarmkeys (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'loaddetails':  # details for given key
        return render_template('admin.alarmkeys.detail.html',
                               keys=Alarmkey.getAlarmkeysByCategoryId(
                                   request.args.get('category'),
                                   keysetid=int(request.args.get(
                                       'keysetid', 0))),
                               department=request.args.get('department'))

    elif request.args.get(
            'action', '') == "changekeyset":  # deliver alarmkeys for given set
        ak = Alarmkey
        if request.args.get('keysetid', '0') == '0':
            counted_keys = db.get(ak.category.label('category'),
                                  func.count(ak.key).label('key'),
                                  ak.id.label('id'),
                                  func.count(
                                      ak.id).label('keysetcount')).group_by(
                                          ak.category).filter_by(_keyset=None)
        else:
            counted_keys = db.get(
                ak.category.label('category'),
                func.count(ak.key).label('key'), ak.id.label('id'),
                func.count(ak.id).label('keysetcount')).group_by(
                    ak.category).filter_by(
                        _keyset=request.args.get('keysetid'))
        _sum = 0
        alarmkeys_count = []
        for r in counted_keys.all():
            alarmkeys_count.append([r.category, r.key, r.id])
            _sum += int(r.key)
        return render_template('admin.alarmkeys.macro.html',
                               alarmkeys_count=alarmkeys_count,
                               depid=request.args.get('department'),
                               sum=_sum)

    elif request.args.get('action') == 'upload':
        if request.files:
            uploadfile = request.files['uploadfile']
            fname = os.path.join(current_app.config.get('PATH_TMP'),
                                 werkzeug.secure_filename(uploadfile.filename))
            uploadfile.save(fname)
            uploadfiles[uploadfile.filename] = XLSFile(fname)

            return render_template(
                'admin.alarmkeys.upload2.html',
                sheets=uploadfiles[uploadfile.filename].getSheets())

    elif request.args.get('action') == 'upload_sheet':  # sheet selector
        definitionfile = uploadfiles[request.args.get('filename')]
        return render_template('admin.alarmkeys.upload3.html',
                               cols=definitionfile.getCols(
                                   request.args.get('sheetname')))

    elif request.args.get('action') == 'testimport':  # build data for preview
        col_definition = {
            'dept': request.args.get('department'),
            'sheet': request.args.get('sheetname'),
            'category': request.form.get('category'),
            'key': request.form.get('key'),
            'keyinternal': request.form.get('keyinternal'),
            'remark': request.form.get('remark'),
            'cars1': request.form.getlist('cars1'),
            'cars2': request.form.getlist('cars2'),
            'material': request.form.getlist('material')
        }

        deffile = uploadfiles[request.args.get('filename')]
        return render_template('admin.alarmkeys.uploadpreview.html',
                               vals=deffile.getValues(col_definition),
                               keysets=AlarmkeySet.getAlarmkeySets())

    elif request.args.get(
            'action') == 'doimport':  # do import and store values
        coldefinition = {
            'dept': request.args.get('department'),
            'sheet': request.args.get('sheetname'),
            'category': request.form.get('category'),
            'key': request.form.get('key'),
            'keyinternal': request.form.get('keyinternal'),
            'remark': request.form.get('remark'),
            'cars1': request.form.getlist('cars1'),
            'cars2': request.form.getlist('cars2'),
            'material': request.form.getlist('material')
        }
        deffile = uploadfiles[request.args.get('filename')]

        vals = deffile.getValues(coldefinition)
        states = []

        if request.form.get('add_material'):  # add new material
            p = re.compile(r'<.*?>')
            for k in vals['carsnotfound']:
                n_car = vals['carsnotfound'][k]
                n_car.name = p.sub('', n_car.name)
                if n_car.name == '':
                    continue
                db.session.add(n_car)
            db.session.flush()

        if request.form.get('add_new'):  # add new keys ( item state=-1)
            states.append('-1')

        if request.form.get(
                'add_update'):  # update existing keys (item state=1)
            states.append('1')

        if request.form.get('add_assign') and request.form.get(
                'keyset', '') != '':  # assign keys to keyset (item state=2)
            keyset = AlarmkeySet.getAlarmkeySets(request.form.get('keyset'))
            states.append('2')

        for key in vals['keys']:  # item list
            if key['state'] in states:  # import only with correct state

                if key['state'] == '-1':  # add key
                    k = Alarmkey(key['category'], key['key'],
                                 key['keyinternal'], key['remark'])
                    db.session.add(k)
                    db.session.flush()
                    k.setCars(coldefinition['dept'],
                              cars1=";".join([str(c.id)
                                              for c in key['cars1']]),
                              cars2=";".join([str(c.id)
                                              for c in key['cars2']]),
                              materials=";".join(
                                  [str(c.id) for c in key['material']]))
                    db.session.commit()
                    key['state'] = '0'

                elif key['state'] == '1':  # update key
                    k = Alarmkey.getAlarmkeys(id=int(key['dbid']))
                    k.category = key['category']
                    k.key = key['key']
                    k.key_internal = key['keyinternal']
                    k.remark = key['remark']
                    k.setCars(coldefinition['dept'],
                              cars1=';'.join(filter(None, key['cars1_ids'])),
                              cars2=';'.join(filter(None, key['cars2_ids'])),
                              materials=';'.join(
                                  filter(None, key['material_ids'])))
                    db.session.commit()

                if '2' in states:  # assign keys to keyset
                    item = filter(
                        lambda x: x.get('stichwort') == k.category and x.get(
                            'schlagwort') == k.key, keyset.alarmkeys)
                    k._keyset = keyset.id
                    if len(item) > 0:
                        k.keysetitem = item[0].get('nr')

        db.session.commit()
        return ""

    elif request.args.get('action') == 'download':
        # build exportfile
        filename = buildDownloadFile(request.args.get('department'),
                                     request.args.get('options'))
        if filename != "":
            return filename

    elif request.args.get('action') == 'keyslookup':
        keys = {}

        for k in Alarmkey.getAlarmkeys(keysetid=request.args.get('keysetid')):
            keys[str(k.id)] = '%s: %s' % (k.category, k.key)
        return keys

    elif request.args.get('action') == 'categorylookup':
        key = Alarmkey.getAlarmkeys(id=int(request.args.get('keyid')))
        return {'id': key.id, 'category': key.category}

    elif request.args.get('action', '') == 'keysetlookup':
        try:
            return AlarmkeySet.getAlarmkeySets(
                request.args.get('setid')).alarmkeys
        except ValueError:  # no base given
            return []

    elif request.args.get('action', '') == 'uploaddefinition':
        if request.files:
            ufile = request.files['uploadfile']
            if not os.path.exists("{}alarmkeysetbase/".format(
                    current_app.config.get('PATH_DATA'))):
                os.makedirs("{}alarmkeysetbase/".format(
                    current_app.config.get('PATH_DATA')))
            fname = os.path.join(
                "{}alarmkeysetbase/".format(
                    current_app.config.get('PATH_DATA')), ufile.filename)
            ufile.save(fname)
            with codecs.open(fname, 'r', encoding='utf-8') as fin:
                aksetbase = AlarmkeySetBase(ufile.filename, json.load(fin),
                                            'external')
                return jsonify(state="ok",
                               name=aksetbase.name,
                               startdate=datetime.datetime.strftime(
                                   aksetbase.start, "%d.%m.%Y"),
                               items=len(aksetbase.items),
                               filename=aksetbase.id,
                               type=aksetbase.settype)

        return jsonify(state="error")

    elif request.args.get('action', '') == 'createbaseset':
        """
        create base keys for given set and return number of updated
        """
        stats = AlarmkeySet.getAlarmkeySets(
            id=request.args.get('setid')).createBaseKeys()
        return babel.gettext('alarmkeys.createbaseset.result',
                             num_success=stats[0],
                             num_error=stats[1])

    if "/download/" in request.url:  # deliver file
        filename = os.path.basename(request.url)
        mime = "application/x.download"
        if filename.endswith('.xlsx'):
            mime = "application/vnd.ms-excel"
        return send_from_directory("%s/" % current_app.config.get('PATH_TMP'),
                                   filename,
                                   as_attachment=True,
                                   mimetype=mime)
    return ""
Esempio n. 9
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmkeys

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')

    if len(module) < 2:
        module.append(u'1')

    if len(module) > 2 and module[2] == 'upload':  # upload alarmkeys
        params.update({'': int(module[1]), 'department': module[1]})
        return render_template('admin.alarmkeys.upload.html', **params)

    else:
        depid = 1
        try:
            if module[1].isnumeric():
                depid = int(module[1])
        except:
            pass

        if request.method == 'POST':
            if depid == 0:
                if request.form.get('action',
                                    '') == 'createset':  # add alarmkeyset
                    params.update({
                        'alarmkeyset':
                        AlarmkeySet('', '', datetime.date.today(),
                                    datetime.date.today(), ''),
                        'setbases':
                        AlarmkeySet.getBases(),
                        'orphankeys':
                        Alarmkey.getOrphanKeys()
                    })
                    return render_template('admin.alarmkeys.set_actions.html',
                                           **params)

                elif request.form.get('action', '').startswith('deleteset_'):
                    db.session.delete(
                        AlarmkeySet.getAlarmkeySets(
                            request.form.get('action', '').split('_')[-1]))
                    db.session.commit()

                elif request.form.get(
                        'action',
                        '').startswith('detailset_'):  # edit alarmkeyset
                    params.update({
                        'alarmkeyset':
                        AlarmkeySet.getAlarmkeySets(
                            request.form.get('action').split('_')[-1]),
                        'setbases':
                        AlarmkeySet.getBases(),
                        'orphankeys':
                        Alarmkey.getOrphanKeys()
                    })
                    return render_template('admin.alarmkeys.set_actions.html',
                                           **params)

                elif request.form.get(
                        'action', '') == 'savealarmkeyset':  # save alarmkeyset
                    if request.form.get('set_id', '') == 'None':  # add
                        akset = AlarmkeySet('', '', datetime.date.today(),
                                            datetime.date.today(), '')
                        db.session.add(akset)
                    else:
                        akset = AlarmkeySet.getAlarmkeySets(
                            request.form.get('set_id'))
                    akset.name = request.form.get('set_name')
                    if request.form.get('set_startdate', '') != "":
                        akset.startdate = datetime.datetime.strptime(
                            request.form.get('set_startdate'), '%d.%m.%Y')
                    else:
                        akset.startdate = None
                    if request.form.get('set_enddate', '') != "":
                        akset.enddate = datetime.datetime.strptime(
                            request.form.get('set_enddate'), '%d.%m.%Y')
                    else:
                        akset.enddate = None
                    akset.remark = request.form.get('set_remark')
                    akset.base = request.form.get('set_base')
                    db.session.commit()
                    if 'set_assignorphan' in request.form.keys(
                    ):  # add all orphan keys to current set
                        for key in Alarmkey.getOrphanKeys():
                            key._keyset = int(akset.id)
                        db.session.commit()

                elif request.form.get('action', '').startswith('deletebase_'):
                    if os.path.exists("{}alarmkeysetbase/{}".format(
                            current_app.config.get('PATH_DATA'), "_".join(
                                request.form.get('action',
                                                 '').split('_')[1:]))):
                        os.remove("{}alarmkeysetbase/{}".format(
                            current_app.config.get('PATH_DATA'), "_".join(
                                request.form.get('action',
                                                 '').split('_')[1:])))

                params.update({
                    'aksets': AlarmkeySet.getAlarmkeySets(),
                    'akbases': AlarmkeySet.getBases()
                })
                return render_template('admin.alarmkeys.set_list.html',
                                       **params)

            if request.form.get('action') == 'adddefault':  # add default aao
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': 0
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get(
                    'action') == 'savedefault':  # save default aao
                alarmkeycar = AlarmkeyCars.getAlarmkeyCars(
                    kid=9999, dept=request.form.get(
                        'deptid'))  # 9999 = default department
                if not alarmkeycar:  # add
                    alarmkeycar = AlarmkeyCars(9999,
                                               request.form.get('deptid'), '',
                                               '', '')
                    db.session.add(alarmkeycar)

                alarmkeycar.cars1 = request.form.get('cars1')
                alarmkeycar.cars2 = request.form.get('cars2')
                alarmkeycar.materials = request.form.get('material')
                if alarmkeycar.kid != 9999 and request.form.get(
                        'cars1') == request.form.get(
                            'cars2') == request.form.get(
                                'material') == '':  # remove
                    db.session.delete(alarmkeycar)
                db.session.commit()

            elif request.form.get(
                    'action') == 'editdefault':  # edit default aao
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'aksets': AlarmkeySet.getAlarmkeySets(),
                    'cars': Car.getCars(),
                    'type': -1
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get('action') == 'addkey':  # add key
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'aksets': AlarmkeySet.getAlarmkeySets(),
                    'cars': Car.getCars(),
                    'type': -2
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get('action') == 'savekey':  # save key
                if request.form.get('keyid') == 'None':  # add new
                    alarmkey = Alarmkey('', '', '', '')
                    db.session.add(alarmkey)
                    db.session.commit()

                else:  # update existing
                    alarmkey = Alarmkey.getAlarmkeys(request.form.get('keyid'))

                alarmkey.category = request.form.get('category')
                alarmkey.key = request.form.get('key')
                alarmkey.key_internal = request.form.get('keyinternal')
                alarmkey.remark = request.form.get('remark')
                if request.form.get('keyset', '') == '':
                    alarmkey._keyset = None
                else:
                    alarmkey._keyset = request.form.get('keyset')
                alarmkey.setCars(int(request.form.get('deptid')),
                                 cars1=request.form.get('cars1'),
                                 cars2=request.form.get('cars2'),
                                 material=request.form.get('material'))

                alarmkey.keysetitem = None
                if request.form.get('keyset', '') != "":
                    keyset = AlarmkeySet.getAlarmkeySets(
                        request.form.get('keyset'))
                    if keyset:
                        item = filter(
                            lambda x: x.get('stichwort') == alarmkey.category
                            and x.get('schlagwort') == alarmkey.key,
                            keyset.alarmkeys)
                        if len(item) > 0:
                            alarmkey.keysetitem = item[0].get('nr')
                db.session.commit()  # readd

            elif request.form.get('action').startswith(
                    'deletecars_'):  # delete car definition
                _op, _kid, _dept = request.form.get('action').split('_')
                keycar = AlarmkeyCars.getAlarmkeyCars(kid=_kid, dept=_dept)
                if keycar:
                    db.session.delete(keycar)
                    db.session.commit()

                # delete key if no definied cars
                if len(AlarmkeyCars.getAlarmkeyCars(kid=_kid)) == 0:
                    key = Alarmkey.getAlarmkeys(id=_kid)
                    db.session.delete(key)
                db.session.commit()

            elif request.form.get('action').startswith(
                    'editcars_'):  # edit key with cars
                _op, _kid, _dept = request.form.get('action').split('_')
                params.update({
                    'alarmkey': Alarmkey.getAlarmkeys(id=_kid),
                    'depid': _dept,
                    'departments': Department.getDepartments(),
                    'aksets': AlarmkeySet.getAlarmkeySets(),
                    'cars': Car.getCars(),
                    'type': 1
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

        if depid == 0:  # edit options
            params.update({
                'aksets': AlarmkeySet.getAlarmkeySets(),
                'departments': Department.getDepartments(),
                'akbases': AlarmkeySet.getBases()
            })
            return render_template('admin.alarmkeys.set_list.html', **params)

        alarmkeys_count = []
        ak = Alarmkey
        counted_keys = db.get(ak.category.label('category'),
                              func.count(ak.key).label('key'),
                              ak.id.label('id')).group_by(ak.category, ak.id)
        _sum = 0
        for r in counted_keys.all():
            alarmkeys_count.append([r.category, r.key, r.id])
            _sum += int(r.key)

        params.update({
            'depid': depid,
            'defaultcars': Alarmkey.getDefault(depid),
            'aksets': AlarmkeySet.getAlarmkeySets()
        })
        return render_template('admin.alarmkeys.html', **params)
    def getValues(self, coldefinition):
        cars = {}
        notfound = {}
        states = {'-1': 0, '0': 0, '1': 0}
        for c in Car.getCars(deptid=coldefinition['dept']):
            cars[unicode(c.name)] = c

        keys = Alarmkey.getAlarmkeys()
        worksheet = self.book.sheet_by_name(self.book.sheet_names()[int(coldefinition['sheet'])])
        
        def getPosForCol(name):
            ret = -65
            while len(name) > 0:
                ret += ord(name[0])
                name = name[1:]
            return ret
            
        def evalValue(crow, ccol):
            try:
                return worksheet.cell_value(crow, ccol)
            except:
                return ""
        
        importkeys = []
        # state -1:new, 0:no changes, 1:need update
        for row in range(self.headerrow + 1, worksheet.nrows - 1):
            item = {'cars1': [], 'cars2': [], 'material': [], 'cars1_ids': [], 'cars2_ids': [], 'material_ids': [],
                    'dbid': None, 'state': '0', 'category': evalValue(row, getPosForCol(coldefinition['category'])),
                    'key': evalValue(row, getPosForCol(coldefinition['key'])),
                    'keyinternal': evalValue(row, getPosForCol(coldefinition['keyinternal'])),
                    'remark': evalValue(row, getPosForCol(coldefinition['remark']))}

            for field in ['cars1', 'cars2', 'material']:
                for c in coldefinition[field]:
                    cell_val = evalValue(row, getPosForCol(c))
                    if unicode(cell_val) in cars.keys():
                        item[field].append(cars[unicode(cell_val)])
                        item[field + '_ids'].append(str(cars[unicode(cell_val)].id))
                    elif cell_val.strip() != '':
                        if unicode(cell_val) not in notfound.keys():
                            n_c = Car('<em style="color:#ff0000">%s</em>' % cell_val, '', '', 0, 'new', coldefinition['dept'])
                            notfound[unicode(cell_val)] = n_c
                        else:
                            n_c = notfound[unicode(cell_val)]
                        item[field].append(n_c)
                        item[field + '_ids'].append(-1)

            # check if key exists
            for k in keys:
                if unicode(k.category) == unicode(item['category']) and unicode(k.key) == unicode(item['key']):
                    item['dbid'] = k.id
                    if k.getCars1(coldefinition['dept']) != item['cars1'] or k.getCars2(coldefinition['dept']) != item['cars2'] or k.getMaterial(coldefinition['dept']) != item['material']:
                        item['cars1'] = k.getCars1(coldefinition['dept'])
                        item['cars2'] = k.getCars2(coldefinition['dept'])
                        item['material'] = k.getMaterial(coldefinition['dept'])
                        item['state'] = '1'  # mark to update

            if not item['dbid']: item['state'] = '-1'  # mark as new
            
            if item['category'] != '' and item['key'] != '':
                states[str(item['state'])] += 1
                importkeys.append(item)

        return dict(keys=importkeys, carsnotfound=notfound, states=states)
Esempio n. 11
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmkeys

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')

    if len(module) < 2:
        module.append(u'1')
    
    if len(module) > 2 and module[2] == 'upload':  # upload alarmkeys
        params.update({'': int(module[1]), 'department': module[1]})
        return render_template('admin.alarmkeys.upload.html', **params)
    
    else:
        depid = 1
        try:
            if module[1].isnumeric():
                depid = int(module[1])
        except:
            pass

        if request.method == 'POST':
            if depid == 0:
                if request.form.get('action', '') == 'createset':  # add alarmkeyset
                    params.update({'alarmkeyset': AlarmkeySet('', '', datetime.date.today(), datetime.date.today(), ''), 'setbases': AlarmkeySet.getBases(), 'orphankeys': Alarmkey.getOrphanKeys()})
                    return render_template('admin.alarmkeys.set_actions.html', **params)

                elif request.form.get('action', '').startswith('deleteset_'):
                    db.session.delete(AlarmkeySet.getAlarmkeySets(request.form.get('action', '').split('_')[-1]))
                    db.session.commit()

                elif request.form.get('action', '').startswith('detailset_'):  # edit alarmkeyset
                    params.update({'alarmkeyset': AlarmkeySet.getAlarmkeySets(request.form.get('action').split('_')[-1]), 'setbases': AlarmkeySet.getBases(), 'orphankeys': Alarmkey.getOrphanKeys()})
                    return render_template('admin.alarmkeys.set_actions.html', **params)

                elif request.form.get('action', '') == 'savealarmkeyset':  # save alarmkeyset
                    if request.form.get('set_id', '') == 'None':  # add
                        akset = AlarmkeySet('', '', datetime.date.today(), datetime.date.today(), '')
                        db.session.add(akset)
                    else:
                        akset = AlarmkeySet.getAlarmkeySets(request.form.get('set_id'))
                    akset.name = request.form.get('set_name')
                    if request.form.get('set_startdate', '') != "":
                        akset.startdate = datetime.datetime.strptime(request.form.get('set_startdate'), '%d.%m.%Y')
                    else:
                        akset.startdate = None
                    if request.form.get('set_enddate', '') != "":
                        akset.enddate = datetime.datetime.strptime(request.form.get('set_enddate'), '%d.%m.%Y')
                    else:
                        akset.enddate = None
                    akset.remark = request.form.get('set_remark')
                    akset.base = request.form.get('set_base')
                    db.session.commit()
                    if 'set_assignorphan' in request.form.keys():  # add all orphan keys to current set
                        for key in Alarmkey.getOrphanKeys():
                            key._keyset = int(akset.id)
                        db.session.commit()

                elif request.form.get('action', '').startswith('deletebase_'):
                    if os.path.exists("{}alarmkeysetbase/{}".format(current_app.config.get('PATH_DATA'), "_".join(request.form.get('action', '').split('_')[1:]))):
                        os.remove("{}alarmkeysetbase/{}".format(current_app.config.get('PATH_DATA'), "_".join(request.form.get('action', '').split('_')[1:])))

                params.update({'aksets': AlarmkeySet.getAlarmkeySets(), 'akbases': AlarmkeySet.getBases()})
                return render_template('admin.alarmkeys.set_list.html', **params)

            if request.form.get('action') == 'adddefault':  # add default aao
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': 0})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'savedefault':  # save default aao
                alarmkeycar = AlarmkeyCars.getAlarmkeyCars(kid=9999, dept=request.form.get('deptid'))  # 9999 = default department
                if not alarmkeycar:  # add
                    alarmkeycar = AlarmkeyCars(9999, request.form.get('deptid'), '', '', '')
                    db.session.add(alarmkeycar)

                alarmkeycar.cars1 = request.form.get('cars1')
                alarmkeycar.cars2 = request.form.get('cars2')
                alarmkeycar.materials = request.form.get('material')
                if alarmkeycar.kid != 9999 and request.form.get('cars1') == request.form.get('cars2') == request.form.get('material') == '':  # remove
                    db.session.delete(alarmkeycar)
                db.session.commit()
                
            elif request.form.get('action') == 'editdefault':  # edit default aao
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'aksets': AlarmkeySet.getAlarmkeySets(), 'cars': Car.getCars(), 'type': -1})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'addkey':  # add key
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'aksets': AlarmkeySet.getAlarmkeySets(), 'cars': Car.getCars(), 'type': -2})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'savekey':  # save key
                if request.form.get('keyid') == 'None':  # add new
                    alarmkey = Alarmkey('', '', '', '')
                    db.session.add(alarmkey)
                    db.session.commit()

                else:  # update existing
                    alarmkey = Alarmkey.getAlarmkeys(request.form.get('keyid'))

                alarmkey.category = request.form.get('category')
                alarmkey.key = request.form.get('key')
                alarmkey.key_internal = request.form.get('keyinternal')
                alarmkey.remark = request.form.get('remark')
                if request.form.get('keyset', '') == '':
                    alarmkey._keyset = None
                else:
                    alarmkey._keyset = request.form.get('keyset')
                alarmkey.setCars(int(request.form.get('deptid')), cars1=request.form.get('cars1'), cars2=request.form.get('cars2'), material=request.form.get('material'))

                alarmkey.keysetitem = None
                if request.form.get('keyset', '') != "":
                    keyset = AlarmkeySet.getAlarmkeySets(request.form.get('keyset'))
                    if keyset:
                        item = filter(lambda x: x.get('stichwort') == alarmkey.category and x.get('schlagwort') == alarmkey.key, keyset.alarmkeys)
                        if len(item) > 0:
                            alarmkey.keysetitem = item[0].get('nr')
                db.session.commit()  # readd

            elif request.form.get('action').startswith('deletecars_'):  # delete car definition
                _op, _kid, _dept = request.form.get('action').split('_')
                keycar = AlarmkeyCars.getAlarmkeyCars(kid=_kid, dept=_dept)
                if keycar:
                    db.session.delete(keycar)
                    db.session.commit()

                # delete key if no definied cars
                if len(AlarmkeyCars.getAlarmkeyCars(kid=_kid)) == 0:
                    key = Alarmkey.getAlarmkeys(id=_kid)
                    db.session.delete(key)
                db.session.commit()
                
            elif request.form.get('action').startswith('editcars_'):  # edit key with cars
                _op, _kid, _dept = request.form.get('action').split('_')
                params.update({'alarmkey': Alarmkey.getAlarmkeys(id=_kid), 'depid': _dept, 'departments': Department.getDepartments(), 'aksets': AlarmkeySet.getAlarmkeySets(), 'cars': Car.getCars(), 'type': 1})
                return render_template('admin.alarmkeys_actions.html', **params)

        if depid == 0:  # edit options
            params.update({'aksets': AlarmkeySet.getAlarmkeySets(), 'departments': Department.getDepartments(), 'akbases': AlarmkeySet.getBases()})
            return render_template('admin.alarmkeys.set_list.html', **params)

        params.update({'depid': depid, 'defaultcars': Alarmkey.getDefault(depid), 'aksets': AlarmkeySet.getAlarmkeySets()})
        return render_template('admin.alarmkeys.html', **params)
Esempio n. 12
0
    def handleEvent(eventname, **kwargs):
        """
        Eventhandler for alarm class

        :param eventname: name of event
        :param kwargs: parameter list: error, fields, filename, id, incomepath, mode, time
        :return: all kwargs
        """
        from emonitor import app
        global LASTALARM

        alarm_fields = dict()
        stime = time.time()
        alarmtype = None
        for t in AlarmType.getAlarmTypes():
            #if re.search(t.keywords.replace('\r\n', '|'), unicode(kwargs['text'], errors='ignore')):
            if re.search(t.keywords.replace('\r\n', '|'), kwargs['text']):
                alarm_fields = t.interpreterclass().buildAlarmFromText(t, kwargs['text'])
                if u'error' in alarm_fields.keys():
                    kwargs['error'] = alarm_fields['error']
                    del alarm_fields['error']
                alarmtype = t
                break

        # copy file -> original name
        if 'time' in alarm_fields and alarm_fields['time'][1] == 1:  # found correct time
            t = datetime.datetime.strptime(alarm_fields['time'][0], '%d.%m.%Y - %H:%M:%S')
        else:
            t = datetime.datetime.now()

        if not os.path.exists('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/'))):
            os.makedirs('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/')))

        try:
            shutil.copy2('{}{}'.format(kwargs['incomepath'], kwargs['filename']), '{}{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs['filename'])[1]))
        except:
            pass
        try:  # remove file
            os.remove('{}{}'.format(kwargs['incomepath'], kwargs['filename']))
        except:
            pass
        kwargs['filename'] = '{}{}'.format(t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs['filename'])[1])
        logger.debug('alarm_fields: {}'.format(alarm_fields))

        if len(alarm_fields) == 0:  # no alarmfields found
            kwargs['id'] = 0
            logger.error('no alarm fields found.')
            return kwargs

        kwargs['fields'] = ''
        for k in alarm_fields:
            kwargs['fields'] = u'{}\n-{}:\n  {}'.format(kwargs['fields'], k, alarm_fields[k])

        if not alarmtype:  # alarmtype not found
            kwargs['id'] = 0
            kwargs['error'] = 'alarmtype not found'
            logger.error('alarmtype not found.')
            return kwargs

        # position
        _position = dict(lat=u'0.0', lng=u'0.0')
        if USE_NOMINATIM == 1:
            try:
                url = 'http://nominatim.openstreetmap.org/search'
                params = 'format=json&city={}&street={}'.format(alarm_fields['city'][0], alarm_fields['address'][0])
                if 'streetno' in alarm_fields:
                    params += ' {}'.format(alarm_fields['streetno'][0].split()[0])  # only first value
                r = requests.get('{}?{}'.format(url, params))
                _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon'])
            except:
                pass

        # create alarm object
        if 'key' not in alarm_fields.keys() or alarm_fields['key'][0] == u'':
            if alarmtype.translation(u'_bma_main_') in alarm_fields['remark'][0] or alarmtype.translation(u'_bma_main_') in alarm_fields['person'][0]:
                alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).all()
                if len(alarmkey) > 0:
                    alarm_fields['key'] = ('{}: {}'.format(alarmkey[0].category, alarmkey[0].key), str(alarmkey[0].id))
                else:
                    alarm_fields['key'] = (alarmtype.translation(u'_bma_key_'), u'0')

        if 'time' in alarm_fields and alarm_fields['time'][1] == 1:  # found correct time
            t = datetime.datetime.strptime(alarm_fields['time'][0], '%d.%m.%Y - %H:%M:%S')
        else:
            t = datetime.datetime.now()

        alarm = Alarm(t, alarm_fields['key'][0], 1, 0)
        alarm.set('id.key', alarm_fields['key'][1])
        alarm.material = dict(cars1='', cars2='', material='')  # set required attributes
        alarm.set('marker', '0')
        alarm.set('filename', kwargs['filename'])
        alarm.set('priority', '1')  # set normal priority
        alarm.set('alarmtype', alarmtype.name)  # set checker name
        alarm.state = 1

        # city
        if 'city' in alarm_fields and alarm_fields['city'][1] != 0:
            alarm.city = City.getCities(id=alarm_fields['city'][1])
            if alarm_fields['address'][1] != 0:
                alarm.street = Street.getStreets(id=alarm_fields['address'][1])
        else:  # city not found -> build from fax
            url = 'http://nominatim.openstreetmap.org/search'
            params = u'format=json&city={}&street={}'.format(alarm_fields['city'][0].split()[0], alarm_fields['address'][0])
            if 'streetno' in alarm_fields and alarm_fields['streetno'][0]:
                params += u' {}'.format(alarm_fields['streetno'][0].split()[0])  # only first value
                alarm.set('streetno', alarm_fields['streetno'][0])

            r = requests.get(u'{}?{}'.format(url, params))
            logger.debug('load address data from nomination with parameters: city=%s street=%s' % (alarm_fields['city'][0].split()[0], alarm_fields['address'][0]))
            try:
                _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon'])
                alarm.position = _position
            except:
                pass

            alarm.set('city', alarm_fields['city'][0].split()[0])
            alarm.set('id.city', alarm_fields['city'][1])
            alarm.set('address', alarm_fields['address'][0])
            if alarm_fields['address'][1] != 0:
                alarm.street = Street.getStreets(id=alarm_fields['address'][1])

            if 'cars' in alarm_fields:  # add cars found in material
                for _c in alarm_fields['cars'][1].split(';'):
                    alarm.set('k.cars1', alarm.get('k.cars1') + ';' + _c)

        # street / street2
        if 'address' in alarm_fields and alarm_fields['address'][0] != '':
            # check correct city -> change if street has different city
            if len(str(alarm_fields['address'][1]).split(';')) > 0 and alarm_fields['address'][1] != 0:
                _c = []

                for s in str(alarm_fields['address'][1]).split(';'):
                    _s = Street.getStreets(id=s)
                    if _s.cityid and _s.cityid not in _c and _s.cityid == alarm_fields['city'][1]:
                        _c.append(_s.cityid)
                        alarm.street = _s
                        if 'object' in alarm_fields and str(alarm_fields['object'][1]) == '0':
                            if 'lat' not in alarm_fields and 'lng' not in alarm_fields:
                                alarm.position = dict(lat=_s.lat, lng=_s.lng, zoom=_s.zoom)
                                if _position['lat'] != u'0.0' and _position['lng'] != u'0.0':  # set marker if nominatim delivers result
                                    alarm.position = _position
                                    alarm.set('marker', '1')
            else:  # add unknown street
                alarm.set('id.address', 0)
                alarm.set('address', alarm_fields['address'][0])
        # houseno
        if 'streetno' in alarm_fields.keys():
            alarm.set('streetno', alarm_fields['streetno'][0])
            if 'id.streetno' in alarm_fields and 'lat' in alarm_fields and 'lng' in alarm_fields:
                alarm.position = dict(lat=alarm_fields['lat'][0], lng=alarm_fields['lng'][0])
                alarm.set('id.streetno', alarm_fields['id.streetno'][1])
            else:
                # new
                hn = alarm.street.getHouseNumber(name=alarm_fields['streetno'][0])
                if hn:
                    alarm.position = hn.getPosition(0)
            if 'zoom' in alarm_fields.keys():
                alarm.set('zoom', alarm_fields['zoom'][0])

        # crossing
        if 'crossing' in alarm_fields and alarm_fields['crossing'][0] != '':
            if 'crossing' in alarm_fields and alarm_fields['address'][1] != alarm_fields['crossing'][1]:
                alarm.set('id.address2', alarm_fields['crossing'][1])
                alarm.set('address2', alarm_fields['crossing'][0])
            else:
                alarm.set('id.address2', '0')
                alarm.set('address2', alarm_fields['crossing'][0])

        # addresspart
        if 'addresspart' in alarm_fields and alarm_fields['addresspart'][0] != '' and alarm_fields['addresspart'][0] != alarm_fields['address'][0]:
            if alarm_fields['addresspart'][1] > 0:
                if len(str(alarm_fields['addresspart'][1]).split(';')) > 0:
                    _c = []

                    for s in str(alarm_fields['addresspart'][1]).split(';'):
                        try:
                            _s = Street.getStreets(id=s)
                            if _s.cityid not in _c and _s.cityid == alarm_fields['city'][1]:
                                _c.append(_s.cityid)
                                alarm.set('id.address2', _s.id)
                        except:
                            pass
                else:
                    alarm.set('id.address2', alarm_fields['addresspart'][1])
            else:
                alarm.set('id.address2', '0')
            alarm.set('address2', alarm_fields['addresspart'][0])

        # person
        if 'person' in alarm_fields and alarm_fields['person'][0] != '':
            alarm.set('person', alarm_fields['person'][0])
        # alarmplan
        if 'alarmplan' in alarm_fields and alarm_fields['alarmplan'][0] != '':
            alarm.set('alarmplan', alarm_fields['alarmplan'][0])

        # alarmobject
        _ao = None
        if 'object' in alarm_fields and alarm_fields['object'][0] != '' and 'city' in alarm_fields and alarm_fields['city'][1] > 0:
            alarm.set('object', alarm_fields['object'][0])
            alarm.set('id.object', alarm_fields['object'][1])
            # alarmplan from object
            if alarm_fields['object'][1] != 0:
                _ao = AlarmObject.getAlarmObjects(id=alarm_fields['object'][1])

            if _ao:
                if _ao.alarmplan != 0:
                    alarm.set('alarmplan', _ao.alarmplan)
                if _ao.street.id != alarm_fields['address'][1]:  # street config from alarmobject
                    alarm.street = Street.getStreets(id=_ao.street.id)
                    if _ao.streetno == "":
                        alarm.set('streetno', alarm_fields['streetno'][0])
                    else:
                        alarm.set('streetno', _ao.streetno)
                alarm.position = dict(lat=_ao.lat, lng=_ao.lng, zoom=_ao.zoom)

        # remark
        if 'remark' in alarm_fields and alarm_fields['remark'][0] != '':
            alarm.set('remark', alarm_fields['remark'][0])
            if alarmtype.translation(u'_bma_main_') in alarm_fields['remark'][0] or alarmtype.translation(u'_bma_main_') in alarm_fields['person'][0]:
                alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).first()
                if alarmkey:
                    alarm.set('id.key', alarmkey.id)
                    alarm._key = u'{}: {}'.format(alarmkey.category, alarmkey.key)
                else:
                    alarm.set('id.key', '0')
                    alarm._key = alarmtype.translation(u'_bma_key_')
        # additional remarks
        if 'remark2' in alarm_fields and alarm_fields['remark2'][0] != '':
            alarm.set('remark', u'%s\n%s' % (alarm.get('remark'), alarm_fields['remark2'][0]))

        # material
        if alarm.get('id.key') != 0 and 'city' in alarm_fields:  # found key with aao
            if alarm_fields['city'][1] != 0:  # default city
                if Department.getDepartments(id=alarm.city.dept).defaultcity == alarm_fields['city'][1]:  # default city for dep
                    if 'material' in alarm_fields:
                        if str(alarm_fields['material'][1])[0] == '0':  # default cars for aao
                            try:
                                alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.street.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.street.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.street.city.dept)]))
                            except AttributeError:
                                alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)]))

                        for _c in u'{}'.format(alarm_fields['material'][1]).split(','):  # add additional cars
                            if _c != '0' and _c not in alarm.get('k.cars1').split(','):
                                alarm.set('k.cars1', u'{},{}'.format(alarm.get('k.cars1'), _c))

                else:  # only alarmed material
                    alarm.material = dict(cars1=alarm_fields['material'][1])

            else:  # else city
                if alarm_fields['material'][1] == u'0':  # default cars for aao
                    alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)]))
                else:
                    alarm.material = dict(cars1=u','.join(list(OrderedDict.fromkeys(filter(lambda x: x != '0', str(alarm_fields['material'][1]).split(','))))))

        else:  # default aao of current department (without aao)
            if alarm_fields['city'][1] != 0:  # found city -> use default aao
                c = City.getCities(id=alarm_fields['city'][1]).dept
                akc = Alarmkey.getDefault(c)
                alarm.material = dict(cars1=u','.join([str(c.id) for c in akc.cars1]), cars2=u",".join([str(c.id) for c in akc.cars2]), material=u",".join([str(c.id) for c in akc.materials]))

            l = (u'%s,%s,%s' % (alarm.get('k.cars1'), alarm.get('k.cars2'), alarm.get('k.material'))).split(',')
            if len(set(str(alarm_fields['material'][1]).split(',')).intersection(set(l))) == 0:
                _dep = Department.getDefaultDepartment()
                for c in alarm_fields['material'][1].split(','):
                    if c == u'0':  # default of home department needed
                        alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(_dep.id)]), cars2=u",".join([str(c.id) for c in alarm.key.getCars2(_dep.id)]), material=u",".join([str(c.id) for c in alarm.key.getMaterial(_dep.id)]))
                        break
                if u'0' not in alarm_fields['material'][1]:  # only single car needed
                    alarm.set('k.cars1', u'{},{}'.format(alarm_fields['material'][1], alarm.get('k.cars1')))

        if _ao and _ao.hasOwnAAO():  # use aao of current object
            alarm.material = dict(cars1=u",".join([str(c.id) for c in _ao.getCars1()]), cars2=u",".join([str(c.id) for c in _ao.getCars2()]), material=u",".join([str(c.id) for c in _ao.getMaterial()]))

        if 'time' not in kwargs.keys():
            kwargs['time'] = []
        etime = time.time()
        kwargs['time'].append('alarm creation done in %s sec.' % (etime - stime))

        if kwargs['mode'] != 'test':
            db.session.add(alarm)
            db.session.commit()
            signal.send('alarm', 'added', alarmid=alarm.id)
            Alarm.changeState(alarm.id, 1)  # activate alarm
            logger.info('alarm created with id %s (%s)' % (alarm.id, (etime - stime)))
        else:
            kwargs['fields'] += '\n\n--------------------------\nALARM-Object\n'
            _cdict = Car.getCarsDict()
            for a in alarm.attributes:
                try:
                    if a in ['k.cars1', 'k.cars2', 'k.material']:
                        kwargs['fields'] += '\n-%s:\n  %s -> %s' % (a, alarm.get(a), ", ".join([_cdict[int(_c)].name for _c in alarm.get(a).split(',') if _c != ""]))
                    elif a in 'id.key':
                        _k = Alarmkey.getAlarmkeys(id=alarm.get(a))
                        kwargs['fields'] += '\n-%s:\n  %s -> %s: %s' % (a, alarm.get(a), _k.category, _k.key)
                    elif a == 'id.address':
                        kwargs['fields'] += '\n-%s:\n  %s -> %s' % (a, alarm.get(a), Street.getStreets(id=alarm.get(a)).name)
                    else:
                        kwargs['fields'] += '\n-%s:\n  %s' % (a, alarm.get(a))
                except (AttributeError, KeyError):
                    kwargs['fields'] += '\n-%s:\n  %s (error)' % (a, alarm.get(a))
            kwargs['id'] = '-0'  # add dummy id
            db.session.rollback()
            logger.info('alarm created in TESTMODE (%s)' % (etime - stime))
        return kwargs
def getAdminData(self):
    """
    Deliver admin content of module alarmkeys (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'loaddetails':  # details for given key
        return render_template('admin.alarmkeys.detail.html', keys=Alarmkey.getAlarmkeysByCategoryId(request.args.get('category')), department=request.args.get('department'))

    elif request.args.get('action') == 'upload':
        if request.files:
            uploadfile = request.files['uploadfile']
            filename = werkzeug.secure_filename(uploadfile.filename)
            fname = os.path.join(current_app.config.get('PATH_TMP'), filename)
            uploadfile.save(fname)
            xlsfile = XLSFile(fname)
            uploadfiles[uploadfile.filename] = xlsfile

            return render_template('admin.alarmkeys.upload2.html', sheets=uploadfiles[uploadfile.filename].getSheets())
            
    elif request.args.get('action') == 'upload_sheet':  # sheet selector
        definitionfile = uploadfiles[request.args.get('filename')]
        return render_template('admin.alarmkeys.upload3.html', cols=definitionfile.getCols(request.args.get('sheetname')))

    elif request.args.get('action') == 'testimport':  # build data for preview
        col_definition = {'dept': request.args.get('department'), 'sheet': request.args.get('sheetname'),
                          'category': request.form.get('category'), 'key': request.form.get('key'),
                          'keyinternal': request.form.get('keyinternal'), 'remark': request.form.get('remark'),
                          'cars1': request.form.getlist('cars1'), 'cars2': request.form.getlist('cars2'),
                          'material': request.form.getlist('material')}

        deffile = uploadfiles[request.args.get('filename')]
        vals = deffile.getValues(col_definition)
        return render_template('admin.alarmkeys.uploadpreview.html', vals=vals)

    elif request.args.get('action') == 'doimport':  # do import and store values
        coldefinition = {'dept': request.args.get('department'), 'sheet': request.args.get('sheetname'),
                         'category': request.form.get('category'), 'key': request.form.get('key'),
                         'keyinternal': request.form.get('keyinternal'), 'remark': request.form.get('remark'),
                         'cars1': request.form.getlist('cars1'), 'cars2': request.form.getlist('cars2'),
                         'material': request.form.getlist('material')}
        deffile = uploadfiles[request.args.get('filename')]

        vals = deffile.getValues(coldefinition)
        states = []

        if request.form.get('add_material'):  # add new material
            p = re.compile(r'<.*?>')
            for k in vals['carsnotfound']:
                n_car = vals['carsnotfound'][k]
                n_car.name = p.sub('', n_car.name)
                if n_car.name == '':
                    continue
                db.session.add(n_car)
            db.session.commit()
            
        if request.form.get('add_new'):  # add new keys ( item state=-1)
            states.append('-1')
            
        if request.form.get('add_update'):  # update existing keys (item state=1)
            states.append('1')
        
        for key in vals['keys']:  # item list
            if key['state'] in states:  # import only with correct state
                
                if key['state'] == '-1':  # add key
                    k = Alarmkey(key['category'], key['key'], key['keyinternal'], key['remark'])
                    db.session.add(k)
                    db.session.commit()
                    k.setCars(coldefinition['dept'],
                              cars1=";".join([str(c.id) for c in key['cars1']]),
                              cars2=";".join([str(c.id) for c in key['cars2']]),
                              materials=";".join([str(c.id) for c in key['material']]))
                    db.session.commit()
                    key['state'] = '0'

                elif key['state'] == '1':  # update key
                    k = Alarmkey.getAlarmkeys(id=int(key['dbid']))
                    k.category = key['category']
                    k.key = key['key']
                    k.key_internal = key['keyinternal']
                    k.remark = key['remark']
                    k.setCars(coldefinition['dept'],
                              cars1=';'.join(filter(None, key['cars1_ids'])),
                              cars2=';'.join(filter(None, key['cars2_ids'])),
                              materials=';'.join(filter(None, key['material_ids'])))
                    db.session.commit()
        return ""
        
    elif request.args.get('action') == 'download':
        # build exportfile
        filename = buildDownloadFile(request.args.get('department'), request.args.get('options'))
        if filename != "":
            return filename
            
    elif request.args.get('action') == 'keyslookup':
        keys = {}
        
        for k in Alarmkey.getAlarmkeys():
            keys[str(k.id)] = '%s: %s' % (k.category, k.key)
        return keys
        
    elif request.args.get('action') == 'categorylookup':
        key = Alarmkey.getAlarmkeys(id=int(request.args.get('keyid')))
        return {'id': key.id, 'category': key.category}

    if "/download/" in request.url:  # deliver file
        filename = os.path.basename(request.url)
        mime = "application/x.download"
        if filename.endswith('.xlsx'):
            mime = "application/vnd.ms-excel"
        return send_from_directory("%s/" % current_app.config.get('PATH_TMP'), filename, as_attachment=True, mimetype=mime)
    return ""
Esempio n. 14
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmkeys

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')

    if len(module) < 2:
        module.append(u'1')

    if len(module) > 2 and module[2] == 'upload':  # upload alarmkeys
        params.update({'': int(module[1]), 'department': module[1]})
        return render_template('admin.alarmkeys.upload.html', **params)

    else:
        depid = 1
        try:
            if int(module[1]):
                depid = int(module[1])
        except:
            pass

        if request.method == 'POST':
            if request.form.get('action') == 'adddefault':  # add default aao
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': 0
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get(
                    'action') == 'savedefault':  # save default aao
                alarmkeycar = AlarmkeyCars.getAlarmkeyCars(
                    kid=9999, dept=request.form.get(
                        'deptid'))  # 9999 = default department
                if not alarmkeycar:  # add
                    alarmkeycar = AlarmkeyCars(9999,
                                               request.form.get('deptid'), '',
                                               '', '')
                    db.session.add(alarmkeycar)

                alarmkeycar.cars1 = request.form.get('cars1')
                alarmkeycar.cars2 = request.form.get('cars2')
                alarmkeycar.materials = request.form.get('material')
                if alarmkeycar.kid != 9999 and request.form.get(
                        'cars1') == request.form.get(
                            'cars2') == request.form.get(
                                'material') == '':  # remove
                    db.session.delete(alarmkeycar)
                db.session.commit()

            elif request.form.get(
                    'action') == 'editdefault':  # edit default aao
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': -1
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get('action') == 'addkey':  # add key
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': -2
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get('action') == 'savekey':  # save key
                if request.form.get('keyid') == 'None':  # add new
                    alarmkey = Alarmkey('', '', '', '')
                    db.session.add(alarmkey)
                    db.session.commit()

                else:  # update existing
                    alarmkey = Alarmkey.getAlarmkeys(request.form.get('keyid'))

                alarmkey.category = request.form.get('category')
                alarmkey.key = request.form.get('key')
                alarmkey.key_internal = request.form.get('keyinternal')
                alarmkey.remark = request.form.get('remark')
                alarmkey.setCars(int(request.form.get('deptid')),
                                 cars1=request.form.get('cars1'),
                                 cars2=request.form.get('cars2'),
                                 material=request.form.get('material'))
                db.session.commit()

            elif request.form.get('action').startswith(
                    'deletecars_'):  # delete car definition
                _op, _kid, _dept = request.form.get('action').split('_')
                keycar = AlarmkeyCars.getAlarmkeyCars(kid=_kid, dept=_dept)
                if keycar:
                    db.session.delete(keycar)
                    db.session.commit()

                # delete key if no definied cars
                if len(AlarmkeyCars.getAlarmkeyCars(kid=_kid)) == 0:
                    key = Alarmkey.getAlarmkeys(id=_kid)
                    db.session.delete(key)
                db.session.commit()

            elif request.form.get('action').startswith(
                    'editcars_'):  # edit key with cars
                _op, _kid, _dept = request.form.get('action').split('_')
                params.update({
                    'alarmkey': Alarmkey.getAlarmkeys(id=_kid),
                    'depid': _dept,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': 1
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

        alarmkeys_count = []
        ak = Alarmkey
        counted_keys = db.get(ak.category.label('category'),
                              func.count(ak.key).label('key'),
                              ak.id.label('id')).group_by(ak.category)
        _sum = 0
        for r in counted_keys.all():
            alarmkeys_count.append([r.category, r.key, r.id])
            _sum += int(r.key)

        params.update({
            'alarmkeys_count': alarmkeys_count,
            'depid': depid,
            'defaultcars': Alarmkey.getDefault(depid),
            'sum': _sum
        })
        return render_template('admin.alarmkeys.html', **params)
Esempio n. 15
0
def getAdminData(self):
    """
    Deliver admin content of module alarmkeys (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'loaddetails':  # details for given key
        return render_template('admin.alarmkeys.detail.html', keys=Alarmkey.getAlarmkeysByCategoryId(request.args.get('category'), keysetid=int(request.args.get('keysetid', 0))), department=request.args.get('department'))

    elif request.args.get('action', '') == "changekeyset":  # deliver alarmkeys for given set
        ak = Alarmkey
        if request.args.get('keysetid', '0') == '0':
            counted_keys = db.get(ak.category.label('category'), func.count(ak.key).label('key'), ak.id.label('id'), func.count(ak.id).label('keysetcount')).group_by(ak.category).filter_by(_keyset=None)
        else:
            counted_keys = db.get(ak.category.label('category'), func.count(ak.key).label('key'), ak.id.label('id'), func.count(ak.id).label('keysetcount')).group_by(ak.category).filter_by(_keyset=request.args.get('keysetid'))
        _sum = 0
        alarmkeys_count = []
        for r in counted_keys.all():
            alarmkeys_count.append([r.category, r.key, r.id])
            _sum += int(r.key)
        return render_template('admin.alarmkeys.macro.html', alarmkeys_count=alarmkeys_count, depid=request.args.get('department'), sum=_sum)

    elif request.args.get('action') == 'upload':
        if request.files:
            uploadfile = request.files['uploadfile']
            fname = os.path.join(current_app.config.get('PATH_TMP'), werkzeug.secure_filename(uploadfile.filename))
            uploadfile.save(fname)
            uploadfiles[uploadfile.filename] = XLSFile(fname)

            return render_template('admin.alarmkeys.upload2.html', sheets=uploadfiles[uploadfile.filename].getSheets())
            
    elif request.args.get('action') == 'upload_sheet':  # sheet selector
        definitionfile = uploadfiles[request.args.get('filename')]
        return render_template('admin.alarmkeys.upload3.html', cols=definitionfile.getCols(request.args.get('sheetname')))

    elif request.args.get('action') == 'testimport':  # build data for preview
        col_definition = {'dept': request.args.get('department'), 'sheet': request.args.get('sheetname'),
                          'category': request.form.get('category'), 'key': request.form.get('key'),
                          'keyinternal': request.form.get('keyinternal'), 'remark': request.form.get('remark'),
                          'cars1': request.form.getlist('cars1'), 'cars2': request.form.getlist('cars2'),
                          'material': request.form.getlist('material')}

        deffile = uploadfiles[request.args.get('filename')]
        return render_template('admin.alarmkeys.uploadpreview.html', vals=deffile.getValues(col_definition), keysets=AlarmkeySet.getAlarmkeySets())

    elif request.args.get('action') == 'doimport':  # do import and store values
        coldefinition = {'dept': request.args.get('department'), 'sheet': request.args.get('sheetname'),
                         'category': request.form.get('category'), 'key': request.form.get('key'),
                         'keyinternal': request.form.get('keyinternal'), 'remark': request.form.get('remark'),
                         'cars1': request.form.getlist('cars1'), 'cars2': request.form.getlist('cars2'),
                         'material': request.form.getlist('material')}
        deffile = uploadfiles[request.args.get('filename')]

        vals = deffile.getValues(coldefinition)
        states = []

        if request.form.get('add_material'):  # add new material
            p = re.compile(r'<.*?>')
            for k in vals['carsnotfound']:
                n_car = vals['carsnotfound'][k]
                n_car.name = p.sub('', n_car.name)
                if n_car.name == '':
                    continue
                db.session.add(n_car)
            db.session.flush()
            
        if request.form.get('add_new'):  # add new keys ( item state=-1)
            states.append('-1')

        if request.form.get('add_update'):  # update existing keys (item state=1)
            states.append('1')

        if request.form.get('add_assign') and request.form.get('keyset', '') != '':  # assign keys to keyset (item state=2)
            keyset = AlarmkeySet.getAlarmkeySets(request.form.get('keyset'))
            states.append('2')

        for key in vals['keys']:  # item list
            if key['state'] in states:  # import only with correct state
                
                if key['state'] == '-1':  # add key
                    k = Alarmkey(key['category'], key['key'], key['keyinternal'], key['remark'])
                    db.session.add(k)
                    db.session.flush()
                    k.setCars(coldefinition['dept'],
                              cars1=";".join([str(c.id) for c in key['cars1']]),
                              cars2=";".join([str(c.id) for c in key['cars2']]),
                              materials=";".join([str(c.id) for c in key['material']]))
                    db.session.commit()
                    key['state'] = '0'

                elif key['state'] == '1':  # update key
                    k = Alarmkey.getAlarmkeys(id=int(key['dbid']))
                    k.category = key['category']
                    k.key = key['key']
                    k.key_internal = key['keyinternal']
                    k.remark = key['remark']
                    k.setCars(coldefinition['dept'],
                              cars1=';'.join(filter(None, key['cars1_ids'])),
                              cars2=';'.join(filter(None, key['cars2_ids'])),
                              materials=';'.join(filter(None, key['material_ids'])))
                    db.session.commit()

                if '2' in states:  # assign keys to keyset
                    item = filter(lambda x: x.get('stichwort') == k.category and x.get('schlagwort') == k.key, keyset.alarmkeys)
                    k._keyset = keyset.id
                    if len(item) > 0:
                        k.keysetitem = item[0].get('nr')

        db.session.commit()
        return ""
        
    elif request.args.get('action') == 'download':
        # build exportfile
        filename = buildDownloadFile(request.args.get('department'), request.args.get('options'))
        if filename != "":
            return filename
            
    elif request.args.get('action') == 'keyslookup':
        keys = {}
        
        for k in Alarmkey.getAlarmkeys(keysetid=request.args.get('keysetid')):
            keys[str(k.id)] = '%s: %s' % (k.category, k.key)
        return keys

    elif request.args.get('action') == 'categorylookup':
        key = Alarmkey.getAlarmkeys(id=int(request.args.get('keyid')))
        return {'id': key.id, 'category': key.category}

    elif request.args.get('action', '') == 'keysetlookup':
        try:
            return AlarmkeySet.getAlarmkeySets(request.args.get('setid')).alarmkeys
        except ValueError:  # no base given
            return []

    elif request.args.get('action', '') == 'uploaddefinition':
        if request.files:
            ufile = request.files['uploadfile']
            if not os.path.exists("{}alarmkeysetbase/".format(current_app.config.get('PATH_DATA'))):
                os.makedirs("{}alarmkeysetbase/".format(current_app.config.get('PATH_DATA')))
            fname = os.path.join("{}alarmkeysetbase/".format(current_app.config.get('PATH_DATA')), ufile.filename)
            ufile.save(fname)
            with codecs.open(fname, 'r', encoding='utf-8') as fin:
                aksetbase = AlarmkeySetBase(ufile.filename, json.load(fin), 'external')
                return jsonify(state="ok", name=aksetbase.name, startdate=datetime.datetime.strftime(aksetbase.start, "%d.%m.%Y"), items=len(aksetbase.items), filename=aksetbase.id, type=aksetbase.settype)

        return jsonify(state="error")

    elif request.args.get('action', '') == 'createbaseset':
        """
        create base keys for given set and return number of updated
        """
        stats = AlarmkeySet.getAlarmkeySets(id=request.args.get('setid')).createBaseKeys()
        return babel.gettext('alarmkeys.createbaseset.result', num_success=stats[0], num_error=stats[1])

    if "/download/" in request.url:  # deliver file
        filename = os.path.basename(request.url)
        mime = "application/x.download"
        if filename.endswith('.xlsx'):
            mime = "application/vnd.ms-excel"
        return send_from_directory("%s/" % current_app.config.get('PATH_TMP'), filename, as_attachment=True, mimetype=mime)
    return ""
Esempio n. 16
0
    def getValues(self, coldefinition):
        cars = {}
        notfound = {}
        states = {'-1': 0, '0': 0, '1': 0}
        for c in Car.getCars(deptid=coldefinition['dept']):
            cars[unicode(c.name)] = c

        keys = Alarmkey.getAlarmkeys()
        worksheet = self.book.sheet_by_name(self.book.sheet_names()[int(
            coldefinition['sheet'])])

        def getPosForCol(name):
            ret = -65
            while len(name) > 0:
                ret += ord(name[0])
                name = name[1:]
            return ret

        def evalValue(crow, ccol):
            try:
                return worksheet.cell_value(crow, ccol)
            except:
                return ""

        importkeys = []
        # state -1:new, 0:no changes, 1:need update
        for row in range(self.headerrow + 1, worksheet.nrows - 1):
            item = {
                'cars1': [],
                'cars2': [],
                'material': [],
                'cars1_ids': [],
                'cars2_ids': [],
                'material_ids': [],
                'dbid':
                None,
                'state':
                '0',
                'category':
                evalValue(row, getPosForCol(coldefinition['category'])),
                'key':
                evalValue(row, getPosForCol(coldefinition['key'])),
                'keyinternal':
                evalValue(row, getPosForCol(coldefinition['keyinternal'])),
                'remark':
                evalValue(row, getPosForCol(coldefinition['remark']))
            }

            for field in ['cars1', 'cars2', 'material']:
                for c in coldefinition[field]:
                    cell_val = evalValue(row, getPosForCol(c))
                    if unicode(cell_val) in cars.keys():
                        item[field].append(cars[unicode(cell_val)])
                        item[field + '_ids'].append(
                            str(cars[unicode(cell_val)].id))
                    elif cell_val.strip() != '':
                        if unicode(cell_val) not in notfound.keys():
                            n_c = Car(
                                '<em style="color:#ff0000">%s</em>' % cell_val,
                                '', '', 0, 'new', coldefinition['dept'])
                            notfound[unicode(cell_val)] = n_c
                        else:
                            n_c = notfound[unicode(cell_val)]
                        item[field].append(n_c)
                        item[field + '_ids'].append(-1)

            # check if key exists
            for k in keys:
                if unicode(k.category) == unicode(
                        item['category']) and unicode(k.key) == unicode(
                            item['key']):
                    item['dbid'] = k.id
                    if k.getCars1(
                            coldefinition['dept']
                    ) != item['cars1'] or k.getCars2(
                            coldefinition['dept']
                    ) != item['cars2'] or k.getMaterial(
                            coldefinition['dept']) != item['material']:
                        item['cars1'] = k.getCars1(coldefinition['dept'])
                        item['cars2'] = k.getCars2(coldefinition['dept'])
                        item['material'] = k.getMaterial(coldefinition['dept'])
                        item['state'] = '1'  # mark to update

            if not item['dbid']: item['state'] = '-1'  # mark as new

            if item['category'] != '' and item['key'] != '':
                states[str(item['state'])] += 1
                importkeys.append(item)

        return dict(keys=importkeys, carsnotfound=notfound, states=states)
Esempio n. 17
0
def buildDownloadFile(department, dtype=0):
    """
    Create XLSX file with definition of given department and store file in tmp directory with filename *aao.xlsx*

    :param department: department object
    :param dtype: 0|1: add default definition if no material definition found for keyword
    :return: filename of created file, on error ''
    """
    alarmkeys = Alarmkey.getAlarmkeys()

    header = ['dbid', 'category', 'key', 'key internal']
    _maxcars1 = 1
    _maxcars2 = 1
    _maxmaterial = 1

    counted_keys = AlarmkeyCars.query.from_statement(
        "select kid, dept, (LENGTH(cars1)-LENGTH(REPLACE(cars1, ';', '')))as cars1, (LENGTH(cars2)-LENGTH(REPLACE(cars2, ';', ''))) as cars2, (LENGTH(material)-LENGTH(REPLACE(material, ';', ''))) as material from alarmkeycars where dept='1';"
    )

    for c_k in counted_keys:
        if _maxcars1 < c_k._cars1: _maxcars1 = c_k._cars1
        if _maxcars2 < c_k._cars2: _maxcars2 = c_k._cars2
        if _maxmaterial < c_k._material: _maxmaterial = c_k._material

    header += ['p_%s' % i for i in range(0, _maxcars1 + 1)]
    header += ['s_%s' % i for i in range(0, _maxcars2 + 1)]
    header += ['m_%s' % i for i in range(0, _maxmaterial + 1)]
    header += ['remark']

    # Create an new Excel file and add a worksheet.
    workbook = xlsxwriter.Workbook('%s/aao.xlsx' %
                                   current_app.config.get('PATH_TMP'))
    worksheet = workbook.add_worksheet('aao')
    bold = workbook.add_format({'bold': 1})

    worksheet.write_row(0, 0, header, bold)

    _w = 0
    for alarmkey in alarmkeys:
        if dtype == '1' and not alarmkey.hasDefinition(department):
            continue
        _w += 1
        data = [
            alarmkey.id, alarmkey.category, alarmkey.key, alarmkey.key_internal
        ]
        _c1 = alarmkey.getCars1(department)
        data += [c1.name for c1 in _c1]
        data += ['' for i in range(0, _maxcars1 - len(_c1) + 1)]
        _c2 = alarmkey.getCars2(department)
        data += [c2.name for c2 in _c2]
        data += ['' for i in range(0, _maxcars2 - len(_c2) + 1)]
        _c3 = alarmkey.getMaterial(department)
        data += [c3.name for c3 in _c3]
        data += ['' for i in range(0, _maxmaterial - len(_c3) + 1)]
        data += [alarmkey.remark]

        worksheet.write_row(list(alarmkeys).index(alarmkey) + 1, 0, data)

    workbook.close()

    if _w == 0:  # no data written
        return ''
    else:
        return 'aao.xlsx'
Esempio n. 18
0
    def handleEvent(eventname, **kwargs):
        """
        Eventhandler for alarm class

        :param eventname: name of event
        :param kwargs: parameter list: error, fields, filename, id, incomepath, mode, time
        :return: all kwargs
        """
        try:
            from emonitor import app
            global LASTALARM

            alarm_fields = dict()
            stime = time.time()
            alarmtype = None
            for t in AlarmType.getAlarmTypes():
                if re.search(t.keywords.replace('\r\n', '|'), kwargs.get('text', '')):
                    alarm_fields = t.interpreterclass().buildAlarmFromText(t, kwargs.get('text', ''))
                    if alarm_fields.get('error'):
                        kwargs['error'] = alarm_fields['error']
                        del alarm_fields['error']
                    alarmtype = t
                    break
            alarm = Alarm(datetime.datetime.now(), '', 1, 0)
            etime = time.time()

            _missing = 0
            for p in ['time', 'city', 'address', 'key']:
                if p not in alarm_fields:  # test required fields
                    _missing += 1
                    kwargs['error'] = kwargs.get('error', 'Missing parameter:') + "<br/>- '{}'".format(p)
            try:
                t = datetime.datetime.strptime(alarm_fields.get('time')[0], '%d.%m.%Y - %H:%M:%S')
            except ValueError:
                t = datetime.datetime.now()
            alarm.timestamp = t

            kwargs['id'] = u'<ul><li>-test-</li></ul>'  # add dummy id
            kwargs['fields'] = u'<ul>'  # set evaluated fields from fax
            for k in sorted(alarm_fields):  # add field values as unicode string
                if len(alarm_fields[k]) > 1:
                    kwargs['fields'] = u'{}<li><b>{}:</b>\n   <small style="color:silver">value:</small> "{}" &rarr; <small style="color:silver">id:</small> {}</li>'.format(kwargs.get('fields'), k, alarm_fields[k][0], alarm_fields[k][1])
                else:
                    kwargs['fields'] = u'{}<li><b>{}:</b>\n  <small style="color:silver">value:</small> "{}"</li>'.format(kwargs.get('fields'), k, alarm_fields[k])
            kwargs['fields'] = kwargs.get('fields', ' ') + '</ul></pre>\n\n<h5> ALARM-Object</h5>\n<pre><ul>'

            if _missing == 0:  # all required parameters found
                if kwargs.get('mode') != 'test':
                    if not os.path.exists('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/'))):
                        os.makedirs('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/')))

                    try:
                        shutil.copy2('{incomepath}{filename}'.format(**kwargs), '{}{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs.get('filename'))[1]))
                    except:
                        pass

                try:  # remove file
                    os.remove('{incomepath}{filename}'.format(**kwargs))
                except:
                    pass
                kwargs['filename'] = '{}{}'.format(t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs['filename'])[1])
                logger.debug('alarm_fields: {}'.format(alarm_fields))

                if len(alarm_fields) == 0:  # no alarmfields found
                    kwargs['id'] = 0
                    logger.error('no alarm fields found.')
                    return kwargs

                if not alarmtype:  # alarmtype not found
                    kwargs['id'] = 0
                    kwargs['error'] = kwargs.get('error', '') + 'alarmtype not found'
                    logger.error('alarmtype not found.')
                    return kwargs

                # position
                if alarm_fields.get('lat'):
                    _position = dict(lat=alarm_fields.get('lat')[0], lng=alarm_fields.get('lng')[0])
                else:
                    _position = dict(lat=u'0.0', lng=u'0.0')
                if USE_NOMINATIM == 1:
                    try:
                        url = 'http://nominatim.openstreetmap.org/search'
                        params = 'format=json&city={}&street={}'.format(alarm_fields['city'][0], alarm_fields['address'][0])
                        if 'streetno' in alarm_fields:
                            params += ' {}'.format(alarm_fields['streetno'][0].split()[0])  # only first value
                        r = requests.get('{}?{}'.format(url, params))
                        _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon'])
                    except:
                        pass

                # create alarm object
                if alarm_fields.get('key', [u'', 0])[0] == u'':
                    if alarmtype.translation(u'_bma_main_') in alarm_fields.get('remark', [u'', 0])[0] or alarmtype.translation(u'_bma_main_') in alarm_fields.get('person', [u'', 0])[0]:
                        alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).all()
                        if len(alarmkey) > 0:
                            alarm_fields['key'] = ('{}: {}'.format(alarmkey[0].category, alarmkey[0].key), str(alarmkey[0].id))
                        else:
                            alarm_fields['key'] = (alarmtype.translation(u'_bma_key_'), u'0')

                if alarm_fields.get('time', [u'', 0])[1] == 1:  # found correct time
                    t = datetime.datetime.strptime(alarm_fields.get('time', [u'', 0])[0], '%d.%m.%Y - %H:%M:%S')
                else:
                    t = datetime.datetime.now()
                alarm.timestamp = t

                alarm.set('id.key', alarm_fields['key'][1])
                alarm._key = alarm_fields['key'][0]
                alarm.material = dict(cars1='', cars2='', material='')  # set required attributes
                alarm.set('marker', '0')
                alarm.set('filename', kwargs['filename'])
                alarm.set('priority', '1')  # set normal priority
                alarm.set('alarmtype', alarmtype.name)  # set checker name
                alarm.position = _position
                alarm.state = 1

                # city
                if alarm_fields.get('city', ['', 0])[1] > 0:
                    alarm.city = City.getCities(id=alarm_fields.get('city')[1])
                    if alarm_fields.get('address'):
                        alarm.street = Street.getStreets(id=alarm_fields.get('address')[1])
                else:  # city not found -> build from fax
                    url = 'http://nominatim.openstreetmap.org/search'

                    if len(alarm_fields.get('city', [u'', 0])[0].split()) > 0:
                        params = u'format=json&city={}&street={}'.format(alarm_fields.get('city', [u'', 0])[0].split()[0], alarm_fields.get('address', [u'', 0])[0])
                        if alarm_fields.get('streetno'):
                            try:
                                params += u' {}'.format(alarm_fields.get('streetno')[0].split()[0])  # only first value
                            except:
                                pass
                            alarm.set('streetno', alarm_fields.get('streetno')[0])
                    try:
                        r = requests.get(u'{}?{}'.format(url, params))
                        logger.debug(u'load address data from nomination with parameters: city={} street={}'.format(alarm_fields.get('city')[0].split()[0], alarm_fields.get('address', ['', 0])[0]))
                        _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon'])
                        alarm.position = _position
                    except:
                        pass
                    if len(alarm_fields.get('city', ['', 0])[0].split()) > 0:
                        alarm.set('city', alarm_fields.get('city', ['', 0])[0].split()[0])
                    alarm.set('id.city', alarm_fields.get('city')[1])
                    alarm.set('address', alarm_fields.get('address', ['', 0])[0])
                    if alarm_fields.get('address', [u'', 0])[1] != 0:
                        alarm.street = Street.getStreets(id=alarm_fields.get('address')[1])

                    if alarm_fields.get('cars'):  # add cars found in material
                        for _c in alarm_fields.get('cars')[1].split(';'):
                            alarm.set('k.cars1', alarm.get('k.cars1') + ';' + _c)

                # street / street2
                if alarm_fields.get('address', [u'', 0]) != '':
                    # check correct city -> change if street has different city
                    if len(str(alarm_fields.get('address')[1]).split(';')) > 0 and alarm_fields.get('address')[1] != 0:
                        _c = []

                        for s in str(alarm_fields.get('address')[1]).split(';'):
                            _s = Street.getStreets(id=s)
                            if _s.cityid and _s.cityid not in _c and _s.cityid == alarm_fields.get('city', [u'', 0])[1]:
                                _c.append(_s.cityid)
                                alarm.street = _s
                                if alarm_fields.get('object', [u'', 0])[1] == 0:
                                    if not alarm_fields.get('lat') and not alarm_fields.get('lng'):
                                        alarm.position = dict(lat=_s.lat, lng=_s.lng, zoom=_s.zoom)
                                        if _position['lat'] != u'0.0' and _position['lng'] != u'0.0':  # set marker if nominatim delivers result
                                            alarm.position = _position
                                            alarm.set('marker', '1')
                    else:  # add unknown street
                        alarm.set('id.address', 0)
                        alarm.set('address', alarm_fields['address'][0])
                # houseno
                if alarm_fields.get('streetno'):
                    alarm.set('streetno', alarm_fields.get('streetno')[0])
                    if alarm_fields.get('id.streetno') and alarm_fields.get('lat') and alarm_fields.get('lng'):
                        alarm.position = dict(lat=alarm_fields.get('lat')[0], lng=alarm_fields.get('lng')[0])
                        alarm.set('id.streetno', alarm_fields.get('id.streetno')[1])
                    else:
                        # new
                        hn = alarm.street.getHouseNumber(name=alarm_fields.get('streetno')[0])
                        if hn:
                            alarm.position = hn.getPosition(0)
                    if alarm_fields.get('zoom'):
                        alarm.set('zoom', alarm_fields.get('zoom')[0])

                # crossing
                if alarm_fields.get('crossing', [u'', 0])[0] != '':
                    if alarm_fields.get('crossing', [u'', 0])[1] != alarm_fields.get('address',[u'', 0])[1]:
                        alarm.set('id.address2', alarm_fields.get('crossing')[1])
                        alarm.set('address2', alarm_fields.get('crossing')[0])
                    else:
                        alarm.set('id.address2', '0')
                        alarm.set('address2', alarm_fields.get('crossing')[0])

                # addresspart
                if alarm_fields.get('addresspart', [u'', 0])[0] != u'' and alarm_fields.get('addresspart', [u'', 0])[0] != alarm_fields.get('address', [u'', 0])[0]:
                    if alarm_fields.get('addresspart')[1] > 0:
                        if len(str(alarm_fields.get('addresspart')[1]).split(';')) > 0:
                            _c = []

                            for s in str(alarm_fields.get('addresspart')[1]).split(';'):
                                try:
                                    _s = Street.getStreets(id=s)
                                    if _s.cityid not in _c and _s.cityid == alarm_fields.get('city')[1]:
                                        _c.append(_s.cityid)
                                        alarm.set('id.address2', _s.id)
                                except:
                                    pass
                        else:
                            alarm.set('id.address2', alarm_fields.get('addresspart')[1])
                    else:
                        alarm.set('id.address2', '0')
                    alarm.set('address2', alarm_fields.get('addresspart')[0])

                # person
                if alarm_fields.get('person', [u'', 0])[0] != u'':
                    alarm.set('person', alarm_fields.get('person')[0])
                # alarmplan
                if alarm_fields.get('alarmplan', [u'', 0])[0] != u'':
                    alarm.set('alarmplan', alarm_fields.get('alarmplan')[0])

                # alarmobject
                _ao = None
                if alarm_fields.get('object', [u'', 0])[0] != u'' and alarm_fields.get('city', [u'', 0])[1] > 0:
                    alarm.set('object', alarm_fields.get('object')[0])
                    alarm.set('id.object', alarm_fields.get('object')[1])
                    # alarmplan from object
                    if alarm_fields.get('object')[1] != 0:
                        _ao = AlarmObject.getAlarmObjects(id=alarm_fields.get('object')[1])

                    if _ao:
                        if _ao.alarmplan != 0:
                            alarm.set('alarmplan', _ao.alarmplan)
                        elif alarm_fields.get('alarmplan'):
                            alarm.set('alarmplan', alarm_fields.get('alarmplan')[0])

                        if _ao.street.id != alarm_fields.get('address', [u'', 0])[1]:  # street config from alarmobject
                            alarm.street = Street.getStreets(id=_ao.street.id)
                            if _ao.streetno == "":
                                alarm.set('streetno', alarm_fields.get('streetno')[0])
                            else:
                                alarm.set('streetno', _ao.streetno)
                        alarm.position = dict(lat=_ao.lat, lng=_ao.lng, zoom=_ao.zoom)

                # remark
                if alarm_fields.get('remark', [u'', 0])[0] != u'':
                    alarm.set('remark', alarm_fields.get('remark')[0])
                    _bma = 0
                    for v in alarmtype.translation(u'_bma_main_').split():
                        if v in alarm_fields.get('remark', [u'', 0])[0] or v in alarm_fields.get('person', [u'', 0])[0]:
                            _bma = 1
                            break
                    if _bma == 1:
                        alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).first()
                        if alarmkey:
                            alarm.set('id.key', alarmkey.id)
                            alarm._key = u'{}: {}'.format(alarmkey.category, alarmkey.key)
                        else:
                            alarm.set('id.key', '0')
                            alarm._key = alarmtype.translation(u'_bma_key_')
                # additional remarks
                if alarm_fields.get('remark2', [u'', 0])[0] != u'':
                    alarm.set('remark', u'{}\n{}'.format(alarm.get('remark'), alarm_fields.get('remark2')[0]))

                # material
                if alarm.get('id.key') != 0 and alarm_fields.get('city'):  # found key with aao
                    if alarm_fields.get('city')[1] not in [0, -1]:  # default city
                        if Department.getDepartments(id=alarm.city.dept).defaultcity == alarm_fields.get('city')[1]:  # default city for dep
                            if alarm_fields.get('material'):
                                if str(alarm_fields.get('material')[1])[0] == '0':  # default cars for aao
                                    try:
                                        alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.street.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.street.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.street.city.dept)]))
                                    except AttributeError:
                                        alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)]))

                                for _c in u'{}'.format(alarm_fields.get('material')[1]).split(','):  # add additional cars
                                    if _c != '0' and _c not in alarm.get('k.cars1').split(','):
                                        alarm.set('k.cars1', u'{},{}'.format(alarm.get('k.cars1'), _c))

                        else:  # only alarmed material
                            alarm.material = dict(cars1=alarm_fields.get('material', [u'', ''])[1])

                    else:  # else city
                        if alarm_fields.get('material', [u'', u''])[1] == u'0':  # default cars for aao
                            alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)]))
                        else:
                            alarm.material = dict(cars1=u','.join(list(OrderedDict.fromkeys(filter(lambda x: x != '0', str(alarm_fields.get('material', ['', '-1'])[1]).split(','))))))

                else:  # default aao of current department (without aao)
                    if alarm_fields.get('city', [u'', 0])[1] != 0:  # found city -> use default aao
                        if City.getCities(id=alarm_fields.get('city')[1]):
                            c = City.getCities(id=alarm_fields.get('city')[1]).dept
                        else:
                            c = City.getDefaultCity().dept
                        akc = Alarmkey.getDefault(c)
                        if len(akc.cars1) + len(akc.cars2) + len(akc.materials) == 0:  # no default aao defined
                            # use cars of fax
                            alarm.material = {'cars1': re.sub(r'^0,', '', alarm_fields.get('material')[1]), 'cars2': '', 'material': ''}
                        else:  # use cars of default aao
                            alarm.material = dict(cars1=u','.join([str(c.id) for c in akc.cars1]), cars2=u",".join([str(c.id) for c in akc.cars2]), material=u",".join([str(c.id) for c in akc.materials]))

                    l = (u'{},{},{}'.format(alarm.get('k.cars1'), alarm.get('k.cars2'), alarm.get('k.material'))).split(',')
                    if len(set(str(alarm_fields.get('material', ([], '-1'))[1]).split(',')).intersection(set(l))) == 0:
                        _dep = Department.getDefaultDepartment()
                        for c in str(alarm_fields.get('material', ([], '-1'))[1]).split(','):
                            if c == u'0':  # default of home department needed
                                alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(_dep.id)]), cars2=u",".join([str(c.id) for c in alarm.key.getCars2(_dep.id)]), material=u",".join([str(c.id) for c in alarm.key.getMaterial(_dep.id)]))
                                break
                        if u'0' not in str(alarm_fields.get('material', ([], '-1'))[1]):  # only single car needed
                            alarm.set('k.cars1', u'{},{}'.format(alarm_fields.get('material', ([], '-1'))[1], alarm.get('k.cars1')))

                if _ao and _ao.hasOwnAAO():  # use aao of current object
                    alarm.material = dict(cars1=u",".join([str(c.id) for c in _ao.getCars1()]), cars2=u",".join([str(c.id) for c in _ao.getCars2()]), material=u",".join([str(c.id) for c in _ao.getMaterial()]))

                if not kwargs.get('time'):
                    kwargs['time'] = []
                kwargs['time'].append('alarm creation done in {} sec.'.format(etime - stime))

            if kwargs.get('mode') != 'test':
                db.session.add(alarm)
                db.session.commit()
                signal.send('alarm', 'added', alarmid=alarm.id)
                Alarm.changeState(alarm.id, 1)  # activate alarm
                logger.info('alarm created with id {} ({})'.format(alarm.id, (etime - stime)))
            else:

                _cdict = Car.getCarsDict()
                for a in sorted(alarm.attributes):
                    try:
                        if a in ['k.cars1', 'k.cars2', 'k.material']:
                            kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">id:</small> "%s" &rarr; "%s"</li>' % (a, alarm.get(a), ", ".join([_cdict[int(_c)].name for _c in alarm.get(a).split(',') if _c not in ['', '0']]))
                        elif a in 'id.key':
                            if alarm.get(a) > 0:
                                _k = Alarmkey.getAlarmkeys(id=alarm.get(a))
                                kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">id:</small> "%s" &rarr; "%s: %s"</li>' % (a, alarm.get(a), _k.category, _k.key)
                            else:
                                kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % (a, alarm.get(a))
                                kwargs['fields'] += '<li><b>key:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % alarm._key
                        elif a == 'id.address':
                            kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">id:</small> "%s" &rarr; "%s"</li>' % (a, alarm.get(a), Street.getStreets(id=alarm.get(a)).name)
                        elif a == 'id.object':
                            kwargs['id.object'] = '<li><b>%s:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % (a, alarm.get(a))
                            kwargs['object'] = '<li><b>object:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % alarm.get('object')
                        else:
                            kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % (a, alarm.get(a))
                    except (AttributeError, KeyError):
                        kwargs['fields'] += '<li style="color:red"><b>%s:</b>\n   <small style="color:silver">value:</small> "%s" (error)</li>' % (a, alarm.get(a))
                kwargs['fields'] += "</ul>"
                db.session.rollback()
                logger.info('alarm created in TESTMODE (%s)' % (etime - stime))
        except:
            signal.send('alarm', 'error', message='alarms.errorincreation', text=kwargs.get('text', ''))

        return kwargs
Esempio n. 19
0
 def getDefinedKeys(self):
     from emonitor.modules.alarmkeys.alarmkey import Alarmkey
     return Alarmkey.getAlarmkeys(keysetid=self.id)
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmkeys

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')

    if len(module) < 2:
        module.append(u'1')
    
    if len(module) > 2 and module[2] == 'upload':  # upload alarmkeys
        params.update({'': int(module[1]), 'department': module[1]})
        return render_template('admin.alarmkeys.upload.html', **params)
    
    else:
        depid = 1
        try:
            if int(module[1]):
                depid = int(module[1])
        except:
            pass
            
        if request.method == 'POST':
            if request.form.get('action') == 'adddefault':  # add default aao
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': 0})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'savedefault':  # save default aao
                alarmkeycar = AlarmkeyCars.getAlarmkeyCars(kid=9999, dept=request.form.get('deptid'))  # 9999 = default department
                if not alarmkeycar:  # add
                    alarmkeycar = AlarmkeyCars(9999, request.form.get('deptid'), '', '', '')
                    db.session.add(alarmkeycar)

                alarmkeycar.cars1 = request.form.get('cars1')
                alarmkeycar.cars2 = request.form.get('cars2')
                alarmkeycar.materials = request.form.get('material')
                if alarmkeycar.kid != 9999 and request.form.get('cars1') == request.form.get('cars2') == request.form.get('material') == '':  # remove
                    db.session.delete(alarmkeycar)
                db.session.commit()
                
            elif request.form.get('action') == 'editdefault':  # edit default aao
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': -1})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'addkey':  # add key
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': -2})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'savekey':  # save key
                if request.form.get('keyid') == 'None':  # add new
                    alarmkey = Alarmkey('', '', '', '')
                    db.session.add(alarmkey)
                    db.session.commit()

                else:  # update existing
                    alarmkey = Alarmkey.getAlarmkeys(request.form.get('keyid'))

                alarmkey.category = request.form.get('category')
                alarmkey.key = request.form.get('key')
                alarmkey.key_internal = request.form.get('keyinternal')
                alarmkey.remark = request.form.get('remark')
                alarmkey.setCars(int(request.form.get('deptid')), cars1=request.form.get('cars1'), cars2=request.form.get('cars2'), material=request.form.get('material'))
                db.session.commit()
                
            elif request.form.get('action').startswith('deletecars_'):  # delete car definition
                _op, _kid, _dept = request.form.get('action').split('_')
                keycar = AlarmkeyCars.getAlarmkeyCars(kid=_kid, dept=_dept)
                if keycar:
                    db.session.delete(keycar)
                    db.session.commit()

                # delete key if no definied cars
                if len(AlarmkeyCars.getAlarmkeyCars(kid=_kid)) == 0:
                    key = Alarmkey.getAlarmkeys(id=_kid)
                    db.session.delete(key)
                db.session.commit()
                
            elif request.form.get('action').startswith('editcars_'):  # edit key with cars
                _op, _kid, _dept = request.form.get('action').split('_')
                params.update({'alarmkey': Alarmkey.getAlarmkeys(id=_kid), 'depid': _dept, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': 1})
                return render_template('admin.alarmkeys_actions.html', **params)

        alarmkeys_count = []
        ak = Alarmkey
        counted_keys = db.get(ak.category.label('category'), func.count(ak.key).label('key'), ak.id.label('id')).group_by(ak.category)
        _sum = 0
        for r in counted_keys.all():
            alarmkeys_count.append([r.category, r.key, r.id])
            _sum += int(r.key)

        params.update({'alarmkeys_count': alarmkeys_count, 'depid': depid, 'defaultcars': Alarmkey.getDefault(depid), 'sum': _sum})
        return render_template('admin.alarmkeys.html', **params)
Esempio n. 21
0
def getAdminData(self):
    """
    Deliver admin content of module alarmkeys (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'loaddetails':  # details for given key
        return render_template('admin.alarmkeys.detail.html',
                               keys=Alarmkey.getAlarmkeysByCategoryId(
                                   request.args.get('category')),
                               department=request.args.get('department'))

    elif request.args.get('action') == 'upload':
        if request.files:
            uploadfile = request.files['uploadfile']
            filename = werkzeug.secure_filename(uploadfile.filename)
            fname = os.path.join(current_app.config.get('PATH_TMP'), filename)
            uploadfile.save(fname)
            xlsfile = XLSFile(fname)
            uploadfiles[uploadfile.filename] = xlsfile

            return render_template(
                'admin.alarmkeys.upload2.html',
                sheets=uploadfiles[uploadfile.filename].getSheets())

    elif request.args.get('action') == 'upload_sheet':  # sheet selector
        definitionfile = uploadfiles[request.args.get('filename')]
        return render_template('admin.alarmkeys.upload3.html',
                               cols=definitionfile.getCols(
                                   request.args.get('sheetname')))

    elif request.args.get('action') == 'testimport':  # build data for preview
        col_definition = {
            'dept': request.args.get('department'),
            'sheet': request.args.get('sheetname'),
            'category': request.form.get('category'),
            'key': request.form.get('key'),
            'keyinternal': request.form.get('keyinternal'),
            'remark': request.form.get('remark'),
            'cars1': request.form.getlist('cars1'),
            'cars2': request.form.getlist('cars2'),
            'material': request.form.getlist('material')
        }

        deffile = uploadfiles[request.args.get('filename')]
        vals = deffile.getValues(col_definition)
        return render_template('admin.alarmkeys.uploadpreview.html', vals=vals)

    elif request.args.get(
            'action') == 'doimport':  # do import and store values
        coldefinition = {
            'dept': request.args.get('department'),
            'sheet': request.args.get('sheetname'),
            'category': request.form.get('category'),
            'key': request.form.get('key'),
            'keyinternal': request.form.get('keyinternal'),
            'remark': request.form.get('remark'),
            'cars1': request.form.getlist('cars1'),
            'cars2': request.form.getlist('cars2'),
            'material': request.form.getlist('material')
        }
        deffile = uploadfiles[request.args.get('filename')]

        vals = deffile.getValues(coldefinition)
        states = []

        if request.form.get('add_material'):  # add new material
            p = re.compile(r'<.*?>')
            for k in vals['carsnotfound']:
                n_car = vals['carsnotfound'][k]
                n_car.name = p.sub('', n_car.name)
                if n_car.name == '':
                    continue
                db.session.add(n_car)
            db.session.commit()

        if request.form.get('add_new'):  # add new keys ( item state=-1)
            states.append('-1')

        if request.form.get(
                'add_update'):  # update existing keys (item state=1)
            states.append('1')

        for key in vals['keys']:  # item list
            if key['state'] in states:  # import only with correct state

                if key['state'] == '-1':  # add key
                    k = Alarmkey(key['category'], key['key'],
                                 key['keyinternal'], key['remark'])
                    db.session.add(k)
                    db.session.commit()
                    k.setCars(coldefinition['dept'],
                              cars1=";".join([str(c.id)
                                              for c in key['cars1']]),
                              cars2=";".join([str(c.id)
                                              for c in key['cars2']]),
                              materials=";".join(
                                  [str(c.id) for c in key['material']]))
                    db.session.commit()
                    key['state'] = '0'

                elif key['state'] == '1':  # update key
                    k = Alarmkey.getAlarmkeys(id=int(key['dbid']))
                    k.category = key['category']
                    k.key = key['key']
                    k.key_internal = key['keyinternal']
                    k.remark = key['remark']
                    k.setCars(coldefinition['dept'],
                              cars1=';'.join(filter(None, key['cars1_ids'])),
                              cars2=';'.join(filter(None, key['cars2_ids'])),
                              materials=';'.join(
                                  filter(None, key['material_ids'])))
                    db.session.commit()
        return ""

    elif request.args.get('action') == 'download':
        # build exportfile
        filename = buildDownloadFile(request.args.get('department'),
                                     request.args.get('options'))
        if filename != "":
            return filename

    elif request.args.get('action') == 'keyslookup':
        keys = {}

        for k in Alarmkey.getAlarmkeys():
            keys[str(k.id)] = '%s: %s' % (k.category, k.key)
        return keys

    elif request.args.get('action') == 'categorylookup':
        key = Alarmkey.getAlarmkeys(id=int(request.args.get('keyid')))
        return {'id': key.id, 'category': key.category}

    if "/download/" in request.url:  # deliver file
        filename = os.path.basename(request.url)
        mime = "application/x.download"
        if filename.endswith('.xlsx'):
            mime = "application/vnd.ms-excel"
        return send_from_directory("%s/" % current_app.config.get('PATH_TMP'),
                                   filename,
                                   as_attachment=True,
                                   mimetype=mime)
    return ""
Esempio n. 22
0
 def getDefinedKeys(self):
     from emonitor.modules.alarmkeys.alarmkey import Alarmkey
     return Alarmkey.getAlarmkeys(keysetid=self.id)