コード例 #1
0
ファイル: server.py プロジェクト: truonghn/infoshopkeeper
    def titlelist(self, **args):
        self.common()
        self._titlelisttemplate.titles = []
        try:
            if type(args['titles']) == type("string"):
                self._titlelisttemplate.titles.append(Title.get(
                    args['titles']))
            else:
                for id in args['titles']:
                    self._titlelisttemplate.titles.append(Title.get(id))
        except KeyError:
            pass

        try:
            if (args['delete']):
                #delete the titles
                for title in self._titlelisttemplate.titles:
                    #                    for author in title.author:
                    #                        Author.delete(author.id)
                    for book in title.books:
                        Book.delete(book.id)
                    for category in title.categorys:
                        Category.delete(category.id)

                    Title.delete(title.id)

            #and back to the search
                from cherrypy.lib import httptools
                httptools.redirect(cherrypy.session['lastsearch'])
        except:
            return self._titlelisttemplate.respond()
コード例 #2
0
 def test_addToInventory_have_title(self):
     random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
     fakeargs = dict(
         title=random_item.title.booktitle,
         authors=random_item.title.authors_as_string(),
         publisher=random_item.title.publisher,
         distributor=random_item.distributor,
         owner="woodenshoe",
         listprice=random_item.listprice,
         ourprice=random_item.ourprice,
         isbn=random_item.title.isbn,
         categories=random_item.title.categories_as_string(),
         location=random_item.location.locationName,
         location_id=random_item.locationID,
         quantity=1,
         known_title=random_item.title,
         types=random_item.title.type,
         kind_name=random_item.title.kind.kindName,
     )
     print(fakeargs)
     inventory.addToInventory(**fakeargs)
     today = now.Now.now.strftime("%Y-%m-%d")
     confirm = Book.selectBy(titleID=random_item.titleID).filter(
         Book.q.inventoried_when == today
     )
     try:
         self.assertTrue(
             confirm,
             "inventory.addToInventory of title that we have does not add item to inventory",
         )
     finally:
         print(("confirm: ", list(confirm), confirm[-1]))
         confirm[-1].destroySelf()
コード例 #3
0
 def test_add_item_to_inventory_that_we_dont_have_returns_object(self):
     random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
     fakeargs = dict(
         title=random_item.title.booktitle,
         authors=random_item.title.authors_as_string(),
         publisher=random_item.title.publisher,
         distributor=random_item.distributor,
         owner="woodenshoe",
         listprice=random_item.listprice,
         ourprice=random_item.ourprice,
         isbn=random_item.title.isbn,
         categories=random_item.title.categories_as_string(),
         location=random_item.location,
         quantity=1,
         known_title=True,
         types=random_item.title.type,
         kind=random_item.title.kind.id,
         kind_name=random_item.title.kind.kindName,
     )
     response = self._my_app.post("/admin/add_item_to_inventory", fakeargs)
     today = Now.now.strftime("%Y-%m-%d")
     confirm = Book.selectBy(titleID=random_item.titleID).filter(
         "inventoried_when=%s" % today)
     self.assertTrue(
         confirm,
         "test_add_item_to_inventory does not add item to inventory")
コード例 #4
0
 def test_add_item_to_inventory_that_we_dont_have_returns_object(self):
     random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
     fakeargs=dict(title=random_item.title.booktitle, authors=random_item.title.authors_as_string(), publisher=random_item.title.publisher, distributor=random_item.distributor, owner='woodenshoe', listprice=random_item.listprice, ourprice=random_item.ourprice, isbn=random_item.title.isbn, categories=random_item.title.categories_as_string(), location=random_item.location, quantity=1, known_title=True, types=random_item.title.type, kind_name=random_item.title.kind.kindName)
     response=self._my_app.post('/admin/add_item_to_inventory', fakeargs)
     today=mx.DateTime.now().strftime('%Y-%m-%d')
     confirm=Book.selectBy(titleID=random_item.titleID).filter('inventoried_when=%s' % today)
     self.assertTrue(confirm, "test_add_item_to_inventory does not add item to inventory")
コード例 #5
0
ファイル: server.py プロジェクト: aliceriot/infoshopkeeper
    def titlelist(self,**args):
        self.common()
        self._titlelisttemplate.titles=[]
        try:
            if type(args['titles']) == type("string"):
                self._titlelisttemplate.titles.append(Title.get(args['titles']))
            else:
                for id in args['titles']:
                    self._titlelisttemplate.titles.append(Title.get(id))
        except KeyError:
            pass

        try: 
            if (args['delete']):
            #delete the titles
                for title in self._titlelisttemplate.titles:
#                    for author in title.author:
#                        Author.delete(author.id)
                    for book in title.books:
                        Book.delete(book.id)
                    for category in title.categorys:
                        Category.delete(category.id)
                    
                    Title.delete(title.id)

            #and back to the search
                from cherrypy.lib import httptools
                httptools.redirect(cherrypy.session['lastsearch'])	
        except:
            return self._titlelisttemplate.respond()
コード例 #6
0
 def test_addToInventory_have_title(self):
     random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
     fakeargs=dict(title=random_item.title.booktitle, authors=random_item.title.authors_as_string(), publisher=random_item.title.publisher, distributor=random_item.distributor, owner='woodenshoe', listprice=random_item.listprice, ourprice=random_item.ourprice, isbn=random_item.title.isbn, categories=random_item.title.categories_as_string(), location=random_item.location.locationName, quantity=1, known_title=True, types=random_item.title.type, kind_name=random_item.title.kind.kindName)
     inventory.addToInventory( **fakeargs )
     today=mx.DateTime.now().strftime('%Y-%m-%d')
     confirm=Book.selectBy(titleID=random_item.titleID).filter( Book.q.inventoried_when == today)
     try:
         self.assertTrue(confirm, "inventory.addToInventory of title that we have does not add item to inventory")
     finally:
         print "confirm: ", list(confirm), confirm[-1]
         confirm[-1].destroySelf()
コード例 #7
0
 def test_remove_item_from_cart_functional(self):
     random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
     item={"department":"Book","isInventoried":"True","isTaxable":"True","booktitle":random_item.title.booktitle,"isbn":random_item.title.isbn,"bookID":random_item.id,"titleID":random_item.titleID,"ourprice":random_item.ourprice}
     self._my_app.post('/register/add_item_to_cart', {'item':json.dumps(item)})
     self._my_app.post('/register/remove_item_from_cart', {'index':0})
     confirm=self._my_app.get('/register/get_cart').json[0]['items']
     self.assertEqual(confirm, [], "/register/remove_item_from_cart failed.")
コード例 #8
0
 def test_add_item_to_inventory_that_we_dont_have_records_transaction(self):
     random_item = random.sample(list(Book.select()), 1)[0]
     fakeargs = dict(
         title=random_item.title.booktitle,
         authors=random_item.title.authors_as_string(),
         publisher=random_item.title.publisher,
         distributor=random_item.distributor,
         owner="woodenshoe",
         listprice=random_item.listprice,
         ourprice=random_item.ourprice,
         isbn=random_item.title.isbn,
         categories=random_item.title.categories_as_string(),
         location=random_item.location,
         quantity=1,
         known_title=True,
         types=random_item.title.type,
         kind=random_item.title.kind.id,
         kind_name=random_item.title.kind.kindName,
     )
     response = self._my_app.post("/admin/add_item_to_inventory", fakeargs)
     nowish = Now.now.strftime("%Y-%m-%d %H:%M:%S")
     confirm = Transaction.select("date > %s" % nowish).filter(
         "info RLIKE %s" % random_item.title.booktitle)
     self.assertTrue(
         confirm,
         "test_add_item_to_inventory does not add item to inventory")
