示例#1
0
def debt_create(user_id):
    """
    GET - Renders a debt form.
    POST - Validates the debt form and check if the values are right. If they pass the informations is stored in
    the database and the debt is registrated. The tenant is redirected to the user page.
    If they fail the debt form is rendered with error messages.

    :param user_id:
    :type user_id: integer
    :return: Redirect to edit user page
    """
    try:
        if check_session():
            cl = user_client.UsersSqlClient()
            dcl = debt_client.DebtSqlClient()
            user = cl.get_users(user_id)[0]
            form = NewDebt()

            if form.validate_on_submit():
                debt = sql_debt.SQLDebt(form.amount.data, user.id,
                                        form.product.data, None, None)
                dcl.add_dept(debt.dict())
                flash('Debt added for %s' %
                      (user.firstname + " " + user.lastname))
                return redirect("/user_page/" + user_id)

            return render_template('debt_create.html',
                                   title='Debt Create',
                                   form=form,
                                   error=form.errors)
        else:
            return redirect_not_logged_in()
    except:
        flash('Error Creating debt, please try again.')
        return redirect('/')
示例#2
0
def user_page(user_index=None):
    """
    Renders a template with user information on a specified user.

    :param user_index:
    :type user_index: integer
    :return: Renders a template
    """
    try:
        if check_session():
            debts, tagevents = [], []
            cl = user_client.UsersSqlClient()
            user = cl.get_users(user_index)[0]

            if user is None:
                return "No user Found"
            else:
                dbl = debt_client.DebtSqlClient()
                ret_depts = dbl.get_debt(user.id)
                if ret_depts is not []:
                    for debt in ret_depts:
                        js = debt.dict()
                        debts.append(js)
                tc = tag_client.TageventsSqlClient()
                tagevents = tc.get_detailed_tagevents(user_index, 20)
                return render_template('user_page.html',
                                       title='User Page',
                                       data=user.dict(),
                                       tags=tagevents,
                                       debts=debts)
        else:
            return redirect_not_logged_in()
    except:
        flash('Error Showing a user page, please try again.')
        return redirect('/')
示例#3
0
def link_user_to_last_tag(user_id):
    """
    Links the user to the last tag. Grabs the last tag stored in the database and binds it to the specified member.
    Grabs only a tag that doesnt belong to another member.

    :param user_id:
    :type user_id: integer
    :return: Redirect to edit user page
    """
    try:
        if check_session():
            try:
                tc = tag_client.TageventsSqlClient()
                tagevent = tc.get_detailed_tagevents(0, 1)[0]

                cl = user_client.UsersSqlClient()
                user = cl.get_users(user_id)[0]

                if user is None:
                    return "No user have this ID"

                user.tag_id = tagevent.tag_id
                cl.update_user(user.dict())

                return redirect("/edit_user/" + str(user_id))
            except:
                flash("No tagging has happened")
                return redirect("/edit_user/" + str(user_id))
        else:
            return redirect_not_logged_in()
    except:
        flash('Error linking user to last tag, please try again.')
        return redirect('/')
示例#4
0
def search_user():
    """
    GET - Renders a search user form.
    POST - Takes the value from the form and pass it to the database. Retrieves a list of user/users based on
    the information that was passed.

    :return: Renders template with the search result
    """
    try:
        if check_session():
            form = SearchUser()
            if form.validate_on_submit():
                mc = user_client.UsersSqlClient()

                tmp_usr = Sqluser(None, None, form.firstname.data,
                                  form.lastname.data, form.email.data, None,
                                  None, None, form.city.data, None, None, None,
                                  None, None, None, None, None, None)

                users = mc.search_user(tmp_usr.dict())

                return render_template('search_user.html',
                                       title='Search User',
                                       form=form,
                                       hits=users)
            return render_template('search_user.html',
                                   title='Search User',
                                   form=form)
        else:
            return redirect_not_logged_in()
    except:
        flash('Error Searching for a user, please try again.')
        return redirect('/')
示例#5
0
def add_new_user():
    """
    GET - Renders a new user form.
    POST - Validates the user form and check if the values are right. If they pass the informations is stored in
    the database and the user is registrated. The tenant is redirected to the user page.
    If they fail the user form is rendered with error messages.

    :return: Redirect or renders template
    """
    try:
        if check_session():
            form = NewUser()
            if form.validate_on_submit():
                mc = user_client.UsersSqlClient()

                tmp_usr = Sqluser(None, None, form.firstname.data,
                                  form.lastname.data, form.email.data,
                                  form.phone.data, form.address.data,
                                  form.address2.data, form.city.data,
                                  form.zip_code.data, None, form.gender.data,
                                  form.ssn.data, form.expiry_date.data, None,
                                  form.status.data, None, None)
                user_id = mc.add_user(tmp_usr.dict())
                return redirect('/user_page/' + str(user_id))

            return render_template('new_user.html',
                                   title='New User',
                                   form=form,
                                   error=form.errors)
        else:
            return redirect_not_logged_in()
    except:
        flash('Error Creating a new user, please try again.')
        return redirect('/')
