def read_mapping(self):
        """ Read CSV file assuming file will have header """
        logger.info("Reading CustomerMapping file: %s" % self.mapping_file)
        if not os.path.exists(self.mapping_file):
            logger.error("CustomerMapping file (%s) not found."  % self.mapping_file)
            return
        configreader = csv.DictReader(open(self.mapping_file))
        result = {}
        for row in configreader:
            for column, value in row.iteritems():
                result.setdefault(column, []).append(value)
        if result and len(result):
            for index in range(len(result[self.KEY_ID])):
                customer =  Customer()
                customer.set(result[self.KEY_ID][index],
                                     result[self.KEY_URL][index],
                                     result[self.KEY_USERNAME][index],
                                     result[self.KEY_PASSWORD][index],
                                     int(result[self.KEY_TICKETING_API][index]),
                                     result[self.KEY_EXTRA_INFO][index]
                                     )
#             int(result[self.KEY_AT_STATUS][index]),
#             int(result[self.KEY_AT_PRIORITY][index]),
#             int(result[self.KEY_AT_QUEUE_ID][index]),
#             int(result[self.KEY_AT_ACCOUNT_ID][index]
            
                customer.print_info()
                self.__customers[customer.id.strip()] = customer
        return len(self.__customers)
            
Example #2
0
def customers_with_id(customer_id):
    if request.method == 'GET':
        data={"error":"Something went wrong. Please try again later."}
        app.logger.error('GET /customers with id method called')

        responseStatusCode = 500
        try:
            customer = collection_customers.find_one({"guid":customer_id})
            app.logger.info('customer object: ' + str(customer))
            customer_obj = Customer.fromDict(customer)
            data = customer_obj
            responseStatusCode = 200
        except KeyError as e:
            data = {"error":"Invalid id for the recording."}
            responseStatusCode = 400
        except Exception as e:
            data = {"error":"Something went wrong. Please try again later. "+str(e)}
            responseStatusCode = 500    
        (data,mime) = (jsonParser.DateTimeJSONEncoder().encode(data),'application/json')
        return Response(data, status=responseStatusCode, mimetype=mime)
    
    if request.method == 'PUT':
        data={"error":"Something went wrong. Please try again later."}
        app.logger.error('PUT /customers with id method called')
        responseStatusCode = 500
        try:
            customer = collection_customers.find_one({"guid":customer_id})
            customer_obj = Customer.fromJson(request.data, request.method, customer_id)
            app.logger.info('customer object 2: ' + str(customer_obj))
            #store the recording in the recording collection
            collection_customers.update({'guid':customer_id},{"$set": customer_obj.toDict()},upsert=True) #upsert creates the object if not existing
            data = customer_obj
            app.logger.info('customer object 3: ' + str(customer_obj))
            responseStatusCode = 200
        except TypeError as e:
            data = {"error":"Customer could not be created because the data in the body of the request was bad." + str(e)}
            responseStatusCode = 400
        except Exception as e:
            data = {"error":"Something went wrong. Please try again later. "+ str(e)}
            responseStatusCode = 500
        (data,mime) = (jsonParser.DateTimeJSONEncoder().encode(data),'application/json')
        return Response(data, status=responseStatusCode, mimetype=mime) 

    if request.method == 'DELETE':
        data={"error":"Something went wrong. Please try again later."}
        responseStatusCode = 500
        try:
            collection_customers.update({'guid':customer_id},{"$set": {"status": "deleted"}})
            data = {"success":"Customer with guid: "+customer_id+" deleted successfully."}
            responseStatusCode = 200
        except KeyError as e:
            data = {"error":"Invalid id for the customer. "+str(e)}
            responseStatusCode = 400
        except Exception as e:
            data = data={"error":"Something went wrong. Please try again later. "+str(e)}
            responseStatusCode = 401
        (data,mime) = (jsonParser.DateTimeJSONEncoder().encode(data),'application/json')
        return Response(data, status=responseStatusCode, mimetype=mime)
def addCombinedQueue():
    cust=Customer(request.json['customerName'], request.json['custId'], request.json['order'],0)
    cust.orderTime = request.json['orderTime']
    combinedOrder.put(cust)
    responsedata = {
        'status': 'Order Received'
    }
    responsedata = json.dumps(responsedata)
    resp = Response(responsedata, status=201, mimetype='application/json')
    return resp
def test_statement():
    checkingAccount = Account(CHECKING)
    savingsAccount = Account(SAVINGS)
    henry = Customer("Henry").openAccount(checkingAccount).openAccount(savingsAccount)
    checkingAccount.deposit(100.0)
    savingsAccount.deposit(4000.0)
    savingsAccount.withdraw(200.0)
    assert_equals(henry.getStatement(),
                  "Statement for Henry" +
                  "\n\nChecking Account\n  deposit $100.00\nTotal $100.00" +
                  "\n\nSavings Account\n  deposit $4000.00\n  withdrawal $200.00\nTotal $3800.00" +
                  "\n\nTotal In All Accounts $3900.00")
def write(user_id, password, model, odoo_id, vals):
    _check_user(user_id, password)
    if model not in ["customer", "product"]:
        raise Fault("unknown_model", "Reference model does not exist!")
    if model == "customer":
        try:
            customer = Customer.get(Customer.odoo_id == odoo_id)
        except Customer.DoesNotExist:
            raise Fault("unknown_registry", "Customer not found!")
        q = Customer.update(**vals).where(Customer.odoo_id == odoo_id)
    else:
        try:
            product = Product.get(Product.odoo_id == odoo_id)
        except Product.DoesNotExist:
            raise Fault("unknown_registry", "Product not found!")
        q = Product.update(**vals).where(Product.odoo_id == odoo_id)
    q.execute()
    return True
Example #6
0
def customers():
    if request.method == 'GET':
        app.logger.error('GET /customers method called')
        data={"error":"Something went wrong. Please try again later."}
        responseStatusCode = 500
        try:
            customers = collection_customers.find()
            response = []
            for customer_dict in customers:
                app.logger.error("sander" + str(customer_dict))
                customer_obj = Customer.fromDict(customer_dict)
                response.append(customer_obj)
            data = response
            app.logger.error('Data sent as part of the GET /customers: ' + str(data))
            responseStatusCode = 200
        except Exception as e:
            data={"error":"Something went wrong. Please try again later. "+str(e)}  
            app.logger.error('Error in GET /customers: '+repr(e)) 
            responseStatusCode = 500
        (data,mime) = (jsonParser.DateTimeJSONEncoder().encode(data),'application/json')
        return Response(data, status=responseStatusCode, mimetype=mime)
    
    if request.method == 'POST':
        app.logger.error('POST /customers method called')
        data={"error":"Something went wrong. Please try again later."}
        responseStatusCode = 500
        try:     
            customer_obj = Customer.fromJson(request.data)
            collection_customers.insert(customer_obj.toDict())
            data = customer_obj
            #app.logger.error('Data sent as part of the POST /customers: ' + str(data))
            (data,mime) = (jsonParser.DateTimeJSONEncoder().encode(data),'application/json')
            responseStatusCode = 200

        except TypeError as e:
            data = {"error":"Customer could not be created because the data in the body of the request was bad." + str(e)}
            responseStatusCode = 400
        except Exception as e:
            data = {"error":"Something went wrong. Please try again later."+ str(e)}
            app.logger.error('Error in POST /customers: '+str(e)) 
            responseStatusCode = 500
        (data,mime) = (jsonParser.DateTimeJSONEncoder().encode(data),'application/json')
        return Response(data, status=responseStatusCode, mimetype=mime)
def create(user_id, password, model, vals):
    _check_user(user_id, password)
    odoo_id = vals["odoo_id"]
    if model not in ["customer", "product"]:
        raise Fault("unknown_model", "Reference model does not exist!")
    if model == "customer":
        try:
            customer = Customer.get(Customer.odoo_id == odoo_id)
        except Customer.DoesNotExist:
            q = Customer.insert(**vals)
        else:
            q = Customer.update(**vals).where(Customer.odoo_id == odoo_id)
    else:
        try:
            product = Product.get(Product.odoo_id == odoo_id)
        except Product.DoesNotExist:
            q = Product.insert(**vals)
        else:
            q = Product.update(**vals).where(Product.odoo_id == odoo_id)
    q.execute()
    return True
