def update_customer_credit(customer_id, credit_limit):
    """
    search an existing customer by customer_id and update their credit limit
    or raise a ValueError exception if the customer does not exist
    """
    try:
        with database.transaction():
            a_customer = Customer.get(Customer.customer_id == customer_id)
        logger.info(f'Customer: {customer_id} credit limit is '
                    f'{a_customer.credit_limit}.')
    except (IndexError, ValueError, peewee.DoesNotExist):
        logger.info(f'Customer: {customer_id} not found.')
        database.close()
        return

    with database.transaction():
        query = (Customer.update({
            Customer.credit_limit: credit_limit
        }).where(Customer.customer_id == customer_id))
        query.execute()

        a_customer = Customer.get(Customer.customer_id == customer_id)

    logger.info(f'Customer: {customer_id} credit limit is updated to '
                f'{a_customer.credit_limit}.')
    database.close()
def add_customer(customer_id, customer_name, customer_lastname,
                 customer_home_address, customer_phone_number,
                 customer_email_address, customer_status,
                 customer_credit_limit):
    '''Adds a customer to the database'''
    try:
        with database.transaction():
            new_customer = Customer.create(
                customer_id=customer_id,
                name=customer_name,
                lastname=customer_lastname,
                home_address=customer_home_address,
                phone_number=customer_phone_number,
                email_address=customer_email_address,
                status=customer_status,
                credit_limit=customer_credit_limit)
            new_customer.save()
            logger.info('Database add successful')
            return new_customer
    except IntegrityError as i_e:
        logger.error(i_e)
        logger.info(
            'Customer was not saved.'
            'A customer with id of %s already exists.', customer_id)
        raise IntegrityError
示例#3
0
def add_customer(**kwargs):
    """
    This function will add a new customer to the sqlite3 database. keyword
    args to keep pylint happy are the following:

    customer_id, name, lastname, home_address, phone_number,
    email_address, status, credit_limit

    Ensure you application will create an empty database if one doesn’t exist
    when the app is first run. Call it customers.db
    """
    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;') # needed for sqlite
        with database.transaction():
            new_cust = Customer.create(
                customer_id=kwargs['customer_id'],
                name=kwargs['name'],
                lastname=kwargs['lastname'],
                home_address=kwargs['home_address'],
                phone_info=kwargs['phone_number'],
                email_address=kwargs['email_address'],
                status=True if kwargs['status'] == 'Active' else False,
                credit_limit=kwargs['credit_limit'])
            new_cust.save()
        # logger.info('Database add successful')
    except KeyError:
        logger.error('kwargs not complete')
        raise ValueError
    except Exception as thrown_exception:
        logger.info('Error creating customer')
        logger.info(thrown_exception)
        logger.info('See how the database protects our data')
    finally:
        database.close()
示例#4
0
def search_customer(customer_id):
    """
    This function will return a dictionary object with name, lastname,
    email address and phone number of a customer or an empty dictionary
    object if no customer was found.
    """
    ret_dict = {}
    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;') # needed for sqlite
        with database.transaction():
            cust = Customer.get(Customer.customer_id == customer_id)
            if cust is not None:
                ret_dict['name'] = cust.name
                ret_dict['lastname'] = cust.lastname
                ret_dict['email_address'] = cust.email_address
                ret_dict['phone_number'] = cust.phone_info
                logger.info('Database query successful')
            else:
                logger.error(f'Customer {customer_id} not found')
                raise ValueError
    except Exception as thrown_exception:
        logger.info(f'Error querying {customer_id}')
        logger.info(thrown_exception)
        logger.info('See how the database protects our data')
    finally:
        database.close()

    return ret_dict
示例#5
0
def delete_customer(customer_id):
    '''Deletes a customer with the given customer id.  Returns false if no delete happened.'''
    successful_delete = False
    with database.transaction():
        cust = search_customer(customer_id)
        if cust is not None:
            successful_delete = cust.delete_instance() > 0
    return successful_delete
def delete_customer(customer_id):
    """ Delete a customer from the database using customer_id """
    logging.info("delete_customer()")
    # Try to find given customer in the database, just want to see logging error
    search_customer(customer_id)
    # Try to delete whether it is found or not
    with database.transaction():
        Customer.delete_by_id(customer_id)
示例#7
0
def update_customer_credit(customer_id, new_credit_limit):
    '''Updates the customer's credit limit'''
    cust = None
    with database.transaction():
        cust = search_customer(customer_id)
        if cust is not None:
            cust.credit_limit = new_credit_limit
            cust.save()
    return cust
