def delete_customer(customer_id):
    """
    Delete a customer from the database.

    :customer_id:   String representing the customer's ID
    """
    try:
        Customers.delete_by_id(customer_id)
        LOGGER.info("Customer deleted successfully.")
    except OperationalError as op_error:
        LOGGER.info("Failed to delete customer with customer_id: %s",
                    customer_id)
        LOGGER.error(op_error)
    def test_customer_schema_as_contact_info_dict(self):
        """
        Validates returning the customer schema as a dictionary with
        contact infomration only.
        """
        with patch("customer_db_schema.Customers.get_or_create") as handle_get:
            handle_get.return_value = [MockCustomer]
            customer = Customers().get_or_create("test")[0]
            cust_dict = customer.as_contact_info_dictionary(MockCustomer)

            self.assertEqual(cust_dict["first_name"], "Amelia")
            self.assertEqual(cust_dict["last_name"], "Bedelia")
            self.assertEqual(cust_dict["phone_number"], "Pennsylvania 65000")
            self.assertEqual(cust_dict["email_address"],
                             "*****@*****.**")
    def test_customer_schema_as_dictionary(self):
        """ Validates returning the customer schema as a dictionary """
        with patch("customer_db_schema.Customers.get_or_create") as handle_get:
            handle_get.return_value = [MockCustomer]
            customer = Customers().get_or_create("test")[0]
            cust_dict = customer.as_dictionary(MockCustomer)

            self.assertEqual(cust_dict["customer_id"], "123")
            self.assertEqual(cust_dict["first_name"], "Amelia")
            self.assertEqual(cust_dict["last_name"], "Bedelia")
            self.assertEqual(cust_dict["home_address"], "123 Starshine Ln.")
            self.assertEqual(cust_dict["phone_number"], "Pennsylvania 65000")
            self.assertEqual(cust_dict["email_address"],
                             "*****@*****.**")
            self.assertEqual(cust_dict["status"], "active")
            self.assertEqual(cust_dict["credit_limit"], 3.14)
            self.assertEqual(cust_dict["date_created"],
                             self.hold_datetime_value)
            self.assertEqual(cust_dict["date_modified"],
                             self.hold_datetime_value)
 def test_customer_schema_fields(self):
     """ Validates the fileds in the customer schema """
     with patch("customer_db_schema.Customers.get_or_create") as handle_get:
         handle_get.return_value = [MockCustomer]
         customer = Customers().get_or_create("test")[0]
         self.assertEqual(customer.customer_id, "123")
         self.assertEqual(customer.first_name, "Amelia")
         self.assertEqual(customer.last_name, "Bedelia")
         self.assertEqual(customer.home_address, "123 Starshine Ln.")
         self.assertEqual(customer.phone_number, "Pennsylvania 65000")
         self.assertEqual(customer.email_address, "*****@*****.**")
         self.assertEqual(customer.status, "active")
         self.assertEqual(customer.credit_limit, 3.14)
         self.assertEqual(customer.date_created, self.hold_datetime_value)
         self.assertEqual(customer.date_modified, self.hold_datetime_value)
def write_to_db(customer):
    """
    Write a customer to the DB.

    This handles exceptions peewee.IntegrityError and peewee.OperationalError
    and writes them to the log when encountered.

    :customer:  The customer to write.
    """
    try:
        current = Customers.get_or_create(**customer)
        logging.info("Customer written successfully.")
        logging.debug(current)
    except (IntegrityError, OperationalError) as error:
        logging.info("Failed to write customer.")
        logging.error(error)
        logging.debug(customer)
def add_customer(customer_id, first_name, last_name, address, phone_number,
                 email, status, credit_limit):
    """
    Add a customer to the database.

    :customer_id:       String representing the customer's ID
    :first_name:        String representing the customer's first name
    :last_name:         String representing the customer's last name
    :home_address:      String representing the customer's home address
    :phone_number:      String representing the customer's phone number
    :email_address:     String representing the customer's email address
    :status:            String representing the customer's state
                        (Accepted values "active" or "inactive")
    :credit_limit:      A decimal representing the customer's credit limit
    """
    if status.lower() not in ["active", "inactive"]:
        msg = "A customer's status can only be\"active\" or \"inactive\""
        raise ValueError(msg)

    try:
        current = Customers.get_or_create(customer_id=customer_id,
                                          first_name=first_name,
                                          last_name=last_name,
                                          home_address=address,
                                          phone_number=phone_number,
                                          email_address=email,
                                          status=status.lower(),
                                          credit_limit=credit_limit)
        LOGGER.info("Saved customer with ID: %s", current[0].customer_id)

    except (IntegrityError, OperationalError) as error:
        debug_dict = {
            "customer_id": customer_id,
            "first_name": first_name,
            "last_name": last_name,
            "home_address": address,
            "phone_number": phone_number,
            "email_address": email,
            "status": status,
            "credit_limit": credit_limit
        }

        LOGGER.info("Unable to save customer.")
        LOGGER.info("Parameters used: %s", debug_dict)
        LOGGER.error(error)
def search_customer(customer_id):
    """
    Look up a customer in the DB and return a dictionary of their contact
    information including first name, last_name, phone number, and email
    address.

    :customer_id:   String representing the customer's ID
    """
    cust_dict = {}
    try:
        customer = Customers.get_or_none(Customers.customer_id == customer_id)

        if customer is not None:
            cust_dict = customer.as_contact_info_dictionary()
        else:
            LOGGER.info("No customer exists with customer_id: %s", customer_id)
    except OperationalError as op_error:
        LOGGER.info("Failed look up of customer with customer_id: %s",
                    customer_id)
        LOGGER.error(op_error)

    return cust_dict
Exemple #8
0
def write_customers(customer_list):
    """
    Write a collection of customers to the database.

    :customer_list:     A list of CSV strings representing customers.
    """
    for customer in customer_list:
        try:
            customer = customer.split(',')
            current = Customers.get_or_create(customer_id=customer[0],
                                              first_name=customer[1],
                                              last_name=customer[2],
                                              home_address=customer[3],
                                              phone_number=customer[4],
                                              email_address=customer[5],
                                              status=customer[6],
                                              credit_limit=customer[7])
            logging.info("Customer written successfully.")
            logging.debug(current)
        except (IntegrityError, OperationalError) as error:
            logging.info("Failed to write customer.")
            logging.error(error)
            logging.debug(customer)
def update_customer_credit(customer_id, credit_limit):
    """
    Update a customer's credit limit.

    :customer_id:   String representing the customer's ID
    :credit_limit:  A decimal representing the customer's credit limit
    """
    try:
        customer = Customers.get_or_none(Customers.customer_id == customer_id)

        if customer is not None:
            limit = customer.credit_limit
            customer.credit_limit = credit_limit
            customer.save()

            msg = str("Credit limit updated from " +
                      f"{limit} to {customer.credit_limit}")
            LOGGER.info(msg)
        else:
            msg = f"No customer exists with customer_id: {customer_id}"
            LOGGER.info(msg)
            raise ValueError(msg)
    except (IntegrityError, OperationalError) as error:
        raise ValueError(error)
 def test_customer_schema_save(self):
     """ Validates saving the customer schema """
     customer = Customers().get_or_create("test")[0]
     customer.save()
     self.assertGreaterEqual(customer.date_modified,
                             self.hold_datetime_value)
def list_active_customers():
    """
    Retur a count of active customers.
    """
    return Customers.select().where(Customers.status == "active").count()