コード例 #1
0
ファイル: product.py プロジェクト: anonymoose/pvscore
    def save_inventory(self):
        prod = Product.load(self.request.POST.get('id'))
        self.forbid_if(not prod or prod.company.enterprise_id != self.enterprise_id)
        InventoryJournal.create_new(prod, 'Inventory Adjust', float(self.request.POST.get('inventory', 0)))
        prod.name = self.request.POST.get('name')
        prod.manufacturer = self.request.POST.get('manufacturer')
        prod.unit_cost = util.nvl(self.request.POST.get('unit_cost'), 0.0)
        prod.sku = self.request.POST.get('sku')
        prod.inventory_par = util.nvl(self.request.POST.get('inventory_par'), None)
        prod.save()

        # save all the prices, prefixed by "cmp_"
        for k in self.request.POST.keys():
            if k.startswith('cmp_'):
                match = re.search(r'^.*_(.*)', k)
                if match:
                    campaign = Campaign.load(match.group(1))
                    price = self.request.POST.get(k)
                    if price:
                        price = util.float_(price)
                        prod.set_price_only(campaign, price)
                    else:
                        prod.remove_price(campaign)
                    prod.invalidate_caches(campaign_id=campaign.campaign_id)
        return 'True'
コード例 #2
0
ファイル: report.py プロジェクト: anonymoose/pvscore
    def results(self):
        report_id = self.request.matchdict.get('report_id')
        rep = Report.load(report_id)
        page = self.request.GET.get('page', 1)
        limit = self.request.GET.get('rows', 100) # get how many rows we want to have into the grid
        sidx = self.request.GET.get('sidx', None)  # get index row - i.e. user click to sort
        sord = self.request.GET.get('sord', 'asc')  # get the direction

        rpt_start_dt = self.request.GET.get('rpt_start_dt') if self.request.GET.get('rpt_start_dt') else util.str_today()
        rpt_end_dt = self.request.GET.get('rpt_end_dt') if self.request.GET.get('rpt_end_dt') else util.str_today()
        rpt_campaign_id = self.request.GET.get('rpt_campaign_id') if 'rpt_campaign_id' in self.request.GET else ''
        rpt_company_id = self.request.GET.get('rpt_company_id') if 'rpt_company_id' in self.request.GET else ''
        rpt_user_id = self.request.GET.get('rpt_user_id') if 'rpt_user_id' in self.request.GET else ''
        rpt_product_id = self.request.GET.get('rpt_product_id') if 'rpt_product_id' in self.request.GET else ''
        rpt_vendor_id = self.request.GET.get('rpt_vendor_id') if 'rpt_vendor_id' in self.request.GET else ''
        rpt_p0 = self.request.GET.get('rpt_p0') if 'rpt_p0' in self.request.GET else ''
        rpt_p1 = self.request.GET.get('rpt_p1') if 'rpt_p1' in self.request.GET else ''
        rpt_p2 = self.request.GET.get('rpt_p2') if 'rpt_p2' in self.request.GET else ''

        sql = rep.sql.format(enterprise_id=self.enterprise_id,
                             vendor_id=self.request.ctx.user.vendor_id,
                             rpt_start_dt=rpt_start_dt,
                             rpt_end_dt=rpt_end_dt,
                             rpt_campaign_id=rpt_campaign_id,
                             rpt_company_id=rpt_company_id,
                             rpt_user_id=rpt_user_id,
                             rpt_product_id=rpt_product_id,
                             rpt_vendor_id=rpt_vendor_id,
                             rpt_p0=rpt_p0,
                             rpt_p1=rpt_p1,
                             rpt_p2=rpt_p2)

        count = db.get_value('select count(0) from (%s) x' % sql)
        total_pages = 0
        if count > 0:
            total_pages = math.ceil(int(count)/int(limit))
            total_pages = total_pages if total_pages > 1 else 1

        page = min(page, total_pages)

        start = max(int(limit)*int(page)-int(limit), 0)  # // do not put $limit*($page - 1)
        limit = util.nvl(limit, 'all')
        results = db.get_list(sql +
                              (' ORDER BY %s %s ' % (sidx, sord) if sidx else '') +
                              ' LIMIT {limit} offset {start}'.format(limit=limit,
                                                                     start=start))
        response = {
            'page': page,
            'total': int(total_pages),
            'records': int(count)}

        rows = []
        for res_row in results:
            rows.append({'id': str(res_row[0]),
                         'cell': list([unicode(util.nvl(i)) for i in res_row])})

        response['rows'] = rows
        return json.dumps(response)
