blob: 3ff3d88050bcc3455e86291597b9852590f7072b [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
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053031def validate_item_variant_attributes(item, args=None):
32 if not args:
Rushabh Mehta20122ae2016-07-15 12:42:41 +053033 args = {d.attribute.lower():d.attribute_value for d in item.attributes}
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053034
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053035 attribute_values = get_attribute_values()
Anand Doshi099bbbd2015-09-02 11:18:32 +053036
Rushabh Mehta20122ae2016-07-15 12:42:41 +053037 numeric_attributes = frappe._dict({d.attribute.lower(): d for d
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053038 in item.attributes if d.numeric_values==1})
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053039
Anand Doshi099bbbd2015-09-02 11:18:32 +053040 for attribute, value in args.items():
Saurabh47fd5e02016-01-21 15:46:55 +053041 if attribute.lower() in numeric_attributes:
42 numeric_attribute = numeric_attributes[attribute.lower()]
Anand Doshi099bbbd2015-09-02 11:18:32 +053043
44 from_range = numeric_attribute.from_range
45 to_range = numeric_attribute.to_range
46 increment = numeric_attribute.increment
47
48 if increment == 0:
49 # defensive validation to prevent ZeroDivisionError
50 frappe.throw(_("Increment for Attribute {0} cannot be 0").format(attribute))
51
52 is_in_range = from_range <= flt(value) <= to_range
Neil Trini Lasradoa4fad722015-10-20 11:58:07 +053053 precision = max(len(cstr(v).split(".")[-1].rstrip("0")) for v in (value, increment))
Anand Doshi099bbbd2015-09-02 11:18:32 +053054 #avoid precision error by rounding the remainder
55 remainder = flt((flt(value) - from_range) % increment, precision)
56
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053057 is_incremental = remainder==0 or remainder==increment
Anand Doshi099bbbd2015-09-02 11:18:32 +053058
59 if not (is_in_range and is_incremental):
60 frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3}")\
61 .format(attribute, from_range, to_range, increment), InvalidItemAttributeValueError)
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053062
Saurabh47fd5e02016-01-21 15:46:55 +053063 elif value not in attribute_values.get(attribute.lower(), []):
Anand Doshi099bbbd2015-09-02 11:18:32 +053064 frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values").format(
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053065 value, attribute), InvalidItemAttributeValueError)
Anand Doshi099bbbd2015-09-02 11:18:32 +053066
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053067def get_attribute_values():
68 if not frappe.flags.attribute_values:
69 attribute_values = {}
70 for t in frappe.get_all("Item Attribute Value", fields=["parent", "attribute_value"]):
71 (attribute_values.setdefault(t.parent.lower(), [])).append(t.attribute_value)
72
73 frappe.flags.attribute_values = attribute_values
74
75 return frappe.flags.attribute_values
76
Nabin Hait6b068e12015-12-31 13:20:32 +053077def find_variant(template, args, variant_item_code=None):
Anand Doshi099bbbd2015-09-02 11:18:32 +053078 conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\
79 .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
80
81 conditions = " or ".join(conditions)
82
83 # use approximate match and shortlist possible variant matches
84 # it is approximate because we are matching using OR condition
85 # and it need not be exact match at this stage
86 # this uses a simpler query instead of using multiple exists conditions
87 possible_variants = frappe.db.sql_list("""select name from `tabItem` item
88 where variant_of=%s and exists (
89 select name from `tabItem Variant Attribute` iv_attribute
90 where iv_attribute.parent=item.name
Nabin Hait6626e322015-12-31 13:20:32 +053091 and ({conditions}) and parent != %s
Nabin Hait6b068e12015-12-31 13:20:32 +053092 )""".format(conditions=conditions), (template, cstr(variant_item_code)))
Anand Doshi099bbbd2015-09-02 11:18:32 +053093
94 for variant in possible_variants:
95 variant = frappe.get_doc("Item", variant)
96
97 if len(args.keys()) == len(variant.get("attributes")):
98 # has the same number of attributes and values
99 # assuming no duplication as per the validation in Item
100 match_count = 0
101
102 for attribute, value in args.items():
103 for row in variant.attributes:
104 if row.attribute==attribute and row.attribute_value== cstr(value):
105 # this row matches
106 match_count += 1
107 break
108
109 if match_count == len(args.keys()):
110 return variant.name
111
112@frappe.whitelist()
113def create_variant(item, args):
114 if isinstance(args, basestring):
115 args = json.loads(args)
116
117 template = frappe.get_doc("Item", item)
118 variant = frappe.new_doc("Item")
119 variant_attributes = []
120
121 for d in template.attributes:
122 variant_attributes.append({
123 "attribute": d.attribute,
124 "attribute_value": args.get(d.attribute)
125 })
126
127 variant.set("attributes", variant_attributes)
128 copy_attributes_to_variant(template, variant)
129 make_variant_item_code(template, variant)
130
131 return variant
132
133def copy_attributes_to_variant(item, variant):
134 from frappe.model import no_value_fields
135 for field in item.meta.fields:
136 if field.fieldtype not in no_value_fields and (not field.no_copy)\
Anand Doshi7c0eadb2015-10-20 17:30:02 +0530137 and field.fieldname not in ("item_code", "item_name", "show_in_website"):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530138 if variant.get(field.fieldname) != item.get(field.fieldname):
139 variant.set(field.fieldname, item.get(field.fieldname))
140 variant.variant_of = item.name
141 variant.has_variants = 0
Anand Doshi099bbbd2015-09-02 11:18:32 +0530142 if variant.attributes:
143 variant.description += "\n"
144 for d in variant.attributes:
145 variant.description += "<p>" + d.attribute + ": " + cstr(d.attribute_value) + "</p>"
146
147def make_variant_item_code(template, variant):
148 """Uses template's item code and abbreviations to make variant's item code"""
149 if variant.item_code:
150 return
151
152 abbreviations = []
153 for attr in variant.attributes:
154 item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr
155 from `tabItem Attribute` i left join `tabItem Attribute Value` v
156 on (i.name=v.parent)
157 where i.name=%(attribute)s and v.attribute_value=%(attribute_value)s""", {
158 "attribute": attr.attribute,
159 "attribute_value": attr.attribute_value
160 }, as_dict=True)
161
162 if not item_attribute:
163 # somehow an invalid item attribute got used
164 return
165
166 if item_attribute[0].numeric_values:
167 # don't generate item code if one of the attributes is numeric
168 return
169
170 abbreviations.append(item_attribute[0].abbr)
171
172 if abbreviations:
173 variant.item_code = "{0}-{1}".format(template.item_code, "-".join(abbreviations))
174
175 if variant.item_code:
176 variant.item_name = variant.item_code