Exemplo n.º 1
0
def login():
    response = Response()

    # Ensure required input parameters are received
    required = ['username', 'password']
    optional = []
    data = checkVars(response, request.get_json(), required, optional)
    if response.hasError(): return response.getJson()

    # Setup database connection, table, and query
    con = mimsDbEng.connect()
    users = Table('users', MetaData(mimsDbEng), autoload=True)
    
    # Get user id of username passed in, also ensure user exists
    stm = select([users]).where(and_(users.c.username == data['username'], users.c.is_deleted == 0))
    user = con.execute(stm).fetchone()
    con.close()
    if not user:
        return response.setError(2)

    # Verify that the password is valid
    if not verifyPassword(user['id'], data['password']):
        return response.setError(2)
    
    # Generate and attach access token to response data
    response.data['access_token'] = jwt.encode({
        'userId': user['id']
    }, config['jwt']['secret'], algorithm='HS256').decode('utf-8')

    response.data['user_type'] = user['type']
    
    return response.getJson()
Exemplo n.º 2
0
def editProduct(itemCode):
    response = Response()

    # Ensure user has permission for this endpoint
    userId = authenticateRequest(response, request)
    if response.hasError(): return response.getJson()

    # Ensure required input parameters are received
    required = []
    optional = ['price']
    data = checkVars(response, request.get_json(), required, optional, atLeastOneOptional=True)
    if response.hasError(): return response.getJson()

    if 'price' in data and not checkPrice(response, data['price']):
        return response.getJson()

    # Setup database connection and table
    con = mimsDbEng.connect()
    users = Table('users', MetaData(mimsDbEng), autoload=True)

    # Get the business reference of the business of the user making this request
    stm = select([users]).where(users.c.id == userId)
    businessId = con.execute(stm).fetchone()['business']

    # Call the relevant get products function depending on business to get response data
    if businessId == 1:
        product = targetGetProduct(itemCode)
        if not product: return response.setError(18)
        response.data['item_code'] = targetEditProduct(itemCode, data)
    
    return response.getJson()
Exemplo n.º 3
0
def getProductMovement(itemCode):
    response = Response()

    # Ensure user has permission for this endpoint
    userId = authenticateRequest(response, request)
    if response.hasError(): return response.getJson()

    # Ensure required input parameters are received
    required = []
    optional = []
    data = checkVars(response, request.values.to_dict(), required, optional)
    if response.hasError(): return response.getJson()

    startDate = datetime.datetime.combine(datetime.date.today(), datetime.time()) - datetime.timedelta(days=7)

    # Setup database connection and table
    con = mimsDbEng.connect()
    users = Table('users', MetaData(mimsDbEng), autoload=True)

    # Get the business reference of the business of the user making this request
    stm = select([users]).where(users.c.id == userId)
    businessId = con.execute(stm).fetchone()['business']

    # Call the relevant get products function depending on business to get response data
    if businessId == 1:
        product = targetGetProduct(itemCode)
        if not product: return response.setError(18)
        response.data['product_movement'] = targetGetProductMovement(itemCode, startDate.date())
    
    return response.getJson()
Exemplo n.º 4
0
def createSale():
    response = Response()

    # Ensure user has permission for this endpoint
    userId = authenticateRequest(response, request, mustBeManager=True)
    if response.hasError(): return response.getJson()

    # Ensure required input parameters are received
    required = ['items']
    optional = []
    data = checkVars(response, request.get_json(), required, optional)
    if response.hasError(): return response.getJson()

    for item in data['items']:
        # Ensure item is not missing required data
        if not 'item_code' in item or not 'amount' in item or not 'datetime' in item:
            return response.setError(23)

        # Ensure amount is formatted properly
        if not type(item['amount']) is int and not type(
                item['amount']) is float:
            return response.setError(21)

        # Ensure datetime is formatted properly
        try:
            datetime.datetime.strptime(item['datetime'], "%Y-%m-%d %H:%M:%S")
        except:
            return response.setError(22)

    # Setup database connection and table
    con = mimsDbEng.connect()
    users = Table('users', MetaData(mimsDbEng), autoload=True)

    # Get the business reference of the business of the user making this request
    stm = select([users]).where(users.c.id == userId)
    businessId = con.execute(stm).fetchone()['business']

    # Call the relevant get products function depending on business to get response data
    if businessId == 1:
        # Ensure each item code is accurate
        for item in data['items']:
            product = targetGetProduct(item['item_code'])
            if not product: return response.setError(24)

        response.data['sale'] = targetCreateSale(data)

    return response.getJson()
Exemplo n.º 5
0
def createUser():
    response = Response()

    # Ensure user has permission for this endpoint
    userId = authenticateRequest(response, request, mustBeManager=True)
    if response.hasError(): return response.getJson()

    # Ensure required input parameters are received
    required = ['username', 'first_name', 'last_name', 'password', 'type']
    optional = []
    data = checkVars(response, request.get_json(), required, optional)
    if response.hasError(): return response.getJson()

    # Setup database connection and table
    con = mimsDbEng.connect()
    users = Table('users', MetaData(mimsDbEng), autoload=True)

    # Select the business of this manager so we know what business to make
    # the user for
    stm = select([users]).where(users.c.id == userId)
    businessId = con.execute(stm).fetchone()['business']

    # Check username validity
    if not checkUsername(response, data['username']):
        return response.getJson()

    # Check validity of type
    if not checkUserType(response, data['type']):
        return response.getJson()

    # Ensure username is not already taken
    stm = select([users]).where(users.c.username == data['username'])
    if con.execute(stm).fetchone():
        return response.setError(7)

    # Check password validity
    if not checkPassword(response, data['password']):
        return response.getJson()

    # Hash password to store in database
    hashedPassword = hashPassword(data['password'])

    # Create user
    stm = users.insert().values(username=data['username'],
                                password_hash=hashedPassword,
                                first_name=data['first_name'],
                                last_name=data['last_name'],
                                type=data['type'],
                                business=businessId)
    result = con.execute(stm)
    con.close()

    # Attach newly created user id to response data
    response.data['user_id'] = result.lastrowid

    return response.getJson()