Example #8
0
    def arrival(self, agenda):
        # Servers are available, service the customer
        service_time = gamma(self.aS, self.bS)
        if agenda.has_servers():
            # Initialise the customer
            customer = Customer(agenda.current_time, service_time)
            customer.set_service_start(agenda.current_time)

            # Schedule customer for departure
            agenda.get_server()
            agenda.schedule(agenda.current_time + service_time, self.departure, [customer])

        # No servers available, add customer to the queue
        else:
            agenda.add_customer(Customer(agenda.current_time, service_time))

        self.arrivals += 1
        if self.arrivals < self.max_arrivals:
            # New arrival
            new_arr_time = gamma(self.aA, self.bA)
            agenda.schedule(agenda.current_time + new_arr_time, self.arrival, [])
def unlink(user_id, password, model, odoo_id):
    _check_user(user_id, password)
    if model not in ["customer", "product"]:
        raise Fault("unknown_model", "Reference model does not exist!")
    q = False
    if model == "customer":
        try:
            customer = Customer.get(Customer.odoo_id == odoo_id)
        except Customer.DoesNotExist:
            pass
        else:
            q = Customer.delete().where(Customer.odoo_id == odoo_id)
    else:
        try:
            product = Product.get(Product.odoo_id == odoo_id)
        except Product.DoesNotExist:
            pass
        else:
            q = Product.delete().where(Product.odoo_id == odoo_id)
    if q:
        q.execute()
    return True
Example #10
0
    def runSimulation(self):
        """Run the clock for n ticks."""
        for currentTime in xrange(self._lengthOfSimulation):
            # Attempt to generate a new customer
            customer = Customer.generateCustomer(
                self._probabilityOfNewArrival,
                currentTime,
                self._averageTimePerCus)

            # Send customer to cashier if successfully generated
            if customer != None:
                self._cashier.addCustomer(customer)

            # Tell cashier to provide another unit of service
            self._cashier.serveCustomers(currentTime)
        return str(self._cashier)
Example #11
0
    def runSimulation(self):
        """Run the clock for n ticks."""
        for currentTime in range(self._lengthOfSimulation):
            # Attempt to generate a new customer
            customer = Customer.generateCustomer(
                self._probabilityOfNewArrival,
                currentTime,
                self._averageTimePerCus)

            # Send customer to a randomly chosen cashier
            # if successfully generated
            if customer != None:
                random.choice(self._cashiers).addCustomer(customer)

            # Tell all cashiers to provide another unit of service
            for cashier in self._cashiers:
                cashier.serveCustomers(currentTime)
def handle_message_event(json):
	tagId = json['data']
	result = Customer.objects(tagId=tagId);
	try:
		customer = result[0]
		oldTracking = customer.tracking
		currentTracking = 'loung'
		newTracking = '?'
		now =  datetime.now()
		if oldTracking != currentTracking:
			customer.update(tracking=currentTracking,trackingDate = now)
			newTracking = currentTracking
		else: 
			customer.update(tracking=newTracking,trackingDate = now)
			newTracking = '?'
		broadcastSelectedCustomer(customer.tagId)
		broadcastCustomerListInLoung()
	except IndexError:
		print('Customer ?')
def broadcastCustomerListInLoung():
	result = Customer.objects(tracking='loung').order_by('-trackingDate')
	customerList = []
	for customer in result:
		customerList.append({
			'tagId':customer.tagId,
			'firstName':customer.firstName,
			'lastName':customer.lastName,
			'sex':customer.sex,
			'tracking':customer.tracking,
			'trackingDate':customer.trackingDate.strftime("%Y-%m-%d %H:%M:%S"),
			'flyingBlueId':customer.flyingBlueId,
			'language':customer.language,
			'phone':customer.phone,
			'email':customer.email,
			'birthday':customer.birthday.strftime("%Y-%m-%d"),
			'flightFrom':customer.flightFrom,
			'flightTo':customer.flightTo,
			'departureTime':customer.departureTime,
			'meal':customer.meal,
			'newsPaper':customer.newsPaper})
	socketio.emit('customerListInLoung', customerList, broadcast=True)
def broadcastSelectedCustomer(tagId):
	result = Customer.objects(tagId=tagId)
	singleCustomerList = []
	for customer in result:
		singleCustomerList.append({
			'tagId':customer.tagId,
			'firstName':customer.firstName,
			'lastName':customer.lastName,
			'sex':customer.sex,
			'tracking':customer.tracking,
			'trackingDate':customer.trackingDate.strftime("%Y-%m-%d %H:%M:%S"),
			'flyingBlueId':customer.flyingBlueId,
			'language':customer.language,
			'phone':customer.phone,
			'email':customer.email,
			'birthday':customer.birthday.strftime("%Y-%m-%d"),
			'flightFrom':customer.flightFrom,
			'flightTo':customer.flightTo,
			'departureTime':customer.departureTime,
			'meal':customer.meal,
			'newsPaper':customer.newsPaper})
	if len(singleCustomerList):
		socketio.emit('selectedCustomer', singleCustomerList, broadcast=True)
    def test_statement_for_many_movies_and_rentals(self):
        customer1 = Customer('David')
        movie1 = Movie('Madagascar', Movie.CHILDRENS)
        rental1 = Rental(movie1, 6) # 6 day rental
        movie2 = Movie('Star Wars', Movie.NEW_RELEASE)
        rental2 = Rental(movie2, 2) # 2 day rental
        movie3 = Movie('Gone with the Wind', Movie.REGULAR)
        rental3 = Rental(movie3, 8) # 8 day rental
        customer1.add_rental(rental1)
        customer1.add_rental(rental2)
        customer1.add_rental(rental3)
        expected = """Rental Record for David
\tMadagascar\t6.0
\tStar Wars\t6.0
\tGone with the Wind\t11.0
Amount owed is 23.0
You earned 4 frequent renter points"""
        statement = customer1.statement()
        self.assertEquals(expected, statement)
Example #16
0
import random
import datetime
from customer import Customer

atm = Customer(id)

while True:
    id = int(input("Masukkan pin anda: "))
    trial = 0

    while (id != int(atm.checkPin()) and trial < 3):
        id = int(input("Pin anda salah. Silahkan masukkan lagi: "))

        trial += 1

        if trial == 3:
            print("Error. SIlahkan ambil kartu dan coba lagi...")
            exit()

    while True:
        print("Selamat datang di ATM Progate...")
        print(
            "\n1 - Cek Saldo \t 2 - Debet \t 3 - Simpan \t 4 - Ganti Pin \t 5 - Keluar"
        )

        selectmenu = int(input("\n Silahkan pilih menu: "))

        if selectmenu == 1:
            print("\n Saldo anda sekarang: Rp. " + str(atm.checkBalance()) +
                  "\n")
def getProfile(tag):
	result = Customer.objects(tagId=tag)
	return result[0].tagId + ' ' + result[0].firstName + ' ' + result[0].lastName + ' ' + result[0].email
Example #18
0
from supplier import Supplier
from item import Item
from supply import Supply
from order import Order
from admin import Administrator

supply = list()
orders = list()
items = list()

admin1 = Administrator("iamgod", "iamthelaw", "*****@*****.**")
supplier1 = Supplier("isupply", "4real", "Crab Shack Company", "Van Crabs",
                     "000-112-35-8", "*****@*****.**")
supplier2 = Supplier("isupplytoo", "4real", "Reliable Company", "Van Reliable",
                     "011-112-35-8", "*****@*****.**")
customer1 = Customer("iamguido", "4sure", "Guido", "Van Rossum",
                     "000-112-35-8", "*****@*****.**", "09-09-1968")
item1 = Item("Banana", "Better than ever before", 799.0,
             ("Golden", "Fresh Green"))
item2 = Item("Best Banana", "Better than others", 899.0,
             ("Truly Golden", "Fresher Green"))

supply.append(supplier1.add_supply(item1, 10))
supply.append(supplier2.add_supply(item2, 3))

customer1.create_order(item2, 5)
print(customer1.orders[0].status)

admin1.update_supply([supplier1, supplier2])
admin1.update_orders([customer1])