コード例 #9
0
 def test_check_out_sells_book(self):
     random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
     item={"department":"Book","isInventoried":"True","isTaxable":"True","booktitle":random_item.title.booktitle,"isbn":random_item.title.isbn,"bookID":random_item.id,"titleID":random_item.titleID,"ourprice":random_item.ourprice}
     self._my_app.post('/register/add_item_to_cart', {'item':json.dumps(item)})
     self._my_app.post('/register/check_out')
     confirm=random_item.status
     self.assertEqual(confirm, 'SOLD', '/register/checkout failed mark book \'SOLD\'')
コード例 #10
0
 def test_add_item_to_inventory_that_we_dont_have_records_transaction(self):
     random_item=random.sample(list(Book.select()), 1)[0]
     fakeargs=dict(title=random_item.title.booktitle, authors=random_item.title.authors_as_string(), publisher=random_item.title.publisher, distributor=random_item.distributor, owner='woodenshoe', listprice=random_item.listprice, ourprice=random_item.ourprice, isbn=random_item.title.isbn, categories=random_item.title.categories_as_string(), location=random_item.location, quantity=1, known_title=True, types=random_item.title.type, kind_name=random_item.title.kind.kindName)
     response=self._my_app.post('/admin/add_item_to_inventory', fakeargs)
     nowish=mx.DateTime.now().strftime('%Y-%m-%d %H:%M:%S')
     confirm=Transaction.select('date > %s' % nowish).filter('info RLIKE %s' % random_item.title.booktitle)
     self.assertTrue(confirm, "test_add_item_to_inventory does not add item to inventory")
コード例 #11
0
 def retrieve(self,number):
     isbn=number
     if len(number)==13:
         isbn=upc2isbn(number)
     books =  Book.select(AND(Book.q.titleID==Title.q.id,Title.q.isbn==isbn,Book.q.status=="STOCK") )
     print books
     if len(list(books))==1:
         theBook = books[0]
         if theBook:
             print theBook
             self.setBook(theBook)
             desc=theBook.title.booktitle
             self.setDescription("%s" % desc)
             self.source=theBook.title.kind.kindName
             self.setPrice(theBook.listprice)
             self.setDistributor(theBook.distributor)
             return 1
     else:
         if len(list(books))>1:
             from popups.browseinventory import BrowseInventoryPopup
             self.browser=BrowseInventoryPopup(self.parent,{"isbn":isbn,"status":"STOCK"})
             self.browser.CenterOnScreen()
             self.browser.ShowModal()
             return -1
         else:
             return 0
コード例 #12
0
 def test_get_item_by_isbn_in_stock(self):
     random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
     result = self._my_class.get_item_by_isbn(
         **{"isbn": random_item.title.isbn})
     # print "isbn_stock", random_item, result
     self.assertTrue(
         result,
         "/register/get_item_by_isbn does not return item when it should")
コード例 #13
0
 def test_void_cart(self):
     random_item_list=random.sample(list(Book.selectBy(status='STOCK')), 3)
     for random_item in random_item_list:
         item={"department":"Book","isInventoried":"True","isTaxable":"True","booktitle":random_item.title.booktitle,"isbn":random_item.title.isbn,"bookID":random_item.id,"titleID":random_item.titleID,"ourprice":random_item.ourprice}
         self._my_app.post('/register/add_item_to_cart', {'item':json.dumps(item)})
     self._my_app.post('/register/void_cart')
     confirm=self._my_app.get('/register/get_cart').json[0]
     self.assertEqual(confirm, {}, '/register/void_cart failed to destroy cart')
コード例 #14
0
ファイル: goodreads.py プロジェクト: seallard/botworm
 def __create_book_object(self, book_dict):
     """ Create a book object from the dictionary. """
     title = book_dict["best_book"]["title"]
     author = book_dict["best_book"]["author"]["name"]
     rating = float(book_dict["average_rating"])
     count = int(book_dict["ratings_count"]["#text"])
     goodreads_id = int(book_dict["best_book"]["id"]["#text"])
     return Book(title, author, rating, count, goodreads_id)
コード例 #15
0
 def test_bookedit_functional(self):
     random_item = random.sample(list(Book.select()), 1)[0]
     response = self._my_app.get("/bookedit", {"id": random_item.id})
     code, error = tidylib.tidy_document(response.body,
                                         options={
                                             "show-errors": 1,
                                             "show-warnings": 0
                                         })
     self.assertFalse(error, "/bookedit did not return valid html page")
コード例 #16
0
 def test_add_item_to_cart_functional(self):
     random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
     item={"department":"Book","isInventoried":"True","isTaxable":"True","booktitle":random_item.title.booktitle,"isbn":random_item.title.isbn,"bookID":random_item.id,"titleID":random_item.titleID,"ourprice":random_item.ourprice}
     result=self._my_app.post('/register/add_item_to_cart', {'item':json.dumps(item)})
     confirm=self._my_app.get('/register/get_cart')
     print "confirm is", confirm
     print "test_add_inventoried", confirm.json[0]['items'][0]
     confirm=confirm.json[0]['items'][0]
     self.assertEqual(item, confirm, '/register/add_item_to_cart returned error in function test')
コード例 #17
0
 def test_check_out_records_transaction(self):
     random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
     item={"department":"Book","isInventoried":"True","isTaxable":"True","booktitle":random_item.title.booktitle,"isbn":random_item.title.isbn,"bookID":random_item.id,"titleID":random_item.titleID,"ourprice":random_item.ourprice}
     self._my_app.post('/register/add_item_to_cart', {'item':json.dumps(item)})
     cart_id=self._my_app.get('/register/get_cart').json[0]['uuid']        
     self._my_app.post('/register/check_out')
     transaction=Transaction.selectBy(cartID=cart_id)
     #print transaction
     self.assertEqual('SOLD', 'SOLD', '/register/checkout failed mark book \'SOLD\'')
コード例 #18
0
 def PayConsigner(self,event):
     
     owner=self.consigner.GetStringSelection()
     #print self.consigner.GetCurrentSelection()
     #print self.consigner.GetSelection()
     #print self.consigner.GetStringSelection()
     books=Book.select(Book.q.owner==owner)
     frame = wxFrame(None, -1, "check in list" , pos=(50,50), size=(500,600),
                      style=wxNO_FULL_REPAINT_ON_RESIZE|wxDEFAULT_FRAME_STYLE)
     frame.Show(True)
     win = ConsignmentListPopup(frame,books,owner)
     self.Close()
コード例 #19
0
 def test_select_item_search(self):
     random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
     code, error = tidylib.tidy_document(
         self._my_class.select_item_search(
             title=random_item.title.booktitle),
         options={
             "show-errors": 1,
             "show-warnings": 0
         },
     )
     self.assertFalse(
         error,
         "/register/select_item_search does not return valid html page")
