blob: 0ea0734676c95616a32081a76f6d1de49cdc227d [file] [log] [blame]
Anand Doshi099bbbd2015-09-02 11:18:32 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
2# License: GNU General Public License v3. See license.txt
3
4from __future__ import unicode_literals
5import frappe
6from frappe import _
7from frappe.utils import cstr, flt
8import json
9
10class ItemVariantExistsError(frappe.ValidationError): pass
11class InvalidItemAttributeValueError(frappe.ValidationError): pass
12class ItemTemplateCannotHaveStock(frappe.ValidationError): pass
13
14@frappe.whitelist()
Nabin Hait6b068e12015-12-31 13:20:32 +053015def get_variant(template, args, variant=None):
Anand Doshi099bbbd2015-09-02 11:18:32 +053016 """Validates Attributes and their Values, then looks for an exactly matching Item Variant
17
18 :param item: Template Item
19 :param args: A dictionary with "Attribute" as key and "Attribute Value" as value
20 """
21 if isinstance(args, basestring):
22 args = json.loads(args)
23
24 if not args:
25 frappe.throw(_("Please specify at least one attribute in the Attributes table"))
26
Nabin Hait6626e322015-12-31 13:20:32 +053027 validate_item_variant_attributes(template, args)
Anand Doshi099bbbd2015-09-02 11:18:32 +053028
Nabin Hait6b068e12015-12-31 13:20:32 +053029 return find_variant(template, args, variant)
Anand Doshi099bbbd2015-09-02 11:18:32 +053030
31def validate_item_variant_attributes(item, args):
32 attribute_values = {}
33 for t in frappe.get_all("Item Attribute Value", fields=["parent", "attribute_value"],
34 filters={"parent": ["in", args.keys()]}):
Saurabh47fd5e02016-01-21 15:46:55 +053035
36 (attribute_values.setdefault(t.parent.lower(), [])).append(t.attribute_value)
Anand Doshi099bbbd2015-09-02 11:18:32 +053037
Saurabh47fd5e02016-01-21 15:46:55 +053038 numeric_attributes = frappe._dict((t.attribute.lower(), t) for t in \
Anand Doshi099bbbd2015-09-02 11:18:32 +053039 frappe.db.sql("""select attribute, from_range, to_range, increment from `tabItem Variant Attribute`
40 where parent = %s and numeric_values=1""", (item), as_dict=1))
Saurabh47fd5e02016-01-21 15:46:55 +053041
Anand Doshi099bbbd2015-09-02 11:18:32 +053042 for attribute, value in args.items():
Saurabh47fd5e02016-01-21 15:46:55 +053043 if attribute.lower() in numeric_attributes:
44 numeric_attribute = numeric_attributes[attribute.lower()]
Anand Doshi099bbbd2015-09-02 11:18:32 +053045
46 from_range = numeric_attribute.from_range
47 to_range = numeric_attribute.to_range
48 increment = numeric_attribute.increment
49
50 if increment == 0:
51 # defensive validation to prevent ZeroDivisionError
52 frappe.throw(_("Increment for Attribute {0} cannot be 0").format(attribute))
53
54 is_in_range = from_range <= flt(value) <= to_range
Neil Trini Lasradoa4fad722015-10-20 11:58:07 +053055 precision = max(len(cstr(v).split(".")[-1].rstrip("0")) for v in (value, increment))
Anand Doshi099bbbd2015-09-02 11:18:32 +053056 #avoid precision error by rounding the remainder
57 remainder = flt((flt(value) - from_range) % increment, precision)
58
59 is_incremental = remainder==0 or remainder==0 or remainder==increment
60
61 if not (is_in_range and is_incremental):
62 frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3}")\
63 .format(attribute, from_range, to_range, increment), InvalidItemAttributeValueError)
Saurabh47fd5e02016-01-21 15:46:55 +053064
65 elif value not in attribute_values.get(attribute.lower(), []):
Anand Doshi099bbbd2015-09-02 11:18:32 +053066 frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values").format(
67 value, attribute))
68
Nabin Hait6b068e12015-12-31 13:20:32 +053069def find_variant(template, args, variant_item_code=None):
Anand Doshi099bbbd2015-09-02 11:18:32 +053070 conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\
71 .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
72
73 conditions = " or ".join(conditions)
74
75 # use approximate match and shortlist possible variant matches
76 # it is approximate because we are matching using OR condition
77 # and it need not be exact match at this stage
78 # this uses a simpler query instead of using multiple exists conditions
79 possible_variants = frappe.db.sql_list("""select name from `tabItem` item
80 where variant_of=%s and exists (
81 select name from `tabItem Variant Attribute` iv_attribute
82 where iv_attribute.parent=item.name
Nabin Hait6626e322015-12-31 13:20:32 +053083 and ({conditions}) and parent != %s
Nabin Hait6b068e12015-12-31 13:20:32 +053084 )""".format(conditions=conditions), (template, cstr(variant_item_code)))
Anand Doshi099bbbd2015-09-02 11:18:32 +053085
86 for variant in possible_variants:
87 variant = frappe.get_doc("Item", variant)
88
89 if len(args.keys()) == len(variant.get("attributes")):
90 # has the same number of attributes and values
91 # assuming no duplication as per the validation in Item
92 match_count = 0
93
94 for attribute, value in args.items():
95 for row in variant.attributes:
96 if row.attribute==attribute and row.attribute_value== cstr(value):
97 # this row matches
98 match_count += 1
99 break
100
101 if match_count == len(args.keys()):
102 return variant.name
103
104@frappe.whitelist()
105def create_variant(item, args):
106 if isinstance(args, basestring):
107 args = json.loads(args)
108
109 template = frappe.get_doc("Item", item)
110 variant = frappe.new_doc("Item")
111 variant_attributes = []
112
113 for d in template.attributes:
114 variant_attributes.append({
115 "attribute": d.attribute,
116 "attribute_value": args.get(d.attribute)
117 })
118
119 variant.set("attributes", variant_attributes)
120 copy_attributes_to_variant(template, variant)
121 make_variant_item_code(template, variant)
122
123 return variant
124
125def copy_attributes_to_variant(item, variant):
126 from frappe.model import no_value_fields
127 for field in item.meta.fields:
128 if field.fieldtype not in no_value_fields and (not field.no_copy)\
Anand Doshi7c0eadb2015-10-20 17:30:02 +0530129 and field.fieldname not in ("item_code", "item_name", "show_in_website"):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530130 if variant.get(field.fieldname) != item.get(field.fieldname):
131 variant.set(field.fieldname, item.get(field.fieldname))
132 variant.variant_of = item.name
133 variant.has_variants = 0
Anand Doshi099bbbd2015-09-02 11:18:32 +0530134 if variant.attributes:
135 variant.description += "\n"
136 for d in variant.attributes:
137 variant.description += "<p>" + d.attribute + ": " + cstr(d.attribute_value) + "</p>"
138
139def make_variant_item_code(template, variant):
140 """Uses template's item code and abbreviations to make variant's item code"""
141 if variant.item_code:
142 return
143
144 abbreviations = []
145 for attr in variant.attributes:
146 item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr
147 from `tabItem Attribute` i left join `tabItem Attribute Value` v
148 on (i.name=v.parent)
149 where i.name=%(attribute)s and v.attribute_value=%(attribute_value)s""", {
150 "attribute": attr.attribute,
151 "attribute_value": attr.attribute_value
152 }, as_dict=True)
153
154 if not item_attribute:
155 # somehow an invalid item attribute got used
156 return
157
158 if item_attribute[0].numeric_values:
159 # don't generate item code if one of the attributes is numeric
160 return
161
162 abbreviations.append(item_attribute[0].abbr)
163
164 if abbreviations:
165 variant.item_code = "{0}-{1}".format(template.item_code, "-".join(abbreviations))
166
167 if variant.item_code:
168 variant.item_name = variant.item_code