admin1.check_order(customer1.orders[0])
Example #19
0
def main():
    # Initialize different plans
    single_plan = Plan('Single', 49, 1)
    plus_plan = Plan('Plus', 99, 3)
    infinite_plan = Plan('Infinite', 249, -1)

    # Initialize multiple websites
    website_1 = Website('https://website_1.com')
    website_2 = Website('https://website_2.com')
    website_3 = Website('https://website_3.com')
    website_4 = Website('https://website_4.com')

    # Initialize multiple customers
    customer_1 = Customer('customer_1', '123456789', '*****@*****.**')
    customer_2 = Customer('customer_2', '123456789', '*****@*****.**')
    customer_3 = Customer('customer_3', '123456789', '*****@*****.**')

    # customer_1 subscribed for single_plan
    customer_1.add_subscription(single_plan)
    print("{} has subscribed for {} plan".format(customer_1,
                                                 customer_1.subscription.plan))

    # customer_1 added one website
    customer_1.add_website(website_1)
    print("{} has added website {} as per the {} plan".format(customer_1, \
            customer_1.websites, customer_1.subscription.plan))

    # customer_1 can not add more website in single_plan
    customer_1.add_website(website_2)
    print("{} can't add website {} as per the {} plan".format(customer_1, \
            website_2, customer_1.subscription.plan))

    # customer_1 can change plan from single_plan to plus_plan
    customer_1.change_plan(plus_plan)
    print("{} has changed his current plan {} to {} plan".format(customer_1, \
            single_plan, customer_1.subscription.plan))

    # customer_2 subscribe for infinite_plan
    customer_2.add_subscription(infinite_plan)

    # customer_2 can add multiple websites
    customer_2.add_website(website_1)
    customer_2.add_website(website_2)
    customer_2.add_website(website_3)
    customer_2.add_website(website_4)

    print("{} has added four websites {} under infinite plan".format(customer_2, \
            customer_2.websites))
Example #20
0
#     for myRow in schedRows:
#         print(myRow["CruiseDate"])
#         print(myRow["CruiseNo"])
#         print(myRow["departure"])
#         print(myRow["name"])
# else:
#     print(sched.error)

#exit()
# cntry = Country()
# (dbStatus, name) = cntry.readCountryByCode(con,'nzl')
# print ('CountryName: ',name)

# Create new customer
custRow = []
cust = Customer(con, 'NZL')
print('Customer country code: ', cust.countryCode)

#(dbStatus, custRow) = cust.readCustbyEmail(con,"*****@*****.**")
# (dbStatus, custRow) = cust.readCustbyEmail(con,"*****@*****.**")
# if (dbStatus == True):
#     print(cust.surname)
# else:
#      print(cust.error)
# cust.surname = ""
# dbStatus = cust.updateCust(con,cust.CustID)
# if dbStatus == True:
#     print('Updated Successfully')
# else:
#     print('Error:', cust.error)
#
Example #21
0
import random
import datetime
from customer import Customer

atm = Customer(id)

while True:
    id = int(input("Enter your pin number: "))
    trial = 0

    while (id != int(atm.checkPin()) and trial < 3):
        id = int(input("Wrong pin number. Try again: "))

        trial += 1

        if trial == 3:
            print("Error! Take a card and Try again..")
            exit()

    while True:
        print("Welcome to ATM Console")
        print(
            "1. Balance Check \n2. Withdraw \n3. Deposit \n4. Change Pin \n5. Exit"
        )

        selectMenu = int(input("Select Menu: "))
        if selectMenu == 1:
            print("\nYour current balance: Rp. " + str(atm.checkBalance()) +
                  "\n")

        elif selectMenu == 2:
Example #22
0
 def __init__(self, accountid, customerid, custname, address,
              contactdetails):
     super().__init__()
     self.accountID = accountid
     self.customer = Customer(customerid, custname, address, contactdetails)
     self.balance = 0
Example #23
0
 def add_customer(self):
     # assign a new customer to the staging queue
     c = Customer(r.randint(1, 5))
     self.staging_queue.enqueue(c)
     self.n_customers += 1  # increment n_customers
Example #24
0
now = datetime.now()
dt_string = now.strftime("%H%M%S_%d_%m_%Y")
#print("date and time =", dt_string)

if not os.path.exists("log"):
    os.mkdir("log")

logging.basicConfig(filename=os.path.join("log", dt_string + '.log'),
                    level=logging.INFO)
random.seed(para.seed)
#'consumer_' + str(i)
# Create 500  Consumers objects and assign initial with tolerance and wallet
customers = [
    Customer(name=names.get_full_name(),
             wallet=500,
             tolerance=0.5 + 0.4 * random.random())
    for i in range(1, (para.numberofcustomer + 1))
]

# Construct a product object with following attributes
iphone = Product(name='iphoneX', price=300, quality=0.9)
galaxy = Product(name='Note', price=200, quality=0.8)
sony = Product(name='Xperia', price=100, quality=0.6)

# Create a Seller object with product as one of the attributes
seller_apple = Seller(name='APPLE INC', product=iphone, wallet=1000)
seller_samsung = Seller(name='SAMSUNG MOBILES', product=galaxy, wallet=500)
seller_sony = Seller(name='SONY', product=sony, wallet=500)
# Wait till the simulation ends
try:
Example #25
0
 def test_when_create_customer_then_customer_should_have_name_and_lastName_notempty(self):
     customer = Customer('vero', 'rodriguez')
     assert customer.get_name()
     assert customer.get_last_name()
Example #26
0
from vendor import Vendor 
from weather import Weather 
from customer import Customer 
from money import Money 
from supplies import Supplies
from lemonade import Lemonade 

vendor = Vendor()
today = Weather()
cash = Money()
supplies = Supplies()
lemonade = Lemonade()
customer = Customer()


def main():
	day = 0
	play_time = today.get_play_duration()
	weekdays = today.get_weekday_list(play_time)
	while day < play_time:
		cash.show_status()
		today.get_forecast()		
		vendor.show_list_buy(supplies, cash, vendor)
		cash.show_status()		
		lemonade.make_lemonade(supplies.lemons, supplies.sugar, supplies.ice, supplies.cups) 		
		vendor.set_price()
		customer.get_customers(vendor.price, cash, today.weather_score, supplies, vendor, lemonade)
		supplies.subtract_supplies(lemonade.sold_lemonade())
		cash.show_earnings()
		for each_day in weekdays:
			weekdays.remove(weekdays[0])
Example #27
0
 def test_when_create_customer_with_identifier_type_passport_then_identifier_type_should_cedula_passport_ruc(self):
     customer = Customer('vero', 'rodri', 'passport')
     self.assertIn(customer.get_identifier_type(), ['celula', 'passport', 'ruc'])
Example #28
0
from customer import Customer

luiz = Customer('Luiz', 32)
luiz.insert_address('Belo Horizonte', 'MG')
print(luiz.name)
luiz.list_addresses()
del luiz

maria = Customer('Maria', 55)
maria.insert_address('Salvador', 'BA')
maria.insert_address('Rio de Janeiro', 'RJ')
print(maria.name)
maria.list_addresses()
del maria

john = Customer('John', 19)
john.insert_address('Sao Paulo', 'SP')
print(john.name)
john.list_addresses()
del john
        if dvd in customer.rented_dvds:
            customer.rented_dvds.remove(dvd)
            dvd.is_rented = False
            return f"{customer.name} has successfully returned {dvd.name}"
        return f"{customer.name} does not have that DVD"

    def __repr__(self):
        result = ""
        for customer in self.customers:
            result += customer.__repr__() + "\n"
        for dvd in self.dvds:
            result += dvd.__repr__() + "\n"
        return result


c1 = Customer("John", 16, 1)
c2 = Customer("Anna", 55, 2)

d1 = DVD("Black Widow", 1, 2020, "April", 18)
d2 = DVD.from_date(2, "The Croods 2", "23.12.2020", 3)

movie_world = MovieWorld("The Best Movie Shop")

movie_world.add_customer(c1)
movie_world.add_customer(c2)

movie_world.add_dvd(d1)
movie_world.add_dvd(d2)

print(movie_world.rent_dvd(1, 1))
print(movie_world.rent_dvd(2, 1))
Example #30
0
 def customer_is_registered(self, customer):
     Customer.customer_is_registered(customer)
