From: <ian...@us...> - 2003-08-26 19:56:25
|
Update of /cvsroot/webware-sandbox/Sandbox/ianbicking/misc In directory sc8-pr-cvs1:/tmp/cvs-serv20429 Added Files: ShoppingCartExample.py ShoppingCart.py Log Message: Added (old) shopping cart --- NEW FILE: ShoppingCartExample.py --- from lib.SitePage import * from lib.ShoppingCart import ShoppingCart from urllib import quote from lib.Invoice import Invoice from lib.Item import Item class ShoppingCartExample(SitePage): def title(self): return 'Shopping cart' def writeContent(self): req = self.request() pieces = asList(req.field('piece_name', None)) ses = self.session() shoppingCart = ses.value('shoppingCart', None) or \ ShoppingCart(displayer=PieceDisplayer, minShipping=5.00) shoppingCart.act(req.fields()) ses.setValue('shoppingCart', shoppingCart) if req.hasField('checkout'): return self.checkout() self.write(shoppingCart.html()) self.write('<br><a href="%s">Return to %s</a>\n' % (req.field('returnTo'), req.field('returnToDesc'))) def checkout(self): ses = self.session() shoppingCart = ses.value('shoppingCart') vars = {} vars['cmd'] = '_xclick' vars['business'] = resources.paypalBusiness totalItems = 0 totalPrice = 0.0 totalShipping = 0.0 itemNames = [] invoicePieceInserts = [] insertItems = [] for itemID, item in shoppingCart.items.items(): quantity = shoppingCart.itemQuantity[itemID] insertItems.append((itemID, quantity)) totalItems += quantity totalPrice += item.price() * quantity totalShipping += item.shipping() * quantity if quantity == 1: itemNames.append(item.description()) elif quantity != 0: itemNames.append('%i of %s' % (quantity, item.description())) itemName = ", ".join(itemNames) if len(itemName) > 127: itemName = "shopping cart with %i items" % totalItems totalShipping = max(5.0, totalShipping) invoice = Invoice.new(status = 'pending_paypal_return', totalPrice=totalPrice, totalShipping=totalShipping) invoice.set(items=insertItems) vars['item_name'] = itemName vars['item_number'] = str(invoice.id()) vars['amount'] = '%.2f' % totalPrice vars['shipping'] = '%.2f' % totalShipping vars['return'] = 'http://murphyarts.colorstudy.net/emily/thankyou/%i' % invoice.id() url = 'https://www.paypal.com/cgi-bin/webscr?' url += '&'.join(map(lambda x: x[0] + '=' + quote(x[1]), vars.items())) self.response().sendRedirect(url) class PieceDisplayer: fieldOrder = (('Description', 'description'), (' ', 'image')) def __init__(self, id): self._id = id def image(self): return Item(self._id).thumbImgSrc() def maxQuantity(self): return Item(self._id).inventory() def price(self): return Item(self._id).price() def shipping(self): return Item(self._id).shipping() def description(self): return Item(self._id).title() --- NEW FILE: ShoppingCart.py --- from StdLib import asList, htmlEncode try: from cStringIO import StringIO except ImportError: from StringIO import StringIO True, False = (1==1), (0==1) class ShoppingCart: def __init__(self, displayer=None, minShipping=0.00, checkoutButton='<input type="submit" name="checkout" value="Purchase now">'): self.itemQuantity = {} self.items = {} self.itemDisplayer = displayer self.minShipping = minShipping self.messages = [] self.checkoutButton = checkoutButton def act(self, fields): for item in asList(fields.get('addItem', [])): self.itemQuantity[item] = self.itemQuantity.get(item, 0) + 1 if not self.items.has_key(item): self.items[item] = self.itemDisplayer(item) for item in asList(fields.get('deleteItem', [])): del self.itemQuantity[item] del self.items[item] for key, value in fields.items(): if key.startswith("editItem-"): item = key[10:] try: self.itemQuantity[item] = int(value) if not self.items.has_key(item): self.items[item] = self.itemDisplayer(item) self.checkQuantity(item) except ValueError: pass elif key.startswith("deleteItem-"): item = key[12:] if self.itemQuantity.has_key(item): del self.itemQuantity[item] del self.items[item] for itemID in self.items.keys(): self.checkQuantity(itemID) self._returnTo = fields.get('returnTo', '') self._returnToDesc = fields.get('returnToDesc', '') def html(self, withEndForm=True): out = StringIO() for message in self.messages: out.write('<span style="color: #ffffff; background-color: #990000">%s</span><br>\n' % message) self.messages = [] if not self.items: out.write('\n<br>Your cart is empty') return out.getvalue() showQuantities = False priceTotal = 0.0 shippingTotal = 0.0 for item in self.items.keys(): if self.items[item] != 1 or self.itemQuantity[item] != 1: showQuantities = True out.write('<form method="POST">\n') out.write('<input type="hidden" name="returnTo" value="%s">\n' % htmlEncode(self._returnTo)) out.write('<input type="hidden" name="returnToDesc" value="%s">\n' % htmlEncode(self._returnToDesc)) out.write('<table cellspacing=3>') for description, attr in self.itemDisplayer.fieldOrder: out.write('<th>%s</th>' % description) out.write('<th>Price Each</th>') if showQuantities: out.write('<th>Quantity</th><th>Total price</th>') out.write('<th>Shipping</th>') for item in self.items.keys(): out.write('<tr>\n') for description, attr in self.itemDisplayer.fieldOrder: value = getattr(self.items[item], attr) if type(value) is type(self.html): value = value() out.write('<td bgcolor="#000055">%s</td>\n' % value) out.write('<td bgcolor="#000055">$%.2f</td>\n' % self.items[item].price()) if self.itemQuantity[item] == 1 and \ self.items[item].maxQuantity() == 1 and showQuantities: out.write('<td bgcolor="#000055">%s</td>\n' % self.itemQuantity[item]) elif showQuantities: out.write('<td bgcolor="#000055"><input type="text" size="2" name="editItem-%s" value="%s">\n' % (item, self.itemQuantity[item])) out.write('<input type="submit" value="update"></td>\n') if showQuantities: out.write('<td bgcolor="#000055">$%.2f</td>\n' % (self.items[item].price() * self.itemQuantity[item])) out.write('<td bgcolor="#000055">$%.2f</td>\n' % (self.items[item].shipping() * self.itemQuantity[item])) out.write('<td><input type="submit" name="deleteItem-%s" value="remove"></td>\n' % item) priceTotal += self.items[item].price() * self.itemQuantity[item] shippingTotal += self.items[item].shipping() * self.itemQuantity[item] out.write('</tr>\n') totalCols = len(self.itemDisplayer.fieldOrder) + 3 if showQuantities: totalCols += 2 out.write('<tr><td bgcolor="#000055" colspan=%i align=right>Subtotal:<td>\n' % (totalCols - 4)) out.write('<td bgcolor="#000055">$%.2f</td>\n' % priceTotal) if self.minShipping > shippingTotal: out.write('<td bgcolor="#000055">$%.2f</td>\n' % self.minShipping) out.write('<td bgcolor="#000055">($%.2f minimum shipping)</td>\n' % self.minShipping) shippingTotal = self.minShipping else: out.write('<td bgcolor="#000055">$%.2f</td>\n' % shippingTotal) out.write('<td></td>\n') out.write('</tr>\n') out.write('<tr><td colspan=%i bgcolor="#000055" align=right>Total:</td>\n' % (totalCols - 1)) out.write('<td bgcolor="#000055"><b>$%.2f</b></td></tr>\n' % (priceTotal + shippingTotal)) out.write('</table>') out.write('<center>%s</center>' % self.checkoutButton) if withEndForm: out.write('</form>') return out.getvalue() def checkQuantity(self, item): if self.itemQuantity[item] > self.items[item].maxQuantity(): self.messages.append("I'm sorry, but you cannot order more than %i of %s" % (self.items[item].maxQuantity(), self.items[item].description())) self.itemQuantity[item] = self.items[item].maxQuantity() |