Exemplo n.º 1
0
def login():
    if request.method == "GET":
        if User.logged_in_user() is None:
            abort(403)
        elif User.logged_in_user() == "tecvest@1010":
            return render_template('admin_home.html')

        else:
            return render_template("enter_data.html")

    elif request.method == "POST":
        username = request.form['username']
        password = request.form['password']
        user_obj = User.query.filter_by(username=username).first_or_404()
        if user_obj.passwordhash != password:
            add_log(username, "Unsuccessful Try to login")
            abort(403)

        user_obj.login()
        add_log(username, "Login")
        if username == "tecvest@1010":
            return render_template('admin_home.html')
        else:
            return render_template("enter_data.html")
    else:

        abort(405)
Exemplo n.º 2
0
def createTask(number, sys_id, EXELA_QUEUE, title, task_description, impact,
               urgency, prio, company):

    url = HOST + '/api/now/table/u_incident_task'
    headers = {
        "Content_Type": "application/json",
        "Accept": "application/json"
    }

    u_error_type = TaskErrorType.get(prio, '')

    if not u_error_type:
        u_error_type = '4 - Low - Other'

    d = json.dumps({
        "assignment_group": EXELA_QUEUE,
        "u_incident": sys_id,
        "short_description": title,
        "description": task_description,
        "impact": impact,
        "urgency": urgency,
        "u_error_type": u_error_type,
        "company": company
    })

    response = requests.post(url, auth=(USR, PWD), headers=headers, data=d)

    if response.status_code == 400:
        log.add_log(number + ':task creation error')

    return response.json()['result']['sys_id']
Exemplo n.º 3
0
def getCasesFromQueue(
):  #build list of tasks to be processed, first validation, if it is B2B request. If yes add to list, if not
    url = HOST + '/api/now/table/task?sysparm_query=' + 'assignment_group=' + ROBOT_GROUP + '^stateIN-6,1,2^numberSTARTSWITHOCRITM^short_descriptionLIKEiAddress'  ###check URL
    response = getDataFromOpusFlow(url)
    lista = list()

    if response != '':
        temp = response.get('result', None)
        if temp:
            for element in temp:
                if "Request for new B2B e-invoice routing to iAddress" in element.get(
                        'short_description'):
                    lista.append(element.get('sys_id', None))
                    assignToRoger(element.get('sys_id', None))
                else:
                    #oddaj do CS, z informacja, ze to nie jest
                    message = returnToCS(
                        element.get('sys_id', None),
                        'Based on short description, this is not B2B routing request',
                        0)
                    if message == 'ERROR':
                        #zaloguj ze nie mozesz oddac do CS, a to nie jest request B2B
                        log.add_log(
                            element.get('sys_id', None) + ':' +
                            element.get('number', None) +
                            ':: this is not B2B reques, problem with returning it to CS'
                        )
        return lista
    else:
        return lista
Exemplo n.º 4
0
def create_log(dbo, user, mid, logcode = "UK00", message = ""):
    """
    Creates a log message related to media
    mid: The media ID
    logcode: The fixed code for reports to use - 
        ES01 = Document signing request
        ES02 = Document signed
    message: Some human readable text to accompany the code
    """
    m = dbo.first_row(get_media_by_id(dbo, mid))
    if m is None: return
    logtypeid = configuration.generate_document_log_type(dbo)
    log.add_log(dbo, user, get_log_from_media_type(m.LINKTYPEID), m.LINKID, logtypeid, "%s:%s:%s - %s" % (logcode, m.ID, message, m.MEDIANOTES))
Exemplo n.º 5
0
def html_mass_edit(backlog_text = None, action = None):
	html = '''<style>
		#backlog {
			background-color:#FFF;
			border:4px solid #5599DD;
			margin:10px;
			margin-top:16px;
			padding:3px;
		}
		#massedit {
			margin:10px;
			margin-top:32px;
		}
	</style>'''
	if backlog_text is not None:
		html += '<table id="backlog" width="96%" border=1 style="margin:32px">'
		html += '<tr><td width="8%"><b>category</b></td><td width="60%"><b>log</b></td><td width="16%"><b>time</b></td><td width="16%"><b>location</b></td></tr>'
		backlog_lines = backlog_text.split('\n')
		for l in backlog_lines:
			logstring = re.compile('^log ').split(l)[-1]
			(logstring, time0, gps, category) = log.process_log_string(logstring, 'log', False)
			print gps
			if gps[0] is None:	location = '<font color="#FF0000">none</font>'
			else:				location = '%0.3f, %0.3f' % gps
			html += '<tr><td>'+category+'</td><td>'+logstring+'</td><td>'+time0+'</td><td>'+location+'</td></tr>'
			if action=='addtolog':	
				log.add_log(logstring, time0, gps, category)
		html += '</table><p>'
	if action != 'addtolog':
		last_log = util.query_db('SELECT rowid, time, log FROM events ORDER BY time DESC LIMIT 1')
		html += '<p><div id="massedit">'
		for l in last_log:	html += '<br>&nbsp;&nbsp;&nbsp;'+str(l[0])+' ('+l[1][:-3]+')  ::  '+l[2]
		html += '''<form name="editor" action="" method="post">
		<textarea id="backlog" name="backlog" cols=110 rows=30 maxlength=2500>'''
		if backlog_text is not None:
			html += backlog_text
		html += '''</textarea><p/>
		<select name="action">
			<option value="validate">validate</option>
			<option value="addtolog">add to log</option>
		</select>
		<input type="submit" value="Submit">&nbsp;&nbsp;&nbsp;&nbsp;
		<input type="button" value="Save" id="save">
		<a href="javascript:removeLimit();">[remove limit]</a>
		</form>
		</div>
		'''
	else:
		html += '<p><a href="/">back</a>'
	return html