コード例 #3
0
ファイル: shipping.py プロジェクト: anonymoose/pvscore
    def get_options(self, customer, site, cart):
        site_config = json.loads(site.config_json) if site.config_json else None
        if not site_config: #pragma: no cover
            raise Exception("No site config for UPS Shipping.")
        shipping_config = site_config[0]['shipping']
        campaign = customer.campaign if customer else site.default_campaign
        company = customer.campaign.company if customer else site.company
        xml = util.literal(render('/catalog/shipping.ups_pricing_call.mako',
                                  {'cart' : cart,
                                   'site' : site,
                                   'cust' : customer,
                                   'campaign' : campaign,
                                   'company' : company,
                                   'api_key' : shipping_config['api_key'],
                                   'user_id' : shipping_config['user_id'],
                                   'account' : shipping_config['account'],
                                   'password' : shipping_config['password'],
                                   'container' : shipping_config['container_choices_default'],
                                   'pickup' : shipping_config['pickup_type_choices_default'],
                                   'total_weight' : max(sum([util.nvl(item['product'].weight, 1.0) for item in cart.items]), 1.0)
                                   }))

        tree = self._process_request(shipping_config['ups_url'], xml)
        try:
            status_code = tree.getiterator('ResponseStatusCode')
            status_val = status_code[0].text
        except AttributeError:  #pragma: no cover
            status_val = "-1"

        options = []
        charges = delivery_days = None
        if status_val == '1':
            all_rates = tree.getiterator('RatedShipment')
            for response in all_rates:
                charges = response.find('.//TotalCharges/MonetaryValue').text
                if response.find('.//GuaranteedDaysToDelivery').text:
                    delivery_days = response.find('.//GuaranteedDaysToDelivery').text
                code = response.find('.//Service/Code')
                if code is not None and code.text in shipping_config['timeframe_choices']:
                    option = {}
                    option['code'] = code.text
                    option['name'] = shipping_config['timeframe_choices'][code.text]
                    option['orig_charges'] = charges
                    option['charges'] = charges
                    option['delivery_days'] = util.nvl(delivery_days)
                    options.append(option)
        else:  #pragma: no cover
            try:
                errors = tree.find('.//Error')
                log.error("UPS %s Error: Code %s - %s" % (errors[0].text, errors[1].text, errors[2].text))
            except AttributeError:
                log.error("UPS error - cannot parse response:\n %s" % self.raw)

        return cart.filter_shipping_options(options)
コード例 #4
0
ファイル: catalog.py プロジェクト: anonymoose/pvscore
    def product(self):
        product_id = self.request.matchdict.get("product_id")
        if not util.is_uuid(product_id):
            # it's not really a product ID, but a search string from a bot.
            raise HTTPFound("/ecom/search?search=%s" % product_id)
        prod = Product.load(product_id)
        self.redir_if(not prod or not prod.enabled or not prod.web_visible)

        page = self.request.matchdict.get(
            "page", util.nvl(prod.render_template, "product")
        )  # /product/{product_id}/{page}

        self.session["last_product_id"] = product_id
        self.session["back_link"] = "/product/%s" % product_id
        params = self.params()
        self._add_to_recent_products(prod)

        params["product"] = prod
        params["products_also_liked"] = SmartCatalog.also_liked_product_list(prod, params["campaign"])
        params["products_related"] = SmartCatalog.related_product_list(prod, params["campaign"])
        params["product_attributes"] = self._prep_product_attributes(prod.get_product_attributes())
        params["attrs"] = prod.get_attrs()
        params["price"] = SmartPricing.product_price(prod, params["campaign"])
        (params["seo_title"], params["seo_keywords"], params["seo_description"]) = SmartSeo.product_seo(
            prod, self.request.ctx.site
        )
        return self.render(page, params)
