blob: 8294b64da92267e8fad9a3f2831cbcc1959193c2 [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 Hait6b068e12015-12-31 13:20:32 +053027 return find_variant(template, args, variant)
Anand Doshi099bbbd2015-09-02 11:18:32 +053028
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053029def validate_item_variant_attributes(item, args=None):
Rushabh Mehta95383bb2016-07-15 15:11:46 +053030 if isinstance(item, basestring):
31 item = frappe.get_doc('Item', item)
32
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053033 if not args:
Rushabh Mehta20122ae2016-07-15 12:42:41 +053034 args = {d.attribute.lower():d.attribute_value for d in item.attributes}
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053035
Rushabh Mehta95383bb2016-07-15 15:11:46 +053036 attribute_values, numeric_values = get_attribute_values()
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053037
Anand Doshi099bbbd2015-09-02 11:18:32 +053038 for attribute, value in args.items():
Rushabh Mehta95383bb2016-07-15 15:11:46 +053039 if not value:
40 continue
41
42 if attribute.lower() in numeric_values:
43 numeric_attribute = numeric_values[attribute.lower()]
Anand Doshi099bbbd2015-09-02 11:18:32 +053044
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
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053058 is_incremental = remainder==0 or remainder==increment
Anand Doshi099bbbd2015-09-02 11:18:32 +053059
60 if not (is_in_range and is_incremental):
Rushabh Mehta95383bb2016-07-15 15:11:46 +053061 frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3} for Item {2}")\
62 .format(attribute, from_range, to_range, increment, item.name), InvalidItemAttributeValueError)
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053063
Saurabh47fd5e02016-01-21 15:46:55 +053064 elif value not in attribute_values.get(attribute.lower(), []):
Rushabh Mehta95383bb2016-07-15 15:11:46 +053065 frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values for Item {2}").format(
66 value, attribute, item.name), InvalidItemAttributeValueError)
Anand Doshi099bbbd2015-09-02 11:18:32 +053067
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053068def get_attribute_values():
69 if not frappe.flags.attribute_values:
70 attribute_values = {}
Rushabh Mehta95383bb2016-07-15 15:11:46 +053071 numeric_values = {}
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053072 for t in frappe.get_all("Item Attribute Value", fields=["parent", "attribute_value"]):
Rushabh Mehta95383bb2016-07-15 15:11:46 +053073 attribute_values.setdefault(t.parent.lower(), []).append(t.attribute_value)
74
75 for t in frappe.get_all('Item Attribute',
76 fields=["name", "from_range", "to_range", "increment"], filters={'numeric_values': 1}):
77 numeric_values[t.name.lower()] = t
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053078
79 frappe.flags.attribute_values = attribute_values
Rushabh Mehta95383bb2016-07-15 15:11:46 +053080 frappe.flags.numeric_values = numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053081
Rushabh Mehta95383bb2016-07-15 15:11:46 +053082 return frappe.flags.attribute_values, frappe.flags.numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053083
Nabin Hait6b068e12015-12-31 13:20:32 +053084def find_variant(template, args, variant_item_code=None):
Anand Doshi099bbbd2015-09-02 11:18:32 +053085 conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\
86 .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
87
88 conditions = " or ".join(conditions)
89
90 # use approximate match and shortlist possible variant matches
91 # it is approximate because we are matching using OR condition
92 # and it need not be exact match at this stage
93 # this uses a simpler query instead of using multiple exists conditions
94 possible_variants = frappe.db.sql_list("""select name from `tabItem` item
95 where variant_of=%s and exists (
96 select name from `tabItem Variant Attribute` iv_attribute
97 where iv_attribute.parent=item.name
Nabin Hait6626e322015-12-31 13:20:32 +053098 and ({conditions}) and parent != %s
Nabin Hait6b068e12015-12-31 13:20:32 +053099 )""".format(conditions=conditions), (template, cstr(variant_item_code)))
Anand Doshi099bbbd2015-09-02 11:18:32 +0530100
101 for variant in possible_variants:
102 variant = frappe.get_doc("Item", variant)
103
104 if len(args.keys()) == len(variant.get("attributes")):
105 # has the same number of attributes and values
106 # assuming no duplication as per the validation in Item
107 match_count = 0
108
109 for attribute, value in args.items():
110 for row in variant.attributes:
111 if row.attribute==attribute and row.attribute_value== cstr(value):
112 # this row matches
113 match_count += 1
114 break
115
116 if match_count == len(args.keys()):
117 return variant.name
118
119@frappe.whitelist()
120def create_variant(item, args):
121 if isinstance(args, basestring):
122 args = json.loads(args)
123
124 template = frappe.get_doc("Item", item)
125 variant = frappe.new_doc("Item")
126 variant_attributes = []
127
128 for d in template.attributes:
129 variant_attributes.append({
130 "attribute": d.attribute,
131 "attribute_value": args.get(d.attribute)
132 })
133
134 variant.set("attributes", variant_attributes)
135 copy_attributes_to_variant(template, variant)
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530136 make_variant_item_code(template.item_code, variant)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530137
138 return variant
139
140def copy_attributes_to_variant(item, variant):
141 from frappe.model import no_value_fields
142 for field in item.meta.fields:
143 if field.fieldtype not in no_value_fields and (not field.no_copy)\
Anand Doshi7c0eadb2015-10-20 17:30:02 +0530144 and field.fieldname not in ("item_code", "item_name", "show_in_website"):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530145 if variant.get(field.fieldname) != item.get(field.fieldname):
146 variant.set(field.fieldname, item.get(field.fieldname))
147 variant.variant_of = item.name
148 variant.has_variants = 0
Anand Doshi099bbbd2015-09-02 11:18:32 +0530149 if variant.attributes:
150 variant.description += "\n"
151 for d in variant.attributes:
152 variant.description += "<p>" + d.attribute + ": " + cstr(d.attribute_value) + "</p>"
153
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530154def make_variant_item_code(template_item_code, variant):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530155 """Uses template's item code and abbreviations to make variant's item code"""
156 if variant.item_code:
157 return
158
159 abbreviations = []
160 for attr in variant.attributes:
161 item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr
162 from `tabItem Attribute` i left join `tabItem Attribute Value` v
163 on (i.name=v.parent)
164 where i.name=%(attribute)s and v.attribute_value=%(attribute_value)s""", {
165 "attribute": attr.attribute,
166 "attribute_value": attr.attribute_value
167 }, as_dict=True)
168
169 if not item_attribute:
Anand Doshi099bbbd2015-09-02 11:18:32 +0530170 return
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530171 # frappe.throw(_('Invalid attribute {0} {1}').format(frappe.bold(attr.attribute),
172 # frappe.bold(attr.attribute_value)), title=_('Invalid Attribute'),
173 # exc=InvalidItemAttributeValueError)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530174
175 if item_attribute[0].numeric_values:
176 # don't generate item code if one of the attributes is numeric
177 return
178
179 abbreviations.append(item_attribute[0].abbr)
180
181 if abbreviations:
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530182 variant.item_code = "{0}-{1}".format(template_item_code, "-".join(abbreviations))
Anand Doshi099bbbd2015-09-02 11:18:32 +0530183
184 if variant.item_code:
185 variant.item_name = variant.item_code