Exemplo n.º 6
0
def main():

    worknotes = ''
    logs = ''

    lista = getDataFromQueue()
    for element in lista:

        number = element.get('number', '')
        sys_id = element.get('sys_id', '')
        title = element.get('short_description', '')
        description = element.get('description', '')
        impact = element.get('impact', '')
        urgency = element.get('urgency', '')
        prio = element.get('priority', '')
        company = element.get('company', '').get('value', '')  ##
        print(number)

        workInProgress(sys_id)
        if log.exists(number):
            returnToCS(sys_id, CS_SE_QUEUE,
                       "Hi,this ticket was processed before, please check.")
            continue

        if title:
            translate_title = MS_translate(title)
        else:
            translate_title = title

        if description:
            translate_description = MS_translate(description)
        else:
            translate_description = description

        if translate_title == 'ERROR' or translate_description == 'ERROR':
            returnToCS(sys_id, "Translation problem, please hadle manually.")
            log.add_log(number + ':translation ERROR')

        task_description = createDescription(translate_title,
                                             translate_description)
        task_id = createTask(number, sys_id, EXELA_QUEUE, title,
                             task_description, impact, urgency, prio, company)

        copyAttachments(sys_id, task_id)
        returnAsAwaiting3rdParty(sys_id, CS_SE_QUEUE)

        log.add_log(number + ':' + sys_id + ':' + ':processed')
        sleep(10)
Exemplo n.º 7
0
def results():
    log = add_log()
    if not session:
        log.warning('Brak sesji')

        return redirect('/login')

    if request.method == 'GET':
        if session['is_admin'] == False:
            if session['only_results'] == True:
                log.info(f'Użytkowanik {session} wyświetlił wyniki')
                every_results = prepare_data_with_every_answers()
                context = {'results': every_results}
                print(session)
                return render_template('only_results.html', **context)

            else:
                user = session['user']
                log.warning(
                    f'Użytkowanik {user} próbował się dostać do bazy wyników')
                print(session)
                return redirect('/ankieta')

        elif session['is_admin'] == True:
            every_results = prepare_data_with_every_answers()
            context = {'results': every_results}
            log.info(f'Wszytskie results obliczeń: {every_results}')
            print(session)
            return render_template('results.html', **context)

        return redirect('/login')
Exemplo n.º 8
0
def pin_verify():
    log = add_log()
    if request.method == 'GET':
        message_pin = get_flashed_messages()
        return render_template('pin.html', message_pin=message_pin)

    if request.method == 'POST':
        conn = connect()
        c = conn.cursor()

        pin = request.form['check']
        log.info(f'Wpisano PIN {pin}')
        # print('pin: ', pin)

        query_pin = """
                        SELECT password FROM "pin" WHERE id = ?;
                        """
        id_pin = 1
        c.execute(query_pin, (id_pin,))
        line_from_base = c.fetchone()
        # print('pin:', line_from_base)

        if line_from_base:
            pin_hash = line_from_base['password']
            if check_password_hash(pin_hash, pin):
                session['pin'] = True
                log.info(f'PIN jest poprawny')
                return redirect('/register')

        flash('Błędny PIN')
        return redirect('/pin')
Exemplo n.º 9
0
def send_email_from_form(dbo, username, data):
    """
    Sends an email to a person from a posted form. Attaches it as
    a log entry if specified.
    """
    emailfrom = utils.df_ks(data, "from")
    emailto = utils.df_ks(data, "to")
    emailcc = utils.df_ks(data, "cc")
    subject = utils.df_ks(data, "subject")
    ishtml = utils.df_kc(data, "html")
    addtolog = utils.df_kc(data, "addtolog")
    logtype = utils.df_ki(data, "logtype")
    body = utils.df_ks(data, "body")
    utils.send_email(dbo, emailfrom, emailto, emailcc, subject, body, ishtml == 1 and "html" or "plain")
    if addtolog == 1:
        log.add_log(dbo, username, log.PERSON, utils.df_ki(data, "personid"), logtype, body)
def delete():
    lg = add_log()
    if not session:

        lg.warning('Brak sesji')

        return redirect('/login')

    if session['is_admin'] == False:
        user = session['user']

        lg.warning(f'Użytkownik {user} próbował usunąć pytanie  ')

        return redirect('/ankieta')

    conn = connect()
    c = conn.cursor()

    query = """
        DELETE FROM "questions" WHERE id = ?;
        """
    delate_question = request.args.get('id')
    # print(delate_question)

    c.execute(query, (delate_question, ))

    conn.commit()
    conn.close()

    lg.info(f'Usunięcie pytania z bazy o numerze id: {delate_question}')

    return redirect('/baza')
def create_admin():
    lg = add_log()
    conn = sqlite3.connect('questionDataBase.db')
    c = conn.cursor()

    query = """
    INSERT INTO "login" ("id", "user", "password", "admin") 
    VALUES (NULL, ?, ?, ?)"""

    login = input('Wpisz login: '******'Wpisz hasło: ')

    password_hash = generate_password_hash(password)
    # print('Login: '******'Haslo: ', password)
    admin = 1
    # admin = input('Czy użytkownik ma mieć uprawnienia "Admin" [T lub N]: ')
    # if admin == 'T' or 't':
    #     admin = 'true'
    # else:
    #     admin = 'false'
    c.execute(query, (login, password_hash, admin))
    conn.commit()
    conn.close()
    lg.debug(
        f'Stworzenie konta admina o loginie: {login} i haśle: {password_hash}')
    return
def logout():
    log = add_log()
    session.clear()

    log.warning('Wylogowanie')

    return redirect('/')
Exemplo n.º 13
0
def send_email_from_form(dbo, username, post):
    """
    Sends an email to a lost/found person from a posted form. Attaches it as
    a log entry if specified.
    """
    emailfrom = post["from"]
    emailto = post["to"]
    emailcc = post["cc"]
    subject = post["subject"]
    ishtml = post.boolean("html")
    addtolog = post.boolean("addtolog")
    logtype = post.integer("logtype")
    body = post["body"]
    rv = utils.send_email(dbo, emailfrom, emailto, emailcc, subject, body, ishtml == 1 and "html" or "plain")
    if addtolog == 1:
        log.add_log(dbo, username, post["lfmode"] == "lost" and log.LOSTANIMAL or log.FOUNDANIMAL, post.integer("lfid"), logtype, body)
    return rv