コード例 #20
0
    def statustag(self,book_id,status):
	book=Book.get(book_id)
        if status == "CONFIRM":
            book.status="STOCK"
            book.set_tag(category="inventory",key="confirmation11",value="stock")
        else:
            if status=="SOLD":
                book.sold_when=now()
                book.status="SOLD"
                book.set_tag(category="inventory",key="confirmation11",value="sold_at_some_point")
            else:
                book.status=status
                book.set_tag(category="inventory",key="confirmation11",value="removed")
	return book.status
コード例 #21
0
ファイル: inventory.py プロジェクト: aliceriot/infoshopkeeper
    def addToInventory(self,title="",status="STOCK",authors=[],publisher="",price="",isbn="",categories=[],distributor="",owner="",notes="",quantity=1,known_title=False,kind_name="",extra_prices={}):
        if not(known_title):
	    #add a title
            the_kinds=list(Kind.select(Kind.q.kindName==kind_name))
            kind_id = None
            if the_kinds:
                kind_id = the_kinds[0].id
	    known_title=Title(isbn=isbn, booktitle=title.encode("ascii", "backslashreplace"), publisher=publisher.encode("ascii", "backslashreplace"),tag=" ",kindID=kind_id)
            for rawAuthor in authors:
	    	author = rawAuthor.encode("ascii", "backslashreplace")
		theAuthors = Author.selectBy(author_name=author)
		theAuthorsList = list(theAuthors)
		if len(theAuthorsList) == 1:
		    known_title.addAuthor(theAuthorsList[0])
		elif len(theAuthorsList) == 0:
		    a = Author(author_name=author)
		    known_title.addAuthor(a)
		else:
		    # We should SQLDataCoherenceLost here
		    print "mmm... looks like you have multiple author of the sama name in your database..."
            for category in categories:
                Category(categoryName=category.encode("ascii", "backslashreplace"),title=known_title)

        for i in range(int(quantity)): 
            print distributor.encode('ascii', "backslashreplace")
            
            wholesale=0
            try:
                wholesale=extra_prices['wholesale']
            except:
                pass

	    b=Book(title=known_title,status=status.encode("ascii", "backslashreplace"), distributor=distributor.encode('ascii', "backslashreplace"),listprice=price,owner=owner.encode("ascii", "backslashreplace"),notes=notes.encode("ascii", "backslashreplace"),consignmentStatus="",wholesale=wholesale)
            b.extracolumns()
            for mp in extra_prices.keys():
                setattr(b,string.replace(mp," ",""),extra_prices[mp])
コード例 #22
0
ファイル: checkin.py プロジェクト: aliceriot/infoshopkeeper
    def Checkin(self,event):
        
        status=self.borrower.GetStringSelection()
        books=Book.select(Book.q.status==status)
        frame = wxFrame(None, -1, "check in list" , pos=(50,50), size=(500,600),
                         style=wxNO_FULL_REPAINT_ON_RESIZE|wxDEFAULT_FRAME_STYLE)
        win = CheckinListPopup(frame,books,status)
        #win.Show()

        self.Destroy()
        win.Raise()   
        
        frame.Raise()
        frame.Show()    
        frame.SetFocus()
コード例 #23
0
def parse_input(input_content: str) -> INPUT_TYPE:
    lines = input_content.split('\n')
    n_books, n_libraries, n_days = get_int_list(lines.pop(0))
    book_scoring = get_int_list(lines.pop(0))

    books = {i: Book(i, score) for i, score in enumerate(book_scoring)}
    libraries = []

    for library_id in range(n_libraries):
        total_books, signup_time, scan_capacity = get_int_list(lines.pop(0))
        libraries.append(
            Library(library_id,
                    {books[book_id]
                     for book_id in get_int_list(lines.pop(0))}, signup_time,
                    scan_capacity))

    return n_days, libraries
コード例 #24
0
 def _set_status_SOLD(self):
     random_item = random.sample(list(Book.select(Book.q.status != "SOLD")),
                                 1)[0]
     random_item_fields = list([
         string(x) for x in [
             radom_item.status,
             random_item.sold_when,
             random_item.inventoried_when,
         ]
     ])
     random_item.status = "SOLD"
     try:
         assertTrue(random_item.status == "STOCK")
         assertTrue(random_item.inventoried_when == datetime.now().date())
     finally:
         random_item.status = random_item_fields[0]
         random_item.sold_when = random_item_fields[1]
コード例 #25
0
 def test_add_item_to_cart_unit(self):
     random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
     args = {
         "item": {
             "department": "Book",
             "isInventoried": "True",
             "isTaxable": "True",
             "booktitle": random_item.title.booktitle,
             "isbn": random_item.title.isbn,
             "bookID": random_item.id,
             "titleID": random_item.titleID,
             "ourprice": random_item.ourprice,
         }
     }
     result = self._my_class.add_item_to_cart(**args)
     self.assertTrue(
         result, "/register/add_item_to_cart returned error in unittest")
コード例 #26
0
    def PayConsigner(self, event):

        owner = self.consigner.GetStringSelection()
        print self.consigner.GetCurrentSelection()
        print self.consigner.GetSelection()
        print self.consigner.GetStringSelection()
        books = Book.select(Book.q.owner == owner)
        frame = wxFrame(None,
                        -1,
                        "check in list",
                        pos=(50, 50),
                        size=(500, 600),
                        style=wxNO_FULL_REPAINT_ON_RESIZE
                        | wxDEFAULT_FRAME_STYLE)
        frame.Show(True)
        win = ConsignmentListPopup(frame, books, owner)
        self.Close()
コード例 #27
0
 def test_remove_item_from_cart_functional(self):
     random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
     item = {
         "department": "Book",
         "isInventoried": "True",
         "isTaxable": "True",
         "booktitle": random_item.title.booktitle,
         "isbn": random_item.title.isbn,
         "bookID": random_item.id,
         "titleID": random_item.titleID,
         "ourprice": random_item.ourprice,
     }
     self._my_app.post("/register/add_item_to_cart",
                       {"item": json.dumps(item)})
     self._my_app.post("/register/remove_item_from_cart", {"index": 0})
     confirm = self._my_app.get("/register/get_cart").json[0]["items"]
     self.assertEqual(confirm, [],
                      "/register/remove_item_from_cart failed.")
コード例 #28
0
 def test_check_out_sells_book(self):
     random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
     item = {
         "department": "Book",
         "isInventoried": "True",
         "isTaxable": "True",
         "booktitle": random_item.title.booktitle,
         "isbn": random_item.title.isbn,
         "bookID": random_item.id,
         "titleID": random_item.titleID,
         "ourprice": random_item.ourprice,
     }
     self._my_app.post("/register/add_item_to_cart",
                       {"item": json.dumps(item)})
     self._my_app.post("/register/check_out")
     confirm = random_item.status
     self.assertEqual(confirm, "SOLD",
                      "/register/checkout failed mark book 'SOLD'")
コード例 #29
0
    def onSelectItem(self,event):
        currentItem = event.m_itemIndex
        m_item=inventoried_merchandise("book")
        m_item.setBook(Book.get(int(self.getColumnText(currentItem, 9))))
        m_item.setPrice(self.getColumnText(currentItem, 2))
        m_item.setDescription(self.list.GetItemText(currentItem))
        m_item.source=self.getColumnText(currentItem,10)
        
        win = InventoriedMerchandisePopup(self.parent,m_item,self.parent)

        # Show the popup right below or above the button
        # depending on available screen space...
        btn = event.GetEventObject()
        pos = btn.ClientToScreen( (0,0) )
        sz =  btn.GetSize()
        #win.Position(pos, (0, sz.height))
        win.CenterOnScreen()
        win.ShowModal()
        win.Destroy()