示例#6
0
def all_users(filter=None):
    """
    Lists all members based on the filter.

    :param filter:
    :type filter: string
    :return: Redirect or renders template
    """
    try:
        if check_session():
            ret, users = [], []

            cl = user_client.UsersSqlClient()
            users = cl.get_users(0)

            # List users depending on the membership
            if filter != 'all':
                users = [x for x in users if x.status == filter.title()]

            users = sorted(users, key=lambda user: user.firstname)
            for hit in users:
                js = hit.dict()
                ret.append(js)
            return render_template('all_users.html',
                                   title='All Users',
                                   hits=ret,
                                   filter=filter,
                                   count=len(users))
        else:
            return redirect_not_logged_in()
    except:
        flash('Error Showing all users, please try again.')
        return redirect('/')
示例#7
0
def statistics_by_date(_month, _day, _year):
    """
    Renders statistic from the database on the specified date from the params.
    1. Tags by hour
    2. Tags by day
    3. Tags by month
    4. Number of genders in database
    5. Number of tags by gender
    6. Number of age groups in database

    :param _month:
    :param _day:
    :param _year:
    :type _month: string
    :type _day: string
    :type _year: string
    :return: Render template for statistic
    """
    try:
        if check_session():
            chosen_date_array = {'year': _year, 'month': _month, 'day': _day}
            gs = GenerateStats()

            ucl = user_client.UsersSqlClient()
            tcl = tag_client.TageventsSqlClient()
            users = ucl.get_users()
            tagevents = tcl.get_statistic_tagevents()

            default_date = datetime.now()
            selected_date = default_date.replace(day=int(_day),
                                                 month=int(_month),
                                                 year=int(_year))
            week_day_name = selected_date.strftime('%A')
            month_name = selected_date.strftime('%B')
            custom_date_day = {
                'weekday':
                week_day_name + ' ' + str(selected_date.day) + '/' +
                str(selected_date.month) + '/' + str(selected_date.year)
            }

            custom_date_month = {
                'month': month_name + ' ' + str(selected_date.year)
            }
            # Send the data to a method who returns an multi dimensional array with statistics.
            ret = gs.get_data(users, tagevents, chosen_date_array)
            return render_template('statistics.html',
                                   plot_paths='',
                                   data=ret,
                                   data2=custom_date_day,
                                   data3=custom_date_month)
        else:
            return redirect_not_logged_in()
    except:
        flash('Error showing statistic, please try again.')
        return redirect('/')
示例#8
0
def edit_user(user_index=None):
    """
    GET - Renders a edit user form.
    POST - Validates the user form and check if the values are right. If they pass the information is stored in
    the database and the user is updated. The tenant is redirected to the user page.
    If they fail the edit user form is rendered with error messages.

    :param user_index:
    :type user_index: integer
    :return: Renders a template
    """
    try:
        if check_session():
            cl = user_client.UsersSqlClient()
            user = cl.get_users(user_index)[0]

            if user is None:
                return "No user have this ID"

            form = EditUser(obj=user)
            if form.validate_on_submit():
                user.firstname = form.firstname.data
                user.lastname = form.lastname.data
                user.email = form.email.data
                user.phone = form.phone.data
                user.address = form.address.data
                user.address2 = form.address2.data
                user.city = form.city.data
                user.zip_code = form.zip_code.data
                user.tag_id = form.tag_id.data
                user.gender = form.gender.data
                user.expiry_date = form.expiry_date.data
                user.status = form.status.data

                cl.update_user(user.dict())
                # Not in use at this point. Will be a future feature..
                # If we successfully edited the user, redirect back to userpage.
                # fortnox_data = Fortnox()
                # fortnox_data.update_customer(user)
                return redirect("/user_page/" + str(user.id))

            if user:
                return render_template('edit_user.html',
                                       title='Edit User',
                                       form=form,
                                       data=user.dict(),
                                       error=form.errors)
            else:
                return "she wrote upon it; no such number, no such zone"
        else:
            return redirect_not_logged_in()
    except:
        flash('Error Editing a user, please try again.')
        return redirect('/')