コード例 #5
0
ファイル: customer.py プロジェクト: anonymoose/pvscore
 def save_and_purchase(self):
     """ KB: [2012-02-05]: Useful for multi-step signup processes where the
     customer is saved after step 1, and at the end you buy something. """
     self.forbid_if(not self.request.ctx.customer)
     cust = self._save(self.request.ctx.customer.customer_id, False) # don't let it redirect
     self._site_purchase(cust)
     return HTTPFound(util.nvl(self.request.POST.get('redir'), '/') + '?customer_id=' + str(cust.customer_id)) #pylint: disable-msg=E1103
コード例 #6
0
ファイル: cart.py プロジェクト: anonymoose/pvscore
    def add_item(self, product, campaign, quantity=1, base_price=None, start_dt=None, attributes={}, note=None): #pylint: disable-msg=R0913,W0102
        """ KB: [2013-02-24]: attribute_ids == {'123abc...' : 3, ...}  where 3 is the quantity """
        if not base_price:
            base_price = product.get_price(campaign)
        base_price = float(base_price)
        unit_price = base_price
        quantity = float(quantity)
        discount_price = product.get_discount_price(campaign)
        if discount_price is not None and round(discount_price, 2) < round(unit_price, 2):
            unit_price = discount_price

        self.items.append({'product': product,
                           'quantity': quantity,
                           'campaign_id': campaign.campaign_id,
                           'attributes': attributes, 
                           'dt': datetime.datetime.date(datetime.datetime.now()),
                           'base_price':base_price,
                           'unit_price':unit_price,
                           'note' : note,
                           'discount_amount':(base_price-unit_price)*quantity,
                           'regular_price':round(base_price*quantity, 2),
                           'price': round(unit_price*quantity, 2),
                           'start_dt':util.parse_date_as_date(util.nvl(str(start_dt), util.str_today())),
                           'handling':(product.handling_price if product.handling_price else 0)*quantity,
                           'weight':(product.weight if product.weight else 0) * quantity})
        self.shipping_options = None
        self.shipping_selection = None
コード例 #7
0
ファイル: product.py プロジェクト: anonymoose/pvscore
    def inventory_list(self):
        products = Product.find_by_vendor(self.request.ctx.user.vendor) if self.request.ctx.user and self.request.ctx.user.is_vendor_user() else Product.find_all(self.enterprise_id) #pylint: disable-msg=E1120

        campaigns = Campaign.find_all(self.enterprise_id)

        response = {
            'page': 1,
            'total': 1,
            'records': len(products)}

        rows = []

        for prod in products:
            #log.debug('%s %s/%s' % (p.product_id, i+1, len(products)))
            # blank spot at the beginning of the row is to make room for the
            # action buttons.  don't remove it.
            cells = ['', unicode(prod.product_id),
                     util.nvl(prod.name),
                     util.nvl(prod.sku),
                     util.nvl(prod.manufacturer),
                     util.nvl(unicode(prod.inventory)),
                     util.nvl(unicode(prod.inventory_par)),
                     util.nvl(unicode(prod.unit_cost))]
            # the column ordering in the UI is dependant on the order of the
            # campaigns that comes back from Campaign.find_all().  We use the
            # same ordering here so we are fine not adding some campaign ID here.
            for camp in campaigns:
                cells.append(util.nvl(util.money(prod.get_retail_price(camp))))

            rows.append({'id': str(prod.product_id),
                         'cell': cells})

        response['rows'] = rows
        return json.dumps(response)
コード例 #8
0
ファイル: catalog.py プロジェクト: anonymoose/pvscore
 def search(self):
     page = self.request.matchdict.get("page", "search_results")
     params = self.params()
     params["subset"] = "search"
     params["products"] = util.page_list(
         Product.catalog_search(self.enterprise_id, str(util.nvl(self.request.GET.get("search"))).strip()),
         self.request.GET.get("offset"),
         self.request.GET.get("limit"),
     )
     return self.render(page, params)