Example #31
0
def __main__():
    # create character
    myName = raw_input("Please enter character name: ")
    myGender = raw_input("Please enter character gender (M/F): ")
    if myName == "":
        myName = "Hero"
    if myGender == "":
        myGender = "M"
    myCustomer = Customer(myName, myGender)
    print str(myCustomer)

    myMonster = CookieMonster()
    print
    print str(myMonster)

    ###
    if DEBUG_MODE:
        print "DEBUG: cust/monst HP: " + str(myCustomer.getHealth()) +\
              "/" + str(myMonster.getHealth())
        print "DEBUG: DEATH: " + str(myCustomer.isDead()) +\
              "/" + str(myMonster.isDead())
    ###

    print "monster found! BATTLE!!"
    # while loop
    while (not myCustomer.isDead()) and myCustomer.getLevel() < 4:
        #if monster is alive
        #battle round
        if myMonster.getHealth() > 0:

            #####
            #USER TURN
            #####
            needInput = True
            monsterHit = False
            while needInput:

                print ""
                print "Your HP: " + str(myCustomer.getHealth()) +\
                      "Monster HP: " + str(myMonster.getHealth())
                print ""
                userIn = raw_input("would you like to (F)ight, " +\
                               "(R)un, or (E)xplode? ").upper()
                print ""
                if userIn == 'E':
                    print "You run up and hug the Cookie Monster, " +\
                          "begin to tick, and blow up, " +\
                          "taking it and all the thin mints with you."
                    myMonster.setHealth(0)
                    myCustomer.setHealth(0)
                    needInput = False

                    ###
                    if DEBUG_MODE:
                        print "DEBUG: cust/monst HP: " + str(myCustomer.getHealth()) +\
                              "/" + str(myMonster.getHealth())
                        print "DEBUG: DEATH: " + str(myCustomer.isDead()) +\
                              "/" + str(myMonster.isDead())
                    ###

                elif userIn == 'R':
                    print "COWARD! You manage to get away, "+\
                          "though not with your dignity..."
                    myMonster.setHealth(0)
                    needInput = False
                elif userIn == 'F':
                    monsterHit = True
                    print "You tell the Cookie Monster " +\
                          "you don't have any money!"
                    if myMonster.isHit():
                        dmg = myCustomer.dealsDamage()
                        print "You weaken the Cookie Monster's " +\
                              "sales pitch by " + str(dmg) + " damage!"
                        myMonster.takesHit(dmg)
                    else:
                        print "The Cookie Monster doesn't believe your lie " +\
                              "and laughs at your incompetence!"
                    needInput = False
                else:
                    print "Lets try this input thing again, shall we?"

            #####
            #MONSTER TURN
            #####
            #if monster is still alive
            if not myMonster.isDead():
                print "The Cookie Monster tries to sell you delicious cookies!"
                if myCustomer.isHit():
                    dmg = myMonster.dealsDamage()
                    print "The Cookie Monster hits your wallet for " +\
                          str(dmg) + " damage!"
                    myCustomer.takesHit(dmg)
                else:
                    print "You start to talk about the weather, " +\
                          "breaking the Cookie Monster's sales pitch!"
            #if monster was killed by player
            elif monsterHit:
                print "You chased her off crying! " +\
                      "\nDon't you feel like a big person!"

                #get XP
                myCustomer.setExperience(myMonster.getXP())
                myCustomer.incrementLevel()
                print "!!!LEVEL UP!!! \n*fireworks, fireworks*\n" +\
                      "You are now level " + str(myCustomer.getLevel())
                #get cookies
                cookiesDropped = myMonster.getThinMints()
                if cookiesDropped > 0:
                    print "Wait, she dropped some cookies! " +\
                          "Well, would be a shame if they went to waste..."
                    print "\nAcquired " + str(cookiesDropped) +\
                          " Cookies!\n"
                    myCustomer.setThinMints(cookiesDropped)

        #if monster is dead
        else:
            #regen
            if myCustomer.getHealth() < myCustomer.getMaxHealth():
                myCustomer.regenHealth()
            #eat cookies
            if myCustomer.getThinMints() != 0:
                print "You have " + str(myCustomer.getThinMints()) +\
                      "\nand " + str(myCustomer.getHealth()) +\
                      "/" + str(myCustomer.getMaxHealth()) +\
                      "health."
                userIn = eval(raw_input("How many thin mints would" +\
                                        "you like to eat? "))
                myCustomer.eatThinMints(userIn)
                print "You NOW have " + str(myCustomer.getThinMints()) +\
                      "\nand " + str(myCustomer.getHealth()) +\
                      "/" + str(myCustomer.getMaxHealth()) +\
                      "health."

            #chance to ATAMO
            if myCustomer.atamo():
                print "REMEMBER THE ALAMO! errr... ATAMO! " +\
                      "\n FULL HEAL!"
                myCustomer.setHealth(myCustomer.getMaxHealth())

            #chance to spawn new monster
            if random.randint(1, 3) == 1:
                myMonster = CookieMonster()
                print "monster found! BATTLE!!"

    #####
    #END GAME LOOP
    #DO END GAME RESULTS
    #####
    #end of game messages, check health and level to determine msg
    print "\n"
    if myCustomer.isDead():
        if myMonster.isDead():
            print "Well, you're in debt for the rest of your life, " +\
                  "but at least you took one down with you!"
        else:
            print "You have fallen to the seductive nature of the thin mint." +\
                  "Enjoy being broke and fat!"
    elif myMonster.isDead():
        if myCustomer.getLevel() >= 4:
            print "You Win!!! You weathered the storm and " +\
                  "managed to keep your bank account in the black... this year!"
        else:
            print "Wait, you shouldn't be here!" +\
                  "Quick! Report this bug to the nearest girlscout!!"

    print "\nGAME OVER\n"
    raw_input("Press Enter to exit.")
## Ch09 P9.26

from customer import Customer

c1 = Customer()
print(c1.makePurchase(90))
print(c1.makePurchase(20))
print(c1.makePurchase(80))
print(c1.makePurchase(100))
print(c1.makePurchase(60))
Example #33
0
def main():
    print("### Testing Products ###")
    p1 = Product("1238223", "Sword", 1899.99, 10)

    print("Id: {}".format(p1.id))
    print("Name: {}".format(p1.name))
    print("Price: {}".format(p1.price))
    print("Quantity: {}".format(p1.quantity))

    p1.display()

    print()

    p2 = Product("838ab883", "Shield", 989.75, 6)
    print("Id: {}".format(p2.id))
    print("Name: {}".format(p2.name))
    print("Price: {}".format(p2.price))
    print("Quantity: {}".format(p2.quantity))

    p2.display()

    print("\n### Testing Orders ###")
    # Now test Orders
    order1 = Order()
    order1.id = "1138"
    order1.add_product(p1)
    order1.add_product(p2)

    order1.display_receipt()

    print("\n### Testing Customers ###")
    # Now test customers
    c = Customer()
    c.id = "aa32"
    c.name = "Gandalf"
    c.add_order(order1)

    c.display_summary()

    print()
    c.display_receipts()

    # Add another product and order and display again

    p3 = Product("2387127", "The Ring", 1000000, 1)
    p4 = Product("1828191", "Wizard Staff", 199.99, 3)

    order2 = Order()
    order2.id = "1277182"
    order2.add_product(p3)
    order2.add_product(p4)

    c.add_order(order2)

    print()
    c.display_summary()

    print()
    c.display_receipts()