Exemplo n.º 14
0
def send_email_from_form(dbo, username, data):
    """
    Sends an email to a person from a posted form. Attaches it as
    a log entry if specified.
    """
    emailfrom = utils.df_ks(data, "from")
    emailto = utils.df_ks(data, "to")
    emailcc = utils.df_ks(data, "cc")
    subject = utils.df_ks(data, "subject")
    ishtml = utils.df_kc(data, "html")
    addtolog = utils.df_kc(data, "addtolog")
    logtype = utils.df_ki(data, "logtype")
    body = utils.df_ks(data, "body")
    utils.send_email(dbo, emailfrom, emailto, emailcc, subject, body,
                     ishtml == 1 and "html" or "plain")
    if addtolog == 1:
        log.add_log(dbo, username, log.PERSON, utils.df_ki(data, "personid"),
                    logtype, body)
Exemplo n.º 15
0
def log_in():
    log = add_log()

    if request.method == 'GET':
        messages = get_flashed_messages()
        return render_template('log_in.html', messages=messages)

    if request.method == 'POST':

        username = request.form['username']
        password = request.form['password']

        conn = connect()
        c = conn.cursor()
        # print('user: '******'password: '******'passwords:', password, line_from_base)
        only_results = ['codeme', 'alek']

        if line_from_base:
            password_hash = line_from_base['password']
            if check_password_hash(password_hash, password):
                print(session)
                log.info(f'poprawne logowanie user: {username}')

                session['user_id'] = line_from_base['id']
                session['user'] = line_from_base['user']
                session['is_admin'] = bool(line_from_base['admin'])

                if username in only_results:
                    session['is_admin'] = False
                    session['only_results'] = True
                    session['pin'] = False
                    return redirect('/wyniki')

                if line_from_base['admin']:
                    log.info(f'konto admina: {username}')
                    session['only_results'] = False
                    return redirect('/dodaj')

                else:
                    user = session['user']
                    session['only_results'] = False
                    log.info(f'konto użytkownika: {user}')

                    return redirect('/ankieta')

        flash('Błędna nazwa użytkownika lub hasło')

        log.warning(f'Błedna nazwa użytkownika "{username}" lub hasło "{password}"')

        return redirect('/login')
Exemplo n.º 16
0
def send_email_from_form(dbo, username, post):
    """
    Sends an email to a lost/found person from a posted form. Attaches it as
    a log entry if specified.
    """
    emailfrom = post["from"]
    emailto = post["to"]
    emailcc = post["cc"]
    emailbcc = post["bcc"]
    subject = post["subject"]
    ishtml = post.boolean("html")
    addtolog = post.boolean("addtolog")
    logtype = post.integer("logtype")
    body = post["body"]
    rv = utils.send_email(dbo, emailfrom, emailto, emailcc, emailbcc, subject, body, ishtml == 1 and "html" or "plain")
    if addtolog == 1:
        log.add_log(dbo, username, post["lfmode"] == "lost" and log.LOSTANIMAL or log.FOUNDANIMAL, post.integer("lfid"), logtype, body)
    return rv
def register():
    log = add_log()
    print(session)

    if request.method == 'GET':

        if session:
            if not session['pin']:
                session.clear()
                return redirect('/login')

            if session['pin']:
                validator = get_flashed_messages()
                double_user = get_flashed_messages()
                return render_template('register_user.html',
                                       validator=validator,
                                       double_user=double_user)

        return redirect('/login')

    if request.method == 'POST':

        username = request.form['username']
        password = request.form['password']
        password2 = request.form['password2']
        log.info('Wprowadzono wszytskie dane do formularza')
        # print('user: '******'password: '******'pasword2: ', password2)

        if password == password2:
            log.info('Walidacja hasła przebiegła pomyślnie')
            conn = connect()
            c = conn.cursor()

            password_hash = generate_password_hash(password)
            isn_admin = 0
            query = """
                        INSERT INTO "login" ("id", "user", "password", "admin") VALUES (NULL, ?, ?, ?);"""

            try:
                c.execute(query, (username, password_hash, isn_admin))

            except sqlite3.IntegrityError:
                double_user = flash('Ten login już istnije')
                log.warning('Ten login już istnieje w bazie')
                return redirect('/register')

            conn.commit()
            # print('dane:', username, password)
            log.info('Prawidłowa rejestracja użytkowanika')
            return redirect('/login')

        else:
            flash('Wpisane hasła nie są identyczne')
            log.warning('Wpisane hasła nie są identyczne')
            return redirect('/register')
Exemplo n.º 18
0
def verify_number_of_every_questions():
    conn = connect()
    c = conn.cursor()
    log = add_log()
    query = """
    SELECT id, question FROM "questions";
    """
    c.execute(query)
    list_of_id = c.fetchall()

    log.info('Sprawdznie ilości wszystkich pytań')

    return list_of_id
def add():
    lg = add_log()
    if not session:
        lg.warning('Brak sesji')

        return redirect('/login')

    if session['is_admin'] == False:
        user = session['user']

        lg.info(f'Konto użytkowanika: {user}')

        return redirect('/ankieta')

    if request.method == 'GET':
        if session['is_admin'] == True:
            # session.pop('_flashes', None)
            added = get_flashed_messages()
            return render_template('input_question.html', added=added)

    if request.method == 'POST':

        conn = connect()
        c = conn.cursor()

        question = request.form['question']

        lg.info(f'Dodano pytanie: "{question}" do bazy danych')

        author = session['user_id']
        user = session['user']

        # print(type(question))

        if question == '':
            lg.warning(f'{user} próbował wprowdzić buste pytanie')

            return redirect('/dodaj')

        add_question = """
        INSERT INTO "questions" ("id", "id_user", "question", "type") VALUES (NULL, ?, ?,'tn')"""

        parameters = (author, question)
        # print(parameters)

        c.execute(add_question, parameters)
        conn.commit()
        flash('Pytanie zapisano w bazie')

        return redirect('/dodaj')