コード例 #9
0
ファイル: comm.py プロジェクト: anonymoose/pvscore
 def render(self, customer, order, extra_message=None):
     ret = ''
     if self.data:
         if 'html' == self.type:
             dat = self.data
             dat = dat.replace('{message}', util.nvl(extra_message, ''))
             dat = dat.replace('{current_date}', util.words_date(util.now()))
             dat = self.tokenize(dat, customer, order)
             for otok in self._other_tokens.keys():
                 dat = dat.replace(otok, self._other_tokens[otok])
             ret = literal(dat)
     return ret
コード例 #10
0
ファイル: customer.py プロジェクト: anonymoose/pvscore
    def _apply_payment(self, customer_id, order_id, pmt_amount=None, pmt_method=None, pmt_note=None):  #pylint: disable-msg=R0913
        """ KB: [2011-03-09]: Check that everything is kosher
        Create a journal entry for the order for the amount and type specified in the UI
        Create a status noting the type and amount of the payment applied.
        """
        customer = Customer.load(customer_id)
        self.forbid_if(not customer or customer.campaign.company.enterprise_id != self.enterprise_id)
        order = customer.get_order(order_id)
        self.forbid_if(not order)
        user = self.request.ctx.user
        current_customer_balance = customer.get_current_balance()
        #prior_payments_applied = order.total_payments_applied()
        prior_total_due = order.total_payments_due()
        balance_amount_to_apply = float(self.request.POST.get('pmt_balance_amount_to_apply', 0.0))
        amt = float(util.nvl(pmt_amount, self.request.POST.get('pmt_amount')))
        method = util.nvl(pmt_method, self.request.POST.get('pmt_method'))
        note = util.nvl(pmt_note, self.request.POST.get('pmt_note'))

        self.forbid_if(round(amt + balance_amount_to_apply, 2) > round(prior_total_due, 2),
                       "amt + balance_amount_to_apply > prior_total_due")
        self.forbid_if(current_customer_balance > 0 and round(balance_amount_to_apply, 2) > round(current_customer_balance, 2),
                       "balance_amount_to_apply > current_customer_balance")

        pmt_type = 'PartialPayment'
        if amt == prior_total_due:
            pmt_type = 'FullPayment'

        Journal.create_new(amt, customer, order, user, pmt_type, method, note)
        status_note = '%s applied: $%s' % (pmt_type, util.money(amt))
        Status.add(customer, order, Status.find_event(self.enterprise_id, order, 'PAYMENT_APPLIED'), status_note)
        self.flash(status_note)
        if balance_amount_to_apply > 0:
            Journal.create_new(balance_amount_to_apply, customer, order, user, 'CreditDecrease')
            status_note = '%s applied: $%s' % ('CreditDecrease', util.money(balance_amount_to_apply))
            Status.add(customer, order, Status.find_event(self.enterprise_id, order, 'PAYMENT_APPLIED'), status_note)
            self.flash(status_note)
        customer.invalidate_caches()
        customer.flush()
        return 'True'
コード例 #11
0
ファイル: cart.py プロジェクト: anonymoose/pvscore
 def save_shipping(self):
     if not 'cart' in self.session:
         return 'True'  #pragma: no cover
     cart = self.session['cart']
     shipping_code = self.request.POST.get('shipping_code', self.request.GET.get('shipping_code'))
     cust = self.request.ctx.customer
     self.redir_if(not cust or not cart)
     cart.shipping_selection = shipping_code
     cart.shipping_addr1 = util.nvl(self.request.POST.get('shipping_addr1'), cust.addr1)
     cart.shipping_addr2 = util.nvl(self.request.POST.get('shipping_addr2'), cust.addr2)
     cart.shipping_city = util.nvl(self.request.POST.get('shipping_city'), cust.city)
     cart.shipping_state = util.nvl(self.request.POST.get('shipping_state'), cust.state)
     cart.shipping_zip = util.nvl(self.request.POST.get('shipping_zip'), cust.zip)
     cart.shipping_country = util.nvl(self.request.POST.get('shipping_country'), cust.country)
     cart.shipping_phone = util.nvl(self.request.POST.get('shipping_phone'), cust.phone)
     self.session.changed()
     return self.find_redirect()
