Ejemplo n.º 1
0
    def readStore(self):  # yuki
        with open('database.json', 'r') as infile:
            savedStore = json.loads(infile.read())
        for productData in savedStore['products']:
            productId = productData['id']
            productName = productData['name']
            productUnit = productData['unit']
            productOriginalPrice = productData['originalPrice']
            productSource = productData['source']
            productShelfLife = productData['shelfLife']
            batches = productData['batch']
            product = Product(productId, productName, productUnit,
                              productOriginalPrice, productSource,
                              productShelfLife)
            for batch in batches:
                sDate = batch['shelfDate'].split('-')
                bShelfDate = datetime.date(int(sDate[0]), int(sDate[1]),
                                           int(sDate[2]))
                batchId = batch['batchId']
                batchActualPrice = batch['actualPrice']
                batchQuantity = batch['quantity']
                batchShelfDate = bShelfDate
                product.buildBatch(batchId, batchActualPrice, batchQuantity,
                                   batchShelfDate, productShelfLife)
            self.products.append(product)
        for customerData in savedStore['customers']:
            cId = customerData['id']
            cPassword = customerData['password']
            cName = customerData['name']
            cPhoneNumber = customerData['phoneNumber']
            cAddress = customerData['address']
            cBalance = customerData['balance']
            cShoppingCart = customerData['shoppingCart']
            customer = CustomerAccount(cId, cPassword, cName, cPhoneNumber,
                                       cAddress, cBalance)
            customer.shoppingCart.setProductsInCart(cShoppingCart)
            self.customers.append(customer)

        for customerId in savedStore['orderHistory']:
            cOrderList = savedStore['orderHistory'][customerId]
            customerOrders = []
            for eachOrder in cOrderList:
                orderId = eachOrder['orderId']
                orderCId = eachOrder['customerId']
                tempShoppingCart = eachOrder['shoppingCart']
                orderShoppingCart = ShoppingCart()
                orderShoppingCart.setProductsInCart(tempShoppingCart)
                orderTotalPrice = eachOrder['totalPrice']
                dateS = eachOrder['transactionDate'].split('-')
                orderTransactionDate = datetime.datetime(
                    int(dateS[0]), int(dateS[1]), int(dateS[2]), int(dateS[3]),
                    int(dateS[4]), int(dateS[5]))
                order = Order(orderId, orderCId, orderShoppingCart,
                              orderTotalPrice, orderTransactionDate)
                customerOrders.append(order)
            self.orderHistory[customerId] = customerOrders

        ownerData = savedStore['owner']
        self.owner = OwnerAccount(ownerData['id'], ownerData['name'],
                                  ownerData['password'])
Ejemplo n.º 2
0
def test_add():
    cart = ShoppingCart()
    item = Apple()
    cart.add(item)
    if len(cart._cart[item.name]) > 1:
        raise Exception("Items in cart should be 1, not {}".format(
            len(cart._cart[item.name])))
Ejemplo n.º 3
0
def main():

    c1 = ShoppingCart()

    c1._customerName = input("Enter customer's name: \n")
    c1._currentDate = input("Enter today's date: (Month Day, Year)\n")

    menu(c1)
Ejemplo n.º 4
0
def test_discount_repeat():
    cart = ShoppingCart()
    item1 = Apple()
    item2 = Banana()
    cart.add(item1)
    cart.add(item1)
    cart.add(item2)
    cart.apply_discount_code("M3GABUCKS")
    try:
        cart.apply_discount_code("M3GABUCKS")
        raise Exception("Failed due to discount code being accepted twice")
    except DiscountCodeAlreadyInUse:
        pass