def execute_script_sql(database='questionDataBase.db',
                       script='data_sql_creating.sql'):
    lg = add_log()
    conn = sqlite3.connect(database)
    c = conn.cursor()
    with open(script, encoding='utf-8') as f:
        query = f.read()
    c.executescript(query)
    conn.commit()
    conn.close()
    lg.debug(
        f'Stworzenie bazy danych o nazwie: {database} przy użyciu skryptu: {script}'
    )
    return
Exemplo n.º 21
0
def id_question_whith_answer():
    conn = connect()
    c = conn.cursor()
    log = add_log()

    log.info('Sprawdzenie listy id pytań z odpowiedziami')

    query_one = """
    SELECT id_question FROM "answers" GROUP BY id_question;
    """
    c.execute(query_one)
    list_of_id_question = c.fetchall()
    # print(list_of_id_question)

    return list_of_id_question
Exemplo n.º 22
0
def answers_of_question(id_question):
    conn = connect()
    c = conn.cursor()
    log = add_log()

    query_two = """
    SELECT id_question, answer, question FROM "answers" WHERE id_question = ?;"""
    # INNER JOIN "questions" ON answers.id_question = questions.id WHERE id_question = ?;"""

    c.execute(query_two, (id_question, ))
    answers_in_data = c.fetchall()
    # print(answers_in_data)

    log.info(f'Pobranie odpowiedzi do pytania: {id_question}')

    return answers_in_data
Exemplo n.º 23
0
def verify_questions_without_answer(
        list_of_answers=id_question_whith_answer(),
        list_of_every_questions=verify_number_of_every_questions()):
    log = add_log()
    log.warning('sprawdzenie pytań bez odpowiedzi')

    for i in list_of_answers:
        # print(i)
        # print(list_of_answers)
        for element in list_of_every_questions:
            # print(element)
            if i[0] == element[0]:
                list_of_every_questions.remove(element)
    # print('lista do dodania: ', list_of_every_questions)

    return list_of_every_questions
def create_pin_for_users():
    lg = add_log()
    conn = sqlite3.connect('questionDataBase.db')
    c = conn.cursor()

    query = """
    INSERT INTO "pin" ("id", "password") 
    VALUES (NULL, ?)"""

    pin = input('Wpisz pin: ')

    pin_hash = generate_password_hash(pin)
    # print('pin: ', pin_hash)
    c.execute(query, (pin_hash, ))
    conn.commit()
    conn.close()
    lg.debug(f'Tworzę pin do rejestracji użytkowników: {pin}')
    return
Exemplo n.º 25
0
def add_to_results_questions_without_answer(
        list_without_answers=verify_questions_without_answer()):
    results = []
    log = add_log()
    for question in list_without_answers:
        id_question = question[0]
        question = question[1]
        result_no_answer = {
            'id_question': id_question,
            'question': question,
            'answer_yes': '0,00 %',
            'answer_no': '0,00 %'
        }
        results.append(result_no_answer)

        log.warning(
            f'Dodanie do wyników pytania bez odpowiedzi: {result_no_answer}')
    # print(results)
    return results
Exemplo n.º 26
0
def index():
    log = add_log()

    if not session:
        log.warning('Brak sesji')

        return redirect('/login')

    if session['is_admin'] == False:
        log.info('Konto użytkownika')

        return redirect('ankieta')

    log.info('Konto admina')

    id = session.get('user_id')
    user = session.get('user')
    is_admin = session.get('is_admin')
    # print('id: ', id, 'user: '******'is admin: ', is_admin)

    return redirect('/dodaj')
Exemplo n.º 27
0
def count_answers(answers_y_or_no):
    log = add_log()
    answer_yes, answer_no = 0, 0
    for id_question, answer, question in answers_y_or_no:
        if answer == 'T':
            answer_yes += 1
        if answer == 'N':
            answer_no += 1
        question = question
        every_answer = answer_yes + answer_no
    result_y_n = {
        'id_question': id_question,
        'question': question,
        'answer_yes': answer_yes,
        'answer_no': answer_no,
        'every_answer': every_answer
    }
    # print(result_y_n)

    log.info(f'Policzenie odpowiedzi dla {result_y_n}')

    return result_y_n
Exemplo n.º 28
0
def data():
    log = add_log()
    if not session:
        log.warning('Brak sesji')

        return redirect('/login')

    conn = connect()
    c = conn.cursor()

    query = """
    SELECT id, question FROM "questions";
    """
    c.execute(query)
    questions = c.fetchall()
    # print(questions)

    dict = {}

    for x in questions:
        # print(x)
        add_to_dict = {x[0]: x[1]}
        dict.update(add_to_dict)
    # print(dict)

    context = {'questions': dict}

    if session['is_admin'] == True:

        log.info('Konto admin')

        return render_template('data.html', **context)
    else:
        user = session['user']

        log.warning(f'Użytkowanik {user} próbował się dostać do bazy pytań')

        return redirect('/ankieta')
Exemplo n.º 29
0
def percentage_share(i):
    log = add_log()
    sum_of_question = i['answer_yes'] + i['answer_no']
    answer_yes = (i['answer_yes'] / sum_of_question) * 100
    answer_yes = f'{answer_yes:.2f} %'
    answer_yes = answer_yes.replace('.', ',')
    id_question = i['id_question']
    answer_no = (i['answer_no'] / sum_of_question) * 100
    answer_no = f'{answer_no:.2f} %'
    answer_no = answer_no.replace('.', ',')
    question = i['question']
    every_answer = i['every_answer']
    result_percent = {
        'id_pytania': id_question,
        'question': question,
        'answer_yes': answer_yes,
        'answer_no': answer_no,
        'every_answer': every_answer
    }

    log.info(f'Dokonuję obliczeń procentowych: {result_percent}')

    return result_percent
