blob: 66b3dd0a94fd62d7a642244615fe1592453a9539 [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()]
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053044 validate_is_incremental(numeric_attribute, attribute, value, item.name)
Anand Doshi099bbbd2015-09-02 11:18:32 +053045
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053046 else:
47 attributes_list = attribute_values.get(attribute.lower(), [])
48 validate_item_attribute_value(attributes_list, attribute, value, item.name)
Anand Doshi099bbbd2015-09-02 11:18:32 +053049
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053050def validate_is_incremental(numeric_attribute, attribute, value, item):
51 from_range = numeric_attribute.from_range
52 to_range = numeric_attribute.to_range
53 increment = numeric_attribute.increment
Anand Doshi099bbbd2015-09-02 11:18:32 +053054
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053055 if increment == 0:
56 # defensive validation to prevent ZeroDivisionError
57 frappe.throw(_("Increment for Attribute {0} cannot be 0").format(attribute))
Anand Doshi099bbbd2015-09-02 11:18:32 +053058
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053059 is_in_range = from_range <= flt(value) <= to_range
60 precision = max(len(cstr(v).split(".")[-1].rstrip("0")) for v in (value, increment))
61 #avoid precision error by rounding the remainder
62 remainder = flt((flt(value) - from_range) % increment, precision)
Anand Doshi099bbbd2015-09-02 11:18:32 +053063
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053064 is_incremental = remainder==0 or remainder==increment
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053065
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053066 if not (is_in_range and is_incremental):
67 frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3} for Item {4}")\
68 .format(attribute, from_range, to_range, increment, item),
69 InvalidItemAttributeValueError, title=_('Invalid Attribute'))
70
71def validate_item_attribute_value(attributes_list, attribute, attribute_value, item):
72 if attribute_value not in attributes_list:
73 frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values for Item {2}").format(
74 attribute_value, attribute, item), InvalidItemAttributeValueError, title=_('Invalid Attribute'))
Anand Doshi099bbbd2015-09-02 11:18:32 +053075
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053076def get_attribute_values():
77 if not frappe.flags.attribute_values:
78 attribute_values = {}
Rushabh Mehta95383bb2016-07-15 15:11:46 +053079 numeric_values = {}
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053080 for t in frappe.get_all("Item Attribute Value", fields=["parent", "attribute_value"]):
Rushabh Mehta95383bb2016-07-15 15:11:46 +053081 attribute_values.setdefault(t.parent.lower(), []).append(t.attribute_value)
82
83 for t in frappe.get_all('Item Attribute',
84 fields=["name", "from_range", "to_range", "increment"], filters={'numeric_values': 1}):
85 numeric_values[t.name.lower()] = t
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053086
87 frappe.flags.attribute_values = attribute_values
Rushabh Mehta95383bb2016-07-15 15:11:46 +053088 frappe.flags.numeric_values = numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053089
Rushabh Mehta95383bb2016-07-15 15:11:46 +053090 return frappe.flags.attribute_values, frappe.flags.numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053091
Nabin Hait6b068e12015-12-31 13:20:32 +053092def find_variant(template, args, variant_item_code=None):
Anand Doshi099bbbd2015-09-02 11:18:32 +053093 conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\
94 .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
95
96 conditions = " or ".join(conditions)
97
98 # use approximate match and shortlist possible variant matches
99 # it is approximate because we are matching using OR condition
100 # and it need not be exact match at this stage
101 # this uses a simpler query instead of using multiple exists conditions
102 possible_variants = frappe.db.sql_list("""select name from `tabItem` item
103 where variant_of=%s and exists (
104 select name from `tabItem Variant Attribute` iv_attribute
105 where iv_attribute.parent=item.name
Nabin Hait6626e322015-12-31 13:20:32 +0530106 and ({conditions}) and parent != %s
Nabin Hait6b068e12015-12-31 13:20:32 +0530107 )""".format(conditions=conditions), (template, cstr(variant_item_code)))
Anand Doshi099bbbd2015-09-02 11:18:32 +0530108
109 for variant in possible_variants:
110 variant = frappe.get_doc("Item", variant)
111
112 if len(args.keys()) == len(variant.get("attributes")):
113 # has the same number of attributes and values
114 # assuming no duplication as per the validation in Item
115 match_count = 0
116
117 for attribute, value in args.items():
118 for row in variant.attributes:
119 if row.attribute==attribute and row.attribute_value== cstr(value):
120 # this row matches
121 match_count += 1
122 break
123
124 if match_count == len(args.keys()):
125 return variant.name
126
127@frappe.whitelist()
128def create_variant(item, args):
129 if isinstance(args, basestring):
130 args = json.loads(args)
131
132 template = frappe.get_doc("Item", item)
133 variant = frappe.new_doc("Item")
134 variant_attributes = []
135
136 for d in template.attributes:
137 variant_attributes.append({
138 "attribute": d.attribute,
139 "attribute_value": args.get(d.attribute)
140 })
141
142 variant.set("attributes", variant_attributes)
143 copy_attributes_to_variant(template, variant)
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530144 make_variant_item_code(template.item_code, variant)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530145
146 return variant
147
148def copy_attributes_to_variant(item, variant):
149 from frappe.model import no_value_fields
150 for field in item.meta.fields:
151 if field.fieldtype not in no_value_fields and (not field.no_copy)\
Anand Doshi7c0eadb2015-10-20 17:30:02 +0530152 and field.fieldname not in ("item_code", "item_name", "show_in_website"):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530153 if variant.get(field.fieldname) != item.get(field.fieldname):
154 variant.set(field.fieldname, item.get(field.fieldname))
155 variant.variant_of = item.name
156 variant.has_variants = 0
Anand Doshi099bbbd2015-09-02 11:18:32 +0530157 if variant.attributes:
158 variant.description += "\n"
159 for d in variant.attributes:
160 variant.description += "<p>" + d.attribute + ": " + cstr(d.attribute_value) + "</p>"
161
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530162def make_variant_item_code(template_item_code, variant):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530163 """Uses template's item code and abbreviations to make variant's item code"""
164 if variant.item_code:
165 return
166
167 abbreviations = []
168 for attr in variant.attributes:
169 item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr
170 from `tabItem Attribute` i left join `tabItem Attribute Value` v
171 on (i.name=v.parent)
172 where i.name=%(attribute)s and v.attribute_value=%(attribute_value)s""", {
173 "attribute": attr.attribute,
174 "attribute_value": attr.attribute_value
175 }, as_dict=True)
176
177 if not item_attribute:
Anand Doshi099bbbd2015-09-02 11:18:32 +0530178 return
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530179 # frappe.throw(_('Invalid attribute {0} {1}').format(frappe.bold(attr.attribute),
180 # frappe.bold(attr.attribute_value)), title=_('Invalid Attribute'),
181 # exc=InvalidItemAttributeValueError)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530182
183 if item_attribute[0].numeric_values:
184 # don't generate item code if one of the attributes is numeric
185 return
186
187 abbreviations.append(item_attribute[0].abbr)
188
189 if abbreviations:
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530190 variant.item_code = "{0}-{1}".format(template_item_code, "-".join(abbreviations))
Anand Doshi099bbbd2015-09-02 11:18:32 +0530191
192 if variant.item_code:
193 variant.item_name = variant.item_code