[wip] shopping cart shipping rule, price list cleanup

This commit is contained in:
Rushabh Mehta 2015-09-17 16:28:30 +05:30
parent 3d76686b82
commit 8ffd483e24
18 changed files with 216 additions and 302 deletions

View File

@ -141,17 +141,17 @@
"allow_on_submit": 0,
"bold": 0,
"collapsible": 0,
"description": "Specify a list of Territories, for which, this Shipping Rule is valid",
"fieldname": "territories",
"fieldname": "countries",
"fieldtype": "Table",
"hidden": 0,
"ignore_user_permissions": 0,
"in_filter": 0,
"in_list_view": 0,
"label": "Valid For Territories",
"label": "Valid for Countries",
"no_copy": 0,
"options": "Applicable Territory",
"options": "Shipping Rule Country",
"permlevel": 0,
"precision": "",
"print_hide": 0,
"read_only": 0,
"report_hide": 0,
@ -296,7 +296,7 @@
"is_submittable": 0,
"issingle": 0,
"istable": 0,
"modified": "2015-09-07 15:51:26",
"modified": "2015-09-17 06:44:05.127516",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Shipping Rule",
@ -304,7 +304,7 @@
"permissions": [
{
"amend": 0,
"apply_user_permissions": 0,
"apply_user_permissions": 1,
"cancel": 0,
"create": 0,
"delete": 0,
@ -324,7 +324,7 @@
},
{
"amend": 0,
"apply_user_permissions": 0,
"apply_user_permissions": 1,
"cancel": 0,
"create": 0,
"delete": 0,

View File

@ -0,0 +1,53 @@
{
"allow_copy": 0,
"allow_import": 0,
"allow_rename": 0,
"creation": "2015-09-17 06:43:22.767534",
"custom": 0,
"docstatus": 0,
"doctype": "DocType",
"document_type": "Other",
"fields": [
{
"allow_on_submit": 0,
"bold": 0,
"collapsible": 0,
"fieldname": "country",
"fieldtype": "Link",
"hidden": 0,
"ignore_user_permissions": 0,
"in_filter": 0,
"in_list_view": 1,
"label": "Country",
"no_copy": 0,
"options": "Country",
"permlevel": 0,
"precision": "",
"print_hide": 0,
"read_only": 0,
"report_hide": 0,
"reqd": 1,
"search_index": 0,
"set_only_once": 0,
"unique": 0
}
],
"hide_heading": 0,
"hide_toolbar": 0,
"in_create": 0,
"in_dialog": 0,
"is_submittable": 0,
"issingle": 0,
"istable": 1,
"modified": "2015-09-17 06:43:22.767534",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Shipping Rule Country",
"name_case": "",
"owner": "Administrator",
"permissions": [],
"read_only": 0,
"read_only_onload": 0,
"sort_field": "modified",
"sort_order": "DESC"
}

View File

@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class ShippingRuleCountry(Document):
pass

View File

@ -30,7 +30,7 @@ $.extend(shopping_cart, {
args: {
item_code: opts.item_code,
qty: opts.qty,
with_doc: opts.with_doc || 0
with_items: opts.with_items || 0
},
btn: opts.btn,
callback: function(r) {

View File

@ -28,6 +28,8 @@ def get_cart_quotation(doc=None):
doc = quotation
set_cart_count(quotation)
print get_applicable_shipping_rules(party)
return {
"doc": decorate_quotation_doc(doc),
"addresses": [{"name": address.name, "display": address.display}
@ -63,7 +65,7 @@ def place_order():
return sales_order.name
@frappe.whitelist()
def update_cart(item_code, qty, with_doc):
def update_cart(item_code, qty, with_items=False):
quotation = _get_cart_quotation()
qty = flt(qty)
@ -95,8 +97,15 @@ def update_cart(item_code, qty, with_doc):
set_cart_count(quotation)
if with_doc:
return get_cart_quotation(quotation)
if with_items:
context = get_cart_quotation(quotation)
return {
"items": frappe.render_template("templates/includes/cart/cart_items.html",
context),
"taxes": frappe.render_template("templates/includes/order/order_taxes.html",
context),
}
else:
return quotation.name

View File

@ -8,8 +8,7 @@ import frappe
from frappe import _, msgprint
from frappe.utils import comma_and
from frappe.model.document import Document
from frappe.utils.nestedset import get_ancestors_of, get_root_of
from erpnext.utilities.doctype.address.address import get_territory_from_address
from frappe.utils.nestedset import get_root_of
class ShoppingCartSetupError(frappe.ValidationError): pass
@ -19,57 +18,8 @@ class ShoppingCartSettings(Document):
def validate(self):
if self.enabled:
self.validate_price_lists()
self.validate_tax_masters()
self.validate_exchange_rates_exist()
self.validate_tax_rule()
def validate_overlapping_territories(self, parentfield, fieldname):
# for displaying message
doctype = self.meta.get_field(parentfield).options
# specify atleast one entry in the table
self.validate_table_has_rows(parentfield, raise_exception=ShoppingCartSetupError)
territory_name_map = self.get_territory_name_map(parentfield, fieldname)
for territory, names in territory_name_map.items():
if len(names) > 1:
frappe.throw(_("{0} {1} has a common territory {2}").format(_(doctype), comma_and(names), territory), ShoppingCartSetupError)
return territory_name_map
def validate_price_lists(self):
self.validate_overlapping_territories("price_lists", "selling_price_list")
# validate that a Shopping Cart Price List exists for the default territory as a catch all!
price_list_for_default_territory = self.get_name_from_territory(self.default_territory, "price_lists",
"selling_price_list")
if not price_list_for_default_territory:
msgprint(_("Please specify a Price List which is valid for Territory") +
": " + self.default_territory, raise_exception=ShoppingCartSetupError)
def get_territory_name_map(self, parentfield, fieldname):
territory_name_map = {}
# entries in table
names = [doc.get(fieldname) for doc in self.get(parentfield)]
if names:
# for condition in territory check
parenttype = frappe.get_meta(self.meta.get_options(parentfield)).get_options(fieldname)
# to validate territory overlap
# make a map of territory: [list of names]
# if list against each territory has more than one element, raise exception
territory_name = frappe.db.sql("""select `territory`, `parent`
from `tabApplicable Territory`
where `parenttype`=%s and `parent` in (%s)""" %
("%s", ", ".join(["%s"]*len(names))), tuple([parenttype] + names))
for territory, name in territory_name:
territory_name_map.setdefault(territory, []).append(name)
if len(territory_name_map[territory]) > 1:
territory_name_map[territory].sort(key=lambda val: names.index(val))
return territory_name_map
def validate_exchange_rates_exist(self):
"""check if exchange rates exist for all Price List currencies (to company's currency)"""
@ -102,20 +52,6 @@ class ShoppingCartSettings(Document):
msgprint(_("Missing Currency Exchange Rates for {0}").format(comma_and(missing)),
raise_exception=ShoppingCartSetupError)
def get_name_from_territory(self, territory, parentfield, fieldname):
name = None
territory_name_map = self.get_territory_name_map(parentfield, fieldname)
if territory_name_map.get(territory):
name = territory_name_map.get(territory)
else:
territory_ancestry = self.get_territory_ancestry(territory)
for ancestor in territory_ancestry:
if territory_name_map.get(ancestor):
name = territory_name_map.get(ancestor)
break
return name
def get_price_list(self, billing_territory):
price_list = self.get_name_from_territory(billing_territory, "price_lists", "selling_price_list")
if not (price_list and price_list[0]):
@ -123,11 +59,11 @@ class ShoppingCartSettings(Document):
"price_lists", "selling_price_list")
return price_list and price_list[0] or None
def validate_tax_rule(self):
if not frappe.db.get_value("Tax Rule", {"use_for_shopping_cart" : 1}, "name"):
frappe.throw(frappe._("Set Tax Rule for shopping cart"), ShoppingCartSetupError)
def get_tax_master(self, billing_territory):
tax_master = self.get_name_from_territory(billing_territory, "sales_taxes_and_charges_masters",
"sales_taxes_and_charges_master")
@ -136,15 +72,6 @@ class ShoppingCartSettings(Document):
def get_shipping_rules(self, shipping_territory):
return self.get_name_from_territory(shipping_territory, "shipping_rules", "shipping_rule")
def get_territory_ancestry(self, territory):
if not hasattr(self, "_territory_ancestry"):
self._territory_ancestry = {}
if not self._territory_ancestry.get(territory):
self._territory_ancestry[territory] = get_ancestors_of("Territory", territory)
return self._territory_ancestry[territory]
def validate_cart_settings(doc, method):
frappe.get_doc("Shopping Cart Settings", "Shopping Cart Settings").run_method("validate")
@ -163,4 +90,4 @@ def get_default_territory():
def check_shopping_cart_enabled():
if not get_shopping_cart_settings().enabled:
frappe.throw(_("You need to enable Shopping Cart"), ShoppingCartSetupError)

View File

@ -163,21 +163,21 @@
"allow_on_submit": 0,
"bold": 0,
"collapsible": 0,
"description": "Specify a list of Territories, for which, this Price List is valid",
"fieldname": "territories",
"fieldname": "countries",
"fieldtype": "Table",
"hidden": 0,
"ignore_user_permissions": 0,
"in_filter": 0,
"in_list_view": 0,
"label": "Valid for Territories",
"label": "Applicable for Countries",
"no_copy": 0,
"options": "Applicable Territory",
"options": "Price List Country",
"permlevel": 0,
"precision": "",
"print_hide": 0,
"read_only": 0,
"report_hide": 0,
"reqd": 1,
"reqd": 0,
"search_index": 0,
"set_only_once": 0,
"unique": 0
@ -193,7 +193,7 @@
"issingle": 0,
"istable": 0,
"max_attachments": 1,
"modified": "2015-09-14 02:55:58.919822",
"modified": "2015-09-17 06:50:31.465221",
"modified_by": "Administrator",
"module": "Stock",
"name": "Price List",
@ -201,7 +201,7 @@
"permissions": [
{
"amend": 0,
"apply_user_permissions": 0,
"apply_user_permissions": 1,
"cancel": 0,
"create": 0,
"delete": 0,
@ -241,7 +241,7 @@
},
{
"amend": 0,
"apply_user_permissions": 0,
"apply_user_permissions": 1,
"cancel": 0,
"create": 0,
"delete": 0,
@ -281,7 +281,7 @@
},
{
"amend": 0,
"apply_user_permissions": 0,
"apply_user_permissions": 1,
"cancel": 0,
"create": 0,
"delete": 0,

View File

@ -13,19 +13,6 @@ class PriceList(Document):
if not cint(self.buying) and not cint(self.selling):
throw(_("Price List must be applicable for Buying or Selling"))
try:
# at least one territory
self.validate_table_has_rows("territories")
except frappe.EmptyTableError:
# if no territory, set default territory
if frappe.defaults.get_user_default("territory"):
self.append("territories", {
"doctype": "Applicable Territory",
"territory": frappe.defaults.get_user_default("territory")
})
else:
raise
def on_update(self):
self.set_default_if_missing()
self.update_item_price()

View File

@ -0,0 +1,53 @@
{
"allow_copy": 0,
"allow_import": 0,
"allow_rename": 0,
"creation": "2015-09-17 06:49:51.810318",
"custom": 0,
"docstatus": 0,
"doctype": "DocType",
"document_type": "",
"fields": [
{
"allow_on_submit": 0,
"bold": 0,
"collapsible": 0,
"fieldname": "country",
"fieldtype": "Link",
"hidden": 0,
"ignore_user_permissions": 0,
"in_filter": 0,
"in_list_view": 1,
"label": "Country",
"no_copy": 0,
"options": "Country",
"permlevel": 0,
"precision": "",
"print_hide": 0,
"read_only": 0,
"report_hide": 0,
"reqd": 1,
"search_index": 0,
"set_only_once": 0,
"unique": 0
}
],
"hide_heading": 0,
"hide_toolbar": 0,
"in_create": 0,
"in_dialog": 0,
"is_submittable": 0,
"issingle": 0,
"istable": 1,
"modified": "2015-09-17 06:49:51.810318",
"modified_by": "Administrator",
"module": "Stock",
"name": "Price List Country",
"name_case": "",
"owner": "Administrator",
"permissions": [],
"read_only": 0,
"read_only_onload": 0,
"sort_field": "modified",
"sort_order": "DESC"
}

View File

@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class PriceListCountry(Document):
pass

View File

@ -14,28 +14,9 @@ $.extend(shopping_cart, {
bind_events: function() {
shopping_cart.bind_address_select();
shopping_cart.bind_place_order();
shopping_cart.bind_change_qty();
// bind update button
$(document).on("click", ".item-update-cart button", function() {
var item_code = $(this).attr("data-item-code");
shopping_cart.update_cart({
item_code: item_code,
qty: $('input[data-item-code="'+item_code+'"]').val(),
with_doc: 1,
btn: this,
callback: function(r) {
if(!r.exc) {
shopping_cart.render(r.message);
var $button = $('button[data-item-code="'+item_code+'"]').addClass("btn-success");
setTimeout(function() { $button.removeClass("btn-success"); }, 1000);
}
},
});
});
$(".btn-place-order").on("click", function() {
shopping_cart.place_order(this);
});
},
bind_address_select: function() {
@ -63,95 +44,31 @@ $.extend(shopping_cart, {
},
render: function(out) {
var doc = out.doc;
var addresses = out.addresses;
var $cart_items = $("#cart-items").empty();
var $cart_taxes = $("#cart-taxes").empty();
var $cart_totals = $("#cart-totals").empty();
var $cart_billing_address = $("#cart-billing-address").empty();
var $cart_shipping_address = $("#cart-shipping-address").empty();
var no_items = $.map(doc.items || [],
function(d) { return d.item_code || null;}).length===0;
if(no_items) {
shopping_cart.show_error("Cart Empty", frappe._("Go ahead and add something to your cart."));
$("#cart-addresses").toggle(false);
return;
}
var shipping_rule_added = false;
var taxes_exist = false;
var shipping_rule_labels = $.map(out.shipping_rules || [], function(rule) { return rule[1]; });
$.each(doc.items || [], function(i, d) {
shopping_cart.render_item_row($cart_items, d);
bind_place_order: function() {
$(".btn-place-order").on("click", function() {
shopping_cart.place_order(this);
});
$.each(doc.taxes || [], function(i, d) {
if(out.shipping_rules && out.shipping_rules.length &&
shipping_rule_labels.indexOf(d.description)!==-1) {
shipping_rule_added = true;
shopping_cart.render_tax_row($cart_taxes, d, out.shipping_rules);
} else {
shopping_cart.render_tax_row($cart_taxes, d);
}
taxes_exist = true;
});
if(out.shipping_rules && out.shipping_rules.length && !shipping_rule_added) {
shopping_cart.render_tax_row($cart_taxes, {description: "", formatted_tax_amount: ""},
out.shipping_rules);
taxes_exist = true;
}
if(taxes_exist)
$('<hr>').appendTo($cart_taxes);
shopping_cart.render_tax_row($cart_totals, {
description: "",
formatted_tax_amount: __("Total") + ": <strong>" + doc.formatted_grand_total_export + "</strong>"
});
if(!(addresses && addresses.length)) {
$cart_shipping_address.html('<p>'+frappe._("Please add a new address")+'</p>');
} else {
shopping_cart.render_address($cart_shipping_address, addresses, doc.shipping_address_name);
shopping_cart.render_address($cart_billing_address, addresses, doc.customer_address);
}
},
render_item_row: function($cart_items, doc) {
doc.image_html = doc.website_image ?
'<div style="height: 120px; overflow: hidden;"><img src="' + doc.website_image + '" /></div>': "";
bind_change_qty: function() {
// bind update button
$(".cart-items").on("change", ".cart-qty", function() {
var item_code = $(this).attr("data-item-code");
shopping_cart.update_cart({
item_code: item_code,
qty: $(this).val(),
with_items: 1,
btn: this,
callback: function(r) {
if(!r.exc) {
$(".cart-items").html(r.message.items);
$(".cart-tax-items").html(r.message.taxes);
}
$(".tax-grand-total").temp_highlight();
},
});
});
if(doc.description === doc.item_name) doc.description = "";
$(repl('<div class="row">\
<div class="col-md-9 col-sm-9">\
<div class="row">\
<div class="col-md-2">%(image_html)s</div>\
<div class="col-md-10">\
<h5><a href="%(page_name)s">%(item_name)s</a></h5>\
<p>%(description)s</p>\
</div>\
</div>\
</div>\
<div class="col-md-3 col-sm-3 text-right">\
<div class="input-group item-update-cart">\
<input type="text" placeholder="Qty" value="%(qty)s" \
data-item-code="%(item_code)s" class="text-right form-control">\
<div class="input-group-btn">\
<button class="btn btn-primary" data-item-code="%(item_code)s">\
<i class="icon-ok"></i></button>\
</div>\
</div>\
<p class="text-muted small" style="margin-top: 10px;">' + __("Rate") + ': %(formatted_rate)s</p>\
<small style="margin-top: 10px;">%(formatted_amount)s</small>\
</div>\
</div><hr>', doc)).appendTo($cart_items);
},
render_tax_row: function($cart_taxes, doc, shipping_rules) {
@ -201,46 +118,6 @@ $.extend(shopping_cart, {
});
},
render_address: function($address_wrapper, addresses, address_name) {
$.each(addresses, function(i, address) {
$(repl('<div class="panel panel-default"> \
<div class="panel-heading"> \
<div class="row"> \
<div class="col-md-10 address-title" \
data-address-name="%(name)s"><strong>%(name)s</strong></div> \
<div class="col-md-2 text-right"><input type="checkbox" \
data-address-name="%(name)s"></div> \
</div> \
</div> \
<div class="panel-collapse collapse" data-address-name="%(name)s"> \
<div class="panel-body text-muted small">%(display)s</div> \
</div> \
</div>', address))
.css({"margin": "10px auto"})
.appendTo($address_wrapper);
});
$address_wrapper.find(".panel-heading")
.find(".address-title")
.css({"cursor": "pointer"})
.on("click", function() {
$address_wrapper.find('.panel-collapse[data-address-name="'
+$(this).attr("data-address-name")+'"]').collapse("toggle");
});
$address_wrapper.find('input[type="checkbox"][data-address-name="'+ address_name +'"]')
.prop("checked", true);
$address_wrapper.find(".panel-collapse").collapse({
parent: $address_wrapper,
toggle: false
});
$address_wrapper.find('.panel-collapse[data-address-name="'+ address_name +'"]')
.collapse("show");
},
place_order: function(btn) {
return frappe.call({
type: "POST",
@ -267,24 +144,4 @@ $.extend(shopping_cart, {
$(document).ready(function() {
shopping_cart.bind_events();
// return frappe.call({
// type: "POST",
// method: "erpnext.shopping_cart.cart.get_cart_quotation",
// callback: function(r) {
// $("#cart-container").removeClass("hide");
// $(".loading").remove();
// if(r.exc) {
// if(r.exc.indexOf("WebsitePriceListMissingError")!==-1) {
// shopping_cart.show_error("Configuration Error", frappe._("Price List not configured."));
// } else if(r["403"]) {
// shopping_cart.show_error("Not Allowed", frappe._("You need to be logged in to view your cart."));
// } else {
// shopping_cart.show_error("Error", frappe._("Something went wrong."));
// }
// } else {
// shopping_cart.set_cart_count();
// shopping_cart.render(r.message);
// }
// }
// });
});

View File

@ -1,16 +0,0 @@
{% from "erpnext/templates/includes/order/order_macros.html" import item_name_and_description %}
<div class="row">
<div class="col-sm-8 col-xs-6" style="margin-bottom: 10px;">
{{ item_name_and_description(d) }}
</div>
<div class="col-sm-2 col-xs-3 text-right">
<div>{{ d.get_formatted('qty') }}</div>
<p class="text-muted small" style="margin-top: 10px;">
{{ _("Rate") + ': ' + d.get_formatted("rate") }}
</p>
</div>
<div class="col-sm-2 col-xs-3 text-right">
{{ d.get_formatted("amount") }}
</div>
</div>

View File

@ -0,0 +1,23 @@
{% from "erpnext/templates/includes/order/order_macros.html" import item_name_and_description %}
{% for d in doc.items %}
<div class="cart-item">
<div class="row">
<div class="col-sm-8 col-xs-6" style="margin-bottom: 10px;">
{{ item_name_and_description(d) }}
</div>
<div class="col-sm-2 col-xs-3 text-right">
<span style="max-width: 50px; display: inline-block">
<input class="form-control text-right cart-qty"
value = "{{ d.get_formatted('qty') }}"
data-item-code="{{ d.item_code }}"></span>
<p class="text-muted small" style="margin-top: 10px;">
{{ _("Rate") + ': ' + d.get_formatted("rate") }}
</p>
</div>
<div class="col-sm-2 col-xs-3 text-right">
{{ d.get_formatted("amount") }}
</div>
</div>
</div>
{% endfor %}

View File

@ -2,13 +2,13 @@
<a class="no-decoration" href="/issues?name={{ doc.name }}" no-pjax>
<div class="row">
<div class="col-xs-8">
<span class="indicator {{ "red" if doc.status=="Open" else "blue" }}">
<span class="indicator {{ "red" if doc.status=="Open" else "darkgrey" }}">
{{ doc.name }}</span>
<span style="margin-left: 15px;">
{{ doc.subject }}</span>
</div>
<div class="col-xs-4 text-right small">
{{ frappe.format_date(doc.creation) }}
<div class="col-xs-4 text-right small text-muted">
{{ frappe.format_date(doc.modified) }}
</div>
</div>
</a>

View File

@ -15,5 +15,8 @@
<div class="row tax-grand-total-row">
<div class="col-xs-6 text-right">{{ _("Grand Total") }}</div>
<div class="col-xs-6 text-right">
{{ doc.get_formatted("grand_total") }}</div>
<span class="tax-grand-total">
{{ doc.get_formatted("grand_total") }}
</span>
</div>
</div>

View File

@ -35,11 +35,9 @@
</div>
</div>
{% if doc.items %}
{% for d in doc.items %}
<div class="cart-item">
{% include "templates/includes/cart/cart_item_line.html" %}
<div class="cart-items">
{% include "templates/includes/cart/cart_items.html" %}
</div>
{% endfor %}
{% else %}
<p>{{ _("Cart is Empty") }}</p>
{% endif %}
@ -48,7 +46,7 @@
<!-- taxes -->
<div class="cart-taxes row small">
<div class="col-sm-8"><!-- empty --></div>
<div class="col-sm-4">
<div class="col-sm-4 cart-tax-items">
{% include "templates/includes/order/order_taxes.html" %}
</div>
</div>