def test_discount_qty_price(self): """Test quantity price discounts""" product = Product.objects.get(slug='PY-Rocks') price = Price(product=product, quantity=Decimal('10'), price=Decimal("10.00")) price.save() self.assertEqual(product.unit_price, Decimal("19.50")) self.assertEqual(product.get_qty_price(Decimal('1')), Decimal("19.50")) self.assertEqual(product.get_qty_price(Decimal('2')), Decimal("19.50")) self.assertEqual(product.get_qty_price(Decimal('10')), Decimal("10.00"))
def save(self, request): self.full_clean() for name, value in self.cleaned_data.items(): opt, key = name.split('__') prod = Product.objects.get(slug__exact=key) subtypes = prod.get_subtypes() if opt=='qty': if value != prod.items_in_stock: messages.add_message(request, messages.INFO, 'Updated %s stock to %s' % (key, value)) log.debug('Saving new qty=%d for %s' % (value, key)) prod.items_in_stock = value prod.save() elif opt=='price': if 'CustomProduct' in subtypes: full_price = prod.customproduct.full_price else: full_price = prod.unit_price if value != full_price: messages.add_message(request, messages.INFO, 'Updated %s unit price to %s' % (key, value)) log.debug('Saving new price %s for %s' % (value, key)) try: price = Price.objects.get(product=prod, quantity='1') except Price.DoesNotExist: price = Price(product=prod, quantity='1') price.price = value price.save() elif opt=="active": if value != prod.active: if value: note = "Activated %s" else: note = "Deactivated %s" messages.add_message(request, messages.INFO, note % (key)) prod.active = value prod.save() elif opt=="featured": if value != prod.featured: if value: note = "%s is now featured" else: note = "%s is no longer featured" messages.add_message(request, messages.INFO, note % (key)) prod.featured = value prod.save()
def save(self, request): self.full_clean() for name, value in self.cleaned_data.items(): opt, key = name.split("__") prod = Product.objects.get(slug__exact=key) subtypes = prod.get_subtypes() if opt == "qty": if value != prod.items_in_stock: request.user.message_set.create(message="Updated %s stock to %s" % (key, value)) log.debug("Saving new qty=%d for %s" % (value, key)) prod.items_in_stock = value prod.save() elif opt == "price": if "CustomProduct" in subtypes: full_price = prod.customproduct.full_price else: full_price = prod.unit_price if value != full_price: request.user.message_set.create(message="Updated %s unit price to %s" % (key, value)) log.debug("Saving new price %s for %s" % (value, key)) try: price = Price.objects.get(product=prod, quantity="1") except Price.DoesNotExist: price = Price(product=prod, quantity="1") price.price = value price.save() elif opt == "active": if value != prod.active: if value: note = "Activated %s" else: note = "Deactivated %s" request.user.message_set.create(message=note % (key)) prod.active = value prod.save() elif opt == "featured": if value != prod.featured: if value: note = "%s is now featured" else: note = "%s is no longer featured" request.user.message_set.create(message=note % (key)) prod.featured = value prod.save()
def save(self): data = self.cleaned_data site = Site.objects.get_current() # create product product = Product(name=data['title'], slug=data['slug'], site=site, active=True) product.save() # create product price price = Price(price=data['price'], product=product) price.save() if data.get('category'): product.category.add(data['category']) if data.get('cover_image'): # create product image ProductImage.objects.create(product=product, picture=data['cover_image']) # check for product attributes for key in data: # if key is not product attribute or # value for the key is blank, goto next key if key in NOT_PRODUCT_ATTRS or not data[key]: continue # get the field related to the key field = self.fields[key] description = (field.label or key.replace('_', ' ')).capitalize() # get or create the attribute try: attribute = AttributeOption.objects.get(name=key) except AttributeOption.DoesNotExist: attribute = AttributeOption(name=key, description=description, validation='product.utils.validation_simple') attribute.save() # create product attribute product_attribute = ProductAttribute(product=product, option=attribute, value=data[key]) product_attribute.save()
def force_recalculate_total(self, save=True): """Calculates sub_total, taxes and total.""" zero = Decimal("0.0000000000") total_discount = Decimal("0.0000000000") discount = Discount.objects.by_code(self.discount_code) discount.calc(self) discounts = discount.item_discounts itemprices = [] fullprices = [] for lineitem in self.orderitem_set.all(): lid = lineitem.id if lid in discounts: lineitem.discount = discounts[lid] else: lineitem.discount = zero # now double check against other discounts, such as tiered discounts adjustment = get_product_quantity_adjustments(lineitem.product, qty=lineitem.quantity) if adjustment and adjustment.price: baseprice = adjustment.price.price finalprice = adjustment.final_price() #We need to add in any OrderItemDetail price adjustments before we do anything else baseprice += lineitem.get_detail_price() finalprice += lineitem.get_detail_price() if baseprice > finalprice or baseprice != lineitem.unit_price: unitdiscount = (lineitem.discount/lineitem.quantity) + baseprice-finalprice unitdiscount = trunc_decimal(unitdiscount, 2) linediscount = unitdiscount * lineitem.quantity total_discount += linediscount fullydiscounted = (baseprice - unitdiscount) * lineitem.quantity lineitem.unit_price = baseprice lineitem.discount = linediscount lineitem.line_item_price = baseprice * lineitem.quantity log.debug('Adjusting lineitem unit price for %s. Full price=%s, discount=%s. Final price for qty %d is %s', lineitem.product.slug, baseprice, unitdiscount, lineitem.quantity, fullydiscounted) if save: lineitem.save() itemprices.append(lineitem.sub_total) fullprices.append(lineitem.line_item_price) shipprice = Price() shipprice.price = self.shipping_cost shipadjust = PriceAdjustmentCalc(shipprice) if 'Shipping' in discounts: shipadjust += PriceAdjustment('discount', _('Discount'), discounts['Shipping']) signals.satchmo_shipping_price_query.send(self, adjustment=shipadjust) shipdiscount = shipadjust.total_adjustment() self.shipping_discount = shipdiscount total_discount += shipdiscount self.discount = total_discount if itemprices: item_sub_total = reduce(operator.add, itemprices) else: item_sub_total = zero if fullprices: full_sub_total = reduce(operator.add, fullprices) else: full_sub_total = zero self.sub_total = full_sub_total taxProcessor = get_tax_processor(self) totaltax, taxrates = taxProcessor.process() self.tax = totaltax # clear old taxes for taxdetl in self.taxes.all(): taxdetl.delete() for taxdesc, taxamt in taxrates.items(): taxdetl = OrderTaxDetail(order=self, tax=taxamt, description=taxdesc, method=taxProcessor.method) taxdetl.save() log.debug("Order #%i, recalc: sub_total=%s, shipping=%s, discount=%s, tax=%s", self.id, moneyfmt(item_sub_total), moneyfmt(self.shipping_sub_total), moneyfmt(self.discount), moneyfmt(self.tax)) self.total = Decimal(item_sub_total + self.shipping_sub_total + self.tax) if save: self.save()
def _get_shipping_choices(request, paymentmodule, cart, contact, default_view_tax=False, order=None): """Iterate through legal shipping modules, building the list for display to the user. Returns the shipping choices list, along with a dictionary of shipping choices, useful for building javascript that operates on shipping choices. """ shipping_options = [] shipping_dict = {} rendered = {} if not order: try: order = Order.objects.from_request(request) except Order.DoesNotExist: pass discount = None if order: try: discount = Discount.objects.by_code(order.discount_code) except Discount.DoesNotExist: pass if not cart.is_shippable: methods = [shipping_method_by_key('NoShipping'),] else: methods = shipping_methods() tax_shipping = config_value_safe('TAX','TAX_SHIPPING', False) shipping_tax = None if tax_shipping: taxer = _get_taxprocessor(request) shipping_tax = TaxClass.objects.get(title=config_value('TAX', 'TAX_CLASS')) for method in methods: method.calculate(cart, contact) if method.valid(): template = lookup_template(paymentmodule, 'shipping/options.html') t = loader.get_template(template) shipcost = finalcost = method.cost() if discount and order: order.shipping_cost = shipcost discount.calc(order) shipdiscount = discount.item_discounts.get('Shipping', 0) else: shipdiscount = 0 # set up query to determine shipping price to show shipprice = Price() shipprice.price = shipcost shipadjust = PriceAdjustmentCalc(shipprice) if shipdiscount: shipadjust += PriceAdjustment('discount', _('Discount'), shipdiscount) satchmo_shipping_price_query.send(cart, adjustment=shipadjust) shipdiscount = shipadjust.total_adjustment() if shipdiscount: finalcost -= shipdiscount shipping_dict[method.id] = {'cost' : shipcost, 'discount' : shipdiscount, 'final' : finalcost} taxed_shipping_price = None if tax_shipping: taxcost = taxer.by_price(shipping_tax, finalcost) total = finalcost + taxcost taxed_shipping_price = moneyfmt(total) shipping_dict[method.id]['taxedcost'] = total shipping_dict[method.id]['tax'] = taxcost c = RequestContext(request, { 'amount': finalcost, 'description' : method.description(), 'method' : method.method(), 'expected_delivery' : method.expectedDelivery(), 'default_view_tax' : default_view_tax, 'shipping_tax': shipping_tax, 'taxed_shipping_price': taxed_shipping_price}) rendered[method.id] = t.render(c) #now sort by price, low to high sortme = [(value['cost'], key) for key, value in shipping_dict.items()] sortme.sort() shipping_options = [(key, rendered[key]) for cost, key in sortme] shipping_choices_query.send(sender=cart, cart=cart, paymentmodule=paymentmodule, contact=contact, default_view_tax=default_view_tax, order=order, shipping_options = shipping_options, shipping_dict = shipping_dict) return shipping_options, shipping_dict
def force_recalculate_total(self, save=True): """Calculates sub_total, taxes and total.""" zero = Decimal("0.0000000000") discount = Discount.objects.by_code(self.discount_code) discount.calc(self) self.discount = discount.total discounts = discount.item_discounts itemprices = [] fullprices = [] for lineitem in self.orderitem_set.all(): lid = lineitem.id if lid in discounts: lineitem.discount = discounts[lid] else: lineitem.discount = zero if save: lineitem.save() itemprices.append(lineitem.sub_total) fullprices.append(lineitem.line_item_price) shipprice = Price() shipprice.price = self.shipping_cost shipadjust = PriceAdjustmentCalc(shipprice) if 'Shipping' in discounts: shipadjust += PriceAdjustment('discount', _('Discount'), discounts['Shipping']) signals.satchmo_shipping_price_query.send(self, adjustment=shipadjust) self.shipping_discount = shipadjust.total_adjustment() if itemprices: item_sub_total = reduce(operator.add, itemprices) else: item_sub_total = zero if fullprices: full_sub_total = reduce(operator.add, fullprices) else: full_sub_total = zero self.sub_total = full_sub_total taxProcessor = get_tax_processor(self) totaltax, taxrates = taxProcessor.process() self.tax = totaltax # clear old taxes for taxdetl in self.taxes.all(): taxdetl.delete() for taxdesc, taxamt in taxrates.items(): taxdetl = OrderTaxDetail(order=self, tax=taxamt, description=taxdesc, method=taxProcessor.method) taxdetl.save() log.debug("Order #%i, recalc: sub_total=%s, shipping=%s, discount=%s, tax=%s", self.id, moneyfmt(item_sub_total), moneyfmt(self.shipping_sub_total), moneyfmt(self.discount), moneyfmt(self.tax)) self.total = Decimal(item_sub_total + self.shipping_sub_total + self.tax) if save: self.save()
def handle_noargs(self, **options): from satchmo_store.contact.models import ( AddressBook, Contact, ContactOrganization, ContactOrganizationRole, ContactRole, Organization, PhoneNumber, ) from product.models import ( Category, OptionGroup, Option, Price, Product, ) from product.modules.configurable.models import ConfigurableProduct from satchmo_store.shop.models import Config from django.conf import settings from l10n.models import Country from django.contrib.sites.models import Site from django.contrib.auth.models import User #idempotency test print "Checking for existing sample data." try: p = Product.objects.get(slug="dj-rocks") print "It looks like you already have loaded the sample store data, quitting." import sys sys.exit(1) except Product.DoesNotExist: pass print "Loading sample store data." #Load basic configuration information print "Creating site..." try: site = Site.objects.get(id=settings.SITE_ID) print "Using existing site #%i" % settings.SITE_ID except Site.DoesNotExist: print "Creating Example Store Site" site = Site(domain="localhost", name="Sample Store") site.domain = settings.SITE_DOMAIN site.name = settings.SITE_NAME site.save() try: store_country = Country.objects.get(iso3_code='USA') except Country.DoesNotExist: print "\nError: Country data should be first loaded by: python manage.py satchmo_load_l10n" import sys sys.exit(1) config = Config(site=site, store_name=settings.SITE_NAME, country=store_country, sales_country=store_country) config.save() config.shipping_countries.add(store_country) config.save() print "Creating Customers..." # Import some customers customer = ContactRole.objects.get(pk='Customer') c1 = Contact(first_name="Chris", last_name="Smith", email="*****@*****.**", role=customer, notes="Really cool stuff") c1.save() p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home",primary=True) p1.save() c2 = Contact(first_name="John", last_name="Smith", email="*****@*****.**", role=customer, notes="Second user") c2.save() p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work",primary=True) p2.save() # Import some addresses for these customers us = Country.objects.get(iso2_code='US'); a1 = AddressBook(description="Home", street1="8235 Pike Street", city="Anywhere Town", state="TN", postal_code="38138", country=us, is_default_shipping=True, contact=c1) a1.save() a2 = AddressBook(description="Work", street1="1245 Main Street", city="Stillwater", state="MN", postal_code="55082", country=us, is_default_shipping=True, contact=c2) a2.save() print "Creating Suppliers..." #Import some suppliers supplier = ContactOrganizationRole.objects.get(pk='Supplier') company = ContactOrganization.objects.get(pk='Company') contactsupplier = ContactRole.objects.get(pk='Supplier') org1 = Organization(name="Rhinestone Ronny", type=company, role=supplier) org1.save() c4 = Contact(first_name="Fred", last_name="Jones", email="*****@*****.**", role=contactsupplier, organization=org1) c4.save() p4 = PhoneNumber(contact=c4,phone="800-188-7611", type="Work", primary=True) p4.save() p5 = PhoneNumber(contact=c4,phone="755-555-1111",type="Fax") p5.save() a3 = AddressBook(contact=c4, description="Mailing address", street1="Receiving Dept", street2="918 Funky Town St", city="Fishkill", state="NJ", country=us, postal_code="19010") a3.save() #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200", # city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="*****@*****.**", # notes="My main supplier") #s1.save() #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane", # city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="*****@*****.**", # notes="Shirt Supplier") #s2.save() print "Creating Categories..." #Create some categories '''cat1 = Category(site=site, name="Shirts",slug="shirts",description="Women's Shirts") cat1.save() cat2 = Category(site=site, name="Short Sleeve",slug="shortsleeve",description="Short sleeve shirts", parent=cat1) cat2.save()''' cat3 = Category(name="Books",slug="book",description="Books") cat3.save() cat3.site.add(site) '''cat4 = Category(site=site, name="Fiction",slug="fiction",description="Fiction Books", parent=cat3) cat4.save() cat5 = Category(site=site, name="Science Fiction",slug="scifi",description="Science Fiction",parent=cat4) cat5.save() cat6 = Category(site=site, name="Non Fiction",slug="nonfiction",description="Non Fiction",parent=cat3) cat6.save() cat7 = Category(site=site, name="Software", slug="software") cat7.save()''' print "Creating products..." #Create some items '''i1 = Product(name="Django Rocks shirt", slug="dj-rocks", description="Really cool shirt", active=True, featured=True) i1.save() p1 = Price(price="20.00", product=i1) p1.save() i1.category.add(cat1) i1.save() i2 = Product(name="Python Rocks shirt", slug="PY-Rocks", description="Really cool python shirt - One Size Fits All", active=True, featured=True) i2.save() p2 = Price(price="19.50", product=i2) p2.save() i2.category.add(cat2) i2.save()''' i3 = Product(name="Purusha Suktam", slug="Advyata", description="A neat book. You should buy it.", active=True, featured=True) i3.save() i3.site.add(site) p3 = Price(price="5.00", product=i3) p3.save() i3.category.add(cat3) i3.save() i3.site.add(site) '''i4 = Product(name="Robots Attack!", slug="robot-attack", description="Robots try to take over the world.", active=True, featured=True) i4.save() p4 = Price(price="7.99", product=i4) p4.save() i4.category.add(cat5) i4.save() # i5 = Product(site=site, name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True) # i5.save() # i5.category.add(cat7) # i5.save() #Create an attribute set optSet1 = OptionGroup(site=site, name="sizes", sort_order=1) optSet2 = OptionGroup(site=site, name="colors", sort_order=2) optSet1.save() optSet2.save()''' optSet3 = OptionGroup(name="Book type", sort_order=1) optSet3.save() optSet3.site.add(site) '''optSet4 = OptionGroup(site=site, name="Full/Upgrade", sort_order=5) optSet4.save() optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1) optItem1a.save() optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1) optItem1b.save() optItem1c = Option(name="Large", value="L", sort_order=3, price_change="1.00", option_group=optSet1) optItem1c.save() optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2) optItem2a.save() optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2) optItem2b.save() optItem2c = Option(name="Blue", value="BL", sort_order=3, price_change="2.00", option_group=optSet2) optItem2c.save()''' optItem3a = Option(name="Hard cover", value="hard", sort_order=1, option_group=optSet3) optItem3a.save() optItem3b = Option(name="Soft cover", value="soft", sort_order=2, price_change="1.00", option_group=optSet3) optItem3b.save() optItem3c = Option(name="On tape", value="tape", sort_order=3, option_group=optSet3) optItem3c.save() '''optItem4a = Option(name="Full Version", value="full", option_group=optSet4, sort_order=1) optItem4a.save() optItem4b = Option(name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2) optItem4b.save()''' #Add the option group to our items '''pg1 = ConfigurableProduct(product=i1) pg1.save() pg1.option_group.add(optSet1) pg1.save() pg1.option_group.add(optSet2) pg1.save()''' pg3 = ConfigurableProduct(product=i3) pg3.save() pg3.option_group.add(optSet3) pg3.save() '''pg4 = ConfigurableProduct(product=i4) pg4.save() pg4.option_group.add(optSet3) pg4.save()''' # pg5 = ConfigurableProduct(product=i5) # pg5.option_group.add(optSet4) # pg5.save() print "Creating product variations..." #Create the required sub_items #pg1.create_all_variations() pg3.create_all_variations() #pg4.create_all_variations() #pg5.create_all_variations() #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required. # pv1 = pg5.get_product_from_options([optItem4a]) # Price(product=pv1, price='5.00').save() # Price(product=pv1, price='2.00', quantity='50.00').save() # DownloadableProduct(product=pv1).save() # pv2 = pg5.get_product_from_options([optItem4b]) # Price(product=pv2, price='1.00').save() # DownloadableProduct(product=pv2).save() print "Create a test user..." #First see if our test user is still there, then use or create that user try: test_user = User.objects.get(username="******") except: test_user = User.objects.create_user('csmith', '*****@*****.**', 'test') test_user.save() c1.user = test_user c1.save()
def _get_shipping_choices(request, paymentmodule, cart, contact, default_view_tax=False, order=None): """Iterate through legal shipping modules, building the list for display to the user. Returns the shipping choices list, along with a dictionary of shipping choices, useful for building javascript that operates on shipping choices. """ shipping_options = [] shipping_dict = {} rendered = {} if not order: try: order = Order.objects.from_request(request) except Order.DoesNotExist: pass discount = None if order: try: discount = Discount.objects.by_code(order.discount_code) except Discount.DoesNotExist: pass if not cart.is_shippable: methods = [ shipping_method_by_key('NoShipping'), ] else: methods = shipping_methods() tax_shipping = config_value_safe('TAX', 'TAX_SHIPPING', False) shipping_tax = None if tax_shipping: taxer = _get_taxprocessor(request) shipping_tax = TaxClass.objects.get( title=config_value('TAX', 'TAX_CLASS')) for method in methods: method.calculate(cart, contact) if method.valid(): template = lookup_template(paymentmodule, 'shipping/options.html') t = loader.get_template(template) shipcost = finalcost = method.cost() if discount and order: order.shipping_cost = shipcost discount.calc(order) shipdiscount = discount.item_discounts.get('Shipping', 0) else: shipdiscount = 0 # set up query to determine shipping price to show shipprice = Price() shipprice.price = shipcost shipadjust = PriceAdjustmentCalc(shipprice) if shipdiscount: shipadjust += PriceAdjustment('discount', _('Discount'), shipdiscount) satchmo_shipping_price_query.send(cart, adjustment=shipadjust) shipdiscount = shipadjust.total_adjustment() if shipdiscount: finalcost -= shipdiscount shipping_dict[method.id] = { 'cost': shipcost, 'discount': shipdiscount, 'final': finalcost } taxed_shipping_price = None if tax_shipping: taxcost = taxer.by_price(shipping_tax, finalcost) total = finalcost + taxcost taxed_shipping_price = moneyfmt(total) shipping_dict[method.id]['taxedcost'] = total shipping_dict[method.id]['tax'] = taxcost c = RequestContext( request, { 'amount': finalcost, 'description': method.description(), 'method': method.method(), 'expected_delivery': method.expectedDelivery(), 'default_view_tax': default_view_tax, 'shipping_tax': shipping_tax, 'taxed_shipping_price': taxed_shipping_price }) rendered[method.id] = t.render(c) #now sort by price, low to high sortme = [(value['cost'], key) for key, value in shipping_dict.items()] sortme.sort() shipping_options = [(key, rendered[key]) for cost, key in sortme] shipping_choices_query.send(sender=cart, cart=cart, paymentmodule=paymentmodule, contact=contact, default_view_tax=default_view_tax, order=order, shipping_options=shipping_options, shipping_dict=shipping_dict) return shipping_options, shipping_dict
def get_product(self, day, schedule=None, tour_time=None, create=True): """ Get the TourProduct for the given day and time. If create is false and product does not exist, return None. """ if schedule and tour_time: assert False, 'Make up your mind, use a schedule or a tour_time, not both' if not schedule and not tour_time: assert False, 'Need a time buddy' try: if schedule: tour_product = TourProduct.objects.filter(tour_type=self, day=day).filter( Q(schedule=schedule) | Q(tour_time=schedule.tour_time))[0] else: tour_product = TourProduct.objects.get(tour_type=self, day=day, tour_time=tour_time) if tour_product.tour_type.has_price_raise(): p = tour_product.product.price_set.all()[0] p.price = self.get_raised_base_price(tour_product.day) p.save() return tour_product except (TourProduct.DoesNotExist, IndexError): if create: # print 'creating product... ', day product = Product() product.site = Site.objects.get_current() product.name = '%s on %s at ' % (self.name, day.strftime('%B %d, %Y')) if schedule: product.name += schedule.tour_time.strftime('%I:%M %p') else: product.name += tour_time.strftime('%I:%M %p') product.items_in_stock = self.get_capacity_for_day(day) product.shipclass = 'NO' # see product.models.SHIP_CLASS_CHOICES product.save() tour_product = TourProduct() tour_product.product = product tour_product.tour_type = self tour_product.day = day if schedule: tour_product.schedule = schedule tour_product.tour_time = schedule.tour_time else: tour_product.schedule = None tour_product.tour_time = tour_time tour_product.save() p = Price() p.product = product if tour_product.tour_type.has_price_raise(): p.price = self.get_raised_base_price(tour_product.day) else: p.price = self.base_price p.save() # Create Variations if self.option_group_id: configurable_product = ConfigurableProduct(product=product) configurable_product.save() configurable_product.option_group.add(self.option_group) configurable_product.create_subs = True configurable_product.save() return tour_product else: return None
def handle_noargs(self, **options): from satchmo_store.contact.models import ( AddressBook, Contact, ContactOrganization, ContactOrganizationRole, ContactRole, Organization, PhoneNumber, ) from product.models import ( Category, OptionGroup, Option, Price, Product, ) from product.modules.configurable.models import ConfigurableProduct from satchmo_store.shop.models import Config from django.conf import settings from l10n.models import Country from django.contrib.sites.models import Site from django.contrib.auth.models import User #idempotency test print "Checking for existing sample data." try: p = Product.objects.get(slug="dj-rocks") print "It looks like you already have loaded the sample store data, quitting." import sys sys.exit(1) except Product.DoesNotExist: pass print "Loading sample store data." #Load basic configuration information print "Creating site..." try: site = Site.objects.get(id=settings.SITE_ID) print "Using existing site #%i" % settings.SITE_ID except Site.DoesNotExist: print "Creating Example Store Site" site = Site(domain="localhost", name="Sample Store") site.domain = settings.SITE_DOMAIN site.name = settings.SITE_NAME site.save() store_country = Country.objects.get(iso3_code='USA') config = Config(site=site, store_name=settings.SITE_NAME, country=store_country, sales_country=store_country) config.save() config.shipping_countries.add(store_country) config.save() print "Creating Customers..." # Import some customers customer = ContactRole.objects.get(pk='Customer') c1 = Contact(first_name="Chris", last_name="Smith", email="*****@*****.**", role=customer, notes="Really cool stuff") c1.save() p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home", primary=True) p1.save() c2 = Contact(first_name="John", last_name="Smith", email="*****@*****.**", role=customer, notes="Second user") c2.save() p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work", primary=True) p2.save() # Import some addresses for these customers us = Country.objects.get(iso2_code='US') a1 = AddressBook(description="Home", street1="8235 Pike Street", city="Anywhere Town", state="TN", postal_code="38138", country=us, is_default_shipping=True, contact=c1) a1.save() a2 = AddressBook(description="Work", street1="1245 Main Street", city="Stillwater", state="MN", postal_code="55082", country=us, is_default_shipping=True, contact=c2) a2.save() print "Creating Suppliers..." #Import some suppliers supplier = ContactOrganizationRole.objects.get(pk='Supplier') company = ContactOrganization.objects.get(pk='Company') contactsupplier = ContactRole.objects.get(pk='Supplier') org1 = Organization(name="Rhinestone Ronny", type=company, role=supplier) org1.save() c4 = Contact(first_name="Fred", last_name="Jones", email="*****@*****.**", role=contactsupplier, organization=org1) c4.save() p4 = PhoneNumber(contact=c4, phone="800-188-7611", type="Work", primary=True) p4.save() p5 = PhoneNumber(contact=c4, phone="755-555-1111", type="Fax") p5.save() a3 = AddressBook(contact=c4, description="Mailing address", street1="Receiving Dept", street2="918 Funky Town St", city="Fishkill", state="NJ", country=us, postal_code="19010") a3.save() #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200", # city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="*****@*****.**", # notes="My main supplier") #s1.save() #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane", # city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="*****@*****.**", # notes="Shirt Supplier") #s2.save() print "Creating Categories..." #Create some categories cat1 = Category(site=site, name="Shirts", slug="shirts", description="Women's Shirts") cat1.save() cat2 = Category(site=site, name="Short Sleeve", slug="shortsleeve", description="Short sleeve shirts", parent=cat1) cat2.save() cat3 = Category(site=site, name="Books", slug="book", description="Books") cat3.save() cat4 = Category(site=site, name="Fiction", slug="fiction", description="Fiction Books", parent=cat3) cat4.save() cat5 = Category(site=site, name="Science Fiction", slug="scifi", description="Science Fiction", parent=cat4) cat5.save() cat6 = Category(site=site, name="Non Fiction", slug="nonfiction", description="Non Fiction", parent=cat3) cat6.save() cat7 = Category(site=site, name="Software", slug="software") cat7.save() print "Creating products..." #Create some items i1 = Product(site=site, name="Django Rocks shirt", slug="dj-rocks", description="Really cool shirt", active=True, featured=True) i1.save() p1 = Price(price="20.00", product=i1) p1.save() i1.category.add(cat1) i1.save() i2 = Product( site=site, name="Python Rocks shirt", slug="PY-Rocks", description="Really cool python shirt - One Size Fits All", active=True, featured=True) i2.save() p2 = Price(price="19.50", product=i2) p2.save() i2.category.add(cat2) i2.save() i3 = Product(site=site, name="A really neat book", slug="neat-book", description="A neat book. You should buy it.", active=True, featured=True) i3.save() p3 = Price(price="5.00", product=i3) p3.save() i3.category.add(cat4) i3.save() i4 = Product(site=site, name="Robots Attack!", slug="robot-attack", description="Robots try to take over the world.", active=True, featured=True) i4.save() p4 = Price(price="7.99", product=i4) p4.save() i4.category.add(cat5) i4.save() # i5 = Product(site=site, name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True) # i5.save() # i5.category.add(cat7) # i5.save() #Create an attribute set optSet1 = OptionGroup(site=site, name="sizes", sort_order=1) optSet2 = OptionGroup(site=site, name="colors", sort_order=2) optSet1.save() optSet2.save() optSet3 = OptionGroup(site=site, name="Book type", sort_order=1) optSet3.save() optSet4 = OptionGroup(site=site, name="Full/Upgrade", sort_order=5) optSet4.save() optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1) optItem1a.save() optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1) optItem1b.save() optItem1c = Option(name="Large", value="L", sort_order=3, price_change="1.00", option_group=optSet1) optItem1c.save() optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2) optItem2a.save() optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2) optItem2b.save() optItem2c = Option(name="Blue", value="BL", sort_order=3, price_change="2.00", option_group=optSet2) optItem2c.save() optItem3a = Option(name="Hard cover", value="hard", sort_order=1, option_group=optSet3) optItem3a.save() optItem3b = Option(name="Soft cover", value="soft", sort_order=2, price_change="1.00", option_group=optSet3) optItem3b.save() optItem3c = Option(name="On tape", value="tape", sort_order=3, option_group=optSet3) optItem3c.save() optItem4a = Option(name="Full Version", value="full", option_group=optSet4, sort_order=1) optItem4a.save() optItem4b = Option(name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2) optItem4b.save() #Add the option group to our items pg1 = ConfigurableProduct(product=i1) pg1.save() pg1.option_group.add(optSet1) pg1.save() pg1.option_group.add(optSet2) pg1.save() pg3 = ConfigurableProduct(product=i3) pg3.save() pg3.option_group.add(optSet3) pg3.save() pg4 = ConfigurableProduct(product=i4) pg4.save() pg4.option_group.add(optSet3) pg4.save() # pg5 = ConfigurableProduct(product=i5) # pg5.option_group.add(optSet4) # pg5.save() print "Creating product variations..." #Create the required sub_items pg1.create_all_variations() pg3.create_all_variations() pg4.create_all_variations() #pg5.create_all_variations() #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required. # pv1 = pg5.get_product_from_options([optItem4a]) # Price(product=pv1, price='5.00').save() # Price(product=pv1, price='2.00', quantity='50.00').save() # DownloadableProduct(product=pv1).save() # pv2 = pg5.get_product_from_options([optItem4b]) # Price(product=pv2, price='1.00').save() # DownloadableProduct(product=pv2).save() print "Create a test user..." #First see if our test user is still there, then use or create that user try: test_user = User.objects.get(username="******") except: test_user = User.objects.create_user('csmith', '*****@*****.**', 'test') test_user.save() c1.user = test_user c1.save()