Ejemplo n.º 5
0
 def addOrder(self,
              customerId,
              pInSc,
              tPrice=0.0,
              tDate=datetime.datetime.now()):
     if customerId not in self.orderHistory:
         self.orderHistory[customerId] = []
     nid = self.generateNewOrderId(customerId)
     scRec = ShoppingCart()
     scRec.setProductsInCart(pInSc)
     newOrder = Order(nid, customerId, scRec, tPrice, tDate)
     self.orderHistory[customerId].append(newOrder)
     return newOrder
    def checkout_to_invoice(self, checkout_form):
        '''Payment'''
        dictionary = {}
        dictionary['type'] = checkout_form.payment_type.data
        if dictionary['type'] == 'pp':
            #PayPal!
            dictionary['pp_email'] = checkout_form.pp_email.data
            dictionary['pp_password'] = checkout_form.pp_password.data

        elif dictionary['type'] == 'cc':
            #Credit Card!
            dictionary['cc_number'] = checkout_form.card.data
            dictionary['cc_exp_m'] = checkout_form.exp_m.data
            dictionary['cc_exp_y'] = checkout_form.exp_y.data
            dictionary['cc_cvv'] = checkout_form.cvv.data
        elif dictionary['type'] == 'fa':
            #Financial aid!
            dictionary['fa_login'] = checkout_form.fa_login.data
            dictionary['fa_password'] = checkout_form.fa_password.data
        '''Shipping'''
        dictionary['ship_name'] = checkout_form.shipping_name.data
        dictionary['ship_addr'] = checkout_form.shipping_addr.data
        dictionary['ship_state'] = checkout_form.shipping_state.data
        dictionary['ship_city'] = checkout_form.shipping_city.data
        dictionary['ship_zip'] = checkout_form.shipping_zip.data
        '''Billing Address'''
        billing = checkout_form.same_as_shipping.data
        dictionary['same_as_shipping'] = str(billing)
        if billing:
            dictionary['bill_name'] = dictionary['ship_name']
            dictionary['bill_addr'] = dictionary['ship_addr']
            dictionary['bill_state'] = dictionary['ship_state']
            dictionary['bill_city'] = dictionary['ship_city']
            dictionary['bill_zip'] = dictionary['ship_zip']
        else:
            dictionary['bill_name'] = checkout_form.billing_name.data
            dictionary['bill_addr'] = checkout_form.billing_addr.data
            dictionary['bill_state'] = checkout_form.billing_state.data
            dictionary['bill_city'] = checkout_form.billing_city.data
            dictionary['bill_zip'] = checkout_form.billing_zip.data
        ''' Financial '''
        sc = ShoppingCart()
        st = sc.get_cart_subtotal()
        s_t = float(st) + 14.99
        tax = float(s_t) * .07
        total = s_t + tax
        dictionary['subtotal'] = st
        dictionary['total'] = total
        dictionary['tax'] = tax

        return dictionary
Ejemplo n.º 7
0
 def take_order(self, shopping_cart: ShoppingCart, shipping_type, cost: int,
                region_id: int):
     product_list = shopping_cart.checkout()
     if product_list.__len__() > 0:
         order = Orders(self._user_id)
         for item in product_list:
             data = ShoppingCart.get_item_details(item)
             product_id = data[0]
             quantity = data[3]
             order.add_order_detail(product_id, quantity)
         order.set_shipping_info(shipping_type, cost, region_id)
         order.place_order()
     else:
         print("product list is empty")
Ejemplo n.º 8
0
    def setUp(self):
        self.food = Category('food')
        self.home = Category('home')
        self.apple = Product('apple', 100.0, self.food)
        self.almond = Product('almond', 50.0, self.food)
        self.chair = Product('chair', 100.0, self.home)

        self.cart = ShoppingCart()
        self.cart.addItem(self.apple, 3)
        self.cart.addItem(self.almond, 1)
        self.cart.addItem(self.chair, 2)

        self.costPerDelivery = 10.0
        self.costPerProduct = 10.0
        self.fixedPrice = 80.0
        self.deliveryCostCalculator = DeliveryCostCalculator(
            self.costPerDelivery, self.costPerProduct, self.fixedPrice)
Ejemplo n.º 9
0
def test_discount():
    cart = ShoppingCart()
    item1 = Apple()
    item2 = Banana()
    cart.add(item1)
    cart.add(item1)
    cart.add(item2)
    cart.apply_discount_code("M3GABUCKS")
    if cart._item_totals['TOTAL'] != 2.8:
        raise Exception("total is incorrect")
Ejemplo n.º 10
0
def test_total():
    cart = ShoppingCart()
    item1 = Apple()
    item2 = Banana()
    cart.add(item1)
    cart.add(item1)
    cart.add(item2)
    cart.totals()
    if cart._item_totals['BANANA'] != 2 or cart._item_totals[
            'APPLE'] != 2 or cart._item_totals['TOTAL'] != 4:
        raise Exception("total is incorrect")
Ejemplo n.º 11
0
    def setUp(self):
        self.food = Category('food')
        self.home = Category('home')
        self.apple = Product('apple', 100.0, self.food)
        self.almond = Product('almond', 50.0, self.food)
        self.chair = Product('chair', 100.0, self.home)

        self.cart = ShoppingCart()
        self.cart.addItem(self.apple, 3)
        self.cart.addItem(self.almond, 1)
        self.cart.addItem(self.chair, 2)

        self.campaign1 = Campaign(self.food, 25.0, 1, DiscountType.Rate)
        self.campaign2 = Campaign(self.home, 50.0, 3, DiscountType.Rate)
        self.campaign3 = Campaign(self.food, 12, 1, DiscountType.Amount)
        self.campaign4 = Campaign(self.home, 10, 3, DiscountType.Amount)

        self.coupon1 = Coupon(100.0, 10.0, DiscountType.Rate)
        self.coupon2 = Coupon(1000.0, 10.0, DiscountType.Rate)
        self.coupon3 = Coupon(100.0, 100.0, DiscountType.Amount)
        self.coupon4 = Coupon(1000.0, 100.0, DiscountType.Amount)
