Example #1
0
    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)
Example #2
0
    def get(self):
        try:
            service = session.query(ServiceModel, Client, Product).join(
                Client,
                Product).filter(ServiceModel.id == self._service._id).first()

            if service is None:
                return None
            else:
                c = ClientClass(service.Client.name, service.Client.cpf,
                                service.Client.segment)
                c._id = service.Client.id

                p = ProductClass(service.Product.name,
                                 service.Product.description,
                                 service.Product.image)
                p._id = service.Product.id

                s = ServiceClass(service.Service.request_date,
                                 service.Service.cancel_date)
                s._id = service.Service.id
                s._client = c
                s._product = p

                return s
        except Exception as e:
            print "Erro: ", e
def parse_products(url, product_list, sub_catalog):
    next_url = url + PAGE
    products_exist = True
    while products_exist:
        products_exist = False
        html_data = get_html_data(url=next_url)
        try:
            if len(html_data) < 3:
                products_exist = True
                print(sub_catalog.name)
                continue
        except TypeError:
            products_exist = True
            print(sub_catalog.name)
            continue
        for tag in (html_data('div', {'class': PRODUCTS_LINK})):
            name = tag.get(PRODUCT_NAME)
            price = tag.get(PRODUCT_PRICE)
            url = complete_url_fullness(url=tag.get(PRODUCT_URL))
            product = Product(name=name, price=price, url=url, available=True)
            product_list.append(
                Product(name=name, price=price, url=url, available=True))
            add_product_to_file(product, FILE)
            products_exist = True
        try:
            next_url = complete_url_fullness(
                (html_data.find('a', {'class': NEXT_PAGE_LINK})).get('href'))
        except AttributeError:
            products_exist = False
Example #4
0
 def AddProduct(self,Commands:list):
     for Command in Commands:  
         NewProduct = Product()
         Events = NewProduct.processForProductCreationCommand(Command)
         NewProduct.applyForProductCreationEvent(Events[0])
         ProductRepository().Create((NewProduct,),Events)
     return f'Products inserted successfully'
Example #5
0
 def load(self, path):
     tree = et.parse(path)
     elem = tree.getroot()
     for productElem in elem.iter("product"):
         product = Product()
         product.load(productElem)
         self._products.append(product)
Example #6
0
def parseProductsDetail(bu, productsContentBlockList):
    buProductsBlockList = []
    for productsContentBlock in productsContentBlockList:
        buProductsBlockList = productsContentBlock.find_all(
            'div', itemindex=bu.itemIndex)
        if len(buProductsBlockList) != 0:
            break

    if len(buProductsBlockList) == 0:
        return []

    productsTable = buProductsBlockList[0].table
    productRowList = productsTable.find_all('tr')
    if len(productRowList) > 0:
        products = []
        for index in range(1, len(productRowList)):
            row = productRowList[index]
            columns = row.find_all('td')
            if len(columns) == 2:
                products.append(
                    Product(bu.name, columns[0].get_text(),
                            columns[1].get_text()))
            elif len(columns) == 4:
                products.append(
                    Product(bu.name, columns[0].get_text(),
                            columns[1].get_text(), columns[2].get_text(),
                            columns[3].get_text()))
            else:
                pass
        return products
    else:
        return []
Example #7
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'])
Example #8
0
def add_product():
    # Retrieve the product from request body
    data = request.json
    log.debug(f'POST /product with product: {data}')

    # Generate an ID for the post
    # new_id = max([product['id'] for product in products]) + 1

    # Create a new product with id as 'None' since auto increment is set for ID column
    product = Product(None, data['name'])

    try:
        # Save the Product to the database
        product.save_to_db()

        # Create new product
        # new_product = {
        #     'id': new_id,
        #     'name': data['name']
        # }
        # add new product to the array
        # products.append(new_product)

        return jsonify(product.json), 201
    except exc.SQLAlchemyError:
        log.exception(
            f'An exception occurred while creating product with name: {product.name}'
        )
        return f'An exception occurred while creating product with name: {product.name}', 500
Example #9
0
    def test_Product_sentinel3_reader_OLCIL1_openProduct_getData_Oa01_radiance_long_lat(
            self):
        from Product import Product

        # Open test product
        testProduct = Product(OLCIL1_test_path)

        # Get Data for Oa01 radiance
        Oa01_radiance = testProduct.getData('Oa01_radiance', 'longitude',
                                            'latitude')

        # Assert attributes equal to test attributes
        for key in OLCIL1_test_attributes.keys():
            self.assertEqual(Oa01_radiance.attrs[key],
                             OLCIL1_test_attributes[key],
                             "Problem with %s" % key)

        # Assert Oa01_variables attributes equal to test variable attributes
        for key in OLCIL1_test_variables['Oa01_radiance'].keys():
            self.assertEqual(Oa01_radiance.Oa01_radiance.attrs[key],
                             OLCIL1_test_variables['Oa01_radiance'][key],
                             "Problem with %s" % key)

        # Assert specific pixel values
        self.assertAlmostEqual(
            round(float(Oa01_radiance.Oa01_radiance.values[0, 126]), 5),
            52.06213)
        self.assertAlmostEqual(
            round(float(Oa01_radiance.Oa01_radiance.values[342, 567]), 5),
            94.15255)

        # Assert no coordinates
        self.assertItemsEqual(Oa01_radiance.coords.keys(),
                              ['longitude', 'latitude'])
Example #10
0
    def test_openProduct(self):
        from Product import Product

        # Create test data and reader
        createTestReader_netCDF(test_reader_directory)
        writeTestData(test_data_path, test_data, test_variable_name)

        # Ensure test data reader generated
        self.assertTrue(exists(test_reader_directory), "Test reader missing")
        self.assertTrue(exists(test_data_path), "Test data missing")

        # Open test product
        testProduct = Product(test_data_path)

        # Test correct data found
        test_data_opened = testProduct.getData(test_variable_name)
        for row, test_row in zip(test_data, test_data_opened):
            for elem, test_elem in zip(row, test_row):
                self.assertEqual(elem, test_elem)

        # Assert varaibles default
        self.assertEqual(testProduct.variables, test_variables)

        # Test attributes found correct
        test_attributes_opened = testProduct.attributes
        for key in testProduct.attributes.keys():
            self.assertEqual(test_attributes[key], test_attributes_opened[key],
                             key + "incorrect")

        # Close product
        testProduct.product.close()

        # Remove test data reader
        shutil.rmtree(test_reader_directory)
        shutil.rmtree(dirname(test_data_path))
Example #11
0
 def add_product(self):
     try:
         if self.prod_name.text() == "" or self.prod_unit.text() == "":
             msg = QMessageBox()
             msg.setIcon(QMessageBox.Critical)
             msg.setText("Error")
             msg.setInformativeText('Please insert data!')
             msg.setWindowTitle("Error")
             msg.exec_()
         else:
             new_prod = Product(self.prod_name.text(),
                                self.prod_unit.text(),
                                self.purchase_price.text(),
                                self.sell_price.text())
             new_prod.insert_product()
             self.update_all_products()
             self.prod_name.setText("")
             self.prod_unit.setText("")
             self.purchase_price.setText("")
             self.sell_price.setText("")
     except:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Critical)
         msg.setText("Error")
         msg.setInformativeText('Please insert data!')
         msg.setWindowTitle("Error")
         msg.exec_()
 def add_product(self,name, measurment_unit, purchase_price, sell_price, listbox):
     new_prod = Product(name.get(), measurment_unit.get(), float(purchase_price.get()), float(sell_price.get()))
     new_prod.insert_product()
     name.delete(0, END)
     measurment_unit.delete(0, END)
     purchase_price.delete(0, END)
     sell_price.delete(0, END)
     self.update_list(listbox)
    def remove_product(self, product_name):
        now = datetime.datetime.now()
        date = "{}-{}-{}".format(now.year, now.month, now.day)
        if not self._is_product_exists(product_name, date):
            raise Exception("[ERROR]::There is no item with shuch name.")

        item = Product.select(Product.q.productName == product_name)[0]
        Product.delete(item.id)