Exemplo n.º 6
0
def createInventoryTransaction():
    response = Response()

    # Ensure user has permission for this endpoint
    userId = authenticateRequest(response, request, mustBeManager=False)
    if response.hasError(): return response.getJson()

    # Ensure required input parameters are received
    required = ['item_code', 'amount', 'unit', 'datetime']
    optional = []
    data = checkVars(response, request.get_json(), required, optional)
    if response.hasError(): return response.getJson()

    if not type(data['amount']) is int and not type(data['amount']) is float:
        return response.setError(21)

    try:
        datetime.datetime.strptime(data['datetime'], "%Y-%m-%d %H:%M:%S")
    except:
        return response.setError(22)

    # Setup database connection and table
    con = mimsDbEng.connect()
    users = Table('users', MetaData(mimsDbEng), autoload=True)

    # Get the business reference of the business of the user making this request
    stm = select([users]).where(users.c.id == userId)
    businessId = con.execute(stm).fetchone()['business']

    # Call the relevant get products function depending on business to get response data
    if businessId == 1:
        product = targetGetProduct(data['item_code'])
        if not product: return response.setError(18)
        unit = targetGetUnit(data['unit'])
        if not unit: return response.setError(20)
        response.data[
            'inventory_transaction'] = targetCreateInventoryTransaction(data)

    return response.getJson()
Exemplo n.º 7
0
def editUser(userIdToEdit):
    response = Response()

    # Ensure user has permission for this endpoint
    userId = authenticateRequest(response, request)
    if response.hasError(): return response.getJson()

    # Ensure required input parameters are received
    required = []
    optional = [
        'username', 'first_name', 'last_name', 'new_password',
        'current_password', 'type', 'is_deleted'
    ]
    data = checkVars(response,
                     request.get_json(),
                     required,
                     optional,
                     atLeastOneOptional=True)
    if response.hasError(): return response.getJson()

    # Setup database connection and table
    con = mimsDbEng.connect()
    users = Table('users', MetaData(mimsDbEng), autoload=True)

    # Ensure user exists
    stm = select([users]).where(users.c.id == userIdToEdit)
    userToEdit = con.execute(stm).fetchone()
    if not userToEdit:
        return response.setError(11)

    # Get user making request
    stm = select([users]).where(users.c.id == userId)
    userMakingRequest = con.execute(stm).fetchone()

    # Permission checking for if user making request is manager
    if userMakingRequest['type'] == 1:
        # Ensure user making request is in same business as user being editted, if not, permission denied
        if userMakingRequest['business'] != userToEdit['business']:
            return response.setError(6)
    elif userMakingRequest['type'] == 2:
        # User is employee, permission checking for if user is employee

        # Ensure they are editing themselves, if not, permission denied
        if userId != userToEdit['id']:
            return response.setError(6)

        # Ensure they are not trying to edit type or is_deleted
        if 'type' in data or 'is_deleted' in data:
            return response.setError(6)

        # If they are trying to set a new password
        if 'new_password' in data:

            # Ensure they passed in their current password
            if not 'current_password' in data:
                return response.setError(13)

            # Verify current password
            if not verifyPassword(userIdToEdit, data['current_password']):
                return response.setError(14)

    # Check validity of username if set
    if 'username' in data:
        # Check username validity
        if not checkUsername(response, data['username']):
            return response.getJson()

        # Ensure username is not already taken
        stm = select([users]).where(
            and_(users.c.username == data['username'],
                 users.c.id != userIdToEdit))
        if con.execute(stm).fetchone():
            return response.setError(7)

    # Check validity of type if set
    if 'type' in data:
        if not checkUserType(response, data['type']):
            return response.getJson()

    # Check validity of is_deleted if set
    if 'is_deleted' in data:
        if not type(data['is_deleted']) is bool:
            return response.setError(16)

    # Handle new password hashing and validity
    hashedNewPassword = None
    if 'new_password' in data:
        # Check validity of new password
        if not checkPassword(response, data['new_password']):
            return response.getJson()

        # Hash new password to store in database
        hashedNewPassword = hashPassword(data['new_password'])

    # Main update statement
    stm = users.update().where(users.c.id == userIdToEdit)

    # Check potential passed in params to update
    if 'username' in data:
        stm = stm.values(username=data['username'])
    if 'first_name' in data:
        stm = stm.values(first_name=data['first_name'])
    if 'last_name' in data:
        stm = stm.values(last_name=data['last_name'])
    if 'new_password' in data:
        stm = stm.values(password_hash=hashedNewPassword)
    if 'type' in data:
        stm = stm.values(type=data['type'])
    if 'is_deleted' in data:
        stm = stm.values(is_deleted=data['is_deleted'])

    result = con.execute(stm)
    con.close()

    # Attach newly created user id to response data
    response.data['user_id'] = int(userIdToEdit)

    return response.getJson()