コード例 #30
0
    def onSelectItem(self, event):
        currentItem = event.m_itemIndex
        m_item = inventoried_merchandise("book")
        m_item.setBook(Book.get(int(self.getColumnText(currentItem, 8))))
        m_item.setPrice(self.getColumnText(currentItem, 2))
        m_item.setDescription(self.list.GetItemText(currentItem))
        m_item.source = self.getColumnText(currentItem, 9)

        win = InventoriedMerchandisePopup(self.parent, m_item, self.parent)

        # Show the popup right below or above the button
        # depending on available screen space...
        btn = event.GetEventObject()
        pos = btn.ClientToScreen((0, 0))
        sz = btn.GetSize()
        #win.Position(pos, (0, sz.height))
        win.CenterOnScreen()
        win.ShowModal()
        win.Destroy()
コード例 #31
0
 def test_check_out_records_transaction(self):
     random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
     item = {
         "department": "Book",
         "isInventoried": "True",
         "isTaxable": "True",
         "booktitle": random_item.title.booktitle,
         "isbn": random_item.title.isbn,
         "bookID": random_item.id,
         "titleID": random_item.titleID,
         "ourprice": random_item.ourprice,
     }
     self._my_app.post("/register/add_item_to_cart",
                       {"item": json.dumps(item)})
     cart_id = self._my_app.get("/register/get_cart").json[0]["uuid"]
     self._my_app.post("/register/check_out")
     transaction = Transaction.selectBy(cartID=cart_id)
     # print transaction
     self.assertEqual("SOLD", "SOLD",
                      "/register/checkout failed mark book 'SOLD'")
コード例 #32
0
 def statustag(self, book_id, status):
     book = Book.get(book_id)
     if status == "CONFIRM":
         book.status = "STOCK"
         book.set_tag(category="inventory",
                      key="confirmation11",
                      value="stock")
     else:
         if status == "SOLD":
             book.sold_when = now()
             book.status = "SOLD"
             book.set_tag(category="inventory",
                          key="confirmation11",
                          value="sold_at_some_point")
         else:
             book.status = status
             book.set_tag(category="inventory",
                          key="confirmation11",
                          value="removed")
     return book.status
コード例 #33
0
 def test_void_cart(self):
     random_item_list = random.sample(list(Book.selectBy(status="STOCK")),
                                      3)
     for random_item in random_item_list:
         item = {
             "department": "Book",
             "isInventoried": "True",
             "isTaxable": "True",
             "booktitle": random_item.title.booktitle,
             "isbn": random_item.title.isbn,
             "bookID": random_item.id,
             "titleID": random_item.titleID,
             "ourprice": random_item.ourprice,
         }
         self._my_app.post("/register/add_item_to_cart",
                           {"item": json.dumps(item)})
     self._my_app.post("/register/void_cart")
     confirm = self._my_app.get("/register/get_cart").json[0]
     self.assertEqual(confirm, {},
                      "/register/void_cart failed to destroy cart")
コード例 #34
0
ファイル: checkin.py プロジェクト: truonghn/infoshopkeeper
    def Checkin(self, event):

        status = self.borrower.GetStringSelection()
        books = Book.select(Book.q.status == status)
        frame = wxFrame(None,
                        -1,
                        "check in list",
                        pos=(50, 50),
                        size=(500, 600),
                        style=wxNO_FULL_REPAINT_ON_RESIZE
                        | wxDEFAULT_FRAME_STYLE)
        win = CheckinListPopup(frame, books, status)
        #win.Show()

        self.Destroy()
        win.Raise()

        frame.Raise()
        frame.Show()
        frame.SetFocus()
コード例 #35
0
 def test_add_item_to_cart_functional(self):
     random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
     item = {
         "department": "Book",
         "isInventoried": "True",
         "isTaxable": "True",
         "booktitle": random_item.title.booktitle,
         "isbn": random_item.title.isbn,
         "bookID": random_item.id,
         "titleID": random_item.titleID,
         "ourprice": random_item.ourprice,
     }
     result = self._my_app.post("/register/add_item_to_cart",
                                {"item": json.dumps(item)})
     confirm = self._my_app.get("/register/get_cart")
     print(("confirm is", confirm))
     print(("test_add_inventoried", confirm.json[0]["items"][0]))
     confirm = confirm.json[0]["items"][0]
     self.assertEqual(
         item, confirm,
         "/register/add_item_to_cart returned error in function test")
コード例 #36
0
ファイル: server.py プロジェクト: truonghn/infoshopkeeper
    def addtocart(self, **args):
        self.common()

        if args.get('reset_quantities') == "true":
            cherrypy.session['quantities'] = []

        #these are multiple copies of the same book
        for a in args.keys():
            match = re.compile("^select_x_like_(\d+)").match(a)
            if match:
                try:
                    number_of_copies_to_sell = int(args[a])
                    id = match.group(1)
                    original = Book.get(id)
                    try:
                        quantities = cherrypy.session.get('quantities', [])
                        quantities.append((original, number_of_copies_to_sell))
                        cherrypy.session['quantities'] = quantities
                    except:
                        pass

                except Exception, e:
                    print str(e)
コード例 #37
0
ファイル: server.py プロジェクト: aliceriot/infoshopkeeper
    def addtocart(self,**args):
        self.common() 
        
        if args.get('reset_quantities')=="true":
            cherrypy.session['quantities']=[]

        #these are multiple copies of the same book
        for a in args.keys():
            match=re.compile("^select_x_like_(\d+)").match(a)
            if match:
                try:
                    number_of_copies_to_sell=int(args[a])
                    id=match.group(1)
                    original=Book.get(id)
                    try:
                        quantities=cherrypy.session.get('quantities',[])
                        quantities.append((original,number_of_copies_to_sell))
                        cherrypy.session['quantities']=quantities
                    except:
                        pass

                except Exception,e:
                    print str(e)