Ejemplo n.º 12
0
class OrderFacade:
    def __init__(self):
        self.stock = Stock()
        self.shoppingCart = ShoppingCart()
        self.order = Order()
        self.shipment = Shipment()
        self.payment = Payment()

    def doOperation(self, name, value=''):
        if name == "вибрати":
            index = -1
            for item in self.stock.product.products:
                index += 1
                if item == value:
                    self.stock.selectStockItem(index)
        elif name == "добавити у кошик":
            self.shoppingCart.addItem(value)
        elif name == "замовлення":
            self.shoppingCart.addItem(value)
        elif name == "доставити":
            self.shipment.createShipment(value)
        elif name == "заплатити":
            if self.payment.verifyPayment(value):
                print("Підтвердження оплати")
                return True
            else:
                if input("Не існує картки, бажаєте зареєструвати одну?\n"
                         ) == "так":
                    self.payment.addCardDetails(value)
                    print("Підтвердження оплати")
                    return True
                else:
                    return False
        elif name == "поновити":
            self.shoppingCart.checkout()
Ejemplo n.º 13
0
class TestDeliveryCostCalculator(unittest.TestCase):
    def setUp(self):
        self.food = Category('food')
        self.home = Category('home')
        self.apple = Product('apple', 100.0, self.food)
        self.almond = Product('almond', 50.0, self.food)
        self.chair = Product('chair', 100.0, self.home)

        self.cart = ShoppingCart()
        self.cart.addItem(self.apple, 3)
        self.cart.addItem(self.almond, 1)
        self.cart.addItem(self.chair, 2)

        self.costPerDelivery = 10.0
        self.costPerProduct = 10.0
        self.fixedPrice = 80.0
        self.deliveryCostCalculator = DeliveryCostCalculator(
            self.costPerDelivery, self.costPerProduct, self.fixedPrice)

    def test_should_calculate_delivery_cost(self):
        expectedDeliveryCost = (self.costPerDelivery * 2) + (
            self.costPerProduct * 3) + self.fixedPrice
        actualResult = self.deliveryCostCalculator.calculateFor(self.cart)

        self.assertEqual(actualResult, expectedDeliveryCost)
        self.assertEqual(self.cart.deliveryCost, actualResult)
Ejemplo n.º 14
0
    def calculateFor(self, cart: ShoppingCart) -> float:
        # I took related categories as unique since they are distinct.
        numberOfDeliveries = len(cart.categories.keys())
        numberOfProducts = 0

        # all products counts as unique since I assumed that product titles are unique
        for category in cart.categories:
            numberOfProducts += len(cart.categories[category]['products'])

        cart.deliveryCost = (self.costPerDelivery * numberOfDeliveries) + (
            self.costPerProduct * numberOfProducts) + self.fixedPrice

        return cart.deliveryCost
Ejemplo n.º 15
0
def test_clear():
    cart = ShoppingCart()
    item = Apple()
    cart.add(item)
    cart.add(item)
    cart.clear()
    if cart._cart.get(item.name):
        raise Exception("Items in cart should be 0, not {}".format(
            len(cart._cart[item.name])))
Ejemplo n.º 16
0
 def __init__(self,
              cid,
              password,
              name,
              phoneNumber,
              address,
              balance=0,
              shoppingCart=None):
     super(CustomerAccount, self).__init__(cid, name, password)
     self.phoneNumber = phoneNumber
     self.address = address
     self.balance = balance
     if shoppingCart == None:
         self.shoppingCart = ShoppingCart()
     else:
         self.shoppingCart = shoppingCart
Ejemplo n.º 17
0
def import_cart(input_file):
    with open(input_file) as f:
        input_data = f.readlines()

    name_date = input_data.pop(0).strip()
    name = name_date[:name_date.find("'s")]
    date = name_date[name_date.find('-') + 1:].strip()

    user_cart = ShoppingCart(
        customer_name=name,
        current_date=date,
        cart_items=[
            ItemToPurchase(
                item_name=i[:i.find(':')],
                item_description=i[i.find(' '):i.find('x')].strip(),
                item_quantity=int(i[i.find('x') + 1:i.find('@')].strip()),
                item_price=int(i[i.find('$') + 1:i.find('=')].strip()))
            for i in input_data
        ])

    return user_cart
Ejemplo n.º 18
0
from ShoppingCart import ShoppingCart
from BookParser import BookParser

sc = ShoppingCart()
bp = BookParser()
''' Tests shopping cart methods '''