class TestCustomer(unittest.TestCase):

    def setUp(self):
        self._customer = Customer('Sallie')
        self._create_movies()
        
    def _create_movies(self):
        self._movies = {}
        for movie in TEST_MOVIES:
            self._movies[movie[0]] = Movie(*movie)

    def test_add_rental(self):
        movie = Movie('Gone with the Wind', Movie.REGULAR)
        rental = Rental(movie, 3) # 3 day rental
        self._customer.add_rental(rental)
        self.assertIn(rental, self._customer.get_rentals())

    def test_get_name(self):
        self.assertEquals('Sallie', self._customer.get_name())

    def rent(self, name, duration):
        rental = Rental(self._movies[name], duration)
        self._customer.add_rental(rental)

    def check_statement(self, expected):
        self.assertEquals(expected, self._customer.statement())

    def test_statement_for_regular_movie(self):
        self.rent('Gone with the Wind', 3)
        self.check_statement("""Rental Record for Sallie
\tGone with the Wind\t3.5
Amount owed is 3.5
You earned 1 frequent renter points""")
    
    def test_statement_for_new_release_movie(self):
        self.rent('Star Wars', 3)
        self.check_statement("""Rental Record for Sallie
\tStar Wars\t9.0
Amount owed is 9.0
You earned 2 frequent renter points""")
    
    def test_statement_for_childrens_movie(self):
        self.rent('Madagascar', 3)
        self.check_statement("""Rental Record for Sallie
\tMadagascar\t1.5
Amount owed is 1.5
You earned 1 frequent renter points""")
    
    def test_statement_for_many_movies_and_rentals(self):
        customer1 = Customer('David')
        movie1 = Movie('Madagascar', Movie.CHILDRENS)
        rental1 = Rental(movie1, 6) # 6 day rental
        movie2 = Movie('Star Wars', Movie.NEW_RELEASE)
        rental2 = Rental(movie2, 2) # 2 day rental
        movie3 = Movie('Gone with the Wind', Movie.REGULAR)
        rental3 = Rental(movie3, 8) # 8 day rental
        customer1.add_rental(rental1)
        customer1.add_rental(rental2)
        customer1.add_rental(rental3)
        expected = """Rental Record for David
\tMadagascar\t6.0
\tStar Wars\t6.0
\tGone with the Wind\t11.0
Amount owed is 23.0
You earned 4 frequent renter points"""
        statement = customer1.statement()
        self.assertEquals(expected, statement)
Example #35
0
    def fill_test(self): 
        show=notification.Notifications() 
        Rotana_hotel = Hotel(1,"Rotana","Abu Dhabi",200,40)
        Rotana_hotel.add_hotel()
        show.display(Rotana_hotel)  # Display General details for ONE hotels
        Sheraton_hotel = Hotel(2,"Sheraton","Abu Dhabi",300,100)
        Sheraton_hotel.add_hotel()
        Hayat_hotel = Hotel(3,"Hayat","Aden",150,100)
        Hayat_hotel.add_hotel()
        Crecent_hotel = Hotel(4,"Crecent","Mukala",200,50)
        Crecent_hotel.add_hotel()
        Holydayin_hotel = Hotel(5,"Holydayin","Sana'a",200,100)
        Holydayin_hotel.add_hotel()
        Rotana_hotel = Hotel(1,"Rotana","Abu Dhabi",200,40)
        Rotana_hotel.add_hotel()
        Zero_hotel = Hotel(6,"Zero","Virtual",200,0)  # used to check unavailablity condition
        Zero_hotel.add_hotel()
        show.display("\t list of the Hotels available")
        show.display(Hotel.hotels)           # Display General details for all hotels
        show.display(Hayat_hotel.hotel_name) # Display the name for ONE hotel
    

        #Create instance objects for 4 customers 
        Saqr_Thabet=Reservation("Hayat","Saqr_thabet","+8613094449161")
        Ali_Ahmed=Reservation("Holydayin","Ali_ahmed","+8613094449161")
        Ameer_Nezar=Reservation("Holydayin","Ameer_nezar","+8613094449161")
        Galal_Taleb=Reservation("Zero","Galal_taleb","+8613228191565")

        #Create reservations for 4 customers
        if Saqr_Thabet.add_new_reservation():
            s_t=Customer(Saqr_Thabet.hotel_name,Saqr_Thabet.customer,Saqr_Thabet.number)
            s_t.add_customer()
            show.display(Saqr_Thabet.message)
            #show.display(Saqr_Thabet.reservations)
            #show.send_message(Saqr_Thabet.message,Saqr_Thabet.number)
    
        if Ali_Ahmed.add_new_reservation():
            m_a=Customer(Ali_Ahmed.hotel_name,Ali_Ahmed.customer,Ali_Ahmed.number)
            m_a.add_customer()
            show.display(Ali_Ahmed.message)
            #show.display(Ali_Ahmed.reservations)
            #show.send_message(Ali_Ahmed.message,Ali_Ahmed.number)
            
        if Ameer_Nezar.add_new_reservation():
            m_b=Customer(Ameer_Nezar.hotel_name,Ameer_Nezar.customer,Ameer_Nezar.number)
            m_b.add_customer()
            show.display(Ameer_Nezar.message)
            #show.display(Ameer_Nezar.reservations)
            #show.send_message(Ameer_Nezar.message,Ameer_Nezar.number)

    #def Test_reservation_disapproval():
        show.display("\t Test_reservation_disapproval ") 
        if Galal_Taleb.add_new_reservation():   # no rooms available 
            m_c=Customer(Galal_Taleb.hotel_name,Galal_Taleb.customer,Galal_Taleb.number)
            #show.display(Galal_Taleb.message)
            #show.display(Galal_Taleb.reservations)
            #m_a1.send_message(Galal_Taleb.message,Galal_Taleb.number)

        
    #def Test_misspelled_hotel_name():
        show.display("\t Test_misspelled_hotel_name ")
        Fagr_khalil=Reservation("Holyday","Fagr_Khalil","+8613094449161")
        Fagr_khalil.add_new_reservation()

    #def Test_delete_a_customer():
        show.display('\t Test_delete_a_customer')
        show.display(m_b.customer_list)        
        m_a.delete_customer()           # delete customer from customer Class
        show.display(m_b.customer_list)
        
    #def Test_reservation_removal():
        show.display('\t Test_reservation_removal')
        show.display(Ameer_Nezar.reservations)
        Ameer_Nezar.delete_a_reservation()   # delete customer booking from reswervation Class
        show.display(Ameer_Nezar.reservations)

    #def Test_delete_a_hotel():
        show.display('\t Test_delete_a_hotel')
        show.display(Hotel.hotels)
        Rotana_hotel.delete_hotel() 
        show.display(Hotel.hotels)

    #def Test_reservation_in_a_hotel(hotel):
        show.display("\t Test_reservation_in_a_hotel('Holydayin')")
        show.display(reservation.list_resevrations_for_hotel('Holydayin')) #from reservation.py
    
    #def Test_list_of_available_hotels_in_a_city(city):
        show.display("\t Test_list_of_available_hotels_in_a_city('Abu Dhabi')") 
        show.display(hotel.list_hotels_in_city('Abu Dhabi')) # from hotel.py
Example #36
0
def insert_customer(cpf, name, active, total_value):
    c = Customer(cpf, name, active, total_value)
    handler.insert(c)
Example #37
0
def main():
    """ The main function """

    # Create two manufacturers and add models of bike
    pinarello = Manufacturer("Pinarello", 0.3)
    pinarello.add_model("TimeAttack", CarbonFrame, TimeTrialWheel)
    pinarello.add_model("RoadWarrior", AluminiumFrame, RoadWheel)
    pinarello.add_model("SanRemo", CarbonFrame, RoadWheel)

    trek = Manufacturer("Trek", 0.3)
    trek.add_model("MountainHawg", SteelFrame, MountainBikeWheel)
    trek.add_model("Rodeo", SteelFrame, RoadWheel)
    trek.add_model("Everest", CarbonFrame, MountainBikeWheel)

    # Create a shop which stocks products from both manufacturers
    bobs_cycles = Shop("Bob's Cycles", 0.2)
    bobs_cycles.add_manufacturer(pinarello)
    bobs_cycles.add_manufacturer(trek)

    # Buy 5 of each bike as stock
    for i in xrange(5):
        bobs_cycles.buy("Pinarello", "TimeAttack")
        bobs_cycles.buy("Pinarello", "RoadWarrior")
        bobs_cycles.buy("Pinarello", "SanRemo")

        bobs_cycles.buy("Trek", "MountainHawg")
        bobs_cycles.buy("Trek", "Rodeo")
        bobs_cycles.buy("Trek", "Everest")

    # Create three customers with different budgets
    alice = Customer("Alice", 200)
    dan = Customer("Dan", 500)
    carol = Customer("Carol", 1000)

    customers = (alice, dan, carol)

    # Print the weight of the bikes sold by Bob's Cycles
    print "Bicycle weights:"
    print ""
    for bike_specification in bobs_cycles.product_range():
        print "{:40} {}kg".format(bike_specification.full_name(),
                                  bike_specification.weight)
    print ""

    # Print the bikes which each customer can afford
    print "Customers:"
    print ""
    for customer in customers:
        print "{} can afford the following bikes:".format(customer.name)
        print ""
        for bike_specification in bobs_cycles.product_range():
            price = bobs_cycles.price(bike_specification.manufacturer_name,
                                      bike_specification.name)
            if price > customer.money:
                continue

            print bike_specification.full_name()
        print ""

    # Print the current stock levels at Bob's Cycles
    print "Inventory of Bob's Cycles: "
    print ""
    for bike_specification in bobs_cycles.product_range():
        stock = bobs_cycles.stock(bike_specification.manufacturer_name,
                                  bike_specification.name)
        print "{:40} {} in stock".format(bike_specification.full_name(), stock)

    # Buy a bike for each customer
    alice.buy(bobs_cycles, "Trek", "MountainHawg")
    dan.buy(bobs_cycles, "Trek", "MountainHawg")
    carol.buy(bobs_cycles, "Pinarello", "SanRemo")
    print ""

    # Print the customer's purchases, and remaining money
    for customer in customers:
        print "{} now owns a {}".format(customer.name,
                                        customer.bike.full_name())
        print "{} has ${:.2f} remaining".format(customer.name, customer.money)
        print ""

    # Print the updates stock levels
    print "Updated inventory of Bob's Cycles: "
    print ""
    for bike_specification in bobs_cycles.product_range():
        stock = bobs_cycles.stock(bike_specification.manufacturer_name,
                                  bike_specification.name)
        print "{:40} {} in stock".format(bike_specification.full_name(), stock)

    print ""

    # Print the amount of profit Bob has made
    print "Profit for Bob's Cycles: ${}".format(bobs_cycles.profit)