def delete_customer(customer_id):
    """ delete a customer from the database """
    try:
        with database.transaction():
            a_customer = Customer.get(Customer.customer_id == customer_id)
            a_customer.delete_instance()
        logger.info(f'Customer: {customer_id} deleted.')
    except peewee.DoesNotExist:
        logger.info(f'Customer: {customer_id} not found.')
    finally:
        database.close()
def list_active_customers():
    """
    return an integer with the number of customers whose status is
    currently active
    """
    count = None

    with database.transaction():
        count = Customer.select().where(Customer.active).count()
    logger.info(f'active customer count: {count}')
    database.close()

    return count
def delete_customer(customer_id):
    '''Deletes a customer with the given customer id.  Returns false if no delete happened.'''
    successful_delete = False
    with database.transaction():
        cust = search_customer(customer_id)
        if cust is not None:
            successful_delete = cust.delete_instance() > 0
            logger.info('Customer %s was deleted.', customer_id)
        else:
            logger.info(
                'Customer not deleted.'
                'Customer with id %s could not be found.', customer_id)
    return successful_delete
示例#11
0
def list_active_customers():
    """
    gets total number of active customers
    :return: (int) # of active customers
    """
    with database.transaction():
        query = (Customer.select(fn.COUNT(
            Customer.status).alias('count')).where(
                Customer.status == 'Active'))
        LOGGER.info(query)

    customer_count = [item.count for item in query]
    LOGGER.info('Number of active customers: %s', customer_count[0])

    return customer_count[0]
def update_customer_credit(customer_id, new_credit_limit):
    '''Updates the customer's credit limit'''
    cust = None
    with database.transaction():
        cust = search_customer(customer_id)
        if cust is not None:
            old_credit_limit = cust.credit_limit
            cust.credit_limit = new_credit_limit
            cust.save()
            logger.info('Customer %s credit was updated from %s to %s.',
                        customer_id, old_credit_limit, new_credit_limit)
        else:
            logger.info(
                'Customer credit not updated.'
                'Customer with id %s could not be found.', customer_id)
    return cust
示例#13
0
def add_customer(customer_id, customer_name, customer_lastname,
                 customer_home_address, customer_phone_number,
                 customer_email_address, customer_status,
                 customer_credit_limit):
    '''Adds a customer to the database'''
    with database.transaction():
        new_customer = Customer.create(customer_id=customer_id,
                                       name=customer_name,
                                       lastname=customer_lastname,
                                       home_address=customer_home_address,
                                       phone_number=customer_phone_number,
                                       email_address=customer_email_address,
                                       status=customer_status,
                                       credit_limit=customer_credit_limit)
        new_customer.save()
        logger.info('Database add successful')
        return new_customer
def search_customer(customer_id):
    """ Search for a customer in the database using customer_id """
    logging.info("search_customer()")
    result = {}
    try:
        with database.transaction():
            person = Customer.get_by_id(customer_id)
            result = {
                'name': person.name,
                'lastname': person.lastname,
                'email_address': person.email_address,
                'phone_number': person.phone_number
            }
    except DoesNotExist:
        logging.error(
            f"Can't find customer data with id = {customer_id} in the database."
        )
    finally:
        return result
def add_customer(customer_id, name, last_name, home_address, phone_number,
                 email_address, active, credit_limit):
    """ add a new customer to the database """
    try:
        with database.transaction():
            new_customer = Customer.create(customer_id=customer_id,
                                           name=name,
                                           last_name=last_name,
                                           home_address=home_address,
                                           phone_number=phone_number,
                                           email_address=email_address,
                                           active=active,
                                           credit_limit=credit_limit)
            new_customer.save()
        logger.info(f'Customer {customer_id} add successful')
    except (peewee.IntegrityError, peewee.OperationalError):
        logger.info(f'Error adding customer: {customer_id}')
    finally:
        database.close()