Exemplo n.º 30
0
        req, hdr, response = utils.post_multipart(
            fb_url,
            (("message", utils.decode_html(posttext).encode("utf-8")), ),
            (("source", "pic.jpg", imagedata), ))
        al.debug("FB response: %s" % response, "social.post_animal_facebook",
                 dbo)

        # If the option is on and all was ok, make a note in the log
        if configuration.facebook_log(dbo):
            al.debug(
                "FB writing entry to animal log: %s %s" %
                (a["SHELTERCODE"], a["ANIMALNAME"]),
                "social.post_animal_facebook", dbo)
            log.add_log(
                dbo, user, log.ANIMAL, utils.cint(oauth_state[1:]),
                configuration.facebook_log_type(dbo),
                _("{0} {1}: posted to Facebook page {2} by {3}",
                  l).format(a["SHELTERCODE"], a["ANIMALNAME"], page_name,
                            user))

    except urllib2.HTTPError, herr:
        em = str(herr.read())
        al.error("Failed posting photo to facebook: %s" % em,
                 "social.post_animal_facebook", dbo, sys.exc_info())
        raise utils.ASMValidationError(
            "Failed posting photo and details to Facebook (http).")
    except Exception, err:
        em = str(err)
        al.error("Failed posting photo to facebook: %s" % em,
                 "social.post_animal_facebook", dbo, sys.exc_info())
        raise utils.ASMValidationError(
            "Failed posting photo and details to Facebook.")
def form():
    log = add_log()

    if not session:
        log.warning('Brak sesji')

        return redirect('/login')

    if session:
        if session['only_results']:
            session.clear()
            return redirect('/')

        elif session['is_admin'] == False:

            if request.method == 'GET':
                conn = connect()
                c = conn.cursor()

                question = """
                    SELECT id, question FROM "questions";
                    """
                c.execute(question)
                questions = c.fetchall()
                # print(questions)

                dictionary = {}
                for x in questions:
                    # print(x)
                    add_to_dict = {x[0]: x[1]}
                    dictionary.update(add_to_dict)
                # print(dictionary)

                log.info(f'Prezentuję formulrz z pytaniami: {dictionary}')

                context = {'questions': dictionary}

                return render_template('form_for_user.html', **context)

            if request.method == 'POST':
                conn = connect()
                c = conn.cursor()

                answers = dict(
                    (key,
                     request.form.getlist(key) if len(request.form.getlist(
                         key)) > 1 else request.form.getlist(key)[0])
                    for key in request.form.keys())

                # print(answers)
                log.info(f'Przechwytywanie odpowiedzi formularza: {answers}')

                answers_dict = {}
                for k, v in answers.items():
                    id = k.strip(' answer')
                    odp = v[-1]
                    answers_dict[id] = odp
                # print(answers_dict)

                log.info(f'Tworzenie słownika z odpowiedziami: {answers_dict}')

                for key, volume in answers_dict.items():
                    add_answers_to_data = """
                            INSERT INTO "answers" ("id", "id_user", "id_question", "question", "answer", "is_answer") VALUES (NULL, ?, ?, ?, ?, ?);
                            """
                    id_user = session.get('user_id')
                    id_question = key

                    query = """
                                SELECT question FROM "questions" WHERE id = ?;
                                """
                    c.execute(query, (id_question, ))
                    answer_to_the_question = c.fetchone()
                    print(list(answer_to_the_question))
                    question = answer_to_the_question[0]
                    print(question)
                    answer = volume
                    is_answer = 1
                    # print(add_answers_to_data)

                    try:
                        c.execute(add_answers_to_data,
                                  (id_user, id_question, question, answer,
                                   is_answer))
                        log.info('Zapisanie odpowedzi do bazy danych')
                        conn.commit()

                    except sqlite3.OperationalError:
                        conn.close()

                        log.warning(
                            'SQLite3 zwrócił błąd: OperationalError i nastąpiło przekierowanie do /ankieta'
                        )

                        return redirect('/ankieta')

                    except sqlite3.IntegrityError:

                        log.warning(
                            'SQLite3 zwrócił błąd: IntegrityError i nastąpiło przekierowanie do strony startowej'
                        )

                        redirect('/')

                session.clear()

                log.info(
                    'Nastąpiło wypełnineie ankiety oraz prawidłowy zapis w bazie danych'
                )

                return render_template('thank_you.html')
Exemplo n.º 32
0
    template = configuration.facebook_template(dbo)
    posttext = wordprocessor.substitute_tags(template, tags, False, "$$", "$$")

    # Post on the wall
    try:

        l = dbo.locale
        fb_url = "https://graph.facebook.com/%s/photos?access_token=%s" % (post_to, access_token)
        al.debug("FB posting photo and text '%s' to '%s' at %s" % (posttext, page_name, fb_url), "social.post_animal_facebook", dbo)
        imagedata = dbfs.get_string(dbo, a["WEBSITEMEDIANAME"])
        req, hdr, response = utils.post_multipart(fb_url, ( ("message", utils.decode_html(posttext).encode("utf-8")),), ( ("source", "pic.jpg", imagedata), ))
        al.debug("FB response: %s" % response, "social.post_animal_facebook", dbo)

        # If the option is on and all was ok, make a note in the log
        if configuration.facebook_log(dbo):
            al.debug("FB writing entry to animal log: %s %s" % (a["SHELTERCODE"], a["ANIMALNAME"]), "social.post_animal_facebook", dbo)
            log.add_log(dbo, user, log.ANIMAL, utils.cint(oauth_state[1:]), configuration.facebook_log_type(dbo),
                _("{0} {1}: posted to Facebook page {2} by {3}", l).format(a["SHELTERCODE"], a["ANIMALNAME"], page_name, 
                user))

    except urllib2.HTTPError,herr:
        em = str(herr.read())
        al.error("Failed posting photo to facebook: %s" % em, "social.post_animal_facebook", dbo, sys.exc_info())
        raise utils.ASMValidationError("Failed posting photo and details to Facebook (http).")
    except Exception,err:
        em = str(err)
        al.error("Failed posting photo to facebook: %s" % em, "social.post_animal_facebook", dbo, sys.exc_info())
        raise utils.ASMValidationError("Failed posting photo and details to Facebook.")


