def test_add_customer(self): '''test add_customer function.''' add_customer(**self.customer1) check = Customer.get(Customer.customer_id == 'Dexter') self.assertEqual(check.credit_limit, 62649) self.customer1['credit_limit'] = 99999 add_customer(**self.customer1) #Peewee does not generate error on attempting to duplicate ID. #Simply verify value has not changed. self.assertEqual(check.credit_limit, 62649)
def list_active_customers(): """list all active customer: status = 1 (Active), status = 0 (Inactive)""" active_count = 0 #for _ in Customer.select().where(Customer.status == True): for _ in Customer.select(): if Customer.status: active_count += 1 LOGGER.info("Total active customers: %d", active_count) return active_count
def list_all_customers(): '''This function returns a list of lists of all the customers''' cust_pp = 'Cust ID#{:5} {:30} Ph: {:11}, Address: {:30}, Active:{:3}, Limit:{:11}' query = Customer.select() return [ cust_pp.format(x.customer_id, x.name + ' ' + x.lastname, x.phone_number, x.home_address, 'Yes' if x.status == 1 else 'No', x.credit_limit) for x in query ]
def return_all_customers(): ''' This function will return all customers object with name, lastname, email address and phone number of a customer or an empty dictionary object if no customer was found. ''' LOGGER.info(f'REturn all customers') customers = Customer.select().where(Customer.id > 0) return customers
def test_update_customer_credit(self): ''' Tests method to update customer credit, verifies new limit ''' self.add_customer_to_database() # Update credit limit basic_operations.update_customer_credit(self.new_customer['id'], 15000) # Verify that credit limit has been updated updated_customer = Customer.get(Customer.id == self.new_customer['id']) self.assertEqual(updated_customer.credit_limit, 15000)
def delete_pizza(): if not 'MyWebsite_customer_id' in session.keys(): return redirect('/') if not Customer.is_logged_in(session['MyWebsite_customer_id'], session['login_session']): return redirect('/danger') py_data = json.loads(request.form['json']) print("delete pizza:", py_data['pizza_id']) Pizza.delete(py_data['pizza_id']) return "ok"
def start_over(id): if not 'MyWebsite_customer_id' in session.keys(): return redirect('/') if not Customer.is_logged_in(session['MyWebsite_customer_id'], session['login_session']): return redirect('/danger') order = Order.get_entering(id) db.session.delete(order) db.session.commit() return redirect('/create')
def search_customer(customer_id): found_customer_dict = {} try: found_customer = Customer.get(Customer.customer_id == customer_id) if found_customer: found_customer_dict = {'name': found_customer.name, 'lastname': found_customer.last_name, 'email address': found_customer.email_address, 'phone number': found_customer.phone_number} except Exception as e: print(e) pass return found_customer_dict
def update_customer_credit(customer_id, credit_limit): """Update an existing customer's credit limit""" try: with DB.atomic(): customer = Customer.get(Customer.customer_id == customer_id) customer.credit_limit = credit_limit customer.save() except pw.DoesNotExist: LOGGER.error("Failed to update ID '%s': not found in database", customer_id) raise ValueError
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 update_customer_credit(customer_id, new_credit_limit): """update credit limit""" print('Updating customer with ID {}...'.format(customer_id)) try: customer_credit_update = Customer.get_by_id(customer_id) customer_credit_update.credit_limit = new_credit_limit customer_credit_update.save() LOGGER.info('Customer with ID %s has been updated', customer_id) except Customer.DoesNotExist: print('No record of customer with Customer ID {}'.format(customer_id)) print('No customer updated')
def delete_customer(customer_id): """ deletes customer from database""" print('Deleting customer with ID {}...'.format(customer_id)) try: customer_delete = Customer.get_by_id(customer_id) customer_delete.delete_instance() LOGGER.info('Customer with Customer ID %s has been deleted', customer_id) except Customer.DoesNotExist: print('No record of customer with Customer ID {}'.format(customer_id)) print('No customer deleted')
def delete_customer(customer_id): ''' Delete customer from database. Args: customer_id (str): Unique customer ID (5 characters) ''' # Retrieve and delete customer from database customer = Customer.get(Customer.id == customer_id) customer.delete_instance()
def clear_order(): if not 'MyWebsite_customer_id' in session.keys(): return redirect('/') if not Customer.is_logged_in(session['MyWebsite_customer_id'], session['login_session']): return redirect('/danger') py_data = json.loads(request.form['json']) order = Order.query.get(py_data['order_id']) for pizza in order.pizzas: Pizza.delete(pizza.id) return "ok"
def list_active_customers(): """ Returns number of active customers. :return: integer representing count """ count_query = (Customer.select( Customer, fn.COUNT(Customer.name).alias('cust_count')).where( Customer.status == 'active')) for count in count_query: return f'There are {count.cust_count} active customers'
def test_update_customer_credit(self): ''' Tests if customer credit gets updated, returns value error if not ''' add_customer(300, 'John', 'Doe', '100 Main St', '123-456-6789', '*****@*****.**', 'active', 10000) update_customer_credit(300, 20000) updated_customer = Customer.select().where(Customer.customer_id == 300).get() self.assertEqual(updated_customer.credit_limit, 20000) with self.assertRaises(ValueError): update_customer_credit(400, 20000)
def search_customer(customer_id=None): search_customer = Customer.select().where( Customer.customer_id == customer_id).dicts() field_names = Customer._meta.sorted_field_names if search_customer: return { field_name: record[field_name] for record in search_customer for field_name in field_names } else: return {}
def delete_customer(customer_id): """use customer ID to find and delete a customer from the database""" try: remove_customer = Customer.get(Customer.customer_id == customer_id) remove_customer.delete_instance() logging.info("Customer %s was found, deleting from the database", customer_id) except DoesNotExist: logging.debug("Customer with id %s does not exist", customer_id) logging.debug(DoesNotExist) raise DoesNotExist
def list_active_customers(): ''' This function will return an integer with the number of customers whose status is currently active. ''' count = Customer.select().where(Customer.status == 'Active').count() LOGGER.info('integer with the number of customers whose status is \ currently active') return count
def display_customers(): """ Display all customer data from database """ # Display customer data to db.log file client_generator = (client for client in Customer.select()) logging.critical("-" * 100) for client in client_generator: logging.critical(", ".join(["{}"] * 8).format( client.customer_id, client.name, client.lastname, client.home_address, client.phone_number, client.email_address, client.status, client.credit_limit)) logging.critical("-" * 100)
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.""" qry = (Customer.update({ Customer.credit_limit: credit_limit }).where(Customer.customer_id == customer_id)) try: qry.execute() except ValueError: logging.error('Customer id {} does not exist'.format(customer_id))
def delete_customer(customer_id): '''delete customer_id info from database''' LOGGER.info(f'Deleting customer ID {customer_id} from Customer table') with db.transaction(): try: del_cust = Customer.get(Customer.customer_id == customer_id) del_cust.delete_instance() del_cust.save() except Customer.DoesNotExist as error_message: LOGGER.error( f'Customer ID {customer_id} not found. {error_message}') raise ValueError
def list_active_customers(): """Display the active customers""" # db.connect() # db.execute_sql('PRAGMA foreign_keys = ON;') active_customers = [ customer.customer_id for customer in Customer.select().where(Customer.status == "1") ] print(active_customers) LOGGER.info( f"Total number of active customers are {len(active_customers)}") return len(active_customers)
def test_add_customer(self): """tests add_customer function""" add_customer("C00001", "Tim", "Cook", "123 fake st, Seattle, WA", "206-123-4567", "*****@*****.**", True, 10000.00) self.assertEqual(Customer.get(Customer.customer_id == "C00001").first_name, "Tim") delete_customer('C00001')
def customer_list_ids(max_records=1000): """ A method to provide a generator to step through the customer list and yield the customer_id. """ customers = Customer.select().dicts() if max_records >= len(customers): max_records = len(customers) max_records -= 1 i = 0 while i <= max_records: yield customers[i]['customer_id'] i += 1
def test_delete_customer(set_up_connection): ''' Tests delete_customer to verify specified customer was deleted from db First add the customer to be deleted, then delete them with joy! Using OK_CUSTOMER_2 for this test module only. ''' add_customer(**OK_CUSTOMER_2) test_customer_2 = Customer.get( Customer.customer_id == OK_CUSTOMER_2['customer_id']) assert test_customer_2.email_address == OK_CUSTOMER_2['email_address'] delete_results = delete_customer(test_customer_2.customer_id) assert delete_results == 'person successfully deleted'
def update_customer_credit(cust_id, credit_limit): """ Query that updates a specific customer's credit limit. :param cust_id: :param new_credit_limit: :return: Updated credit limit """ update_query = Customer.update(credit_limit=credit_limit) \ .where(Customer.customer_id == cust_id) if not update_query.execute(): raise ValueError("Record does not exist") return True
def filter_by_credit(min_credit): """ Return names and the associated customer ID of active customers who meet the specified minimum credit limit criteria. """ acustomer_list = Customer.select().where(Customer.status) LOGGER.info(f'Retrieving the active customers in the database '+\ f'who meet the minimum credit criteria.') return [ f'{cust.name} ({cust.customer_id})' for cust in acustomer_list if cust.credit_limit >= min_credit ]
def update_customer_credit(customer_id, credit_limit): '''Updates a customer's credit limit''' try: LOGGER.info('Attempting to update credit limit for customer ID: %s to $%s', customer_id, credit_limit) customer = Customer.get(Customer.cust_id == customer_id) customer.credit = credit_limit customer.save() LOGGER.info('Updated credit limit for cutomer ID: %s to $%s', customer_id, customer.credit) except peewee.DoesNotExist: LOGGER.info('Customer ID: %s does not exist in the database', customer_id) raise ValueError
def test_create_add_customers(self): """Tests creating and adding numerous customers to database.""" # Add all people to database for i, fname, lname, addr, phone, email, status, limit in \ zip(range(1, self.num_customers + 1), self.fnames, self.lnames, self.addresses, self.phones, self.emails, self.statuses, self.credit_limits): created = Customer.create(id=i, name=fname, last_name=lname, address=addr, phone=phone, email=email, status=status, credit_limit=limit) created.save() # Assert have self.num_customers customers in DB customer_count = Customer.select().count() self.assertEqual(self.num_customers, customer_count)