示例#16
0
def update_customer_credit(customer_id, credit_limit):
    """
    This function will search an existing customer by customer_id
    and update their credit limit or raise a ValueError exception
    if the customer does not exist.

    The credit limit stored in the database is returned as a float.
    The value is 0.0 if the customer_id is not valid. The value is
    the current value in the database if it _cannot_ be updated,
    else it is the updated value stored in the databsae
    """
    ret_credit = float(0.0)

    if credit_limit < 0.0:
        logger.info(f'Error setting credit limit for {customer_id}')
        logger.info(f'Credit limit is below 0: {credit_limit}')
        raise ValueError

    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;') # needed for sqlite
        with database.transaction():
            cust = Customer.get(Customer.customer_id == customer_id)
            if cust is not None:
                ret_credit = cust.credit_limit
                logger.info(f'Updating credit limit from {cust.credit_limit} \
                              to {credit_limit}')
                cust.credit_limit = credit_limit
                ret_credit = cust.credit_limit
                cust.save()
                logger.info('Database update successful')
            else:
                logger.error(f'Customer {customer_id} not found')
                raise ValueError
    except Exception as thrown_exception:
        logger.info(f'Error querying {customer_id}')
        logger.info(thrown_exception)
        logger.info('See how the database protects our data')
    finally:
        database.close()

    return ret_credit
示例#17
0
def update_customer(customer_id, credit_limit):
    """
    update customer credit limit by customer id
    :return:
    """
    try:
        with database.transaction():
            customer_update = Customer.get(Customer.customer_id == customer_id)
            LOGGER.info('Current limit: %s', customer_update.credit_limit)
            customer_update.credit_limit = credit_limit
            LOGGER.info('New credit limit: %s', customer_update.credit_limit)

            return True

    except DoesNotExist as err:

        LOGGER.warning('Customer ID: %s does not exist', customer_id)
        LOGGER.warning(err)

        return False
示例#18
0
def add_customer(customer_id, firstname, lastname, address, phone, email, status, credit_limit):
    '''
    Add customer to database, handle several peewee exceptions in the event
    of an error.

    Args:
        customer_id (str):
            Unique customer id (5 characters)
        firstname (str):
            Customer's first name
        lastname (str):
            Customer's last name
        address (str):
            Customer's address
        phone (str):
            Customer's phone number (format XXX-XXX-XXXX)
        email (str):
            Customer's email address
        status (boolean):
            Customer's status (active or not)
        credit_limit (float):
            Customer's credit limit in dollars

    '''
    try:
        with database.transaction():
            new_customer = Customer.create(
                id=customer_id,
                firstname=firstname,
                lastname=lastname,
                address=address,
                phone=phone,
                email=email,
                status=status,
                credit_limit=credit_limit)
        new_customer.save()
        LOGGER.info('Database add successful')
    except (OperationalError, IntegrityError, DoesNotExist) as exc:
        LOGGER.info(f'Error creating entry for customer {customer_id}, see error below')
        LOGGER.info(exc)
示例#19
0
def delete_customer(customer_id):
    """
    This function will delete the record of a customer matching
    customer_id
    """
    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;') # needed for sqlite
        with database.transaction():
            cust = Customer.get(Customer.customer_id == customer_id)
            if cust is not None:
                cust.delete_instance()
                logger.info('Database delete successful')
            else:
                logger.error(f'Customer {customer_id} not found')
                raise ValueError
    except Exception as thrown_exception:
        logger.info(f'Error getting {customer_id}')
        logger.info(thrown_exception)
        logger.info('See how the database protects our data')
    finally:
        database.close()
def search_customer(customer_id):
    """
    look up a customer and return a dictionary object with customer information
    or an empty dictionary object if no customer was found
    """
    customer_info = {}
    try:
        with database.transaction():
            a_customer = Customer.get(Customer.customer_id == customer_id)

        customer_info['name'] = a_customer.name
        customer_info['last name'] = a_customer.last_name
        customer_info['email address'] = a_customer.email_address
        customer_info['phone number'] = a_customer.phone_number

        logger.info(f'Customer: {customer_id} info returned.')
    except peewee.DoesNotExist:
        logger.info(f'Customer: {customer_id} not found.')
    finally:
        database.close()

    return customer_info
示例#21
0
def add_customer(customer_id, first, last, addr, phone, email, status, limit):
    """
    adds a new customer to Customer table
    :return: Customer table
    """
    try:
        LOGGER.info('Creating customer record')
        with database.transaction():
            new_customer = Customer.create(customer_id=customer_id,
                                           first_name=first,
                                           last_name=last,
                                           home_address=addr,
                                           phone_number=phone,
                                           email_address=email,
                                           status=status,
                                           credit_limit=limit)
            new_customer.save()
            LOGGER.info('Added customer: %s', new_customer.customer_id)
    except IntegrityError as err:
        LOGGER.warning('Error creating = ID: %s', customer_id)
        LOGGER.warning(err)

    return Customer
def customer_generator():
    """ generator to get one customer at a time """
    with database.transaction():
        all_customers = Customer.select()
    for customer in all_customers:
        yield customer