Example #14
0
 def setUp(self):
     self.s1 = Store()
     self.p1 = Product("1", "Apple", "ea", 5.00, "SA", 14)
     self.p1.addBatch(10)
     self.p1.addBatch(5)
     self.p1.batches.append(
         Batch("3", 5.00, 10,
               datetime.date.today() - datetime.timedelta(days=12), 14))
     self.p1.updateDiscount()
Example #15
0
 def test_jsonify_product(self):
     p = Product(id ="test", name = "test", description = "test",price = "test")
     encoded_json = p.to_json("test")
     print encoded_json
     self.assertEqual(encoded_json['prodName'],"test")
     self.assertEqual(encoded_json['prodDesc'],"test")
     self.assertEqual(encoded_json['price'],"test")
     self.assertEqual(encoded_json['quantity'],1)
     self.assertEqual(encoded_json['category'],"perishable")
     self.assertEqual(encoded_json['vendorId'],"test")
def init_product_list(p_list):
    p = Product('1001', 'Apple iPhone', 1088.00)
    p_list.append(p)
    p = Product('1005', 'HTC Desire', 888.00)
    p_list.append(p)
    p = Product('1013', 'LG Optimus', 788.00)
    p_list.append(p)
    p = Product('1022', 'Sony Xperia', 958.00)
    p_list.append(p)
    p = Product('1027', 'Samsung Galaxy', 988.00)
    p_list.append(p)
Example #17
0
    def testGetCostsPerPerson(self):
        groupFactory = OwnerGroupFactory()
        infoFactory = OwnerInfoFactory()

        info1 = infoFactory.create("Me", 0.25)
        info2 = infoFactory.create("You", 0.75)

        group = groupFactory.create([info1, info2])
        product = Product("Test", 12, group)

        self.assertEqual(product.costPerPerson(), {"Me": 3, "You": 9})
def construct_product_items(productItemsArrayList):
    productItemsArrayList.append(Product(501,"Chocolate",1,100))
    productItemsArrayList.append(Product(502,"PopCorn",1,45))
    productItemsArrayList.append(Product(503,"Biscuit",2,18))
    productItemsArrayList.append(Product(504,"FaceWash",1,180))
    productItemsArrayList.append(Product(505,"Oil",6,30))
    productItemsArrayList.append(Product(506,"Soup, 2 Packets",2,50))
    productItemsArrayList.append(Product(508,"Pillow Cover",1,300))
    productItemsArrayList.append(Product(507,"Mango, 3 Pieces",3,90))
    productItemsArrayList.append(Product(509,"Pen Stand",1,50))
    productItemsArrayList.append(Product(510,"Milk, 2 Litres",2,2.0))
Example #19
0
 def delete_product(self):
     try:
         Product.delete_product_by_name(self.prod_name)
         self.close()
     except:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Critical)
         msg.setText("Error")
         msg.setInformativeText('Please insert data!!!')
         msg.setWindowTitle("Error")
         msg.exec_()
Example #20
0
 def change_name(self):
     try:
         Product.update_product_name(self.prod_name, self.enterName.text())
         self.enterName.setText("")
     except:
         msg = QMessageBox()
         msg.setIcon(QMessageBox.Critical)
         msg.setText("Error")
         msg.setInformativeText('Please insert data!!!')
         msg.setWindowTitle("Error")
         msg.exec_()
Example #21
0
 def addProduct(self, name, description, manufacturer, wholesale, sale,
                stock):
     if self.checkNames(name) == False:
         id_ = str(uuid.uuid4())
         product = Product(id_, name, description, manufacturer, wholesale,
                           sale, stock)
         self.database.update({(id_, name): product})
     else:
         product = self.getProductByName(name)
         product.stock = product.stock + stock
         self.database.update({(product.id, product.name): product})
Example #22
0
 def format_bigbuy_products(self, products, products_categories):
     print "Format products to BigBuy format"
     formatted_products = []
     all_product_images = self.get_products_images()
     products_infos = self.get_products_infos()
     for item in products:
         product = Product(item, products_infos, all_product_images,
                           products_categories)
         if product.is_valid_product:
             formatted_products.append(product.to_json())
             print "Product added " + str(product.to_json())
     return formatted_products
Example #23
0
 def add_product(self):
     img = self.prod_image
     name = self.prod_name_entry.get()
     date = self.prod_date_entry.get()
     num = self.num_entry.get()
     endurance = self.endurance_entry.get()
     price = self.price_entry.get()
     self.new_prod = Product(self.prod_label, img, name, date, num,
                             endurance, price)
     self.new_prod.add_to_label(self.prod_label)
     ProductsPage.products.insert(len(ProductsPage.products), self.new_prod)
     self.new_prod_frame.destroy()
Example #24
0
    def scrape_product_page(self) -> None:
        for product_sku in self.sku_list:
            product_sku = product_sku.strip()
            # search_page_url = f"https://www.bestbuy.com/site/searchpage.jsp?st={product_sku}"
            product_url = f"https://www.bestbuy.com/site/{product_sku}.p?skuId={product_sku}"
            product_activation_url = f"https://www.bestbuy.com/wireless/transaction-types/render/carriers" \
                                     f"?numberOfPayments=1&purchaseType=FULL_SRP&skuId={product_sku} "
            product_brand = "-1"
            product_model = "-1"
            product_name = "-1"
            product_unlocked_price = "-1"
            product_activation_price = "-1"
            product_carrier_compatibility = "-1"
            product_pricing = {}
            has_multiple_activation_offers = False

            self.driver.get(product_url)
            self.driver.implicitly_wait(3)

            if not self.no_results_flag(self.driver) and not self.multiple_products_flag(self.driver):
                html = self.driver.execute_script("return document.documentElement.innerHTML;")
                page_contents = BeautifulSoup(html, "html5lib")

                try:
                    product_unlocked_price = self.find_price_in_string(self.get_unlocked_price(page_contents))
                    product_activation_price = self.find_price_in_string(self.get_activated_price(page_contents))
                except AttributeError:
                    print(f"No activation price for {product_sku} at {product_url}")

                product_brand, product_model, product_name, product_carrier_compatibility = [s for s in self.get_product_attrs(page_contents)]
            else:
                # Skip trying to find attributes of the current sku
                continue

            self.driver.get(product_activation_url)
            self.driver.implicitly_wait(3)

            if not self.no_results_flag(self.driver) and not self.multiple_products_flag(self.driver):
                html = self.driver.execute_script("return document.documentElement.innerHTML;")
                page_contents = BeautifulSoup(html, "html5lib")
                product_pricing = self.get_product_activation_attrs(page_contents)

            if product_pricing["ATT"]["newline"] == "AT&T":
                product_pricing["ATT"]["newline"] = product_activation_price

            product = Product(product_sku, product_brand, product_model, product_name, product_carrier_compatibility, product_url,
                              product_unlocked_price, product_activation_price, product_pricing)

            product.disseminate_pricing()
            print(product.get_json())

        # Close the selenium webdriver on conclusion of the sku list
        self.driver.quit()
Example #25
0
 def GetWarehouseState(self,Command):
     Warehouse = {
                 'Samsung galaxy 9': 0,
                 'Samsung galaxy A70 Dual': 0,
                 'Apple iphone 11': 0
                 }
     for Events in ProductRepository().LoadEachProductEvents(Command.Date):
         product = Product()
         if Events:
             product.r(Events)
             if product.State not in ['Sold','Validated']:
                 Warehouse[product.Name] = Warehouse[product.Name] + 1
     return Warehouse            
Example #26
0
def init_data():
    customers = [Customer("01223", "Peter Parker", "Qo'yliq", 2.2, "90-932-75-98", ["Silver", 'Gold']),
                 Customer("75884", "Sherlock Holmes", "Backer street", 31415, "90-987-65-43", ["Regular", 'VIP']),
                 Customer("70070", "James Bond", "NY City", 450, "90-900-90-90", ["Silver", 'Gold'])]
    store = Store('U1510375', "John's Mall", "Ziyolar-9", "90-123-45-67")
    staff_members = [Staff("0", "02213", "Uncle Ben", "Manager"),
                     Staff("1", "45646", "Aunt May", "Cashier"),
                     Staff('2', "12345", "John Doe", "Owner")]
    products = [Product(69, "Cucumber", "Fresh and long cucumber", 69.69, 666),
                Product(666, "Tomatoes", "Red and plump", 12.14, 314),
                Product(123, "_Candies_", "Sweet sweet candies", 50, 100),
                Product(314, "_Bananas_", "My favorite", 42, 450)]
    return products, customers, staff_members, store
