blob: a8f69cac33d092bfb305aa7557c3ae6102834ef6 [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 Hait6626e322015-12-31 13:20:32 +053015def get_variant(variant, template, args):
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 Hait6626e322015-12-31 13:20:32 +053029 return find_variant(variant, template, args)
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()]}):
35 (attribute_values.setdefault(t.parent, [])).append(t.attribute_value)
36
37 numeric_attributes = frappe._dict((t.attribute, t) for t in \
38 frappe.db.sql("""select attribute, from_range, to_range, increment from `tabItem Variant Attribute`
39 where parent = %s and numeric_values=1""", (item), as_dict=1))
40
41 for attribute, value in args.items():
42 if attribute in numeric_attributes:
43 numeric_attribute = numeric_attributes[attribute]
44
45 from_range = numeric_attribute.from_range
46 to_range = numeric_attribute.to_range
47 increment = numeric_attribute.increment
48
49 if increment == 0:
50 # defensive validation to prevent ZeroDivisionError
51 frappe.throw(_("Increment for Attribute {0} cannot be 0").format(attribute))
52
53 is_in_range = from_range <= flt(value) <= to_range
Neil Trini Lasradoa4fad722015-10-20 11:58:07 +053054 precision = max(len(cstr(v).split(".")[-1].rstrip("0")) for v in (value, increment))
Anand Doshi099bbbd2015-09-02 11:18:32 +053055 #avoid precision error by rounding the remainder
56 remainder = flt((flt(value) - from_range) % increment, precision)
57
58 is_incremental = remainder==0 or remainder==0 or remainder==increment
59
60 if not (is_in_range and is_incremental):
61 frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3}")\
62 .format(attribute, from_range, to_range, increment), InvalidItemAttributeValueError)
Anand Doshi7c0eadb2015-10-20 17:30:02 +053063
Saurabh5fe00862015-09-16 16:59:24 +053064 elif value not in attribute_values.get(attribute, []):
Anand Doshi099bbbd2015-09-02 11:18:32 +053065 frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values").format(
66 value, attribute))
67
Nabin Hait6626e322015-12-31 13:20:32 +053068def find_variant(variant_item_code, template, args):
Anand Doshi099bbbd2015-09-02 11:18:32 +053069 conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\
70 .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
71
72 conditions = " or ".join(conditions)
73
74 # use approximate match and shortlist possible variant matches
75 # it is approximate because we are matching using OR condition
76 # and it need not be exact match at this stage
77 # this uses a simpler query instead of using multiple exists conditions
78 possible_variants = frappe.db.sql_list("""select name from `tabItem` item
79 where variant_of=%s and exists (
80 select name from `tabItem Variant Attribute` iv_attribute
81 where iv_attribute.parent=item.name
Nabin Hait6626e322015-12-31 13:20:32 +053082 and ({conditions}) and parent != %s
83 )""".format(conditions=conditions), (template, variant_item_code))
Anand Doshi099bbbd2015-09-02 11:18:32 +053084
85 for variant in possible_variants:
86 variant = frappe.get_doc("Item", variant)
87
88 if len(args.keys()) == len(variant.get("attributes")):
89 # has the same number of attributes and values
90 # assuming no duplication as per the validation in Item
91 match_count = 0
92
93 for attribute, value in args.items():
94 for row in variant.attributes:
95 if row.attribute==attribute and row.attribute_value== cstr(value):
96 # this row matches
97 match_count += 1
98 break
99
100 if match_count == len(args.keys()):
101 return variant.name
102
103@frappe.whitelist()
104def create_variant(item, args):
105 if isinstance(args, basestring):
106 args = json.loads(args)
107
108 template = frappe.get_doc("Item", item)
109 variant = frappe.new_doc("Item")
110 variant_attributes = []
111
112 for d in template.attributes:
113 variant_attributes.append({
114 "attribute": d.attribute,
115 "attribute_value": args.get(d.attribute)
116 })
117
118 variant.set("attributes", variant_attributes)
119 copy_attributes_to_variant(template, variant)
120 make_variant_item_code(template, variant)
121
122 return variant
123
124def copy_attributes_to_variant(item, variant):
125 from frappe.model import no_value_fields
126 for field in item.meta.fields:
127 if field.fieldtype not in no_value_fields and (not field.no_copy)\
Anand Doshi7c0eadb2015-10-20 17:30:02 +0530128 and field.fieldname not in ("item_code", "item_name", "show_in_website"):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530129 if variant.get(field.fieldname) != item.get(field.fieldname):
130 variant.set(field.fieldname, item.get(field.fieldname))
131 variant.variant_of = item.name
132 variant.has_variants = 0
Anand Doshi099bbbd2015-09-02 11:18:32 +0530133 if variant.attributes:
134 variant.description += "\n"
135 for d in variant.attributes:
136 variant.description += "<p>" + d.attribute + ": " + cstr(d.attribute_value) + "</p>"
137
138def make_variant_item_code(template, variant):
139 """Uses template's item code and abbreviations to make variant's item code"""
140 if variant.item_code:
141 return
142
143 abbreviations = []
144 for attr in variant.attributes:
145 item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr
146 from `tabItem Attribute` i left join `tabItem Attribute Value` v
147 on (i.name=v.parent)
148 where i.name=%(attribute)s and v.attribute_value=%(attribute_value)s""", {
149 "attribute": attr.attribute,
150 "attribute_value": attr.attribute_value
151 }, as_dict=True)
152
153 if not item_attribute:
154 # somehow an invalid item attribute got used
155 return
156
157 if item_attribute[0].numeric_values:
158 # don't generate item code if one of the attributes is numeric
159 return
160
161 abbreviations.append(item_attribute[0].abbr)
162
163 if abbreviations:
164 variant.item_code = "{0}-{1}".format(template.item_code, "-".join(abbreviations))
165
166 if variant.item_code:
167 variant.item_name = variant.item_code