blob: 9eee6cc6df47b93a5c2ab5eeb4672a461d6b221c [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
Nabin Hait945f5022017-09-29 15:11:50 +05308import json, copy
Anand Doshi099bbbd2015-09-02 11:18:32 +05309
10class ItemVariantExistsError(frappe.ValidationError): pass
11class InvalidItemAttributeValueError(frappe.ValidationError): pass
12class ItemTemplateCannotHaveStock(frappe.ValidationError): pass
13
14@frappe.whitelist()
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010015def get_variant(template, args=None, variant=None, manufacturer=None,
16 manufacturer_part_no=None):
17 """Validates Attributes and their Values, then looks for an exactly
18 matching Item Variant
Anand Doshi099bbbd2015-09-02 11:18:32 +053019
20 :param item: Template Item
21 :param args: A dictionary with "Attribute" as key and "Attribute Value" as value
22 """
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010023 item_template = frappe.get_doc('Item', template)
Anand Doshi099bbbd2015-09-02 11:18:32 +053024
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010025 if item_template.variant_based_on=='Manufacturer' and manufacturer:
26 return make_variant_based_on_manufacturer(item_template, manufacturer,
27 manufacturer_part_no)
28 else:
29 if isinstance(args, basestring):
30 args = json.loads(args)
Anand Doshi099bbbd2015-09-02 11:18:32 +053031
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010032 if not args:
33 frappe.throw(_("Please specify at least one attribute in the Attributes table"))
34 return find_variant(template, args, variant)
35
36def make_variant_based_on_manufacturer(template, manufacturer, manufacturer_part_no):
37 '''Make and return a new variant based on manufacturer and
38 manufacturer part no'''
39 from frappe.model.naming import append_number_if_name_exists
40
41 variant = frappe.new_doc('Item')
42
43 copy_attributes_to_variant(template, variant)
44
Nabin Haitb6a89202017-04-25 17:27:53 +053045 variant.manufacturer = manufacturer
46 variant.manufacturer_part_no = manufacturer_part_no
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010047
48 variant.item_code = append_number_if_name_exists('Item', template.name)
49
50 return variant
Anand Doshi099bbbd2015-09-02 11:18:32 +053051
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053052def validate_item_variant_attributes(item, args=None):
Rushabh Mehta95383bb2016-07-15 15:11:46 +053053 if isinstance(item, basestring):
54 item = frappe.get_doc('Item', item)
55
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053056 if not args:
Rushabh Mehta20122ae2016-07-15 12:42:41 +053057 args = {d.attribute.lower():d.attribute_value for d in item.attributes}
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053058
Nabin Haitaaf378e2017-12-13 18:40:52 +053059 attribute_values, numeric_values = get_attribute_values(item)
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053060
Anand Doshi099bbbd2015-09-02 11:18:32 +053061 for attribute, value in args.items():
Rushabh Mehta95383bb2016-07-15 15:11:46 +053062 if not value:
63 continue
64
65 if attribute.lower() in numeric_values:
66 numeric_attribute = numeric_values[attribute.lower()]
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053067 validate_is_incremental(numeric_attribute, attribute, value, item.name)
Anand Doshi099bbbd2015-09-02 11:18:32 +053068
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053069 else:
70 attributes_list = attribute_values.get(attribute.lower(), [])
71 validate_item_attribute_value(attributes_list, attribute, value, item.name)
Anand Doshi099bbbd2015-09-02 11:18:32 +053072
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053073def validate_is_incremental(numeric_attribute, attribute, value, item):
74 from_range = numeric_attribute.from_range
75 to_range = numeric_attribute.to_range
76 increment = numeric_attribute.increment
Anand Doshi099bbbd2015-09-02 11:18:32 +053077
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053078 if increment == 0:
79 # defensive validation to prevent ZeroDivisionError
80 frappe.throw(_("Increment for Attribute {0} cannot be 0").format(attribute))
Anand Doshi099bbbd2015-09-02 11:18:32 +053081
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053082 is_in_range = from_range <= flt(value) <= to_range
83 precision = max(len(cstr(v).split(".")[-1].rstrip("0")) for v in (value, increment))
84 #avoid precision error by rounding the remainder
85 remainder = flt((flt(value) - from_range) % increment, precision)
Anand Doshi099bbbd2015-09-02 11:18:32 +053086
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053087 is_incremental = remainder==0 or remainder==increment
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053088
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053089 if not (is_in_range and is_incremental):
90 frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3} for Item {4}")\
91 .format(attribute, from_range, to_range, increment, item),
92 InvalidItemAttributeValueError, title=_('Invalid Attribute'))
93
94def validate_item_attribute_value(attributes_list, attribute, attribute_value, item):
95 if attribute_value not in attributes_list:
96 frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values for Item {2}").format(
97 attribute_value, attribute, item), InvalidItemAttributeValueError, title=_('Invalid Attribute'))
Anand Doshi099bbbd2015-09-02 11:18:32 +053098
Nabin Haitaaf378e2017-12-13 18:40:52 +053099def get_attribute_values(item):
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530100 if not frappe.flags.attribute_values:
101 attribute_values = {}
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530102 numeric_values = {}
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530103 for t in frappe.get_all("Item Attribute Value", fields=["parent", "attribute_value"]):
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530104 attribute_values.setdefault(t.parent.lower(), []).append(t.attribute_value)
105
Nabin Haitaaf378e2017-12-13 18:40:52 +0530106 for t in frappe.get_all('Item Variant Attribute',
107 fields=["attribute", "from_range", "to_range", "increment"],
108 filters={'numeric_values': 1, 'parent': item.variant_of}):
109 numeric_values[t.attribute.lower()] = t
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530110
111 frappe.flags.attribute_values = attribute_values
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530112 frappe.flags.numeric_values = numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530113
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530114 return frappe.flags.attribute_values, frappe.flags.numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530115
Nabin Hait6b068e12015-12-31 13:20:32 +0530116def find_variant(template, args, variant_item_code=None):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530117 conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\
118 .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
119
120 conditions = " or ".join(conditions)
121
122 # use approximate match and shortlist possible variant matches
123 # it is approximate because we are matching using OR condition
124 # and it need not be exact match at this stage
125 # this uses a simpler query instead of using multiple exists conditions
126 possible_variants = frappe.db.sql_list("""select name from `tabItem` item
127 where variant_of=%s and exists (
128 select name from `tabItem Variant Attribute` iv_attribute
129 where iv_attribute.parent=item.name
Nabin Hait6626e322015-12-31 13:20:32 +0530130 and ({conditions}) and parent != %s
Nabin Hait6b068e12015-12-31 13:20:32 +0530131 )""".format(conditions=conditions), (template, cstr(variant_item_code)))
Anand Doshi099bbbd2015-09-02 11:18:32 +0530132
133 for variant in possible_variants:
134 variant = frappe.get_doc("Item", variant)
135
136 if len(args.keys()) == len(variant.get("attributes")):
137 # has the same number of attributes and values
138 # assuming no duplication as per the validation in Item
139 match_count = 0
140
141 for attribute, value in args.items():
142 for row in variant.attributes:
143 if row.attribute==attribute and row.attribute_value== cstr(value):
144 # this row matches
145 match_count += 1
146 break
147
148 if match_count == len(args.keys()):
149 return variant.name
150
151@frappe.whitelist()
152def create_variant(item, args):
153 if isinstance(args, basestring):
154 args = json.loads(args)
155
156 template = frappe.get_doc("Item", item)
157 variant = frappe.new_doc("Item")
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100158 variant.variant_based_on = 'Item Attribute'
Anand Doshi099bbbd2015-09-02 11:18:32 +0530159 variant_attributes = []
160
161 for d in template.attributes:
162 variant_attributes.append({
163 "attribute": d.attribute,
164 "attribute_value": args.get(d.attribute)
165 })
166
167 variant.set("attributes", variant_attributes)
168 copy_attributes_to_variant(template, variant)
Prateeksha Singh89cec182017-05-19 12:35:36 +0530169 make_variant_item_code(template.item_code, template.item_name, variant)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530170
171 return variant
172
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530173@frappe.whitelist()
174def enqueue_multiple_variant_creation(item, args):
175 # There can be innumerable attribute combinations, enqueue
176 frappe.enqueue("erpnext.controllers.item_variant.create_multiple_variants",
177 item=item, args=args, now=frappe.flags.in_test);
178
179def create_multiple_variants(item, args):
180 if isinstance(args, basestring):
181 args = json.loads(args)
182
183 args_set = generate_keyed_value_combinations(args)
184
185 for attribute_values in args_set:
186 if not get_variant(item, args=attribute_values):
187 variant = create_variant(item, attribute_values)
188 variant.save()
189
190def generate_keyed_value_combinations(args):
191 """
192 From this:
193
194 args = {"attr1": ["a", "b", "c"], "attr2": ["1", "2"], "attr3": ["A"]}
195
196 To this:
197
198 [
199 {u'attr1': u'a', u'attr2': u'1', u'attr3': u'A'},
200 {u'attr1': u'b', u'attr2': u'1', u'attr3': u'A'},
201 {u'attr1': u'c', u'attr2': u'1', u'attr3': u'A'},
202 {u'attr1': u'a', u'attr2': u'2', u'attr3': u'A'},
203 {u'attr1': u'b', u'attr2': u'2', u'attr3': u'A'},
204 {u'attr1': u'c', u'attr2': u'2', u'attr3': u'A'}
205 ]
206
207 """
208 # Return empty list if empty
209 if not args:
210 return []
211
212 # Turn `args` into a list of lists of key-value tuples:
213 # [
214 # [(u'attr2', u'1'), (u'attr2', u'2')],
215 # [(u'attr3', u'A')],
216 # [(u'attr1', u'a'), (u'attr1', u'b'), (u'attr1', u'c')]
217 # ]
218 key_value_lists = [[(key, val) for val in args[key]] for key in args.keys()]
219
220 # Store the first, but as objects
221 # [{u'attr2': u'1'}, {u'attr2': u'2'}]
222 results = key_value_lists.pop(0)
223 results = [{d[0]: d[1]} for d in results]
224
225 # Iterate the remaining
226 # Take the next list to fuse with existing results
227 for l in key_value_lists:
228 new_results = []
229 for res in results:
230 for key_val in l:
231 # create a new clone of object in result
232 obj = copy.deepcopy(res)
233 # to be used with every incoming new value
234 obj[key_val[0]] = key_val[1]
235 # and pushed into new_results
236 new_results.append(obj)
237 results = new_results
238
239 return results
240
Anand Doshi099bbbd2015-09-02 11:18:32 +0530241def copy_attributes_to_variant(item, variant):
242 from frappe.model import no_value_fields
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100243
244 # copy non no-copy fields
245
Nabin Haitc3144852017-09-28 18:55:40 +0530246 exclude_fields = ["naming_series", "item_code", "item_name", "show_in_website",
Nabin Hait945f5022017-09-29 15:11:50 +0530247 "show_variant_in_website", "opening_stock", "variant_of", "valuation_rate"]
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100248
249 if item.variant_based_on=='Manufacturer':
250 # don't copy manufacturer values if based on part no
251 exclude_fields += ['manufacturer', 'manufacturer_part_no']
252
Rohit Waghchaure0e28fcc2017-08-29 18:15:57 +0530253 allow_fields = [d.field_name for d in frappe.get_all("Variant Field", fields = ['field_name'])]
Nabin Hait945f5022017-09-29 15:11:50 +0530254 if "variant_based_on" not in allow_fields:
255 allow_fields.append("variant_based_on")
Anand Doshi099bbbd2015-09-02 11:18:32 +0530256 for field in item.meta.fields:
tundebabzy6015f0f2017-07-04 11:13:02 +0100257 # "Table" is part of `no_value_field` but we shouldn't ignore tables
Rohit Waghchaure0e28fcc2017-08-29 18:15:57 +0530258 if (field.reqd or field.fieldname in allow_fields) and field.fieldname not in exclude_fields:
Anand Doshi099bbbd2015-09-02 11:18:32 +0530259 if variant.get(field.fieldname) != item.get(field.fieldname):
Nabin Hait945f5022017-09-29 15:11:50 +0530260 if field.fieldtype == "Table":
261 variant.set(field.fieldname, [])
262 for d in item.get(field.fieldname):
263 row = copy.deepcopy(d)
264 if row.get("name"):
265 row.name = None
266 variant.append(field.fieldname, row)
267 else:
268 variant.set(field.fieldname, item.get(field.fieldname))
Nabin Haitc3144852017-09-28 18:55:40 +0530269
Anand Doshi099bbbd2015-09-02 11:18:32 +0530270 variant.variant_of = item.name
271 variant.has_variants = 0
Makarand Bauskarce436b72017-08-02 18:16:53 +0530272 if not variant.description:
Nabin Hait82c93522017-10-25 11:46:20 +0530273 variant.description = ""
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100274
275 if item.variant_based_on=='Item Attribute':
276 if variant.attributes:
Nabin Hait82c93522017-10-25 11:46:20 +0530277 attributes_description = ""
278 for d in variant.attributes:
279 attributes_description += "<div>" + d.attribute + ": " + cstr(d.attribute_value) + "</div>"
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530280
Nabin Hait82c93522017-10-25 11:46:20 +0530281 if attributes_description not in variant.description:
282 variant.description += attributes_description
Anand Doshi099bbbd2015-09-02 11:18:32 +0530283
Prateeksha Singh89cec182017-05-19 12:35:36 +0530284def make_variant_item_code(template_item_code, template_item_name, variant):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530285 """Uses template's item code and abbreviations to make variant's item code"""
286 if variant.item_code:
287 return
288
289 abbreviations = []
290 for attr in variant.attributes:
291 item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr
292 from `tabItem Attribute` i left join `tabItem Attribute Value` v
293 on (i.name=v.parent)
Rohit Waghchaure01693412017-03-09 17:02:55 +0530294 where i.name=%(attribute)s and (v.attribute_value=%(attribute_value)s or i.numeric_values = 1)""", {
Anand Doshi099bbbd2015-09-02 11:18:32 +0530295 "attribute": attr.attribute,
296 "attribute_value": attr.attribute_value
297 }, as_dict=True)
298
299 if not item_attribute:
Anand Doshi099bbbd2015-09-02 11:18:32 +0530300 return
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530301 # frappe.throw(_('Invalid attribute {0} {1}').format(frappe.bold(attr.attribute),
302 # frappe.bold(attr.attribute_value)), title=_('Invalid Attribute'),
303 # exc=InvalidItemAttributeValueError)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530304
Rohit Waghchaure01693412017-03-09 17:02:55 +0530305 abbr_or_value = cstr(attr.attribute_value) if item_attribute[0].numeric_values else item_attribute[0].abbr
306 abbreviations.append(abbr_or_value)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530307
308 if abbreviations:
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530309 variant.item_code = "{0}-{1}".format(template_item_code, "-".join(abbreviations))
Prateeksha Singh89cec182017-05-19 12:35:36 +0530310 variant.item_name = "{0}-{1}".format(template_item_name, "-".join(abbreviations))
Rushabh Mehtad5c64162017-11-14 15:27:28 +0530311
312@frappe.whitelist()
313def create_variant_doc_for_quick_entry(template, args):
314 variant_based_on = frappe.db.get_value("Item", template, "variant_based_on")
315 args = json.loads(args)
316 if variant_based_on == "Manufacturer":
317 variant = get_variant(template, **args)
318 else:
319 existing_variant = get_variant(template, args)
320 if existing_variant:
321 return existing_variant
322 else:
323 variant = create_variant(template, args=args)
324 variant.name = variant.item_code
325 validate_item_variant_attributes(variant, args)
326 return variant.as_dict()
327