コード例 #38
0
ファイル: server.py プロジェクト: truonghn/infoshopkeeper
class InventoryServer:
    def __init__(self):
        self.reportlist = [
            getattr(__import__('reports.' + x, globals(), {}, [1]), x)
            for x in cfg.get("reports")
        ]

        self._indextemplate = IndexTemplate()
        self._carttemplate = CartTemplate()
        self._checkouttemplate = CheckoutTemplate()
        self._searchtemplate = SearchTemplate()
        self._bookedittemplate = BookEditTemplate()
        self._authoredittemplate = AuthorEditTemplate()
        self._categoryedittemplate = CategoryEditTemplate()
        self._kindedittemplate = KindEditTemplate()
        self._kindlisttemplate = KindListTemplate()
        self._titleedittemplate = TitleEditTemplate()
        self._titlelisttemplate = TitleListTemplate()
        self._reportlisttemplate = ReportListTemplate()
        self._reporttemplate = ReportTemplate()
        self._transactionstemplate = TransactionsTemplate()

        self.conn = db.connect()

    def common(self):
        for x in [getattr(self, x) for x in dir(self) if 'template' in x]:
            x.lastsearch = cherrypy.session.get('lastsearch', False)

    def index(self, **args):
        self.common()
        cherrypy.session['c'] = cherrypy.session.get('c', 0) + 1
        print cherrypy.session['c']
        return self._indextemplate.respond()

    def bookedit(self, **args):
        self.common()
        self._bookedittemplate.book = Book.form_to_object(Book, args)
        return self._bookedittemplate.respond()

    def authoredit(self, **args):
        self.common()
        self._authoredittemplate.author = Author.form_to_object(Author, args)
        return self._authoredittemplate.respond()

    def categoryedit(self, **args):
        self.common()
        self._categoryedittemplate.category = Category.form_to_object(
            Category, args)
        return self._categoryedittemplate.respond()

    def kindedit(self, **args):
        self.common()
        if ('kindName' in args.keys()):
            self._kindedittemplate.kind = Kind.form_to_object(Kind, args)
            return self.kindlist()
        else:
            self._kindedittemplate.kind = Kind.form_to_object(Kind, args)
            return self._kindedittemplate.respond()

    def kindlist(self, **args):
        self.common()
        self._kindlisttemplate.kinds = list(Kind.select())
        return self._kindlisttemplate.respond()

    def titleedit(self, **args):
        self.common()
        self._titleedittemplate.title = Title.form_to_object(Title, args)
        return self._titleedittemplate.respond()

    def titlelist(self, **args):
        self.common()
        self._titlelisttemplate.titles = []
        try:
            if type(args['titles']) == type("string"):
                self._titlelisttemplate.titles.append(Title.get(
                    args['titles']))
            else:
                for id in args['titles']:
                    self._titlelisttemplate.titles.append(Title.get(id))
        except KeyError:
            pass

        try:
            if (args['delete']):
                #delete the titles
                for title in self._titlelisttemplate.titles:
                    #                    for author in title.author:
                    #                        Author.delete(author.id)
                    for book in title.books:
                        Book.delete(book.id)
                    for category in title.categorys:
                        Category.delete(category.id)

                    Title.delete(title.id)

            #and back to the search
                from cherrypy.lib import httptools
                httptools.redirect(cherrypy.session['lastsearch'])
        except:
            return self._titlelisttemplate.respond()

    def checkout(self, **args):
        self.common()
        self._checkouttemplate.status_from = args.get("status_from", "STOCK")
        self._checkouttemplate.status_to = args.get("status_to", "RETURNED")
        self._checkouttemplate.schedules = [("list price", 1)
                                            ] + cfg.get("multiple_prices")

        if "change" in args:
            return self.addtocart(**args)
        if "finalize" in args:
            schedule_name = args["schedule"]
            schedule = [
                x for x in cfg.get("multiple_prices") + [("list price", 1)]
                if x[0] == schedule_name
            ]
            schedule_price = schedule[0][1]
            receipt = ""
            for q in cherrypy.session.get('quantities', []):

                original = q[0]
                howmany = q[1]

                for copy in list(
                        Book.select(
                            AND(Book.q.titleID == original.titleID,
                                Book.q.status == "STOCK", Book.q.listprice ==
                                original.listprice)))[0:howmany]:
                    cursor = self.conn.cursor()
                    cursor.execute(
                        """
                        INSERT INTO transactionLog SET
                        action = "SALE",
                        amount = %s,
                        cashier = %s,
                        date = NOW(),
                        info = %s,
                        schedule = %s,
                        owner = %s
                        """,
                        (copy.listprice * schedule_price, args["cashier"],
                         "[%s] %s" % (copy.distributor, copy.title.booktitle),
                         schedule_name, copy.owner))
                    copy.sellme()
                    cursor.close()
                line_pt_1 = "%s  X  %s  @ $%.2f * %i%%" % (
                    original.title.booktitle[:25], howmany, original.listprice,
                    schedule_price * 100)
                receipt = receipt + string.ljust(line_pt_1, 50) + string.rjust(
                    "$%.2f" %
                    (howmany * schedule_price * original.listprice), 10)
            return receipt

        if "restatus" in args and "status_to" in args and "status_from" in args:
            for q in cherrypy.session.get('quantities', []):
                original = q[0]
                howmany = q[1]
                for copy in list(
                        Book.select(
                            AND(Book.q.titleID == original.titleID,
                                Book.q.status == args["status_from"],
                                Book.q.listprice ==
                                original.listprice)))[0:howmany]:

                    copy.status = args["status_to"]

            cherrypy.session['quantities'] = []

        if "delete" in args:
            for q in cherrypy.session.get('quantities', []):
                original = q[0]
                original_price = original.listprice
                original_status = original.status
                original_title_id = original.titleID
                howmany = q[1]
                for copy in list(
                        Book.select(
                            AND(Book.q.titleID == original_title_id,
                                Book.q.status == original_status,
                                Book.q.listprice ==
                                original_price)))[0:howmany]:

                    Book.delete(copy.id)

            cherrypy.session['quantities'] = []

        self._checkouttemplate.quantities = cherrypy.session.get(
            'quantities', [])
        return self._checkouttemplate.respond()

    def addtocart(self, **args):
        self.common()

        if args.get('reset_quantities') == "true":
            cherrypy.session['quantities'] = []

        #these are multiple copies of the same book
        for a in args.keys():
            match = re.compile("^select_x_like_(\d+)").match(a)
            if match:
                try:
                    number_of_copies_to_sell = int(args[a])
                    id = match.group(1)
                    original = Book.get(id)
                    try:
                        quantities = cherrypy.session.get('quantities', [])
                        quantities.append((original, number_of_copies_to_sell))
                        cherrypy.session['quantities'] = quantities
                    except:
                        pass

                except Exception, e:
                    print str(e)

        #these are checked individual copies
        copy_ids = []
        try:
            if type(args['copy_id']) == type([0, 1]):
                for copy_id in args['copy_id']:
                    copy_ids.append(copy_id)
            else:
                copy_ids.append(args['copy_id'])
        except:
            pass

        for copy_id in copy_ids:
            quantities = cherrypy.session.get('quantities', [])
            quantities.append((Book.get(copy_id), 1))
            cherrypy.session['quantities'] = quantities

        if "checkout" in args:
            return self.checkout(**args)
        else:
            self._carttemplate.quantities = cherrypy.session.get(
                'quantities', [])
            return self._carttemplate.respond()