Exemplo n.º 33
0
def handler(dbo, user, post):
    """
    Handles posts from the frontend. Depending on the type we either
    return more HTML for the javascript to inject, or GO URL to have
    the controller redirect to URL
    """
    l = dbo.locale
    homelink = "<a href='mobile' class='ui-btn-right' data-icon='home' data-theme='b'>%s</a>" % _(
        "Home", l)
    mode = post["posttype"]
    pid = post.integer("id")
    animalid = post.integer("animalid")

    if mode == "vacc":
        # We're vaccinating an animal
        a = animal.get_animal(dbo, animalid)
        medical.update_vaccination_today(dbo, user, pid)
        return jqm_page_header("", _("Vaccination Given", l), homelink) + \
            jqm_p(_("Vaccination marked as given for {0} - {1}", l).format(a["ANIMALNAME"], a["SHELTERCODE"])) + \
            jqm_button("mobile#vacc", _("More Vaccinations", l), "", "false") + \
            jqm_page_footer()

    if mode == "test":
        # We're performing a test on an animal
        a = animal.get_animal(dbo, animalid)
        medical.update_test_today(dbo, user, pid, post.integer("resultid"))
        return jqm_page_header("", _("Test Performed", l), homelink) + \
            jqm_p(_("Test marked as performed for {0} - {1}", l).format(a["ANIMALNAME"], a["SHELTERCODE"])) + \
            jqm_button("mobile#test", _("More Tests", l), "", "false") + \
            jqm_page_footer()

    elif mode == "med":
        # We're treating an animal
        a = animal.get_animal(dbo, animalid)
        medical.update_treatment_today(dbo, user, pid)
        return jqm_page_header("", _("Treatment Given", l), homelink) + \
            jqm_p(_("Treatment marked as given for {0} - {1}", l).format(a["ANIMALNAME"], a["SHELTERCODE"])) + \
            jqm_button("mobile#med", _("More Medications", l), "", "false") + \
            jqm_page_footer()

    elif mode == "dia":
        # We're completing a diary task
        d = diary.get_diary(dbo, pid)
        if post["on"] == "0":
            diary.complete_diary_note(dbo, user, pid)
            return jqm_page_header("", _("Completed", l), homelink) + \
                jqm_p(_("Diary note {0} marked completed", l).format(d["SUBJECT"])) + \
                jqm_button("mobile#diary", _("More diary notes", l), "", "false") + \
                jqm_page_footer()
        else:
            diary.rediarise_diary_note(dbo, user, pid, post.date("on"))
            return jqm_page_header("", _("Rediarised", l), homelink) + \
                jqm_p(_("Diary note {0} rediarised for {1}", l).format(d["SUBJECT"], post["on"])) + \
                jqm_button("mobile#diary", _("More diary notes", l), "", "false") + \
                jqm_page_footer()

    elif mode == "dianew":
        # We're adding a diary note
        diary.insert_diary(dbo, user, 0, 0, post.date("diarydate"),
                           post["diaryfor"], post["subject"], post["note"])
        return "GO mobile"

    elif mode == "message":
        # We're adding a message
        lookups.add_message(dbo, user, post.boolean("email"), post["message"],
                            post["forname"], post.integer("priority"),
                            post.date("expires"))
        return "GO mobile"

    elif mode == "log":
        # We're adding a log to an animal
        a = animal.get_animal(dbo, animalid)
        log.add_log(dbo, user, log.ANIMAL, animalid, post.integer("logtypeid"),
                    post["logtext"])
        return "GO mobile"

    elif mode == "hc":
        # We're marking an owner homechecked
        person.update_pass_homecheck(dbo, user, post.integer("personid"),
                                     post["comments"])
        return "GO mobile"

    elif mode == "vsa":
        # Return a list of the shelter animals
        h = []
        alin = []
        h.append(header(l))
        h.append(jqm_page_header("", _("Shelter Animals", l), homelink))
        an = animal.get_animal_find_simple(dbo, "", "all")
        for a in an:
            alin.append(
                jqm_listitem_link(
                    "mobile_post?posttype=va&id=%d" % a["ID"],
                    "%s - %s (%s %s %s) %s" %
                    (a["CODE"], a["ANIMALNAME"], a["SEXNAME"], a["BREEDNAME"],
                     a["SPECIESNAME"], a["IDENTICHIPNUMBER"]), "animal"))
        h.append(jqm_list("\n".join(alin), True))
        h.append(jqm_page_footer())
        h.append("</body></html>")
        return "\n".join(h)

    elif mode == "uai":
        # Upload an animal image
        media.attach_file_from_form(dbo, user, media.ANIMAL, animalid,
                                    post.data)
        return "GO mobile_post?posttype=va&id=%d&success=true" % animalid

    elif mode == "va":
        # Display a page containing the selected animal by id
        a = animal.get_animal(dbo, pid)
        af = additional.get_additional_fields(dbo, pid, "animal")
        return handler_viewanimal(l, a, af, homelink, post)