コード例 #12
0
ファイル: billing_api.py プロジェクト: anonymoose/pvscore
 def _charge_card(self, amount, order, customer, billing):
     post = {}
     post['invoice_num'] = str(order.order_id)
     post['description'] = "%s Order" % order.campaign.company.name
     post['card_num'] = billing.get_cc_num()
     post['card_code'] = billing.get_cc_cvv()
     post['exp_date'] = billing.cc_exp
     post['first_name'] = customer.fname
     post['last_name'] = customer.lname
     post['address'] = customer.addr1 + ' ' + util.nvl(customer.addr2)
     post['company'] = customer.company_name
     post['phone'] = customer.phone
     post['zip'] = customer.zip
     post['city'] = customer.city
     post['country'] = customer.country
     post['state'] = customer.state
     post['email'] = customer.email
     post['cust_id'] = customer.customer_id
     #post['customer_ip'] = options['ip']
     return self._commit('AUTH_CAPTURE', amount, post)
コード例 #13
0
ファイル: customer.py プロジェクト: anonymoose/pvscore
    def add_order(self):
        """ KB: [2013-02-20]: MOD ATTR CustomerController.add_order : Modify to allow for attributes to be passed in the post. """
        customer_id = self.request.matchdict.get('customer_id')
        cust = Customer.load(customer_id)
        self.forbid_if(not cust)

        # KB: [2013-02-24]: products are passed as products[$product_id] = quantity
        product_ids = {}
        for key in self.request.POST.keys():
            if key.startswith('products'):
                match = re.search(r'^.*\[(.*)\]', key)
                if match:
                    pid = match.group(1)
                    quant = float(util.nvl(self.request.POST.get(key), '1.0'))
                    if pid not in product_ids:
                        product_ids[pid] = 0
                    product_ids[pid] += quant


        # KB: [2013-02-24]: attributes are passed as attributes[$attribute_id] = $parent_product_id
        attributes = {}
        for key in self.request.POST.keys():
            if key.startswith('attributes'):
                match = re.search(r'^.*\[(.*)\]', key)
                if match:
                    attribute_product_id = match.group(1)
                    parent_product_id = self.request.POST.get(key)
                    attributes[attribute_product_id] = { 'parent_product' : Product.load(parent_product_id),
                                                         'attribute_product' : Product.load(attribute_product_id) }

        order_id = self._add_order_impl(customer_id, product_ids, attributes,
                                        None, self.request.ctx.user,
                                        self.request.POST.get('discount_id'),
                                        self.request.POST.get('campaign_id', self.request.GET.get('campaign_id')),
                                        self.incl_tax)
        cust.invalidate_caches()
        return str(order_id)
コード例 #14
0
ファイル: customer.py プロジェクト: anonymoose/pvscore
    def contact(self):
        camp = self.request.ctx.campaign
        message = self.request.POST.get('message')
        email = self.request.POST.get('email')
        msg = "%s %s<br>(%s)<br><br>%s<br><br>%s" % (self.request.POST.get('fname'),
                                                     self.request.POST.get('lname'),
                                                     email,
                                                     self.request.POST.get('phone'),
                                                     message)
        if util.nvl(self.request.POST.get('save')):
            cust = Customer.find(email, camp)
            if not cust:
                cust = Customer()
                cust.campaign = camp
                cust.bind(self.request.POST)
                cust.phone = cust.phone[:20] if cust.phone else None # prevents people from putting in "904-716-7487 (mobile)" and it barfs
                cust.save()
            Status.add(cust, cust, Status.find_event(self.enterprise_id, cust, 'NOTE'),
                       'NOTE FROM CUSTOMER\n%s' % message)

        email_info = camp.get_email_info()
        mail = UserMail(camp)
        mail.send(email_info.email, 'SITE CONTACT FORM %s' % self.request.host, msg)
        return self.find_redirect()