def should_add_book():
    res = 'should_add_book: '
    cart = len(sc.get_cart())
    book = bp.search_by_isbn('978-0205734610')[0]
    sc.add_to_cart(book)
    if len(sc.get_cart()) > cart:
        print res + 'PASS'
    else:
        print sc.get_cart()
        print res + 'FAIL'


def run_all_tests():
    should_add_book()


run_all_tests()
Ejemplo n.º 19
0
    # New Products
    pet_cat.add_product(Product("Scratch Post", 34.99))
    pet_cat.add_product(Product("Litter Box", 10.99))
    pet_cat.add_product(Product("Wet Food", 1.99))

    home_cat.add_product(Product("Towel", 5.98))
    home_cat.add_product(Product("Utensil", 12.49))
    home_cat.add_product(Product("Sofa", 1099.48))

    #New Session
    session = Session(user)

    #Shopping Cart

    shoppingCart = ShoppingCart(session)
    shoppingCart.attach(RecommendationEngineA())
    item1 = pet_cat.get_products()[0]
    item2 = home_cat.get_products()[2]
    shoppingCart.add_item(item1)
    shoppingCart.add_item(item2)

    # Checkout Process
    context = OrderContext(shoppingCart)
    context.set_order_id('12345678')
    context.set_state(OrderCheckoutState())
    context.proceed()
    context.renderView()

    context.proceed()
    context.renderView()
Ejemplo n.º 20
0
from Counter import Counter
from Discount import Discount
from ShoppingCart import ShoppingCart
from Weekday import Weekday
from Product import Product
import calendar
from datetime import *
print(calendar.day_name[date.today().weekday()])

washing_powder = Product('washing powder', 8, Discount.percentage_discount_with_threshold, percentage=30, threshold=2)
chocolate = Product('chocolate', 2)
chinese_vegetables = Product('chinese veggies', 3)
yoghurt = Product('yoghurt', 1.5, Discount.weekday_price, weekday="Wednesday", discount_price=1)
butter = Product('butter', 2.25, Discount.x_for_price_of_y, x=4,y=3)

cart = ShoppingCart({washing_powder:2, chocolate:3, chinese_vegetables:2, yoghurt:3, butter:2})
counter = Counter(cart)

print(washing_powder.is_discounted())

print(cart.products)
print('Total without discounts: €' + str(counter.total_without_discounts()))

print('Total with discounts: €' + str(counter.total_with_discounts()))
Ejemplo n.º 21
0
# Solutions/Classes/Client.py
#

from ShoppingCart import ShoppingCart
from Product import Product
from ProductFactory import ProductFactory
from IllegalArgumentException import IllegalArgumentException

cart = ShoppingCart('Tony Stark')
products = ProductFactory.getProducts()
# products = ProductFactory.queryDBProducts()

for p in products:
    try:
        cart.addProduct(p)
    except IllegalArgumentException as e:
        print(f"Received IllegalArgumentException exception: {str(e)}")

# list the Employees
print('\nList Products:')
cart.listProducts()

# Calulate the total Price
print('\nTotal Price: {}'.format(cart.getTotal()))
Ejemplo n.º 22
0
def welcomeMenu():
    print " ======================================================================\n"
    print " ************ Welcome to the 600.466 Automatic BookShopper ************\n"
    print " ======================================================================\n"
    print "1. Search books by the Book Name"
    print "2. Search books by the Author Name"
    print "3. Get the details (price / review) of a book"
    print "4. Exit"


loop = True

while loop:
    #create cart
    cart = ShoppingCart()

    welcomeMenu()
    option = input("Enter choice: ")
    if option == 1:
        print "Enter the name of the book you wish to buy: "
        bookName = raw_input()
        print "\n\nYou're currently searching for books named : ", bookName
        shopper(bookName)
    if option == 2:
        print "Enter the name of the author whose book you wish to buy: "
        authorName = raw_input()
        print "\n\nYou're currently searching for books authored by : ", authorName
        author_search(authorName)
    if option == 4:
        sys.exit()
Ejemplo n.º 23
0
 def __init__(self):
     self.stock = Stock()
     self.shoppingCart = ShoppingCart()
     self.order = Order()
     self.shipment = Shipment()
     self.payment = Payment()
Ejemplo n.º 24
0
# Aheidenreich

if __name__ == "__main__" and args.interactive:

    # School required code

    name = input("Enter customer's name (First Last): ")
    print("Enter today's date (YYYY-MM-DD)")
    date = input("Default is {}: ".format(dt.today()))

    if not date.strip():
        logging.info("No date entered. Using today's date.")
        date = dt.today()

    # Create new Shopping cart object from input
    user_cart = ShoppingCart(customer_name=name, current_date=date)

    # Print input back to screen
    print("\nCustomer name: {}".format(name))
    print("Today's date: {}".format(date))

    while execute_option(print_menu(), user_cart) != 'q':
        continue

    if input("Do you want to save your cart? ").lower()[0] == 'y':
        user_cart.export_cart(
            input("Enter a filename(Default is {}): ".format(
                args.output or "cart_export.txt")) or args.output
            or "cart_export.txt")