示例#9
0
def statistics():
    """
    Renders statistic from the database on todays date.
    1. Tags by hour
    2. Tags by day
    3. Tags by month
    4. Number of genders in database
    5. Number of tags by gender
    6. Number of age groups in database

    :return: Render template for statistic
    """
    try:
        if check_session():
            default_date = datetime.now()
            default_date_array = {
                'year': str(default_date.year),
                'month': str(default_date.strftime('%m')),
                'day': str(default_date.strftime('%d'))
            }
            gs = GenerateStats()

            ucl = user_client.UsersSqlClient()
            tcl = tag_client.TageventsSqlClient()
            users = ucl.get_users()
            tagevents = tcl.get_statistic_tagevents()
            week_day_name = default_date.strftime('%A')
            month_name = default_date.strftime('%B')
            custom_date_day = {
                'weekday':
                week_day_name + ' ' + str(default_date.day) + '/' +
                str(default_date.month) + '/' + str(default_date.year)
            }
            custom_date_month = {
                'month': month_name + ' ' + str(default_date.year)
            }
            # Send the data to a method who returns an multi dimensional array with statistics.
            ret = gs.get_data(users, tagevents, default_date_array)
            return render_template('statistics.html',
                                   plot_paths='',
                                   data=ret,
                                   data2=custom_date_day,
                                   data3=custom_date_month)
        else:
            return redirect_not_logged_in()
    except:
        flash('Error showing statistic, please try again.')
        return redirect('/')
示例#10
0
def remove_user(user_id):
    """
    Deletes a user from the database.

    :param user_id:
    :type user_id: integer
    :return: Redirect
    """
    try:
        if check_session():
            cl = user_client.UsersSqlClient()
            cl.remove_user(user_id)
            flash('Member was removed!')
            return redirect("/all_users/all")
        else:
            return redirect_not_logged_in()
    except:
        flash('Error Removing a user, please try again.')
        return redirect('/')
示例#11
0
def inactive_check():
    """
    Renders a template with a list of all users that have not tagged in for the last 2 weeks

    :return: Renders template with a user list
    """
    try:
        if check_session():
            ret = []
            mc = user_client.UsersSqlClient()
            users = mc.get_inactive_users()

            return render_template('inactive_check.html',
                                   title='Inactive Members',
                                   hits=users)
        else:
            return redirect_not_logged_in()
    except:
        flash('Error Showing Inactive Users, please try again.')
        return redirect('/')
def sync_from_fortnox():
    """
    Helper script to sync the local database with the content of the database on fortnox.
    Either updates an existing customer or creates a new.
    """
    try:
        fortnox_data = Fortnox()
        customers = fortnox_data.get_all_customers()
        ret = []
        for element in customers:
            for customer in element:
                # Split firstname and lastname
                name = customer['Name'].split()
                # If the user only got a firstname, add blank to the lastname
                if len(name) < 2:
                    name.append('')

                cust = sql_user.SQLUser(None, customer['CustomerNumber'],
                                        name[0], name[1], customer['Email'],
                                        customer['Phone'], customer['Address1'],
                                        customer['Address2'], customer['City'],
                                        customer['ZipCode'], None,
                                        get_gender_from_ssn(customer),
                                        customer['OrganisationNumber'][:-5], None, None, None,
                                        None, None)
                ret.append(cust.dict())

        cl = client.UsersSqlClient()
        # If the user from Fortnox all ready exists in the database, update it. If it doesn't exist, create a new.
        for customer in ret:
            if cl.does_user_exist(customer['fortnox_id']):
                cl.add_user(customer)
            else:
                cl.update_user(customer)

        flash("Members from Fortnox is added/updated to the database!")
    except:
        flash("Something happend while adding/updating from fortnox")
示例#13
0
def tagevent(tag_id, api_key, timestamp):
    """
    Gets a tagevent from crosstag_reader with tag_id, api_key and timestamp of the tagevent.
    Checks if the api-key is valid and then creates the tag and saves it in the database.
    If the api-key is wrong a KeyError is raised.

    :param tag_id:
    :param api_key:
    :param timestamp:
    :type tag_id: string
    :type api_key: string
    :type timestamp: string
    :return: Redirect or renders template
    :raises: KeyError
    """
    cl = registration_client.RegisterLoginSqlClient()
    username = cl.get_tenant_with_api_key(api_key)
    if username[0]['username'] is not None:
        try:
            cl = user_client.UsersSqlClient(username[0]['username'])
            user = cl.search_user_on_tag(tag_id)[0][0]
            if user is None:
                id = 0
            else:
                id = user
            timestamp = timestamp.replace('%', ' ')
            tmp__detailed_tagevent = Sql_detailed_tag(None, tag_id, timestamp,
                                                      id)

            cl = tag_client.TageventsSqlClient(username[0]['username'])
            cl.add_tagevents(tmp__detailed_tagevent.dict())

            return "%s server tagged %s" % (datetime.now(), tag_id)
        except:
            return "Can't create a tag with that Tag ID or Api Key"
    else:
        raise KeyError('Wrong API-Key')