コード例 #15
0
ファイル: cart.py プロジェクト: anonymoose/pvscore
    def add_attributed_product(self):
        """ KB: [2013-02-24]:
            var attributes = {};
            attributes[$('#color_id').val()] = 0;  // quantity of zero, unless its really something that requires a quantity.
            attributes[$('#size_id').val()] = 0;

            $.post('/ecom/cart/add_attributed_product',
                   { product_id : base_product_id,
                     attributes : attributes,
                     quantity : $('#qty').val()
                   },
                   function(resp) {
                       if (resp == 'True') {
                           window.location = '/product/' + base_product_id;
                       }
                   });
        
        """
        redir = self.request.POST.get('redir')
        product_id = self.request.POST.get('product_id')
        quantity = self.request.POST.get('quantity')
        cart = self.session['cart']
        attributes = {}
        for key in self.request.POST.keys():
            if key.startswith('attributes'):
                match = re.search(r'^.*\[(.*)\]', key)
                if match:
                    pid = match.group(1)
                    quant = float(util.nvl(self.request.POST.get(key), '1.0'))
                    attributes[pid] = { 'quantity' : quant,
                                        'product' : Product.load(pid) }
        product = Product.load(product_id)
        self.forbid_if(not product)
        cart.add_item(product, self.request.ctx.campaign, quantity, attributes=attributes)
        self.session.changed()
        return 'True' if not redir else HTTPFound(redir)
コード例 #16
0
ファイル: orderitem.py プロジェクト: anonymoose/pvscore
 def total(self):
     unit_price = self.unit_price
     pretax = (util.nvl(self.product.handling_price, 0.0) + util.nvl(unit_price, 0.0)) * util.nvl(self.quantity, 1.0)
     return pretax + self.tax   # self.tax is not the tax rate.  it's the actual tax amount calculated in customerorder
コード例 #17
0
ファイル: product.py プロジェクト: anonymoose/pvscore
    def save(self):  #pylint: disable-msg=R0912,R0915
        product_id = self.request.POST.get('product_id')
        if product_id:
            prod = Product.load(product_id)
        else:
            prod = Product()
        prod.bind(self.request.POST, True)
        prod.mod_dt = util.now()
        prod.save()
        self.db_flush()

        new_children = {}
        for k in self.request.POST.keys():
            if k.startswith('campaign_price'):
                match = re.search(r'^.*\[(.*)\]', k)
                if match:
                    campaign = Campaign.load(match.group(1))
                    price = self.request.POST.get(k)
                    discount = self.request.POST.get('campaign_discount[%s]' % campaign.campaign_id)
                    if price:
                        price = util.float_(price)
                        discount = util.float_(util.nvl(discount, 0.0))
                        prod.set_price(campaign, price, discount)
                    else:
                        prod.remove_price(campaign)

            if k.startswith('child_incl'):
                child_product_id = self.request.POST.get(k)
                child_product_quantity = self.request.POST.get('child_quantity_%s' % child_product_id)
                new_children[child_product_id] = child_product_quantity


        # KB: [2013-02-23]: Clear out old children that were just deselected and add the ones that are still selected.
        for current_child in prod.get_children():
            if current_child.child_id not in new_children.keys():
                prod.clear_child(current_child.child_id)
                
        for new_child_product_id in new_children.keys():
            new_child_product_quantity = new_children[new_child_product_id]
            prod.add_child(new_child_product_id, new_child_product_quantity)

        prod.save()
        self.db_flush()

        redir_params = ''
        if 'parent_id' in self.request.POST and self.request.POST['parent_id']:
            parent = Product.load(self.request.POST['parent_id'])
            if not parent.has_child(prod.product_id):
                parent.add_child(prod.product_id)
                parent.save()
            redir_params = '?is_attribute=True&parent_id=%s' % parent.product_id

        inventory = str(self.request.POST.get('prod_inventory', '0'))
        if inventory and str(round(float(inventory), 2)) != str(round(util.nvl(InventoryJournal.total(prod), 0), 2)):
            InventoryJournal.create_new(prod, 'Inventory Adjust', inventory)
            self.db_flush()
            self.flash('Inventory Adjusted to %s' % inventory)

        prod.clear_attributes()
        for i in range(30):
            attr_name = self.request.POST.get('attr_name[%d]' % i)
            attr_value = self.request.POST.get('attr_value[%d]' % i)
            if attr_name and attr_value:
                prod.set_attr(attr_name, attr_value)

        category_id = self.request.POST.get('category_id')
        if category_id:
            category = ProductCategory.load(category_id)
            self.forbid_if(not category)
            category.add_product(prod.product_id)

        self.flash('Successfully saved %s.' % prod.name)
        return HTTPFound('/crm/product/edit/%s%s' % (prod.product_id, redir_params))