elif args.input:
Ejemplo n.º 25
0
            print()
            print("Item Descriptions")
            cart.print_descriptions()

        elif user_input == 'o':
            print("OUTPUT SHOPPING CART")
            cart.print_total()

    return user_input


# Main
if __name__ == "__main__":

    # School required code

    name = input("Enter customer's name:\n")
    date = input("Enter today's date:\n")

    # Create new Shopping cart object from input
    user_cart = ShoppingCart(
            customer_name=name,
            current_date=date)
    
    # Print input back to screen
    print("\nCustomer name: {}".format(name))
    print("Today's date: {}".format(date))

    user_selection = "none"
    while user_selection != 'q':
        user_selection = print_menu(user_cart)
Ejemplo n.º 26
0
class TestShoppingCart(unittest.TestCase):
    def setUp(self):
        self.food = Category('food')
        self.home = Category('home')
        self.apple = Product('apple', 100.0, self.food)
        self.almond = Product('almond', 50.0, self.food)
        self.chair = Product('chair', 100.0, self.home)

        self.cart = ShoppingCart()
        self.cart.addItem(self.apple, 3)
        self.cart.addItem(self.almond, 1)
        self.cart.addItem(self.chair, 2)

        self.campaign1 = Campaign(self.food, 25.0, 1, DiscountType.Rate)
        self.campaign2 = Campaign(self.home, 50.0, 3, DiscountType.Rate)
        self.campaign3 = Campaign(self.food, 12, 1, DiscountType.Amount)
        self.campaign4 = Campaign(self.home, 10, 3, DiscountType.Amount)

        self.coupon1 = Coupon(100.0, 10.0, DiscountType.Rate)
        self.coupon2 = Coupon(1000.0, 10.0, DiscountType.Rate)
        self.coupon3 = Coupon(100.0, 100.0, DiscountType.Amount)
        self.coupon4 = Coupon(1000.0, 100.0, DiscountType.Amount)

    def test_should_add_the_first_product_into_a_new_category(self):
        newCategory = Category('new')
        firstProduct = Product('firstProduct', 100.0, newCategory)
        self.cart.addItem(firstProduct, 1)

        expectedCategoryProductCount = 1
        expectedCategoryCurrentPrice = 100.0
        expectedProductCount = 1
        expectedProductCurrentPrice = 100.0

        self.assertEqual(self.cart.categories['new']['productCount'],
                         expectedCategoryProductCount)
        self.assertEqual(self.cart.categories['new']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['new']['products']['firstProduct']['count'],
            expectedProductCount)
        self.assertEqual(
            self.cart.categories['new']['products']['firstProduct']
            ['currentPrice'], expectedProductCurrentPrice)

    def test_should_add_a_product_into_already_existing_category(self):
        existingCategory = Category('existingCategory')
        firstProduct = Product('firstProduct', 100.0, existingCategory)
        secondProduct = Product('secondProduct', 200.0, existingCategory)
        self.cart.addItem(firstProduct, 1)
        self.cart.addItem(secondProduct, 1)

        expectedCategoryProductCount = 2
        expectedCategoryCurrentPrice = 300.0
        expectedSecondProductCount = 1
        expectedSecondProductCurrentPrice = 200.0

        self.assertEqual(
            self.cart.categories['existingCategory']['productCount'],
            expectedCategoryProductCount)
        self.assertEqual(
            self.cart.categories['existingCategory']['currentPrice'],
            expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['existingCategory']['products']
            ['secondProduct']['count'], expectedSecondProductCount)
        self.assertEqual(
            self.cart.categories['existingCategory']['products']
            ['secondProduct']['currentPrice'],
            expectedSecondProductCurrentPrice)

    def test_should_add_the_same_product_again(self):
        category = Category('category')
        product = Product('product', 100.0, category)
        self.cart.addItem(product, 1)
        self.cart.addItem(product, 1)

        expectedCategoryProductCount = 2
        expectedCategoryCurrentPrice = 200.0
        expectedProductCount = 2
        expectedProductCurrentPrice = 200.0

        self.assertEqual(self.cart.categories['category']['productCount'],
                         expectedCategoryProductCount)
        self.assertEqual(self.cart.categories['category']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['category']['products']['product']['count'],
            expectedProductCount)
        self.assertEqual(
            self.cart.categories['category']['products']['product']
            ['currentPrice'], expectedProductCurrentPrice)

    def test_should_apply_rate_campaign_to_category_with_enough_products(self):
        totalPriceBeforeDiscounts = self.cart.currentTotalAmount
        curCategoryCurrentPrice = self.cart.categories['food']['currentPrice']
        curAppleProductCurrentPrice = self.cart.categories['food']['products'][
            'apple']['currentPrice']
        curAlmondProductCurrentPrice = self.cart.categories['food'][
            'products']['almond']['currentPrice']

        expectedCategoryDiscount = curCategoryCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedCategoryCurrentPrice = curCategoryCurrentPrice - expectedCategoryDiscount

        expectedAppleProductDiscount = curAppleProductCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedAppleProductCurrentPrice = curAppleProductCurrentPrice - expectedAppleProductDiscount

        expectedAlmondProductDiscount = curAlmondProductCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedAlmondProductCurrentPrice = curAlmondProductCurrentPrice - expectedAlmondProductDiscount

        self.cart.applyDiscounts(self.campaign1)

        self.assertEqual(self.cart.categories['food']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['food']['products']['apple']['currentPrice'],
            expectedAppleProductCurrentPrice)
        self.assertEqual(
            self.cart.categories['food']['products']['almond']['currentPrice'],
            expectedAlmondProductCurrentPrice)
        self.assertEqual(self.cart.campaignDiscount, expectedCategoryDiscount)
        self.assertEqual(self.cart.currentTotalAmount,
                         totalPriceBeforeDiscounts - expectedCategoryDiscount)

    def test_should_not_apply_rate_campaign_to_category_without_enough_products(
            self):
        expectedCategoryCurrentPrice = self.cart.categories['home'][
            'currentPrice']
        expectedChairProductCurrentPrice = self.cart.categories['home'][
            'products']['chair']['currentPrice']

        self.cart.applyDiscounts(self.campaign2)

        self.assertEqual(self.cart.categories['home']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['home']['products']['chair']['currentPrice'],
            expectedChairProductCurrentPrice)

    def test_should_apply_a_campaign_to_child_categories(self):
        vegetable = Category('vegetable', self.food)
        tomato = Product('tomato', 100.0, vegetable)
        self.cart.addItem(tomato, 1)

        curCategoryCurrentPrice = self.cart.categories['vegetable'][
            'currentPrice']
        curTomatoProductCurrentPrice = self.cart.categories['vegetable'][
            'products']['tomato']['currentPrice']

        expectedCategoryDiscount = curCategoryCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedCategoryCurrentPrice = curCategoryCurrentPrice - expectedCategoryDiscount

        expectedTomatoProductDiscount = curTomatoProductCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedTomatoProductCurrentPrice = curTomatoProductCurrentPrice - expectedTomatoProductDiscount

        self.cart.applyDiscounts(self.campaign1)

        self.assertEqual(self.cart.categories['vegetable']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['vegetable']['products']['tomato']
            ['currentPrice'], expectedTomatoProductCurrentPrice)

    def test_should_apply_amount_campaign_to_category_with_enough_products(
            self):
        totalPriceBeforeDiscounts = self.cart.currentTotalAmount
        curCategoryCurrentPrice = self.cart.categories['food']['currentPrice']
        curAppleProductCurrentPrice = self.cart.categories['food']['products'][
            'apple']['currentPrice']
        curAlmondProductCurrentPrice = self.cart.categories['food'][
            'products']['almond']['currentPrice']

        expectedCategoryCurrentPrice = curCategoryCurrentPrice - self.campaign3.discount

        expectedAppleProductDiscount = self.campaign3.discount * (
            curAppleProductCurrentPrice / curCategoryCurrentPrice)
        expectedAppleProductCurrentPrice = curAppleProductCurrentPrice - expectedAppleProductDiscount

        expectedAlmondProductDiscount = self.campaign3.discount * (
            curAlmondProductCurrentPrice / curCategoryCurrentPrice)
        expectedAlmondProductCurrentPrice = curAlmondProductCurrentPrice - expectedAlmondProductDiscount

        self.cart.applyDiscounts(self.campaign3)

        self.assertEqual(self.cart.categories['food']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['food']['products']['apple']['currentPrice'],
            expectedAppleProductCurrentPrice)
        self.assertEqual(
            self.cart.categories['food']['products']['almond']['currentPrice'],
            expectedAlmondProductCurrentPrice)
        self.assertEqual(self.cart.campaignDiscount, self.campaign3.discount)
        self.assertEqual(self.cart.currentTotalAmount,
                         totalPriceBeforeDiscounts - self.campaign3.discount)

    def test_should_not_apply_amount_campaign_to_category_without_enough_products(
            self):
        expectedCategoryCurrentPrice = self.cart.categories['home'][
            'currentPrice']
        expectedChairProductCurrentPrice = self.cart.categories['home'][
            'products']['chair']['currentPrice']

        self.cart.applyDiscounts(self.campaign4)

        self.assertEqual(self.cart.categories['home']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['home']['products']['chair']['currentPrice'],
            expectedChairProductCurrentPrice)

    def test_should_apply_rate_and_amount_campaigns_together(self):
        totalPriceBeforeDiscounts = self.cart.currentTotalAmount
        curCategoryCurrentPrice = self.cart.categories['food']['currentPrice']
        curAppleProductCurrentPrice = self.cart.categories['food']['products'][
            'apple']['currentPrice']
        curAlmondProductCurrentPrice = self.cart.categories['food'][
            'products']['almond']['currentPrice']

        # first rate campaigns should be applied
        expectedCategoryRateDiscount = curCategoryCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedCategoryCurrentPriceAfterRateDiscount = curCategoryCurrentPrice - expectedCategoryRateDiscount

        expectedAppleProductRateDiscount = curAppleProductCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedAppleProductCurrentPriceAfterRateDiscount = curAppleProductCurrentPrice - expectedAppleProductRateDiscount

        expectedAlmondProductRateDiscount = curAlmondProductCurrentPrice * (
            self.campaign1.discount / 100.0)
        expectedAlmondProductCurrentPriceAfterRateDiscount = curAlmondProductCurrentPrice - expectedAlmondProductRateDiscount

        # then amount campaigns should be applied
        expectedCategoryCurrentPriceAfterAmountDiscount = expectedCategoryCurrentPriceAfterRateDiscount - self.campaign3.discount

        expectedAppleProductAmountDiscount = self.campaign3.discount * (
            expectedAppleProductCurrentPriceAfterRateDiscount /
            expectedCategoryCurrentPriceAfterRateDiscount)
        expectedAppleProductCurrentPriceAfterAmountDiscount = expectedAppleProductCurrentPriceAfterRateDiscount - expectedAppleProductAmountDiscount

        expectedAlmondProductAmountDiscount = self.campaign3.discount * (
            expectedAlmondProductCurrentPriceAfterRateDiscount /
            expectedCategoryCurrentPriceAfterRateDiscount)
        expectedAlmondProductCurrentPriceAfterAmountDiscount = expectedAlmondProductCurrentPriceAfterRateDiscount - expectedAlmondProductAmountDiscount

        self.cart.applyDiscounts(self.campaign1, self.campaign3)

        self.assertEqual(self.cart.categories['food']['currentPrice'],
                         expectedCategoryCurrentPriceAfterAmountDiscount)
        self.assertEqual(
            self.cart.categories['food']['products']['apple']['currentPrice'],
            expectedAppleProductCurrentPriceAfterAmountDiscount)
        self.assertEqual(
            self.cart.categories['food']['products']['almond']['currentPrice'],
            expectedAlmondProductCurrentPriceAfterAmountDiscount)
        self.assertEqual(
            self.cart.campaignDiscount,
            expectedCategoryRateDiscount + self.campaign3.discount)
        self.assertEqual(
            self.cart.currentTotalAmount, totalPriceBeforeDiscounts -
            (expectedCategoryRateDiscount + self.campaign3.discount))

    def test_should_apply_rate_coupon_with_enough_amount_on_the_cart(self):
        totalPriceBeforeDiscounts = self.cart.currentTotalAmount
        curCategoryCurrentPrice = self.cart.categories['food']['currentPrice']
        curAppleProductCurrentPrice = self.cart.categories['food']['products'][
            'apple']['currentPrice']
        curAlmondProductCurrentPrice = self.cart.categories['food'][
            'products']['almond']['currentPrice']

        expectedCategoryDiscount = curCategoryCurrentPrice * (
            self.coupon1.discount / 100.0)
        expectedCategoryCurrentPrice = curCategoryCurrentPrice - expectedCategoryDiscount

        expectedAppleProductDiscount = curAppleProductCurrentPrice * (
            self.coupon1.discount / 100.0)
        expectedAppleProductCurrentPrice = curAppleProductCurrentPrice - expectedAppleProductDiscount

        expectedAlmondProductDiscount = curAlmondProductCurrentPrice * (
            self.coupon1.discount / 100.0)
        expectedAlmondProductCurrentPrice = curAlmondProductCurrentPrice - expectedAlmondProductDiscount

        expectedTotalCouponDiscount = totalPriceBeforeDiscounts * (
            self.coupon1.discount / 100.0)
        expectedTotalPrice = totalPriceBeforeDiscounts - expectedTotalCouponDiscount

        self.cart.applyCoupon(self.coupon1)

        self.assertEqual(self.cart.categories['food']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['food']['products']['apple']['currentPrice'],
            expectedAppleProductCurrentPrice)
        self.assertEqual(
            self.cart.categories['food']['products']['almond']['currentPrice'],
            expectedAlmondProductCurrentPrice)
        self.assertEqual(self.cart.couponDiscount, expectedTotalCouponDiscount)
        self.assertEqual(self.cart.currentTotalAmount, expectedTotalPrice)

    def test_should_not_apply_rate_coupon_without_enough_amount_on_the_cart(
            self):
        totalPriceBeforeDiscounts = self.cart.currentTotalAmount

        self.cart.applyCoupon(self.coupon2)

        self.assertEqual(self.cart.couponDiscount, 0.0)
        self.assertEqual(self.cart.currentTotalAmount,
                         totalPriceBeforeDiscounts)

    def test_should_apply_amount_coupon_with_enough_amount_on_the_cart(self):
        totalPriceBeforeDiscounts = self.cart.currentTotalAmount
        curCategoryCurrentPrice = self.cart.categories['food']['currentPrice']
        curAppleProductCurrentPrice = self.cart.categories['food']['products'][
            'apple']['currentPrice']
        curAlmondProductCurrentPrice = self.cart.categories['food'][
            'products']['almond']['currentPrice']

        expectedCategoryDiscount = self.coupon3.discount * (
            curCategoryCurrentPrice / totalPriceBeforeDiscounts)
        expectedCategoryCurrentPrice = curCategoryCurrentPrice - expectedCategoryDiscount

        expectedAppleProductDiscount = self.coupon3.discount * (
            curAppleProductCurrentPrice / totalPriceBeforeDiscounts)
        expectedAppleProductCurrentPrice = curAppleProductCurrentPrice - expectedAppleProductDiscount

        expectedAlmondProductDiscount = self.coupon3.discount * (
            curAlmondProductCurrentPrice / totalPriceBeforeDiscounts)
        expectedAlmondProductCurrentPrice = curAlmondProductCurrentPrice - expectedAlmondProductDiscount

        self.cart.applyCoupon(self.coupon3)

        self.assertEqual(self.cart.categories['food']['currentPrice'],
                         expectedCategoryCurrentPrice)
        self.assertEqual(
            self.cart.categories['food']['products']['apple']['currentPrice'],
            expectedAppleProductCurrentPrice)
        self.assertEqual(
            self.cart.categories['food']['products']['almond']['currentPrice'],
            expectedAlmondProductCurrentPrice)
        self.assertEqual(self.cart.couponDiscount, self.coupon3.discount)
        self.assertEqual(self.cart.currentTotalAmount,
                         totalPriceBeforeDiscounts - self.coupon3.discount)

    def test_should_not_apply_amount_coupon_without_enough_amount_on_the_cart(
            self):
        totalPriceBeforeDiscounts = self.cart.currentTotalAmount

        self.cart.applyCoupon(self.coupon4)

        self.assertEqual(self.cart.couponDiscount, 0.0)
        self.assertEqual(self.cart.currentTotalAmount,
                         totalPriceBeforeDiscounts)
