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