コード例 #18
0
ファイル: customerorder.py プロジェクト: anonymoose/pvscore
 def total_item_price(self):
     tot = 0.0
     for oitem in self.active_items:
         tot += util.nvl(oitem.unit_price, 0.0) * (util.nvl(oitem.quantity, 1.0))
     return tot
コード例 #19
0
ファイル: customerorder.py プロジェクト: anonymoose/pvscore
 def google_data(self):
     dat1 = ",".join([str(round(util.nvl(res.revenue, 0.0), 2)) for res in self.results])
     dat2 = ",".join([str(round(util.nvl(res.cost, 0.0), 2)) for res in self.results])
     return "%s|%s" % (dat1, dat2)
コード例 #20
0
ファイル: scatalog.py プロジェクト: anonymoose/pvscore
 def obj_seo(obj, site):
     title = util.nvl(obj.seo_title, site.seo_title)
     keywords = util.nvl(obj.seo_keywords, site.seo_title)
     description = util.nvl(obj.seo_description, site.seo_title)
     return (title, keywords, description)
コード例 #21
0
ファイル: meta.py プロジェクト: anonymoose/pvscore
 def col_max(self, colname, convert=float):
     seq = [convert(util.nvl(getattr(r, colname), 0)) for r in self.results if hasattr(r, colname)]
     return max(seq) if len(seq) else 0