Ejemplo n.º 27
0
 def __init__(self, user_id, password, name, address, date_of_birth):
     super().__init__(user_id, password, name, address, date_of_birth)
     self.cart = ShoppingCart(Storage.get_instance())
def shoppingCart():
    shoppingCart = ShoppingCart()
    shoppingCart.itemPrice("z", 1)
    shoppingCart.itemPrice("y", 2)
    return shoppingCart
Ejemplo n.º 29
0
sesManag = SessionManager()
user = sesManag.add_user("qwerty", "pass", "name", "customer", "as", "asa",
                         1231, "asdas", "asdas")
admin = sesManag.add_user("qwertyAdmin", "pass", "name", "admin", "Asda")

user.register()
admin.register()
prod1 = Product("prod1", "prod1", 14, "as", 12431)
prod2 = Product("prod2", "prod1", 14, "as", 12412)
prod3 = Product("prod3", "prod1", 14, "as", 12413)

prod1.add_product()
prod2.add_product()
prod3.add_product()

shopping = ShoppingCart()
shopping.add_cart_item(prod1, 1)
shopping.add_cart_item(prod2, 2)
shopping.add_cart_item(prod3, 3)

shopping.view_cart_details()
user.take_order(shopping, "post", 12, 14)
user_order = Orders.get_orders_by_user_id("qwerty").pop()
print(user_order._order_id)
prod4 = Product("prod4", "prod1", 14, "as")
prod4.add_product("keker")
admin.create_category("keker", "asfdasdfa", "dep1")
admin.create_department("dep1", "asdasfas")
admin.create_category("keker", "asfdasdfa", "dep1")
prod4.add_product("keker")
Ejemplo n.º 30
0
 def setUp(self):
     self.sc1 = ShoppingCart()
     self.sc1.addToShoppingCart('1', 5.12, 1)
     self.sc1.addToShoppingCart('2', 1.23, 100)