Example #27
0
 def makeAll(self):
     for i in self.root_shufersal[5]:
         product = Product("shufersal", i[3].text, str(i[12].text),
                           str(i[4].text), i[1].text)
         self.data_shufersal.append(product)
     for i in self.root_market[4]:
         product = Product("market Store", i[3].text, i[12].text,
                           str(i[4].text), i[1].text)
         self.data_market.append(product)
     for i in self.root_ramilevi[6]:
         product = Product("rami levi Store", i[3].text, i[12].text,
                           i[4].text, i[1].text)
         self.data_ramilevi.append(product)
Example #28
0
def update():
    counter = shelf.getSize()
    node = shelf.head
    node = node.next
    product_update = []
    list_a = []
    df = []
    product_update.append(Product(None, None, None, None, None, None))
    list_a.append(None)
    df.append(None)
    xlsfile = 'output.xlsx'

    writer = pd.ExcelWriter(xlsfile, engine='xlsxwriter')
    for i in range(1, counter):
        product_update.append(
            Product(node.data.sku, node.data.length, node.data.width,
                    node.data.height, node.data.frag, node.data.weight))
        node = node.next
        list_a.append([
            product_update[i].sku, product_update[i].length,
            product_update[i].width, product_update[i].height,
            product_update[i].frag, product_update[i].weight
        ])
        df.append([pd.DataFrame(list_a[i])])

    header = ['Sku', 'length', 'width', 'height', 'fragile', 'weight']
    #header=['a','b']
    df1 = pd.DataFrame(header)
    # df1.transpose()
    df1 = df1.transpose()

    df1.to_excel(writer,
                 sheet_name="Sheet1",
                 startrow=0,
                 startcol=0,
                 header=False,
                 index=False)
    for i in range(0, counter):
        df[i] = pd.DataFrame(list_a[i])
        # df1.transpose()
        df[i] = df[i].transpose()

        df[i].to_excel(writer,
                       sheet_name="Sheet1",
                       startrow=i,
                       startcol=0,
                       header=False,
                       index=False)

    writer.save()
    print('successfully export to excel')
Example #29
0
 def ConnectProductToOrder(self, ProductName):  # prepei try catch
     for Entity in self.session.execute(
             "SELECT MIN(EventTime), EntityId, EntityType FROM Snapshots WHERE SnapshotType = %s and SemantickLock = %s LIMIT 1 ALLOW FILTERING ",
         [ProductName, 'Unlock']):
         try:
             for product in self.session.execute(
                     "SELECT EntityId, EntityType, SnapshotData FROM Snapshots WHERE EventTime = %s ALLOW FILTERING",
                 [Entity.system_min_eventtime]):
                 UpdatedRow = self.session.execute(
                     "UPDATE Snapshots SET  SemantickLock = %s WHERE EntityId = %s and EntityType = %s  IF SemantickLock = %s",
                     [
                         'Locked', product.entityid, product.entitytype,
                         'Unlock'
                     ])
                 if UpdatedRow[0].applied:
                     return product.snapshotdata
                 else:
                     NewProduct = Product()
                     Event = ProductInsertedEvent(str(randint(0, 1000)),
                                                  ProductName, 'Free')
                     NewProduct.applyForProductCreationEvent(Event)
                     self.Create((NewProduct, ), (Event, ))
                     raise NotAvailableProduct()
         except Exception:
             NewProduct = Product()
             Event = ProductInsertedEvent(str(randint(0, 1000)),
                                          ProductName, 'Free')
             NewProduct.applyForProductCreationEvent(Event)
             self.Create((NewProduct, ), (Event, ))
             raise NotAvailableProduct()
Example #30
0
    def define_test_data(self):
        s1 = Shop("Aldi", (10, 10))
        s2 = Shop("Real", (200, 200))

        p1 = Product(product_name="Butter", price=10.0, barCode=None)
        p2 = Product(product_name="Milch", price=0.61, barCode=None)
        p3 = Product("Wasser", 1.5, 3057640182693)
        p4 = Product("Brot", 2.5, 3057640182693)

        s1.stock.append(p1)
        s1.stock.append(p2)
        s1.stock.append(p3)
        s1.stock.append(p4)

        p5 = Product("Butter", 9.8, None)
        p6 = Product("Milch", 0.65, None)
        p7 = Product("Wasser", 1.5, 3057640182693)
        p8 = Product("Brot", 2.5, 3057640182693)

        s2.stock.append(p5)
        s2.stock.append(p6)
        s2.stock.append(p7)
        s2.stock.append(p8)

        self.products = [p1, p2, p3, p4, p5, p6, p7, p8]

        self.shops = [s1, s2]
Example #31
0
    def __init__(self):

        self.app = Flask(__name__)
        self.host = "0.0.0.0"
        self.port = 5001
        self.server = ''
        self.database = ''
        self.url = "http://" + self.host + ":" + str(
            self.port) + "/ol-ti-itcpfegem-beta/billService?wsdl"
        self.category = Category()
        self.client = Client()
        self.product = Product()
        self.sale = Sale()
        self.user = User()
Example #32
0
def add_product():
    while True:
        #se pide la información del producto
        try: 
            name = input('Producto que desea agregar: ')
            classification = int(input('Indique si el producto es un alimento(1) o bebida(2): '))
            if classification == 1:
                classification = 'alimento'
                type_of_food = int(input('Indique si el alimento es de empaque(1) o de preparación(2): '))
                if type_of_food == 1:
                    type_of_food = 'empaque'
                elif type_of_food == 2:
                    type_of_food = 'preparación'
                else:
                    raise Exception
                beverage_size = 'No aplica'
            elif classification == 2:
                classification = 'bebida'
                beverage_size = int(input('Indique tamaño de la bebida: pequeño(1), mediano(2), grande(3): '))
                if beverage_size == 1:
                    beverage_size = 'pequeño'
                elif beverage_size == 2:
                    beverage_size = 'mediano'
                elif beverage_size == 3:
                    beverage_size = 'grande'
                else:
                    raise Exception
                type_of_food = 'No aplica'
            else:
                raise Exception

            raw_price = float(input('Precio: '))
            
            price = Product.product_price(raw_price)

            break
        
        except:
            print('Error: ingrese una opción válida')
    
    #guardo el producto en una variable y se lo paso a la función que lo va a agregar al menú
    product = Product(name, classification, beverage_size, type_of_food, price)

    m = ProductMenu(product)
    #función de la clase para agregar el producto al menú
    m.add_product('product_menu.txt')

    print(f'Producto {product.name} agregado exitosamente')
    return m.show_menu()
Example #33
0
 def import_product(self, product, to_append=True):
     new_product = Product(product['name'], product['categories'], product['description'], product['image'],
                           product['start_price'],
                           product['start_date'], product['end_date'], product['shipping_cost'],
                           product['vendor_id'], product['is_direct'], product['bidders'], product['bid_count'],
                           product['current_price'],
                           product['id'])
     for category in new_product.get_categories():
         try:
             cat = self.categories_mng.get_category_by_id(category)
             cat.increase_products_count()
         except ValueError:
             raise AssertionError('Category with id [' + category.__str__() + '] does not exists')
     if to_append:
         self.products.append(new_product)
     else:
         return new_product
 def testEncodeProduct(self):
      product = Product()
      product.name = "name"
      product.kids = 0
      product.price = 123.45
      product.sizes = "sizes"
      product.delivery = "delivery"
      product.url = "url"
      product.img_url = "img_url"
      
      output = json.dumps(product, cls=ProductJsonEncoder)
      self.assertEqual('{"kids": 0, "name": "name", "package": "", "kid_adult": 0, "free_porto": 0, "price": 123.45, "sizes": "sizes", "delivery": "delivery", "url": "url", "price_old": 0, "img_url": "img_url", "id": 0, "women": 0}', output)