コード例 #39
0
ファイル: server.py プロジェクト: truonghn/infoshopkeeper
    def checkout(self, **args):
        self.common()
        self._checkouttemplate.status_from = args.get("status_from", "STOCK")
        self._checkouttemplate.status_to = args.get("status_to", "RETURNED")
        self._checkouttemplate.schedules = [("list price", 1)
                                            ] + cfg.get("multiple_prices")

        if "change" in args:
            return self.addtocart(**args)
        if "finalize" in args:
            schedule_name = args["schedule"]
            schedule = [
                x for x in cfg.get("multiple_prices") + [("list price", 1)]
                if x[0] == schedule_name
            ]
            schedule_price = schedule[0][1]
            receipt = ""
            for q in cherrypy.session.get('quantities', []):

                original = q[0]
                howmany = q[1]

                for copy in list(
                        Book.select(
                            AND(Book.q.titleID == original.titleID,
                                Book.q.status == "STOCK", Book.q.listprice ==
                                original.listprice)))[0:howmany]:
                    cursor = self.conn.cursor()
                    cursor.execute(
                        """
                        INSERT INTO transactionLog SET
                        action = "SALE",
                        amount = %s,
                        cashier = %s,
                        date = NOW(),
                        info = %s,
                        schedule = %s,
                        owner = %s
                        """,
                        (copy.listprice * schedule_price, args["cashier"],
                         "[%s] %s" % (copy.distributor, copy.title.booktitle),
                         schedule_name, copy.owner))
                    copy.sellme()
                    cursor.close()
                line_pt_1 = "%s  X  %s  @ $%.2f * %i%%" % (
                    original.title.booktitle[:25], howmany, original.listprice,
                    schedule_price * 100)
                receipt = receipt + string.ljust(line_pt_1, 50) + string.rjust(
                    "$%.2f" %
                    (howmany * schedule_price * original.listprice), 10)
            return receipt

        if "restatus" in args and "status_to" in args and "status_from" in args:
            for q in cherrypy.session.get('quantities', []):
                original = q[0]
                howmany = q[1]
                for copy in list(
                        Book.select(
                            AND(Book.q.titleID == original.titleID,
                                Book.q.status == args["status_from"],
                                Book.q.listprice ==
                                original.listprice)))[0:howmany]:

                    copy.status = args["status_to"]

            cherrypy.session['quantities'] = []

        if "delete" in args:
            for q in cherrypy.session.get('quantities', []):
                original = q[0]
                original_price = original.listprice
                original_status = original.status
                original_title_id = original.titleID
                howmany = q[1]
                for copy in list(
                        Book.select(
                            AND(Book.q.titleID == original_title_id,
                                Book.q.status == original_status,
                                Book.q.listprice ==
                                original_price)))[0:howmany]:

                    Book.delete(copy.id)

            cherrypy.session['quantities'] = []

        self._checkouttemplate.quantities = cherrypy.session.get(
            'quantities', [])
        return self._checkouttemplate.respond()
コード例 #40
0
from wsgiapp_local import application

try:
    _my_app=webtest.TestApp(application)
except Exception as excp:
    sys.exit(0)

oldstderr=sys.stderr
oldstdout=sys.stdout

sys.stderr = sys.stdout = open(os.devnull, 'w')
random_app_urls=['/notes/noteboard', '/report?what=&begin_date=2012-01-01&end_date=2012-01-08&query_made=yes&reportname=salesreport', '/admin/kindlist']    
assertion_errcount=0
for j in range(1, 5):
    for i in range(1, 10):
        random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
        item={"department":"Book","isInventoried":"True","isTaxable":"True","booktitle":random_item.title.booktitle,"isbn":random_item.title.isbn,"bookID":random_item.id,"titleID":random_item.titleID,"ourprice":random_item.ourprice}
        result=_my_app.post('/register/add_item_to_cart', {'item':json.dumps(item)})
        for k in range(0, random.randint(0,5)):
            _my_app.get(random.choice(random_app_urls))
        confirm=_my_app.get('/register/get_cart').json[0]['items']
        #print "test_add_inventoried", result, confirm
        try:
            assert i == len(confirm), '/register/add_item_to_cart dropped item'
        except:
            print >> oldstdout, i, len(confirm)
            assertion_errcount = assertion_errcount +1
    _my_app.get('/register/void_cart')

sys.stdout=oldstdout
sys.stderr=oldstderr
コード例 #41
0
ファイル: server.py プロジェクト: aliceriot/infoshopkeeper
    def checkout(self,**args):
        self.common()
        self._checkouttemplate.status_from=args.get("status_from","STOCK")
        self._checkouttemplate.status_to=args.get("status_to","RETURNED")
        self._checkouttemplate.schedules = [("list price",1)]+cfg.get("multiple_prices")
        
        if "change" in args:
            return self.addtocart(**args)
        if "finalize" in args:
            schedule_name=args["schedule"]
            schedule=[x for x in cfg.get("multiple_prices")+[("list price",1)] if x[0]==schedule_name] 
            schedule_price=schedule[0][1]
            receipt=""
            for q in cherrypy.session.get('quantities',[]):

                original=q[0]
                howmany=q[1]
                
                for copy in list(Book.select(AND(Book.q.titleID==original.titleID,Book.q.status=="STOCK",Book.q.listprice==original.listprice)))[0:howmany]:
                    cursor=self.conn.cursor()
                    cursor.execute("""
                        INSERT INTO transactionLog SET
                        action = "SALE",
                        amount = %s,
                        cashier = %s,
                        date = NOW(),
                        info = %s,
                        schedule = %s,
                        owner = %s
                        """,(copy.listprice * schedule_price,args["cashier"],"[%s] %s" % (copy.distributor,copy.title.booktitle),schedule_name,copy.owner))
                    copy.sellme()
                    cursor.close()
                line_pt_1 =  "%s  X  %s  @ $%.2f * %i%%" % (original.title.booktitle[:25],howmany,original.listprice,schedule_price * 100)
                receipt=receipt+string.ljust(line_pt_1,50)+string.rjust("$%.2f" % (howmany*schedule_price*original.listprice),10)
            return receipt
        
        if "restatus" in args and "status_to" in args and "status_from" in args:
            for q in cherrypy.session.get('quantities',[]):
                original=q[0]
                howmany=q[1]
                for copy in list(Book.select(AND(Book.q.titleID==original.titleID,Book.q.status==args["status_from"],Book.q.listprice==original.listprice)))[0:howmany]:
                    
                    copy.status=args["status_to"]
                    
            cherrypy.session['quantities']=[]

        if "delete" in args:
            for q in cherrypy.session.get('quantities',[]):
                original=q[0]
                original_price=original.listprice
                original_status=original.status
                original_title_id=original.titleID
                howmany=q[1]
                for copy in list(Book.select(AND(Book.q.titleID==original_title_id,Book.q.status==original_status,Book.q.listprice==original_price)))[0:howmany]:
                    
                    Book.delete(copy.id)
                    
            cherrypy.session['quantities']=[]

            
        
        self._checkouttemplate.quantities=cherrypy.session.get('quantities',[])
        return self._checkouttemplate.respond()
コード例 #42
0
ファイル: run.py プロジェクト: clarkbk/amazon-reading-list
logger.info(f'Got {len(items)} books from Amazon wishlist.')
for item in items:
    byline = item.find('span', id=re.compile('^item-byline')).text
    author = re.search(r'^by\s([\w\s.]+)[,(]', byline)
    d = {
        'title': item.find('a', id=re.compile('^itemName_')).text,
        'author': str.replace(author.group(1), '.', '').strip(),
    }
    dict_list.append(d)

logger.info(f'Getting book metadata...')
r = ReadingList()
with tqdm(total=len(dict_list)) as pbar:
    for item in dict_list:
        pbar.update(1)

        book = Book(**item)
        found = book.find_goodreads_id()
        if not found:
            continue
        book.update_from_goodreads_api()
        r.add_book(book)

logger.info(f'Calculating Ben scores...')
r.calculate_ben_scores()
r.sort()

logger.info(f'Writing to CSV...')
r.csv_export('output/readinglist.csv')
logger.info(f'Done!')
コード例 #43
0
except Exception as excp:
    sys.exit(0)

oldstderr = sys.stderr
oldstdout = sys.stdout