Example #38
0
    datestring = generate_datestring(curr_date)

    amount = round(random.uniform(0.01, 999999.99), 2)

    signed_transaction = merchants[merchant_id].create_transaction(
        customers[customer_id], datestring, amount)

    miner.add_block(signed_transaction)

    return curr_date


if __name__ == "__main__":
    curr_date = datetime.date(2020, 1, 1)

    customers = [Customer() for i in range(5)]
    merchants = [Merchant() for i in range(2)]
    miner = MinerNode()

    for i in range(0, 25):
        curr_date = generate_transaction(customers, merchants, miner,
                                         curr_date)

    if sys.argv[1] == '0':
        miner.display()
    elif sys.argv[1] == '1':
        if miner.is_chain_valid():
            print("The Blockchain has not been tampered with!")
        else:
            print("The Blockchain HAS been tampered with!")
        miner.increment_fifteen()
def test_oneAccount():
    oscar = Customer("Oscar").openAccount(Account(SAVINGS))
    assert_equals(oscar.numAccs(), 1)
Example #40
0
 def register_customer(self, customer):
     Customer.register_customer_in_db(self, customer)
 def setUp(self):
     self._customer = Customer('Sallie')
     self._create_movies()
Example #42
0
from supplier import Supplier
from log_orm import logger
from item import Item
from supply import Supply
from order import Order

supply = list()
orders = list()
item = list()

admin1 = Administrator("iamgod", "iamthelaw", "*****@*****.**")
supplier1 = Supplier("isupply", "4real", "Crab Shack Company", "Van Crabs",
                    "000-112-35-8", "*****@*****.**")
supplier2 = Supplier("isupplytoo", "4real", "Reliable Company", "Van Reliable",
                    "011-112-35-8", "*****@*****.**")
customer1 = Customer("iamguido", "4sure", "Guido", "Van Rossum", "000-112-35-8",
                    "*****@*****.**", "09-09-1968")
customer2 = Customer("_iamguido", "_4sure", "_Guido", "_Van Rossum", "000-112-35-8",
                    "*****@*****.**", "09-09-1968")
item1 = Item("Banana", "Better than ever before", 799.0,
            ("Golden", "Fresh Green"))
item2 = Item("Best Banana", "Better than others", 899.0,
            ("Truly Golden", "Fresher Green"))

supply.append(supplier1.add_supply(item1, 10))
supply.append(supplier2.add_supply(item2, 5))

customer1.create_order(item2, 5)
logger.info(customer1.orders[0].status)
customer1.create_review(item1, 10)
logger.info(customer1.reviews[0].status)
from customer import Customer
from Menu import *

PrintCustManMenu()

cust1 = Customer("0001", "Jessie", "Andy", "Delso", "336 N. Martha St. Lombard, IL 60148","September 18, 2010")

cust1.printCustomer()

Example #44
0
    def add_customers(self, N_cust, added=False):
        """
        Initialize customers on random positions.
        Returns a list of all customers
        """

        # a list of weights of which the indices correspond to the id of the agent
        # to who this weight is given
        weights_list = []

        # Adaptive strategy
        if self.adaptive is True:

            # Decide weights for every customer
            for j in self.strategy_composition.keys():
                for i in range(round(N_cust * self.strategy_composition[j])):
                    weights_list.append(j)

            # Add weights for the random strategy
            if len(weights_list) < self.N_cust:
                rand = random.choice(self.strategies)
                weights_list.append(rand)
            elif len(weights_list) > self.N_cust:
                rand = random.choice(weights_list)
                weights_list.remove(rand)

        else:
            if self.strategy is not "Random":
                for i in range(round(N_cust)):
                    print(self.weight)
                    weights_list.append(self.weight)

        cust_list = []
        for i in range(N_cust):

            # Get random location within grid height and width
            pos_temp = [
                random.randint(0, WIDTH - 1),
                random.randint(0, HEIGHT - 1)
            ]
            rand_x, rand_y = pos_temp[0], pos_temp[1]
            pos = (rand_x, rand_y)

            if added is True:
                i = self.cust_ids
            if self.strategy == "Random_test_4":
                if weights_list[i] == "Random_test_4":
                    strategy = "Random_test_4"
                else:
                    strategy = "Closest_by"
            else:
                strategy = self.strategy

            if weights_list == []:
                weight = None
            else:
                weight = weights_list[i]

            # make customer
            a = Customer(i, self, pos, strategy, weight, self.adaptive)
            self.schedule_Customer.add(a)
            self.grid.place_agent(a, pos)
            cust_list.append(a)

        return cust_list
Example #45
0
import unittest
from customer import Customer
import json

cust = Customer()


class testadd(unittest.TestCase):
    #def initialize(self, customers):
    #self.customers  = customers

    def test_add(self):
        result = cust.add_customer("90000000", "RCB", "*****@*****.**")
        self.assertIn("RCB", result)