Example #35
0
class TestFridge(unittest.TestCase):
    def setUp(self):
        self.yaourt = Product('yaourt', 'Danone', "25102000")
        self.banana = Product('fruit', 'banana', "25102000")
        self.banana2 = Product('fruit', 'banana', "26102000")
        self.banana3 = Product('fruit', 'banana', "26102000")

    def test_equals(self):
        self.assertTrue(self.banana2.equals(self.banana3))
        self.assertFalse(self.yaourt.equals(self.banana))
        self.assertFalse(self.banana.equals(self.banana2))

    def test_get_name(self):
        self.assertEqual("Danone", self.yaourt.get_name())
        self.assertEqual("banana", self.banana.get_name())

    def test_product_type(self):
        self.assertEqual("yaourt", self.yaourt.get_product_type())
        self.assertEqual("fruit", self.banana2.get_product_type())

    def test_get_use_by(self):
        self.assertEqual("25102000", self.yaourt.get_use_by())
        self.assertEqual("26102000", self.banana3.get_use_by())
  def post(self, mode=""):

    if mode == "set_ec":

      sid = self.request.get("sid")
      user_info = memcache.get(sid)

      product = Product.getProduct()

      nvp_params = {
              'L_PAYMENTREQUEST_0_NAME0' : str(product['quantity']) + ' ' + product['units'],
              'L_PAYMENTREQUEST_0_AMT0' : str(product['price']),
              'L_PAYMENTREQUEST_0_QTY0' : 1,
              'L_PAYMENTREQUEST_0_ITEMCATEGORY0' : 'Digital',

              'PAYMENTREQUEST_0_AMT' : str(product['price']),
              'RETURNURL' : self.request.host_url+"/do_ec_payment?sid="+sid,
              'CANCELURL': self.request.host_url+"/cancel_ec?sid="+sid
            }

      response = EC.set_express_checkout(nvp_params)

      if response.status_code != 200:
        logging.error("Failure for SetExpressCheckout")

        template_values = {
          'title' : 'Error',
          'operation' : 'SetExpressCheckout'
        }
        
        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unknown_error.html')
        return self.response.out.write(template.render(path, template_values))

      # The remainder of the transaction is completed in context

      parsed_qs = cgi.parse_qs(response.content)

      redirect_url = EC.generate_express_checkout_digital_goods_redirect_url(parsed_qs['TOKEN'][0])
      return self.redirect(redirect_url)

    else:
      logging.error("Unknown mode for POST request!")
  def post(self, mode=""):

    if mode == "pay":

      sid = self.request.get("sid")

      returnUrl = self.request.host_url+"/completed_payment?sid="+sid,
      cancelUrl = self.request.host_url+"/cancelled_payment?sid="+sid

      product = Product.getProduct()

      seller = {'email' : SELLER_EMAIL, 'amount' : product['price']}

      response = AP.pay(receiver=[seller], cancelUrl=cancelUrl, returnUrl=returnUrl)
      result = json.loads(response.content)
      logging.info(result)

      if result['responseEnvelope']['ack'] == 'Failure':
        logging.error("Failure for Pay")

        template_values = {
          'title' : 'Error',
          'operation' : 'Pay'
        }
        
        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unknown_error.html')
        return self.response.out.write(template.render(path, template_values))

      # Stash away the payKey for later use 

      user_info = memcache.get(sid)
      user_info['payKey'] = result['payKey']
      memcache.set(sid, user_info, time=60*10) # seconds

      # Redirect to PayPal and allow user to confirm payment details.

      redirect_url = AP.generate_adaptive_payment_redirect_url(result['payKey'])
      return self.redirect(redirect_url)

    else:
      logging.error("Unknown mode for POST request!")
  def post(self, mode=""):

    if mode == "set_ec":

      sid = self.request.get("sid")
      user_info = memcache.get(sid)

      product = Product.getProduct()

      nvp_params = {
              'PAYMENTREQUEST_0_AMT' : str(product['price']),
              'RETURNURL' : self.request.host_url+"/get_ec_details?sid="+sid,
              'CANCELURL': self.request.host_url+"/cancel_ec?sid="+sid
            }

      response = EC.set_express_checkout(nvp_params)

      if response.status_code != 200:
        logging.error("Failure for SetExpressCheckout")

        template_values = {
          'title' : 'Error',
          'operation' : 'SetExpressCheckout'
        }
        
        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unknown_error.html')
        return self.response.out.write(template.render(path, template_values))

      # Redirect to PayPal and allow user to confirm payment details.
      # Then PayPal redirects back to the /get_ec_details or /cancel_ec endpoints.
      # Assuming /get_ec_details, we complete the transaction with PayPal.get_express_checkout_details
      # and PayPal.do_express_checkout_payment

      parsed_qs = cgi.parse_qs(response.content)

      redirect_url = EC.generate_express_checkout_redirect_url(parsed_qs['TOKEN'][0])
      return self.redirect(redirect_url)

    else:
      logging.error("Unknown mode for POST request!")
    def test_Product_From_Sortable_Challenge(self):
        """
        Tests the first entry from the sortable challenge, namely:
        "product_name":"Sony_Cyber-shot_DSC-W310",
        "manufacturer":"Sony",
        "model":"DSC-W310",
        "family":"Cyber-shot",
        "announced-date":"2010-01-06T19:00:00.000-05:00"
        We test if the Product is correctly initiated, if all the
        getters work properly, the string representation is right and
        the json representation is right.
        """
        name = "Sony_Cyber-shot_DSC-W310"
        manufacturer = "Sony"
        model = "DSC-W310"
        family = "Cyber-shot"
        a_d ="2010-01-06T19:00:00.000-05:00"
        stringRep = """Name: Sony_Cyber-shot_DSC-W310
Manufacturer: Sony
Family: Cyber-shot
Model: DSC-W310
Announced Date: 2010-01-06T19:00:00.000-05:00"""
        jsonRep="""{"product_name":"Sony_Cyber-shot_DSC-W310","manufacturer":"Sony","model":"DSC-W310","family":"Cyber-shot","announced-date":"2010-01-06T19:00:00.000-05:00"}"""
        try:
            testProduct = Product(name,manufacturer,family,model,a_d)
        except:
            self.fail("Correct product initialization was not possible")
        self.assertEqual(name, testProduct.getName(),
                         "The name did not coincide with the given one")
        self.assertEqual(manufacturer,testProduct.getManufacturer(),
                         "The manufacturer was not stored properly")
        self.assertEqual(model,testProduct.getModel(),
                         "The model name was not stored properly")
        self.assertEqual(family,testProduct.getFamily(),
                         "The family name was not stored properly")
        self.assertEqual(a_d,testProduct.getAnnouncementDate(),
                         "The announcement date was not stored properly")
        self.assertEqual(stringRep,str(testProduct),
                         "String representation was not correct")
        self.assertEqual(json.loads(jsonRep),json.loads(testProduct.toJSON()),
                         "JSON representation was not correct")
Example #40
0
product_file = "products.txt"
listing_file = "listings.txt"
scan_product_f = open(product_file)
scan_listing_f = open(listing_file)
scan_product_sentinel = True
product_list = []

#LOOP INVARIANT:
#products.txt has unread products
while True:
	argData = scan_product_f.readline()
	if not argData:
		break # reached EOF
	json_data = json.loads(argData)
	tempProduct = Product()
	tempProduct.initializeValues(json_data)	
	product_list.append(tempProduct)

feature = Feature_Extractor()
for product in product_list:
	feature.processProduct(product)