sys.stderr = sys.stdout = open(os.devnull, "w")
random_app_urls = [
    "/notes/noteboard",
    "/report?what=&begin_date=2012-01-01&end_date=2012-01-08&query_made=yes&reportname=salesreport",
    "/admin/kindlist",
]
assertion_errcount = 0
for j in range(1, 5):
    for i in range(1, 10):
        random_item = random.sample(list(Book.selectBy(status="STOCK")), 1)[0]
        item = {
            "department": "Book",
            "isInventoried": "True",
            "isTaxable": "True",
            "booktitle": random_item.title.booktitle,
            "isbn": random_item.title.isbn,
            "bookID": random_item.id,
            "titleID": random_item.titleID,
            "ourprice": random_item.ourprice,
        }
        result = _my_app.post("/register/add_item_to_cart",
                              {"item": json.dumps(item)})
        for k in range(0, random.randint(0, 5)):
            _my_app.get(random.choice(random_app_urls))
        confirm = _my_app.get("/register/get_cart").json[0]["items"]
コード例 #44
0
ファイル: server.py プロジェクト: aliceriot/infoshopkeeper
 def bookedit(self,**args):
     self.common()
     self._bookedittemplate.book=Book.form_to_object(Book,args)
     return self._bookedittemplate.respond()
コード例 #45
0
 def test_add_item_to_cart_unit(self):
     random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
     args={'item':{"department":"Book","isInventoried":"True","isTaxable":"True","booktitle":random_item.title.booktitle,"isbn":random_item.title.isbn,"bookID":random_item.id,"titleID":random_item.titleID,"ourprice":random_item.ourprice}}
     result=self._my_class.add_item_to_cart(**args)
     self.assertTrue(result, '/register/add_item_to_cart returned error in unittest')
コード例 #46
0
 def test_bookedit_functional(self):
     random_item=random.sample(list(Book.select()), 1)[0]
     response=self._my_app.get('/bookedit', {'id':random_item.id})
     code, error=tidylib.tidy_document(response.body, options={'show-errors':1, 'show-warnings':0})
     self.assertFalse(error, '/bookedit did not return valid html page')
コード例 #47
0
 def test_select_item_search(self):
     random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
     code, error=tidylib.tidy_document(self._my_class.select_item_search(title=random_item.title.booktitle), options={'show-errors':1,'show-warnings':0})
     self.assertFalse(error, "/register/select_item_search does not return valid html page")
コード例 #48
0
ファイル: server.py プロジェクト: truonghn/infoshopkeeper
 def bookedit(self, **args):
     self.common()
     self._bookedittemplate.book = Book.form_to_object(Book, args)
     return self._bookedittemplate.respond()
コード例 #49
0
ファイル: inventory.py プロジェクト: truonghn/infoshopkeeper
    def addToInventory(self,
                       title="",
                       status="STOCK",
                       authors=[],
                       publisher="",
                       price="",
                       isbn="",
                       categories=[],
                       distributor="",
                       owner="",
                       notes="",
                       quantity=1,
                       known_title=False,
                       kind_name="",
                       extra_prices={}):
        if not (known_title):
            #add a title
            the_kinds = list(Kind.select(Kind.q.kindName == kind_name))
            kind_id = None
            if the_kinds:
                kind_id = the_kinds[0].id
            known_title = Title(isbn=isbn,
                                booktitle=title.encode("ascii",
                                                       "backslashreplace"),
                                publisher=publisher.encode(
                                    "ascii", "backslashreplace"),
                                tag=" ",
                                kindID=kind_id)
            for rawAuthor in authors:
                author = rawAuthor.encode("ascii", "backslashreplace")
                theAuthors = Author.selectBy(author_name=author)
                theAuthorsList = list(theAuthors)
                if len(theAuthorsList) == 1:
                    known_title.addAuthor(theAuthorsList[0])
                elif len(theAuthorsList) == 0:
                    a = Author(author_name=author)
                    known_title.addAuthor(a)
                else:
                    # We should SQLDataCoherenceLost here
                    print "mmm... looks like you have multiple author of the sama name in your database..."
            for category in categories:
                Category(categoryName=category.encode("ascii",
                                                      "backslashreplace"),
                         title=known_title)

        for i in range(int(quantity)):
            print distributor.encode('ascii', "backslashreplace")

            wholesale = 0
            try:
                wholesale = extra_prices['wholesale']
            except:
                pass

            b = Book(title=known_title,
                     status=status.encode("ascii", "backslashreplace"),
                     distributor=distributor.encode('ascii',
                                                    "backslashreplace"),
                     listprice=price,
                     owner=owner.encode("ascii", "backslashreplace"),
                     notes=notes.encode("ascii", "backslashreplace"),
                     consignmentStatus="",
                     wholesale=wholesale)
            b.extracolumns()
            for mp in extra_prices.keys():
                setattr(b, string.replace(mp, " ", ""), extra_prices[mp])
コード例 #50
0
ファイル: inventory.py プロジェクト: truonghn/infoshopkeeper
    def getInventory(self, queryTerms):
        keys = queryTerms.keys()

        isbnSelect = ""
        kindSelect = ""
        statusSelect = ""
        titleSelect = ""
        authorSelect = ""
        categorySelect = ""
        clauseTables = []

        if "kind" in keys:  # joins suck, avoid if possible
            kind_map = {}
            for k in [(x.kindName, x.id) for x in list(Kind.select())]:
                kind_map[k[0]] = k[1]
            try:
                kind_id = kind_map[queryTerms['kind']]
                kindSelect = Book.sqlrepr(
                    AND(
                        Field("book", "title_id") == Field("title", "id"),
                        Field("title", "kind_id") == kind_id))
            except:
                pass

        if 'status' in keys:
            statusSelect = Book.sqlrepr(
                Field("book", "status") == queryTerms["status"])

        if ('title' in keys) or ('authorName' in keys) or ('kind' in keys) or (
                'categoryName' in keys) or ('isbn' in keys):
            clauseTables.append('title')
            #we are going to need to do a join

            if 'title' in keys:
                titleSelect = Book.sqlrepr(
                    AND(
                        Field("book", "title_id") == Field("title", "id"),
                        RLIKE(Field("title", "booktitle"),
                              queryTerms["title"])))

            if 'isbn' in keys:
                titleSelect = Book.sqlrepr(
                    AND(
                        Field("book", "title_id") == Field("title", "id"),
                        Field("title", "isbn") == queryTerms["isbn"]))

            if 'authorName' in keys:
                #~ authorSelect="""book.title_id = title.id AND author.title_id=title.id AND author.author_name RLIKE %s""" % (Book.sqlrepr(queryTerms["authorName"]))
                authorSelect = Book.sqlrepr(
                    AND(
                        Field("book", "title_id") == Field("title", "id"),
                        Field("author", "id") == Field("author_title",
                                                       "author_id"),
                        Field("title", "id") == Field("author_title",
                                                      "title_id"),
                        RLIKE(Field("author", "author_name"),
                              queryTerms["authorName"])))
                clauseTables.append('author')
                clauseTables.append('author_title')

            if 'categoryName' in keys:
                #~ categorySelect="""book.title_id = title.id AND category.title_id=title.id AND category.category_name RLIKE %s""" % (Book.sqlrepr(queryTerms["categoryName"]))
                categorySelect = Book.sqlrepr(
                    AND(
                        Field("book", "title_id") == Field("title", "id"),
                        Field("category", "title_id") == Field("title", "id"),
                        RLIKE(Field("category", "category_name"),
                              queryTerms["categoryName"])))
                clauseTables.append('category')

    # At this time, ubuntu install sqlobject 0.6.1 if apt-get install python2.4-sqlobject,