コード例 #22
0
ファイル: customerorder.py プロジェクト: anonymoose/pvscore
    def create_new(cart, customer, enterprise_id, campaign, user_created, order_note=None, incl_tax=True):
        """ KB: [2010-09-09]: Given a cart full of products, create a new order and return it.
        if a given product is a parent, then create an kid order_item of zero cost and attach it to the parent.
        """
        cord = CustomerOrder()
        cord.creator = user_created
        cord.customer = customer
        cord.campaign = campaign
        cord.shipping_total = util.nvl(cart.shipping_total, 0.0)
        cord.shipping_note = cart.shipping_selection_name
        cord.handling_total = util.nvl(cart.handling_total, 0.0)
        cord.shipping_addr1 = cart.shipping_addr1
        cord.shipping_addr2 = cart.shipping_addr2
        cord.shipping_city = cart.shipping_city
        cord.shipping_state = cart.shipping_state
        cord.shipping_zip = cart.shipping_zip
        cord.shipping_country = cart.shipping_country
        cord.shipping_phone = cart.shipping_phone
        cart.calculate_cart_discount_for_order(cord)
        cord.note = order_note
        cord.save()
        cord.flush()
        for cart_item in cart.items:
            prd = Product.load(cart_item["product"].product_id)
            item = OrderItem()
            item.order = cord
            item.product = prd
            item.creator = user_created
            item.start_dt = cart_item["start_dt"]
            item.note = cart_item["note"]
            item.save()
            item.flush()

            attribute_order_items = []
            for attribute_product_id in cart_item["attributes"].keys():
                attribute_order_item = OrderItem()
                attribute_order_item.parent_id = item.order_item_id
                attribute_order_item.order = cord
                ao_prd = Product.load(attribute_product_id)
                attribute_order_item.product = ao_prd
                attribute_order_item.creator = user_created
                attribute_order_item.unit_cost = ao_prd.unit_cost
                attribute_order_item.unit_discount_price = ao_prd.get_discount_price(campaign)
                attribute_order_item.unit_retail_price = ao_prd.get_retail_price(campaign)
                attribute_order_item.quantity = cart_item["attributes"][attribute_product_id]["quantity"]
                attribute_order_item.save()
                attribute_order_items.append(attribute_order_item)

            # KB: [2013-02-24]: Discount is calculated by using the highest price of the discounts for the product and all of its selected attributes
            discount = max(
                [util.nvl(aois.unit_discount_price) for aois in attribute_order_items]
                + [prd.get_discount_price(campaign)]
            )
            # KB: [2013-02-24]: Retail is calculated by using the highest price of the retail prices for the product and all its selected attributes.
            retail = max(
                [util.nvl(aois.unit_retail_price, 0.0) for aois in attribute_order_items]
                + [cart_item["base_price"] if "base_price" in cart_item else prd.get_retail_price(campaign)]
            )

            item.quantity = float(cart_item["quantity"])
            item.unit_price = discount if discount else retail
            if campaign.tax_rate and incl_tax:
                item.tax = (item.unit_price * item.quantity) * campaign.tax_rate
            item.unit_cost = prd.unit_cost
            item.unit_discount_price = discount if discount else None
            item.unit_retail_price = retail
            item.save()
            if prd.track_inventory:
                InventoryJournal.create_new(prd, "Sale", int(item.quantity), item)
            if item.unit_discount_price is not None:
                discount = DiscountProduct.find_by_product(prd)
                Journal.create_new(
                    (item.unit_retail_price - item.unit_discount_price) * int(item.quantity),
                    customer,
                    cord,
                    None,
                    typ="AutomaticDiscount",
                    attachment=discount,
                )
            Status.add(
                customer,
                item,
                Status.find_event(enterprise_id, item, "CREATED"),
                "Item added to order %s @ $%s" % (prd.name, util.money(item.unit_price)),
            )
            if prd.can_have_children():
                item.flush()  # we need this to get the parent ID.
                children = prd.get_children()
                if children and len(children) > 0:
                    for kid in children:
                        child_item = OrderItem()
                        child_item.order = cord
                        child_item.parent_id = item.order_item_id
                        child_item.product = kid.child
                        child_item.creator = user_created
                        child_item.start_dt = cart_item["start_dt"]
                        child_item.unit_price = 0.0
                        child_item.unit_discount_price = None
                        child_item.unit_retail_price = 0.0
                        child_item.unit_cost = prd.unit_cost
                        child_item.quantity = kid.child_quantity
                        if kid.child.track_inventory:
                            InventoryJournal.create_new(kid.child, "Sale", child_item.quantity, child_item)
        Status.add(customer, cord, Status.find_event(enterprise_id, cord, "CREATED"), "Order created ")
        if cord.discount:
            discount_amount = None
            if cord.discount.percent_off:
                item_price = cord.total_item_price()
                discount_amount = item_price - (item_price * cord.discount.percent_off)
            elif cord.discount.shipping_percent_off:
                # (9.0 / (1.0-0.1)) = 10.00
                discount_amount = cart.shipping_discount_total
            if discount_amount and int(discount_amount) > 0:
                Journal.create_new(
                    discount_amount, customer, cord, None, typ="AutomaticDiscount", attachment=cord.discount
                )
        cord.save()
        cord.flush()
        return cord
コード例 #23
0
ファイル: cart.py プロジェクト: anonymoose/pvscore
 def product_discount_total(self):
     return util.nvl(reduce(lambda x, y: x + y['discount_amount'], self.items, 0.0), 0.0)
コード例 #24
0
ファイル: cart.py プロジェクト: anonymoose/pvscore
 def handling_total(self):
     return util.nvl(reduce(lambda x, y: x + y['handling'], self.items, 0.0), 0.0)
コード例 #25
0
ファイル: cart.py プロジェクト: anonymoose/pvscore
 def product_total(self):
     return util.nvl(reduce(lambda x, y: x + y['price'], self.items, 0.0), 0.0)