Example #46
0
    def post(self):
        # Check user
        user = users.get_current_user()
        url_linktext, greeting, user_class = check.check_user(user, self.request.uri)

        # check user are shoping or not
        shop = self.request.get("shop")
        # check client requesting service
        client = self.request.get("client")

        if user_class not in ["manager", "employee"] and not shop and client != "mobile":
            # render
            template_values = {
                "greeting": greeting,
                "user_class": user_class,
                "url_linktext": url_linktext,
                "detail": "Limited Access!",
            }
            path = os.path.join(os.path.dirname(__file__), "error.html")
            self.response.out.write(template.render(path, template_values))
            return

            # Get var from request and pass to data model object
        code = self.request.get("code")

        # shoping user cant mofify order
        if shop and code:
            # render
            template_values = {
                "greeting": greeting,
                "user_class": user_class,
                "url_linktext": url_linktext,
                "detail": "Limited Access!",
            }
            path = os.path.join(os.path.dirname(__file__), "error.html")
            self.response.out.write(template.render(path, template_values))
            return

            # Query
        # 		query = db.Query(Product, keys_only=False);
        # 		query.filter("code =", code);
        # 		data = query.fetch(1);
        try:
            order = db.get(db.Key.from_path("Order", int(code)))
        except:
            order = None

        status = ""
        if order:
            status = "Sửa thông tin thành công!"
        else:
            status = "Tạo Đơn Hàng thành công!"
            order = Order()
            order.created = datetime.datetime.now()
            order.who_created = user
            # save order to get auto generated code
            order.put()
            order.code = str(order.key().id())

        order.modified = datetime.datetime.now()
        order.who_modified = user
        # get customer of order
        try:
            customer = db.get(db.Key.from_path("Customer", order.customer))
        except:
            customer = None

        # freely to change if confirm is false
        if not order.confirm:
            try:
                order.confirm = bool(self.request.get("confirm"))
            except:
                pass
                # get list_item and list_quantity, list_chosen (and make changes to database if confirm = true
            for i in range(15):
                # save last item code
                prev_item_code = order.list_item[i]
                # get new item code
                order.list_item[i] = self.request.get("item" + str(i))
                try:
                    order.list_price[i] = float(self.request.get("price" + str(i)))
                except:
                    pass
                # get price if item code change
                try:
                    item = db.get(db.Key.from_path("Product", order.list_item[i]))
                except:
                    item = None

                    # clear price when no product code
                if not item:
                    order.list_price[i] = 0.0
                    # update quantity and spec chosen
                try:
                    order.list_quantity[i] = int(self.request.get("quantity" + str(i)))
                except:
                    order.list_quantity[i] = 0
                order.list_chosen[i] = self.request.get("chosen" + str(i))

                # clear spec_chosen when phoduct code change (except for the case shop , client mobile) or product code = ''
                if not shop and client != "mobile" and prev_item_code != order.list_item[i] or order.list_item[i] == "":
                    order.list_chosen[i] = ""

                # only update price when product code changes
                if item and prev_item_code != order.list_item[i]:
                    # price = item.sell_price*(1-item.on_sale% or customer.private_sale%)
                    sale_off = 0
                    if customer:
                        sale_off = customer.private_sale
                    if item.on_sale:
                        sale_off = item.on_sale
                    if sale_off > 100:
                        sale_off = 100
                    order.list_price[i] = item.sell_price * (1 - float(sale_off) / 100)

                    # also make quantity = 1 if quantity=0
                    if not order.list_quantity[i]:
                        order.list_quantity[i] = 1

                    # check for remove quantity and spec_choice from database when confirm change from false to true. If cant remove, confirm order = false.
                if item and order.confirm:
                    if (item.quantity < order.list_quantity[i]) or (
                        item.spec_choices and order.list_chosen[i] not in item.spec_choices
                    ):
                        status = "Đơn hàng này ko xác nhận được! Kiểm tra lại các thông tin sản phẩm!"
                        order.confirm = False
                        # get var from request
            try:
                order.hidden = bool(self.request.get("hidden"))
            except:
                order.hidden = False

                # actually remove quantity and spec_choice from database
            if order.confirm:
                for i in range(15):
                    try:
                        item = db.get(db.Key.from_path("Product", order.list_item[i]))
                    except:
                        continue
                    if not item:
                        continue
                    # save root_price at the time product being sold
                    order.list_root_price[i] = item.root_price
                    # change and save item
                    item.quantity -= order.list_quantity[i]
                    for iter0 in range(order.list_quantity[i]):
                        try:
                            item.spec_choices.remove(order.list_chosen[i])
                        except:
                            pass
                    item.put()
                    # make hidden = False ( confirmed order cant be hidden)
                order.hidden = False

                # get var from request
            order.customer = self.request.get("customer")
            try:
                order.note = db.Text(self.request.get("note"))
            except:
                order.note = ""

                # order is confirmed, cant change but only unconfirmed.
        if order.confirm:
            try:
                order.confirm = bool(self.request.get("confirm"))
            except:
                pass
            if order.confirm:
                status = "Đơn hàng này đã được xác nhận! Thông tin sẽ ko thể thay đổi cho tới khi hủy xác nhận!"
            else:  # unconfirming order
                # undo the changes from database and get list_item and list_quantity, list_chosen
                for i in range(15):
                    # save last item code
                    prev_item_code = order.list_item[i]
                    # get new item code
                    order.list_item[i] = self.request.get("item" + str(i))
                    try:
                        item = db.get(db.Key.from_path("Product", order.list_item[i]))
                    except:
                        item = None
                        # undo the changes from database when confirm change from true to false.
                        # find prev item
                    if prev_item_code == order.list_item[i]:
                        prev_item = item
                    elif prev_item_code:
                        prev_item = db.get(db.Key.from_path("Product", prev_item_code))
                    if prev_item:
                        # undo changes and save
                        prev_item.quantity += order.list_quantity[i]
                        for iter0 in range(order.list_quantity[i]):
                            prev_item.spec_choices += [order.list_chosen[i]]
                        prev_item.put()

                        # Get price
                    try:
                        order.list_price[i] = float(self.request.get("price" + str(i)))
                    except:
                        pass
                    # only update price when product code changes
                    if item and prev_item_code != order.list_item[i]:
                        # price = item.sell_price*(1-item.on_sale% or customer.private_sale%)
                        sale_off = 0
                        if customer:
                            sale_off = customer.private_sale
                        if item.on_sale:
                            sale_off = item.on_sale
                        if sale_off > 100:
                            sale_off = 100
                        order.list_price[i] = item.sell_price * (1 - float(sale_off) / 100)

                        # update quantity and spec chosen
                    try:
                        order.list_quantity[i] = int(self.request.get("quantity" + str(i)))
                    except:
                        order.list_quantity[i] = 0
                    order.list_chosen[i] = self.request.get("chosen" + str(i))

                order.customer = self.request.get("customer")
                try:
                    order.note = db.Text(self.request.get("note"))
                except:
                    order.note = ""
                try:
                    order.hidden = bool(self.request.get("hidden"))
                except:
                    order.hidden = False

        order.put()  # save data model object to data base
        # create account at first time user send an order
        if shop and order.customer and not customer:
            customer = Customer(key_name=order.customer)
            customer.created = datetime.datetime.now()
            customer.who_created = user
            customer.code = order.customer
            customer.email = db.Email(order.customer)
            customer.modified = datetime.datetime.now()
            customer.who_modified = user

            m = re.search(r"Ten KH:\s*(.+)", self.request.get("note"))
            if m:
                customer.name = m.group(1)

            m = re.search(r"Dia Chi:\s*(.+)\nSo DT:", self.request.get("note"), re.DOTALL)
            if m:
                customer.address = db.Text(m.group(1))

            m = re.search(r"So DT:\s*(.+)", self.request.get("note"))
            if m:
                customer.phone = m.group(1)

            m = re.search(r"Ngay Sinh Nhat:\s*(\d+)\s*/\s*(\d+)\s*", self.request.get("note"))
            if m:
                customer.birth_day = int(m.group(1))
                customer.birth_month = int(m.group(2))

            customer.put()

            # response and redirect
        self.response.out.write(status)
        if shop:
            if user:
                self.redirect("/user/?" + urllib.urlencode({"code": order.code, "status": status}))
            else:
                self.redirect("/")
        else:
            self.redirect("/order/?" + urllib.urlencode({"code": order.code, "status": status, "client": client}))
Example #47
0
    oscar = Customer("Oscar").openAccount(Account(SAVINGS))
    oscar.openAccount(Account(CHECKING))
    assert_equals(oscar.numAccs(), 2)


@nottest
def test_threeAccounts():
    oscar = Customer("Oscar").openAccount(Account(SAVINGS))
    oscar.openAccount(Account(CHECKING))
    assert_equals(oscar.numAccs(), 3)


bank = Bank()
checkingAccount = Account(CHECKING)
savingAccount = Account(SAVINGS)
bill = Customer("Bill")
bill.openAccount(checkingAccount)
bill.openAccount(savingAccount)
bank.addCustomer(bill)
checkingAccount.deposit(100.0)
checkingAccount.deposit(500.0)
checkingAccount.deposit(2000.0)
savingAccount.deposit(900.0)

from_acc = checkingAccount
to_acc = savingAccount


def test_transfer_success():
    transfer_amount = 100
    result = bill.transfer(from_acc, to_acc, transfer_amount)
Example #48
0
def test_oneAccount():
    oscar = Customer("Oscar").openAccount(Account(SAVINGS))
    assert_equals(oscar.numAccs(), 1)
Example #49
0
def test_threeAccounts():
    oscar = Customer("Oscar").openAccount(Account(SAVINGS))
    oscar.openAccount(Account(CHECKING))
    assert_equals(oscar.numAccs(), 3)
Example #50
0
 def customer(self):
     if self.customer_id is None:
         return False
     return Customer.fetch(self.customer_id)