# which make the search crash, since the distinct attribute is defined somewhere after 0.6.1
        try:
            books = Book.select(string.join([
                term for term in [
                    statusSelect, titleSelect, authorSelect, kindSelect,
                    categorySelect
                ] if term != ""
            ], " AND "),
                                clauseTables=clauseTables,
                                distinct=True)
        except TypeError:
            books = Book.select(string.join([
                term for term in [
                    statusSelect, titleSelect, authorSelect, kindSelect,
                    categorySelect
                ] if term != ""
            ], " AND "),
                                clauseTables=clauseTables)

        results = {}
        i = 1
        for b in books:
            theTitle = b.title.booktitle.decode("unicode_escape")
            if b.notes == None:
                b.notes = ""
            authorString = string.join([
                a.author_name.decode("unicode_escape") for a in b.title.author
            ], ",")
            results[i] = (string.capitalize(theTitle), authorString,
                          b.listprice,
                          b.title.publisher.decode("unicode_escape"),
                          b.status.decode("unicode_escape"), b.title.isbn,
                          b.distributor.decode("unicode_escape"),
                          b.notes.decode("unicode_escape"), b.id,
                          b.title.kind and b.title.kind.kindName or '')
            i = i + 1

        return results
コード例 #51
0
 def csv_export(self, outfile):
     fieldnames = vars(Book('', '')).keys()
     with open(outfile, 'w') as f:
         writer = csv.DictWriter(f, fieldnames=fieldnames)
         writer.writeheader()
         writer.writerows([b.__dict__ for b in self.books])
コード例 #52
0
 def test_get_item_by_isbn_in_stock(self):
     random_item=random.sample(list(Book.selectBy(status='STOCK')), 1)[0]
     result=self._my_class.get_item_by_isbn(**{'isbn':random_item.title.isbn})
     #print "isbn_stock", random_item, result
     self.assertTrue(result, "/register/get_item_by_isbn does not return item when it should")
コード例 #53
0
    def getInventory(self,queryTerms):
        #print queryTerms
        keys=queryTerms.keys()
        
        isbnSelect=""
        kindSelect=""
        statusSelect=""
        titleSelect=""
        authorSelect=""
        categorySelect=""
        clauseTables=[]

        if "kind" in keys: # joins suck, avoid if possible
            kind_map={}
            for k in [(x.kindName,x.id) for x in list(Kind.select())]:
                kind_map[k[0]]=k[1]
            try:
                kind_id=kind_map[queryTerms['kind']]
                kindSelect=Book.sqlrepr(AND(Field("book","title_id")==Field("title","id"), Field("title","kind_id")==kind_id))
            except: 
                pass
            
        if 'status' in keys:
            statusSelect=Book.sqlrepr(Field("book","status")==queryTerms["status"])
            

        if ('title' in keys) or ('authorName' in keys) or ('kind' in keys) or ('categoryName' in keys) or ('isbn' in keys):
            clauseTables.append('title') 
            #we are going to need to do a join 

            if 'title' in keys:
                titleSelect=Book.sqlrepr(AND(Field("book","title_id")==Field("title","id"), RLIKE(Field("title","booktitle"), queryTerms["title"])))


            if 'isbn' in keys:
                titleSelect=Book.sqlrepr(AND(Field("book","title_id")==Field("title","id"), Field("title","isbn")==queryTerms["isbn"]))


            if 'authorName' in keys:
                #authorSelect="""book.title_id = title.id AND author.title_id=title.id AND author.author_name RLIKE %s""" % (Book.sqlrepr(queryTerms["authorName"]))    
               authorSelect=Book.sqlrepr(AND(Field("book","title_id")==Field("title","id"), Field("author","id")==Field("author_title","author_id"), Field("title","id")==Field("author_title","title_id"), RLIKE(Field("author","author_name"), queryTerms["authorName"])))
               clauseTables.append('author')
               clauseTables.append('author_title')
            
            if 'categoryName' in keys:
                categorySelect="""book.title_id = title.id AND category.title_id=title.id AND category.category_name RLIKE %s""" % (Book.sqlrepr(queryTerms["categoryName"]))
                #categorySelect=Book.sqlrepr(AND(Field("book","title_id")==Field("title","id"), Field("category","title_id")==Field("title","id"), RLIKE(Field("category","category_name"), queryTerms["categoryName"])))
                clauseTables.append('category')
            # At this time, ubuntu install sqlobject 0.6.1 if apt-get install python2.4-sqlobject,
            # which make the search crash, since the distinct attribute is defined somewhere after 0.6.1 
        try:
            books=Book.select(
                string.join([term for term in [statusSelect,titleSelect,authorSelect,kindSelect,categorySelect] if term !=""]," AND "),
                clauseTables=clauseTables,
                distinct=True    )
        except TypeError:
            books=Book.select(
                string.join([term for term in [statusSelect,titleSelect,authorSelect,kindSelect,categorySelect] if term !=""]," AND "),
                clauseTables=clauseTables   )
            
        
        results={}
        i=1
        for b in books:
            theTitle=b.title.booktitle
            authorString=string.join([a.authorName for a in b.title.author],",")
            categoryString=string.join([c.categoryName for c in b.title.categorys],",")
            results[i]=(string.capitalize(theTitle),
                        authorString, 
                        b.listprice  if b.listprice is not None else '',
                        b.title.publisher if b.title.publisher is not None else '',
                        b.status if b.status is not None else'',
                        b.title.isbn,
                        b.distributor if b.distributor is not None else '',
                        b.location.locationName if b.location is not None else '',
                        b.notes if b.notes is not None else '',
                        b.id,
                        b.title.kind and b.title.kind.kindName if b.title.kind is not None else '',
            categoryString,
            b.title.type if b.title.type is not None else '')
        #~ for b in books:
            #~ theTitle=b.title.booktitle.format()
            #~ authorString=string.join([a.authorName.format() for a in b.title.author],",")
            #~ categoryString=string.join([c.categoryName.format() for c in b.title.categorys],",")
            #~ results[i]=(string.capitalize(theTitle),
                        #~ authorString, 
                        #~ b.listprice  if b.listprice is not None else '',
                        #~ b.title.publisher.format() if b.title.publisher is not None else '',
                        #~ b.status.format() if b.status is not None else'',
                        #~ b.title.isbn,
                        #~ b.distributor.format() if b.distributor is not None else '',
            #~ b.location.locationName.format() if b.location is not None else '',
                        #~ b.notes.format() if b.notes is not None else '',
                        #~ b.id,
                        #~ b.title.kind and b.title.kind.kindName if b.title.kind is not None else '',
            #~ categoryString,
            #~ b.title.type if b.title.type is not None else '')

            i=i+1                
        #print "results are ", results
        return results
コード例 #54
0
 def confirm(self,title,book,**kw):
     book=Book.get(book)
     title=Title.get(title)
     book.set_tag(category="inventory",key="confirmation11",value="stock")
     return self.title(title.id)