Exemplo n.º 34
0
def mainFlow():

    driver = DRIVER.start()

    lista = OF.getCasesFromQueue()  #create list of tasks

    if lista:

        temp = OF.checkLogs(lista)  #check remove previously processed task
        lista = temp
    else:
        print('no tasks in queue exit program')
        #exit() ##no tasks in queue exit program, czy to potrzebne?

    ###buduje liste slownikow do dalszej analizy
    ###tu tez moze byc oddany task do cs, z informacja
    ###albo zamkniety z infrmacja dla klienta, musi to byc zalogowane
    ###w tym momencie odbywa sie tez walidacja danych z taska
    main_lista = list()

    for ticket in lista:

        temp = OF.getDataFromTask(ticket)
        if temp != 'ERROR':
            main_lista.append(temp)

    ###ytj validation

    print('ilosc tixow przed ytj check:' + len(main_lista))

    temp = main_lista

    for ticket in main_lista:
        cn = ticket.get('company_name', '')
        bi = ticket.get('busines_id', '')
        bi.strip(' ')
        if bi:

            ytj_d = YTJ_Module.ytjCheck(driver, bi, cn)

        error = ytj_d.get('ytj_error', '')

        if error == 'OK':
            ticket.update({'ytj_name': ytj_d.get('ytj_company_name', '')})
        else:
            OF.informCustomer(ticket['sys_id'], '2')  #inform customer
            OF.returnToCS(
                ticket['sys_id'],
                ytj_d.get('ytj_error', '') +
                ' - please inform customer, scenario 2')  ##send to CS
            log.add_log(ticket['sys_id'] + ':' + ticket['number'] + ':' +
                        ytj_d.get('ytj_error', '') +
                        ':customer informed - scenario 2, ticket send to CS')
            temp.remove(ticket)

    main_lista = temp
    print('ilosc tixow po ytj check:' + len(main_lista))
    ###iAddress validation, and actions
    ###return to CS if OC routing, 2 enables, exist as requested
    ###create "Add new" list of dictionaries
    ###create "change existing" list of dict
    ###create "all disabled" list of dictionaries

    addNew = list()
    changeExisting = list()
    allDisabled = list()

    DRIVER.logToiAddress(driver)

    temp = main_lista

    for ticket in main_lista:
        bi = ticket.get('busines_id', '')
        bi.strip(' ')

        l = IADDRESS_Module.getData(bi, driver)

        if l == '':
            d = dict()
            d = ticket
            addNew.append(d)
            temp.remove(ticket)
            continue

        if ocRouting(l):
            OF.returnToCS(ticket['sys_id'],
                          'OC routing enabled')  ##poten przesylac do klienta
            log.add_log(ticket['sys_id'] + ':' + ticket['number'] + ':' +
                        'OC routing enabled')
            temp.remove(ticket)
            continue

        numberOfEnabled = twoRoutings(l)  ##count number of enabled routings
        if numberOfEnabled == 2:
            OF.returnToCS(ticket['sys_id'],
                          '2 routing enabled')  ##poten przesylac do klienta
            log.add_log(ticket['sys_id'] + ':' + ticket['number'] + ':' +
                        '2 routing enabled')
            temp.remove(ticket)
            continue
        if numberOfEnabled == 0:
            ###co potrzebne mi przy dodawaniu nowego situ ?
            d = dict()
            d = ticket
            d.update({'org_link': l[0].get('org_link', '')})
            allDisabled.append(d)
            temp.remove(ticket)
            continue

        d = dict()
        d = getData(l, ticket)
        if d:
            changeExisting.append(d)
            temp.remove(ticket)
            continue
        ###na koncu sprawdz co nigdzie nie wpadlo.

    main_lista = temp

    print("\n\n kompletnie nowe\n")
    print(addNew)
    if addNew:
        potwierdzenie = input("is it correct? y/n ")
        if potwierdzenie == 'y':

            ####funkcja w petli
            for element in addNew:
                link = AddNew.addNewOrg(driver, element.get('ytj_name'),
                                        element.get('number'))
                #operator = operator_number(element.get('operator'))
                operator = element.get('operator')
                AddNew.addNewSite(driver, link, operator,
                                  element.get('busines_id'),
                                  element.get('address_tbc'),
                                  element.get('number'))
                time.sleep(10)
                ##zalogowac
                log.add_log(element['sys_id'] + ':' + element['number'] + ':' +
                            'New routing has been added')
                OF.returnToCS(
                    element['sys_id'],
                    'New routing has been added, please inform customer')
                ##oddac do CS/ponformowac klienta

    print("\n\n do zmiany \n\n")
    print(changeExisting)

    if changeExisting:
        potwierdzenie = input("is it correct? y/n ")
        if potwierdzenie == 'y':
            for element in changeExisting:
                ##porownanie operatorow i addresow, czy w ogole wchodzic w funkcje, jak nie to wyjsc z logiem odpowiednim
                ##rozbicie, zmien operator, zmien address, zmien operator i adress z data??

                #decyzja o dacie
                if_date = data(element.get('date'))

                if if_date:
                    data_ = zmodyfikuj_date(element.get('date'))
                else:
                    data_ = ''

                if element.get('electronic_adr') == element.get(
                        'address_tbc') and element.get(
                            'lmc') == OPERATORS.op.get(
                                element.get('operator')):
                    log.add_log(element['sys_id'] + ':' + element['number'] +
                                ':' + 'Routing exist')
                    OF.returnToCS(element['sys_id'], 'Routing exist')
                    continue

                odp = ChangeExisting.changeSite(driver,
                                                element.get('site_link'),
                                                element.get('operator'),
                                                element.get('address_tbc'),
                                                data_, element.get('number'))
                time.sleep(10)
                if odp == 'OK':
                    log.add_log(element['sys_id'] + ':' + element['number'] +
                                ':' + 'Routing has been changed')
                    OF.returnToCS(
                        element['sys_id'],
                        'Routing has been changed, please inform customer')
                elif odp == 'ERROR':
                    log.add_log(element['sys_id'] + ':' + element['number'] +
                                ':' + '2 Receiving Identifiers please check')
                    OF.returnToCS(element['sys_id'],
                                  '2 Receiving Identifiers please check')

    print("\n\n wszystko disabled \n\n")
    print(allDisabled)

    if allDisabled:
        potwierdzenie = input("is it correct? y/n ")
        if potwierdzenie == 'y':
            for element in allDisabled:
                addSite.addNewSite(driver, element.get('site_link'),
                                   element.get('operator'),
                                   element.get('address_tbc'),
                                   element.get('number'))
                time.sleep(10)
                log.add_log(element['sys_id'] + ':' + element['number'] + ':' +
                            'Routing has been added')
                OF.returnToCS(
                    element['sys_id'],
                    'Routing has been changed, please inform customer')

    print("\n\nbez akcji \n\n")  #oddac do CS
    print(main_lista)

    if main_lista:
        print(
            'wywolaj jeszcze raz narazie, trzeba sprawdzic dlaczego wszystkie sie nie lapia do akcji!!!i i dopisz tieto'
        )