Example #51
0
class VideoStoreTest(unittest.TestCase):

    def setUp(self):
        self.customer = Customer('Fred')

    def test_single_new_release_statement(self):
        self.customer.add_rental(Rental(Movie('The Cell', Movie.NEW_RELEASE), 3))
        self.assertEquals('Rental Record for Fred\n\tThe Cell\t9\nYou owed 9\nYou earned 2 frequent renter points\n', self.customer.statement())

    def test_dual_new_release_statement(self):
        self.customer.add_rental(Rental(Movie('The Cell', Movie.NEW_RELEASE), 3))
        self.customer.add_rental(Rental(Movie('The Tigger Movie', Movie.NEW_RELEASE), 3))
        self.assertEquals('Rental Record for Fred\n\tThe Cell\t9\n\tThe Tigger Movie\t9\nYou owed 18\nYou earned 4 frequent renter points\n', self.customer.statement())

    def test_single_childrens_statement(self):
        self.customer.add_rental(Rental(Movie('The Tigger Movie', Movie.CHILDRENS), 3))
        self.assertEquals('Rental Record for Fred\n\tThe Tigger Movie\t1.5\nYou owed 1.5\nYou earned 1 frequent renter points\n', self.customer.statement())

    def test_multiple_regular_statement(self):
        self.customer.add_rental(Rental(Movie('Plan 9 from Outer Space', Movie.REGULAR), 1))
        self.customer.add_rental(Rental(Movie('8 1/2', Movie.REGULAR), 2))
        self.customer.add_rental(Rental(Movie('Eraserhead', Movie.REGULAR), 3))

        self.assertEquals('Rental Record for Fred\n\tPlan 9 from Outer Space\t2\n\t8 1/2\t2\n\tEraserhead\t3.5\nYou owed 7.5\nYou earned 3 frequent renter points\n', self.customer.statement())
def test_threeAccounts():
    oscar = Customer("Oscar").openAccount(Account(SAVINGS))
    oscar.openAccount(Account(CHECKING))
    assert_equals(oscar.numAccs(), 3)
Example #53
0
 def customers(cls, **kwargs):
     return Customer._build_list(cls.get("customers", **kwargs))
Example #54
0
def main():
    """ The main function """

    # Create two manufacturers and add models of bike
    pinarello = Manufacturer("Pinarello", 0.3)
    pinarello.add_model("TimeAttack", CarbonFrame, TimeTrialWheel)
    pinarello.add_model("RoadWarrior", AluminiumFrame, RoadWheel)
    pinarello.add_model("SanRemo", CarbonFrame, RoadWheel)

    trek = Manufacturer("Trek", 0.3)
    trek.add_model("MountainHawg", SteelFrame, MountainBikeWheel)
    trek.add_model("Rodeo", SteelFrame, RoadWheel)
    trek.add_model("Everest", CarbonFrame, MountainBikeWheel)

    # Create a shop which stocks products from both manufacturers
    bobs_cycles = Shop("Bob's Cycles", 0.2)
    bobs_cycles.add_manufacturer(pinarello)
    bobs_cycles.add_manufacturer(trek)

    # Buy 5 of each bike as stock
    for i in xrange(5):
        bobs_cycles.buy("Pinarello", "TimeAttack")
        bobs_cycles.buy("Pinarello", "RoadWarrior")
        bobs_cycles.buy("Pinarello", "SanRemo")

        bobs_cycles.buy("Trek", "MountainHawg")
        bobs_cycles.buy("Trek", "Rodeo")
        bobs_cycles.buy("Trek", "Everest")

    # Create three customers with different budgets
    alice = Customer("Alice", 200)
    dan = Customer("Dan", 500)
    carol = Customer("Carol", 1000)

    customers = (alice, dan, carol)

    # Print the weight of the bikes sold by Bob's Cycles
    print "Bicycle weights:"
    print ""
    for bike_specification in bobs_cycles.product_range():
        print "{:40} {}kg".format(bike_specification.full_name(),
                                  bike_specification.weight)
    print ""

    # Print the bikes which each customer can afford
    print "Customers:"
    print ""
    for customer in customers:
        print "{} can afford the following bikes:".format(customer.name)
        print ""
        for bike_specification in bobs_cycles.product_range():
            price = bobs_cycles.price(bike_specification.manufacturer_name,
                                      bike_specification.name)
            if price > customer.money:
                continue

            print bike_specification.full_name()
        print ""

    # Print the current stock levels at Bob's Cycles
    print "Inventory of Bob's Cycles: "
    print ""
    for bike_specification in bobs_cycles.product_range():
        stock = bobs_cycles.stock(bike_specification.manufacturer_name,
                                  bike_specification.name)
        print "{:40} {} in stock".format(bike_specification.full_name(), stock)

    # Buy a bike for each customer
    alice.buy(bobs_cycles, "Trek", "MountainHawg")
    dan.buy(bobs_cycles, "Trek", "MountainHawg")
    carol.buy(bobs_cycles, "Pinarello", "SanRemo")
    print ""

    # Print the customer's purchases, and remaining money
    for customer in customers:
        print "{} now owns a {}".format(customer.name,
                                        customer.bike.full_name())
        print "{} has ${:.2f} remaining".format(customer.name, customer.money)
        print ""


    # Print the updates stock levels
    print "Updated inventory of Bob's Cycles: "
    print ""
    for bike_specification in bobs_cycles.product_range():
        stock = bobs_cycles.stock(bike_specification.manufacturer_name,
                                  bike_specification.name)
        print "{:40} {} in stock".format(bike_specification.full_name(), stock)

    print ""

    # Print the amount of profit Bob has made
    print "Profit for Bob's Cycles: ${}".format(bobs_cycles.profit)
Example #55
0
    c.execute("SELECT * FROM customers WHERE last=:last", {'last': lastname})
    return c.fetchall()


def update_points(cust, points):
    with conn:
        c.execute("""UPDATE customers SET points = :points
                    WHERE first = :first AND last = :last""",
                  {'first': cust.first, 'last': cust.last, 'points': points})


def remove_custs(cust):
    with conn:
        c.execute("DELETE from customers WHERE first = :first AND last = :last",
                  {'first': cust.first, 'last': cust.last})
cust_1 = Customer('James', 'Gibson', 670)
cust_2= Customer('Holly ', 'Burns', 12039)
cust_3 = Customer('Alyson', 'Harper', 835)
cust_4 = Customer('Kimberly', 'Reeves', 23489)

def input_answer():
    while True: 
    answer= input("Enter Y for yes  or N for No:")
    if answer == "y":
    
        
print("Welcome to Esobar Mart.")
print("Are you a returning customer?")


 def customers(cls, **kwargs):
     return Customer._build_list(cls.get("customers", **kwargs))
Example #57
0
import tornado.ioloop
import tornado.web
from customer import Customer
from addhandler import AddHandler
from delhandler import DelHandler
from gethandler import GetHandler
from query import GetDetails

custs = Customer()


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Customers information Microservice v1")


def make_app():
    return tornado.web.Application([
        (r"/v1", MainHandler),
        (r"/v1/addcustomer", AddHandler, dict(custs=custs)),
        (r"/v1/delcustomer", DelHandler, dict(custs=custs)),
        (r"/v1/getcustomers", GetHandler, dict(custs=custs)),
        (r"/v1/getdetails", GetDetails, dict(custs=custs))
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
Example #58
0
from customer import Customer
from supplier import Supplier
from item import Item
from supply import Supply
from order import Order
from admin import Administrator
from review import Review

supply = list()
orders = list()
items = list()
reviews = list()

admin1 = Administrator("iamgod", "iamthelaw", "*****@*****.**")
supplier1 = Supplier("isupply", "4real", "Crab Shack Company", "Van Crabs",
                     "000-112-35-8", "*****@*****.**")
supplier2 = Supplier("isupplytoo", "4real", "Reliable Company", "Van Reliable",
                     "011-112-35-8", "*****@*****.**")
customer1 = Customer("iamguido", "4sure", "Guido", "Van Rossum",
                     "000-112-35-8", "*****@*****.**", "09-09-1968")
item1 = Item("Banana", "Better than ever before", 799.0,
             ("Golden", "Fresh Green"))
item2 = Item("Best Banana", "Better than others", 899.0,
             ("Truly Golden", "Fresher Green"))

customer1.add_review(item2, "very tasty", 5)
reviews.append(customer1.add_review(item2, "very tasty", 5))
Example #59
0
 def setUp(self):
     self.customer = Customer('Fred')