feature.complete_preprocessing();
'''
#Plotting data analysis
feature.plot(10,feature.tags_pname)
feature.plot(20,feature.tags_manfact)
feature.plot(30,feature.tags_fam)
feature.plot(40,feature.tags_model)
feature.plot(50,feature.tags_date)
feature.draw()
Example #41
0
 def parse_product(f):
     product = Product()
     product.name = f['name']
     product.description = f['description']
     return product
Example #42
0
print 'Got all worksheets...'

# product_ids = product_sheet.col_values(2)
product_rows = product_sheet.get_all_values()
print 'Product total: ' + str(len(product_rows) - 1)
print 'Start processing product item...'

for product_index in range(1, len(product_rows)):

    product_row = product_rows[product_index]

    # create product object
    product = Product(id=product_row[1],
                      name=product_row[2],
                      eng_name=product_row[3],
                      detail=product_row[4],
                      categories=product_row[5].split(','),
                      status=product_row[0],
                      table_type=int(product_row[6]))

    print '[' + product.id + '] start -----------'

    ###### Parse data table #######
    # print '     parsing data table...'
    # if product.table_type == 2:
    #     product.table_info = parse_table_info(product, data_table_rows)
    # elif product.table_type == 1:
    #     product.table_info = parse_table_junk(product, product_row)
    # elif product.table_type == 0:
    #     print '         No data table exist.'
    # else:
  def get(self, mode=""):

    if mode == "completed_payment":

      if memcache.get(self.request.get("sid")) is not None: # Without an account reference, we can't credit the purchase
        user_info = memcache.get(self.request.get("sid"))

        payKey = user_info["payKey"]

        response = AP.get_payment_details(payKey)
        result = json.loads(response.content)
        logging.info(result)

        if result['responseEnvelope']['ack'] == 'Failure' or \
           result['status'] != 'COMPLETED': # Something went wrong!

          logging.error("Failure for PaymentDetails")

          template_values = {
            'title' : 'Error',
            'operation' : 'ExecutePayment'
          }
        
          path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unknown_error.html')
          return self.response.out.write(template.render(path, template_values))


        if result['paymentInfoList']['paymentInfo'][0]['transactionStatus'] != 'COMPLETED': # An eCheck?

          logging.error("Payment transaction status is not complete!")

          template_values = {
            'title' : 'Error',
            'details' : 'Sorry, eChecks are not accepted. Please send an instant payment.'
          }
        
          path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unsuccessful_payment.html')
          return self.response.out.write(template.render(path, template_values))


        # Credit the user's account

        twitter_username = user_info['username']
        product = Product.getProduct()

        AppHandler.creditUserAccount(twitter_username, product['quantity'])

        template_values = {
          'title' : 'Successful Payment',
          'quantity' : product['quantity'],
          'units' : product['units']
        }
        
        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'successful_payment.html')
        self.response.out.write(template.render(path, template_values))

      else:
        logging.error("Invalid/expired session in /completed_payment")

        template_values = {
          'title' : 'Session Expired',
        }

        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'session_expired.html')
        self.response.out.write(template.render(path, template_values))

    elif mode == "cancelled_payment":
      template_values = {
        'title' : 'Cancel Purchase',
      }

      path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'cancel_purchase.html')
      self.response.out.write(template.render(path, template_values))
 def test_profit(self):
     my_product = Product("Laptop", 1000, 1200)
     self.assertEqual(200, my_product.profit())
Example #45
0
 def setUp(self):
     self.yaourt = Product('yaourt', 'Danone', "25102000")
     self.banana = Product('fruit', 'banana', "25102000")
     self.banana2 = Product('fruit', 'banana', "26102000")
     self.banana3 = Product('fruit', 'banana', "26102000")
Example #46
0
def csvParser(myString):
	products = myString.split('\r')
	for i in range(len(products)):
		products[i] = products[i].split(',')
	products.pop(0)
	for i in range(len(products)):
		try:
			int(products[i][7])
		except:
			continue
		else:
			temp = Product()
			if(products[i][0] != "n/a"):
				temp.setSku(products[i][0].upper())
			if(products[i][1] != "n/a"):
				temp.setDeviceType(products[i][1].upper())
			if(products[i][2] != "n/a"):
				temp.setColor(products[i][2].upper())
			if(products[i][3] != "n/a"):
				temp.setCarrier(products[i][3].upper())
			if(products[i][4] != "n/a"):
				temp.setSize(products[i][4].upper())
			if(products[i][5] != "n/a"):
				temp.setSpecs(products[i][5].upper())
			if(products[i][6] != "n/a"):
				temp.setName(products[i][6])
			if(products[i][7] != "n/a"):
				temp.setNumLabels(int(products[i][7]))
			products[i] = temp
	return products
Example #47
0
 def __init__(self, p=None):
     Product.__init__(self, path)
     print " init class MphProduct, path=%s" % p
     self.path=p
     self.type=Product.TYPE_MPH
  def get(self, mode=""):
    
    client = oauth.TwitterClient(
                twitter_config.TWITTER_CONSUMER_KEY, 
                twitter_config.TWITTER_CONSUMER_SECRET, 
                "%s/app" % self.request.host_url)
   
    # The /app context ensures that the user's account is in good standing in
    # terms of payment, computes relevance for tweets from their home timeline, 
    # stashes the data and serves up the app. The app then requests the stashed 
    # data via /data.

    if mode == "app":

      # Pull out auth token/verifier in order to get an access token
      # and in order to get some basic information about the user.
      # Subsequent requests will be performed via client.make_request

      auth_token = self.request.get("oauth_token")
      auth_verifier = self.request.get("oauth_verifier")
      user_info = client.get_user_info(auth_token, auth_verifier=auth_verifier)

      twitter_username = user_info['username']

      # Has a user already used this webapp with twitter_username?

      query = User.all().filter("twitter_username ="******"home_timeline" : "http://api.twitter.com/1/statuses/home_timeline.json",
          "favorites_timeline" : "http://api.twitter.com/1/favorites.json",
        }

        # Fetch the first 5 pages of results for the data urls. (More pages could be requested.)
        # By default, there are 20 tweets per page for favorites and the home timeline

        num_pages = 5
        data = {}
        for name, url in data_urls.items():
          data[name] = []
          for page in range(1,num_pages+1):
            result = client.make_request(url=url, token=user_info['token'], secret=user_info['secret'], additional_params={'page' : page})
            if result.status_code == 200:
              data[name] += json.loads(result.content)
            else:
              # Could do any number of useful things to actually handle this error
              logging.error(("Expected 200 response but received %d for request " + url) % (result.status_code, page,))

        # Split out the text of the tweets, remove some leading/trailing punctuation, and filter
        # common stopwords 

        terms = [
            self._cleanupTerm(term.lower())
            for tweet in data['favorites_timeline']
                for term in tweet['text'].split() 
                    if self._cleanupTerm(term.lower()) not in self._getStopwords()
        ]

        # Build a frequency map and sort by value

        freqs = {}
        for term in terms:
          freqs[term] = freqs.get(term, 0) + 1           

        sorted_terms = sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True)

        # Iterate through each tweet in the home_timeline and assign a relevance score based upon 
        # the ratio of how many of the top N frequent terms from the favorities appeared in the tweet

        n = 200
        top_n_terms = set([term for (term, freq) in sorted_terms[:n]])

        # Useful for gaining intuition into how the trivial algorithm works

        logging.info("\n\nTOP N TERMS FROM FAVORITES:")
        logging.info(top_n_terms)
        logging.info("\n\n")

        for tweet in data['home_timeline']:
          tweet_terms = set([ self._cleanupTerm(term.lower())
                              for term in tweet['text'].split() 
                                if self._cleanupTerm(term.lower()) not in self._getStopwords()
                        ])

          num_frequent_terms = len(tweet_terms.intersection(top_n_terms))

          tweet['relevance'] = 1.0*num_frequent_terms/len(tweet_terms)

          # You could optionally do any number of other things like normalize tweet scores at this point,
          # boost relevance scores based upon additional criteria, throw in a random amount of serendipity 
          # into scores, etc. We'll just be boring  and filter out any tweet with a relevance greater than 0.0
          # so that only tweets with a relevance of 0.0 or higher are returned in the final response
          # The sky is the limit

        user_info['relevant_tweets'] = [tweet for tweet in data['home_timeline'] if tweet['relevance'] > 0]

        # For purposes of not frustrating users of this sample code who don't have any favorites (and would
        # hence not have any "relevant tweets", check to make sure at least one relevant tweet exists and
        # if it doesn't, just go ahead and assign all tweets as relevant since we have no information to 
        # otherwise make a decision

        if len(user_info['relevant_tweets']) == 0:
          user_info['relevant_tweets'] = data['home_timeline']

        # Store the ranked tweets as to user_info as "relevant_tweets" and 
        # stash the latest results from relevance algorithm so the client app can grab them
        # from a subsequent request to /data 

        memcache.set(sid, user_info, time=60*10) # seconds

        db.put(user)

        # Redirect to a mobile client application that will use sid to make a request for the 
        # tweets we just filtered and stashed away

        return self.redirect('/tweetview/index.html?sid='+sid)
      
      # If an account exists but no logins are remaining, then direct the user to ante up
      # via a PayPal Express Checkout pay flow

      else: 

        # Store the user_info so we can retrieve it in the next request

        memcache.set(sid, user_info, time=60*10) # seconds

        product = Product.getProduct()

        template_values = {
          'title' : 'Payment Required',
          'msg' : 'Get unlimited access to Tweet Relevance for %s %s for a one-time charge of only $%s!' % (product['quantity'], product['units'], str(product['price'])),
          'sid' : sid,
          'amt' : str(product['price'])
        }

        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'checkout.html')
        self.response.out.write(template.render(path, template_values))

    # Serves up stashed data (which takes place in a prior request to /app). A ?refresh=true parameter could
    # be built in to the /data request to charge the user for another request handle associated details if so
    # desired. This /data implementation simply returns the most previously calculated data

    elif mode == "data":

      user_info = memcache.get(self.request.get("sid"))
      self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
      self.response.out.write(json.dumps(user_info['relevant_tweets'], indent=2))

    elif mode == "login":

      return self.redirect(client.get_authorization_url())

    else: # root URL context 

      template_values = {
        'title' : 'Tweet Relevance',
      }

      path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'root.html')
      self.response.out.write(template.render(path, template_values))
  def get(self, mode=""):

    if mode == "get_ec_details":
      response = EC.get_express_checkout_details(self.request.get("token"))

      if response.status_code != 200:
        logging.error("Failure for GetExpressCheckoutDetails")

        template_values = {
          'title' : 'Error',
          'operation' : 'GetExpressCheckoutDetails'
        }
        
        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unknown_error.html')
        return self.response.out.write(template.render(path, template_values))

      product = Product.getProduct()

      parsed_qs = cgi.parse_qs(response.content)

      template_values = {
        'title' : 'Confirm Purchase',
        'quantity' : product['quantity'], 
        'units' : product['units'], 
        'email' : parsed_qs['EMAIL'][0], 
        'amount' : parsed_qs['PAYMENTREQUEST_0_AMT'][0],
        'query_string_params' : self.request.query_string
      }

      path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'confirm_purchase.html')
      self.response.out.write(template.render(path, template_values))

    elif mode == "do_ec_payment":

      if memcache.get(self.request.get("sid")) is not None: # Without an account reference, we can't credit the purchase
        payerid = self.request.get("PayerID")

        product = Product.getProduct()

        nvp_params = { 
                'PAYERID' : payerid, 
                'PAYMENTREQUEST_0_AMT' : str(product['price'])
        }

        response = EC.do_express_checkout_payment(
                        self.request.get("token"), 
                        nvp_params
                   )

        if response.status_code != 200:
          logging.error("Failure for DoExpressCheckoutPayment")

          template_values = {
            'title' : 'Error',
            'operation' : 'DoExpressCheckoutPayment'
          }
        
          path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unknown_error.html')
          return self.response.out.write(template.render(path, template_values))


        # Ensure that the payment was successful
  
        parsed_qs = cgi.parse_qs(response.content)

        if parsed_qs['ACK'][0] != 'Success': 
          logging.error("Unsuccessful DoExpressCheckoutPayment")
  
          template_values = {
            'title' : 'Error',
            'details' : parsed_qs['L_LONGMESSAGE0'][0]
          }
        
          path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unsuccessful_payment.html')
          return self.response.out.write(template.render(path, template_values))

        if parsed_qs['PAYMENTINFO_0_PAYMENTSTATUS'][0] != 'Completed': # Probably an eCheck
          logging.error("Unsuccessful DoExpressCheckoutPayment")
          logging.error(parsed_qs)
  
          template_values = {
            'title' : 'Error',
            'details' : 'Sorry, eChecks are not accepted. Please send an instant payment.'
          }
        
          path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unsuccessful_payment.html')
          return self.response.out.write(template.render(path, template_values))


        # Credit the user's account

        user_info = memcache.get(self.request.get("sid"))
        twitter_username = user_info['username']
        product = Product.getProduct()

        AppHandler.creditUserAccount(twitter_username, product['quantity'])

        template_values = {
          'title' : 'Successful Payment',
          'quantity' : product['quantity'],
          'units' : product['units']
        }
        
        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'successful_payment.html')
        self.response.out.write(template.render(path, template_values))

      else:
        logging.error("Invalid/expired session in /do_ec_payment")

        template_values = {
          'title' : 'Session Expired',
        }

        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'session_expired.html')
        self.response.out.write(template.render(path, template_values))

    elif mode == "cancel_ec":
      template_values = {
        'title' : 'Cancel Purchase',
      }

      path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'cancel_purchase.html')
      self.response.out.write(template.render(path, template_values))
Example #50
0
def loadAllProducts():
    jsonProducts = json.loads('{"latest": [{"kids": "1", "name": "Nike - Spilletr\u00f8je Classic III B\u00f8rn R\u00f8d/Hvid", "sizes": "140-152 cm/Boys M,152-158 cm/Boys L,158-170 cm/Boys XL", "url": "http://www.unisport.dk/fodboldudstyr/nike-spilletroje-classic-iii-born-rodhvid/50626/", "free_porto": "0", "price": "134,00", "package": "0", "delivery": "5-14 dage", "kid_adult": "0", "price_old": "179,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/50626_mellem.jpg", "id": "50626", "women": "0"}, {"kids": "1", "name": "Puma - Spilletr\u00f8je Vencida Bl\u00e5 B\u00f8rn TILBUD", "sizes": "YXS/116 cm,YM/140 cm,YXL/164 cm", "url": "http://www.unisport.dk/fodboldudstyr/puma-spilletroje-vencida-bla-born-tilbud/59954/", "free_porto": "0", "price": "99,00", "package": "0", "delivery": "1-2 dage", "kid_adult": "0", "price_old": "199,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/59954_mellem.jpg", "id": "59954", "women": "0"}, {"kids": "1", "name": "Puma - Spilletr\u00f8je Vencida Hvid/Bl\u00e5 B\u00f8rn TILBUD", "sizes": "YXS/116 cm,YM/140 cm,YXL/164 cm", "url": "http://www.unisport.dk/fodboldudstyr/puma-spilletroje-vencida-hvidbla-born-tilbud/59961/", "free_porto": "0", "price": "99,00", "package": "0", "delivery": "1-2 dage", "kid_adult": "0", "price_old": "199,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/59961_mellem.jpg", "id": "59961", "women": "0"}, {"kids": "1", "name": "Puma - Shorts Vencida II Bl\u00e5 B\u00f8rn TILBUD", "sizes": "YXS/116 cm,YXL/164 cm", "url": "http://www.unisport.dk/fodboldudstyr/puma-shorts-vencida-ii-bla-born-tilbud/59972/", "free_porto": "0", "price": "79,00", "package": "0", "delivery": "1-2 dage", "kid_adult": "0", "price_old": "159,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/59972_mellem.jpg", "id": "59972", "women": "0"}, {"kids": "1", "name": "Adidas - F10 AdiZero FG Bl\u00e5/Lilla/Hvid B\u00f8rn ", "sizes": "EU 32,EU 33,EU 36/UK 3\u00bd,EU 36\u2154/UK 4,EU 37\u2153/UK 4\u00bd,EU 38/UK 5,EU 38\u2154/UK 5\u00bd", "url": "http://www.unisport.dk/fodboldstoevler/adidas-f10-adizero-fg-blalillahvid-born/95763/", "free_porto": "0", "price": "199,00", "package": "0", "delivery": "1-2 dage", "kid_adult": "0", "price_old": "399,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/95763_mellem.jpg", "id": "95763", "women": "0"}, {"kids": "1", "name": "Macron - Spilles\u00e6t Raven Hvid/Sort B\u00f8rn", "sizes": "140/2XS,152/X-Small", "url": "http://www.unisport.dk/fodboldudstyr/macron-spillesaet-raven-hvidsort-born/65458/", "free_porto": "0", "price": "199,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "0", "price_old": "349,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/65458_mellem.jpg", "id": "65458", "women": "0"}, {"kids": "1", "name": "Macron - Spilles\u00e6t Trend Bordeaux/Hvid B\u00f8rn", "sizes": "116/3XS,140/2XS,152/X-Small", "url": "http://www.unisport.dk/fodboldudstyr/macron-spillesaet-trend-bordeauxhvid-born/65478/", "free_porto": "0", "price": "229,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "0", "price_old": "349,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/65478_mellem.jpg", "id": "65478", "women": "0"}, {"kids": "1", "name": "Macron - Spilles\u00e6t Trend R\u00f8d/Sort B\u00f8rn", "sizes": "116/3XS,140/2XS,152/X-Small", "url": "http://www.unisport.dk/fodboldudstyr/macron-spillesaet-trend-rodsort-born/65480/", "free_porto": "0", "price": "229,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "0", "price_old": "349,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/65480_mellem.jpg", "id": "65480", "women": "0"}, {"kids": "1", "name": "Macron - Spilles\u00e6t Trend Navy/R\u00f8d B\u00f8rn", "sizes": "116/3XS,140/2XS,152/X-Small", "url": "http://www.unisport.dk/fodboldudstyr/macron-spillesaet-trend-marinerod-born/65481/", "free_porto": "0", "price": "229,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "0", "price_old": "299,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/65481_mellem.jpg", "id": "65481", "women": "0"}, {"kids": "0", "name": "Italien - Track Top 70 Italia Copa", "sizes": "Small,Medium,Large,X-Large,XX-Large", "url": "http://www.unisport.dk/fodboldtroejer/italien-track-top-70-italia-copa/24421/", "free_porto": "0", "price": "599,00", "package": "0", "delivery": "5-10 dage", "kid_adult": "0", "price_old": "599,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/24421_mellem.jpg", "id": "24421", "women": "0"}, {"kids": "0", "name": "Puma - King Top DI FG ", "sizes": "EU 38/UK 5,EU 38\u00bd/UK 5\u00bd,EU 39/UK 6,EU 40/UK 6\u00bd,EU 40\u00bd/UK 7,EU 41/UK 7\u00bd,EU 42/UK 8,EU 42\u00bd/UK 8\u00bd,EU 43/UK 9,EU 44/UK 9\u00bd,EU 44\u00bd/UK 10,EU 45/UK 10\u00bd,EU 46/UK 11,EU 46\u00bd/UK 11\u00bd", "url": "http://www.unisport.dk/fodboldstoevler/puma-king-top-di-fg/26487/", "free_porto": "0", "price": "699,00", "package": "0", "delivery": "1-2 dage", "kid_adult": "0", "price_old": "999,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/26487_mellem.jpg", "id": "26487", "women": "0"}, {"kids": "0", "name": "Sells - M\u00e5lmandsbukser Supreme", "sizes": "X-Large", "url": "http://www.unisport.dk/maalmandshandsker/sells-malmandsbukser-supreme/28683/", "free_porto": "0", "price": "299,00", "package": "0", "delivery": "1-2 dage", "kid_adult": "0", "price_old": "349,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/28683_mellem.jpg", "id": "28683", "women": "0"}, {"kids": "0", "name": "Nike - Vest 10 stk Gr\u00f8n", "sizes": "Small/Medium,Large/X-Large", "url": "http://www.unisport.dk/fodboldudstyr/nike-vest-10-stk-gron/45357/", "free_porto": "0", "price": "679,00", "package": "0", "delivery": "5-14 dage", "kid_adult": "0", "price_old": "799,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/45357_mellem.jpg", "id": "45357", "women": "0"}, {"kids": "0", "name": "Hummel - Polo Corporate Basic Hvid", "sizes": "X-Small,Large,X-Large", "url": "http://www.unisport.dk/fodboldudstyr/hummel-polo-corporate-basic-hvid/48286/", "free_porto": "0", "price": "129,00", "package": "0", "delivery": "5-10 dage", "kid_adult": "0", "price_old": "299,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/48286_mellem.jpg", "id": "48286", "women": "0"}, {"kids": "1", "name": "Nike - Spilletr\u00f8je Classic III B\u00f8rn R\u00f8d/Hvid", "sizes": "140-152 cm/Boys M,152-158 cm/Boys L,158-170 cm/Boys XL", "url": "http://www.unisport.dk/fodboldudstyr/nike-spilletroje-classic-iii-born-rodhvid/50626/", "free_porto": "0", "price": "134,00", "package": "0", "delivery": "5-14 dage", "kid_adult": "0", "price_old": "179,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/50626_mellem.jpg", "id": "50626", "women": "0"}, {"kids": "0", "name": "Select - Fodboldstr\u00f8mper Italia Sort", "sizes": "28-32,33-36,37-41,42-47", "url": "http://www.unisport.dk/fodboldudstyr/select-fodboldstromper-italia-sort/51126/", "free_porto": "0", "price": "59,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "1", "price_old": "69,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/51126_mellem.jpg", "id": "51126", "women": "0"}, {"kids": "0", "name": "Select - Fodboldstr\u00f8mper Italia Hvid", "sizes": "28-32,33-36,37-41,42-47", "url": "http://www.unisport.dk/fodboldudstyr/select-fodboldstromper-italia-hvid/51127/", "free_porto": "0", "price": "59,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "1", "price_old": "69,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/51127_mellem.jpg", "id": "51127", "women": "0"}, {"kids": "0", "name": "Select - Fodboldstr\u00f8mper Italia Bl\u00e5", "sizes": "28-32,33-36,37-41,42-47", "url": "http://www.unisport.dk/fodboldudstyr/select-fodboldstromper-italia-bla/51128/", "free_porto": "0", "price": "59,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "1", "price_old": "69,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/51128_mellem.jpg", "id": "51128", "women": "0"}, {"kids": "0", "name": "Select - Fodboldstr\u00f8mper Italia Gr\u00f8n", "sizes": "28-32,33-36,37-41,42-47", "url": "http://www.unisport.dk/fodboldudstyr/select-fodboldstromper-italia-gron/51129/", "free_porto": "0", "price": "59,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "1", "price_old": "69,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/51129_mellem.jpg", "id": "51129", "women": "0"}, {"kids": "0", "name": "Select - Fodboldstr\u00f8mper Italia Lysebl\u00e5", "sizes": "28-32,33-36,37-41,42-47", "url": "http://www.unisport.dk/fodboldudstyr/select-fodboldstromper-italia-lysebla/51130/", "free_porto": "0", "price": "59,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "1", "price_old": "69,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/51130_mellem.jpg", "id": "51130", "women": "0"}, {"kids": "0", "name": "Select - Fodboldstr\u00f8mper Italia Navy", "sizes": "28-32,33-36,37-41,42-47", "url": "http://www.unisport.dk/fodboldudstyr/select-fodboldstromper-italia-navy/51131/", "free_porto": "0", "price": "59,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "1", "price_old": "69,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/51131_mellem.jpg", "id": "51131", "women": "0"}, {"kids": "0", "name": "Select - Fodboldstr\u00f8mper Italia R\u00f8d", "sizes": "28-32,33-36,37-41,42-47", "url": "http://www.unisport.dk/fodboldudstyr/select-fodboldstromper-italia-rod/51132/", "free_porto": "0", "price": "59,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "1", "price_old": "69,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/51132_mellem.jpg", "id": "51132", "women": "0"}, {"kids": "0", "name": "Select - Fodboldstr\u00f8mper Italia Bl\u00e5/hvid", "sizes": "28-32,33-36,37-41", "url": "http://www.unisport.dk/fodboldudstyr/select-fodboldstromper-italia-blahvid/51134/", "free_porto": "0", "price": "59,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "1", "price_old": "69,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/51134_mellem.jpg", "id": "51134", "women": "0"}, {"kids": "0", "name": "Adidas - Spezial Navy/Lysebl\u00e5", "sizes": "EU 36\u2154/UK 4,EU 38/UK 5,EU 38\u2154/UK 5\u00bd,EU 40/UK 6\u00bd,EU 40\u2154/UK 7,EU 41\u2153/UK 7\u00bd,EU 42\u2154/UK 8\u00bd,EU 43\u2153/UK 9,EU 44/UK 9\u00bd,EU 44\u2154/UK 10,EU 46/UK 11,EU 47\u2153/UK 12", "url": "http://www.unisport.dk/fodboldstoevler/adidas-spezial-navylysebla/52041/", "free_porto": "0", "price": "509,00", "package": "0", "delivery": "1-2 dage", "kid_adult": "1", "price_old": "599,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/52041_mellem.jpg", "id": "52041", "women": "0"}, {"kids": "0", "name": "Macron - Spilles\u00e6t Raven Hvid/Sort", "sizes": "Small,Medium", "url": "http://www.unisport.dk/fodboldudstyr/macron-spillesaet-raven-hvidsort/65457/", "free_porto": "0", "price": "199,00", "package": "0", "delivery": "4-8 dage", "kid_adult": "0", "price_old": "349,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/65457_mellem.jpg", "id": "65457", "women": "0"}, {"kids": "0", "name": "Danmark - H\u00f8j Hat", "sizes": "One Size Adult", "url": "http://www.unisport.dk/fodboldtroejer/danmark-hoj-hat/54834/", "free_porto": "0", "price": "49,00", "package": "0", "delivery": "1-2 dage", "kid_adult": "0", "price_old": "0,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/54834_mellem.jpg", "id": "54834", "women": "0"}, {"kids": "0", "name": "Nike - Shorts Woven Dame R\u00f8d", "sizes": "X-Small,Small,Large,X-Large", "url": "http://www.unisport.dk/fodboldudstyr/nike-shorts-woven-dame-rod/57508/", "free_porto": "0", "price": "149,00", "package": "0", "delivery": "5-14 dage", "kid_adult": "0", "price_old": "199,00", "img_url": "http://s3-eu-west-1.amazonaws.com/product-img/57508_mellem.jpg", "id": "57508", "women": "1"}]}')

    products = []

    for jsonProduct in jsonProducts['latest']:
        product = Product()
        product.name = toAscii(jsonProduct['name'])
        product.kids = int(jsonProduct['kids'])
        product.price = toFloatDkInput(jsonProduct['price'])
        product.sizes = toAscii(jsonProduct['sizes'])
        product.url = toAscii(jsonProduct['url'])
        product.free_porto = int(jsonProduct['free_porto'])
        product.package = toAscii(jsonProduct['package'])
        product.delivery = toAscii(jsonProduct['delivery'])
        product.kid_adult = int(jsonProduct['kid_adult'])
        product.price_old = toFloatDkInput(jsonProduct['price_old'])
        product.img_url = toAscii(jsonProduct['img_url'])
        product.id = int(jsonProduct['id'])
        product.women = int(jsonProduct['women'])

        products.append(product)
        
    return products
  def get(self, mode=""):

    if mode == "do_ec_payment":

      if memcache.get(self.request.get("sid")) is not None: # Without an account reference, we can't credit the purchase
        payerid = self.request.get("PayerID")

        product = Product.getProduct()

        nvp_params = { 
                'PAYERID' : payerid, 

                'L_PAYMENTREQUEST_0_NAME0' : str(product['quantity']) + ' ' + product['units'],
                'L_PAYMENTREQUEST_0_AMT0' : str(product['price']),
                'L_PAYMENTREQUEST_0_QTY0' : 1,
                'L_PAYMENTREQUEST_0_ITEMCATEGORY0' : 'Digital',

                'PAYMENTREQUEST_0_AMT' : str(product['price'])
        }

        response = EC.do_express_checkout_payment(
                        self.request.get("token"), 
                        nvp_params
                   )

        if response.status_code != 200:
          logging.error("Failure for DoExpressCheckoutPayment")

          template_values = {
            'title' : 'Error',
            'operation' : 'DoExpressCheckoutPayment'
          }
        
          path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unknown_error.html')
          return self.response.out.write(template.render(path, template_values))


        # Ensure that the payment was successful
  
        parsed_qs = cgi.parse_qs(response.content)
  
        if parsed_qs['ACK'][0] != 'Success':
          logging.error("Unsuccessful DoExpressCheckoutPayment")
  
          template_values = {
            'title' : 'Error',
            'details' : parsed_qs['L_LONGMESSAGE0'][0]
          }
        
          path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unsuccessful_payment.html')
          return self.response.out.write(template.render(path, template_values))

        if parsed_qs['PAYMENTINFO_0_PAYMENTSTATUS'][0] != 'Completed':
          logging.error("Unsuccessful DoExpressCheckoutPayment")
          logging.error(parsed_qs)
  
          template_values = {
            'title' : 'Error',
            'details' : 'Sorry, but there was an unexpected problem processing your payment.'
          }
        
          path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'unsuccessful_payment.html')
          return self.response.out.write(template.render(path, template_values))


        # Credit the user's account

        user_info = memcache.get(self.request.get("sid"))
        twitter_username = user_info['username']
        product = Product.getProduct()

        AppHandler.creditUserAccount(twitter_username, product['quantity'])

        template_values = {
          'title' : 'Successful Payment',
          'quantity' : product['quantity'],
          'units' : product['units']
        }
        
        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'successful_payment.html')
        self.response.out.write(template.render(path, template_values))

      else:
        logging.error("Invalid/expired session in /do_ec_payment")

        template_values = {
          'title' : 'Session Expired',
        }

        path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'session_expired.html')
        self.response.out.write(template.render(path, template_values))

    elif mode == "cancel_ec":
      template_values = {
        'title' : 'Cancel Purchase',
      }

      path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'cancel_purchase.html')
      self.response.out.write(template.render(path, template_values))
    def post(self, mode=""):

        if mode == "do_direct_payment":

            # To be on the safe side, filter through a pre-defined list of fields
            # to pass through to DoDirectPayment. i.e. prevent the client from
            # potentially overriding IPADDRESS, AMT, etc.

            valid_fields = [
                "FIRSTNAME",
                "LASTNAME",
                "STREET",
                "CITY",
                "STATE",
                "ZIP",
                "COUNTRYCODE",
                "CREDITCARDTYPE",
                "ACCT",
                "EXPDATE",
                "CVV2",
            ]

            product = Product.getProduct()

            nvp_params = {"AMT": str(product["price"]), "IPADDRESS": self.request.remote_addr}

            for field in valid_fields:
                nvp_params[field] = self.request.get(field)

            response = DP.do_direct_payment(nvp_params)

            if response.status_code != 200:
                logging.error("Failure for DoDirectPayment")

                template_values = {"title": "Error", "operation": "DoDirectPayment"}

                path = os.path.join(os.path.dirname(__file__), "..", "templates", "unknown_error.html")
                return self.response.out.write(template.render(path, template_values))

            # Ensure that the payment was successful

            parsed_qs = cgi.parse_qs(response.content)

            if parsed_qs["ACK"][0] != "Success":
                logging.error("Unsuccessful DoDirectPayment")

                template_values = {"title": "Error", "details": parsed_qs["L_LONGMESSAGE0"][0]}

                path = os.path.join(os.path.dirname(__file__), "..", "templates", "unsuccessful_payment.html")
                return self.response.out.write(template.render(path, template_values))

            # Credit the user's account

            user_info = memcache.get(self.request.get("sid"))
            twitter_username = user_info["username"]
            product = Product.getProduct()

            AppHandler.creditUserAccount(twitter_username, product["quantity"])

            template_values = {
                "title": "Successful Payment",
                "quantity": product["quantity"],
                "units": product["units"],
            }

            path = os.path.join(os.path.dirname(__file__), "..", "templates", "successful_payment.html")
            self.response.out.write(template.render(path, template_values))

        else:
            logging.error("Unknown mode for POST request!")