Exemplo n.º 35
0
def handler(dbo, user, post):
    """
    Handles posts from the frontend. Depending on the type we either
    return more HTML for the javascript to inject, or GO URL to have
    the controller redirect to URL
    """
    l = dbo.locale
    homelink = "<a href='mobile' class='ui-btn-right' data-icon='home' data-theme='b'>%s</a>" % _("Home", l)
    mode = post["posttype"]
    pid = post.integer("id")
    animalid = post.integer("animalid")

    if mode == "vacc":
        # We're vaccinating an animal
        a = animal.get_animal(dbo, animalid)
        medical.update_vaccination_today(dbo, user, pid)
        return (
            jqm_page_header("", _("Vaccination Given", l), homelink)
            + jqm_p(_("Vaccination marked as given for {0} - {1}", l).format(a["ANIMALNAME"], a["SHELTERCODE"]))
            + jqm_button("mobile#vacc", _("More Vaccinations", l), "", "false")
            + jqm_page_footer()
        )

    if mode == "test":
        # We're performing a test on an animal
        a = animal.get_animal(dbo, animalid)
        medical.update_test_today(dbo, user, pid, post.integer("resultid"))
        return (
            jqm_page_header("", _("Test Performed", l), homelink)
            + jqm_p(_("Test marked as performed for {0} - {1}", l).format(a["ANIMALNAME"], a["SHELTERCODE"]))
            + jqm_button("mobile#test", _("More Tests", l), "", "false")
            + jqm_page_footer()
        )

    elif mode == "med":
        # We're treating an animal
        a = animal.get_animal(dbo, animalid)
        medical.update_treatment_today(dbo, user, pid)
        return (
            jqm_page_header("", _("Treatment Given", l), homelink)
            + jqm_p(_("Treatment marked as given for {0} - {1}", l).format(a["ANIMALNAME"], a["SHELTERCODE"]))
            + jqm_button("mobile#med", _("More Medications", l), "", "false")
            + jqm_page_footer()
        )

    elif mode == "dia":
        # We're completing a diary task
        d = diary.get_diary(dbo, pid)
        if post["on"] == "0":
            diary.complete_diary_note(dbo, user, pid)
            return (
                jqm_page_header("", _("Completed", l), homelink)
                + jqm_p(_("Diary note {0} marked completed", l).format(d["SUBJECT"]))
                + jqm_button("mobile#diary", _("More diary notes", l), "", "false")
                + jqm_page_footer()
            )
        else:
            diary.rediarise_diary_note(dbo, user, pid, post.date("on"))
            return (
                jqm_page_header("", _("Rediarised", l), homelink)
                + jqm_p(_("Diary note {0} rediarised for {1}", l).format(d["SUBJECT"], post["on"]))
                + jqm_button("mobile#diary", _("More diary notes", l), "", "false")
                + jqm_page_footer()
            )

    elif mode == "dianew":
        # We're adding a diary note
        diary.insert_diary(dbo, user, 0, 0, post.date("diarydate"), post["diaryfor"], post["subject"], post["note"])
        return "GO mobile"

    elif mode == "message":
        # We're adding a message
        lookups.add_message(
            dbo,
            user,
            post.boolean("email"),
            post["message"],
            post["forname"],
            post.integer("priority"),
            post.date("expires"),
        )
        return "GO mobile"

    elif mode == "log":
        # We're adding a log to an animal
        a = animal.get_animal(dbo, animalid)
        log.add_log(dbo, user, log.ANIMAL, animalid, post.integer("logtypeid"), post["logtext"])
        return "GO mobile"

    elif mode == "hc":
        # We're marking an owner homechecked
        person.update_pass_homecheck(dbo, user, post.integer("personid"), post["comments"])
        return "GO mobile"

    elif mode == "vsa":
        # Return a list of the shelter animals
        h = []
        alin = []
        h.append(header(l))
        h.append(jqm_page_header("", _("Shelter Animals", l), homelink))
        an = animal.get_animal_find_simple(dbo, "", "all")
        for a in an:
            alin.append(
                jqm_listitem_link(
                    "mobile_post?posttype=va&id=%d" % a["ID"],
                    "%s - %s (%s %s %s) %s"
                    % (
                        a["CODE"],
                        a["ANIMALNAME"],
                        a["SEXNAME"],
                        a["BREEDNAME"],
                        a["SPECIESNAME"],
                        a["IDENTICHIPNUMBER"],
                    ),
                    "animal",
                )
            )
        h.append(jqm_list("\n".join(alin), True))
        h.append(jqm_page_footer())
        h.append("</body></html>")
        return "\n".join(h)

    elif mode == "uai":
        # Upload an animal image
        media.attach_file_from_form(dbo, user, media.ANIMAL, animalid, post.data)
        return "GO mobile_post?posttype=va&id=%d&success=true" % animalid

    elif mode == "va":
        # Display a page containing the selected animal by id
        a = animal.get_animal(dbo, pid)
        af = additional.get_additional_fields(dbo, pid, "animal")
        return handler_viewanimal(l, a, af, homelink, post)