blob: a54411903ca9385b90d68131b49541e9d404ccaf [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
Achilles Rasquinha56b2e122018-02-13 14:42:40 +053010from six import string_types
11
Anand Doshi099bbbd2015-09-02 11:18:32 +053012class ItemVariantExistsError(frappe.ValidationError): pass
13class InvalidItemAttributeValueError(frappe.ValidationError): pass
14class ItemTemplateCannotHaveStock(frappe.ValidationError): pass
15
16@frappe.whitelist()
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010017def get_variant(template, args=None, variant=None, manufacturer=None,
18 manufacturer_part_no=None):
19 """Validates Attributes and their Values, then looks for an exactly
20 matching Item Variant
Anand Doshi099bbbd2015-09-02 11:18:32 +053021
22 :param item: Template Item
23 :param args: A dictionary with "Attribute" as key and "Attribute Value" as value
24 """
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010025 item_template = frappe.get_doc('Item', template)
Anand Doshi099bbbd2015-09-02 11:18:32 +053026
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010027 if item_template.variant_based_on=='Manufacturer' and manufacturer:
28 return make_variant_based_on_manufacturer(item_template, manufacturer,
29 manufacturer_part_no)
30 else:
Achilles Rasquinha56b2e122018-02-13 14:42:40 +053031 if isinstance(args, string_types):
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010032 args = json.loads(args)
Anand Doshi099bbbd2015-09-02 11:18:32 +053033
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010034 if not args:
35 frappe.throw(_("Please specify at least one attribute in the Attributes table"))
36 return find_variant(template, args, variant)
37
38def make_variant_based_on_manufacturer(template, manufacturer, manufacturer_part_no):
39 '''Make and return a new variant based on manufacturer and
40 manufacturer part no'''
41 from frappe.model.naming import append_number_if_name_exists
42
43 variant = frappe.new_doc('Item')
44
45 copy_attributes_to_variant(template, variant)
46
Nabin Haitb6a89202017-04-25 17:27:53 +053047 variant.manufacturer = manufacturer
48 variant.manufacturer_part_no = manufacturer_part_no
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010049
50 variant.item_code = append_number_if_name_exists('Item', template.name)
51
52 return variant
Anand Doshi099bbbd2015-09-02 11:18:32 +053053
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053054def validate_item_variant_attributes(item, args=None):
Achilles Rasquinha1697a7a2018-02-15 11:39:45 +053055 if isinstance(item, string_types):
Rushabh Mehta95383bb2016-07-15 15:11:46 +053056 item = frappe.get_doc('Item', item)
57
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053058 if not args:
Rushabh Mehta20122ae2016-07-15 12:42:41 +053059 args = {d.attribute.lower():d.attribute_value for d in item.attributes}
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053060
Nabin Haitaaf378e2017-12-13 18:40:52 +053061 attribute_values, numeric_values = get_attribute_values(item)
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053062
Anand Doshi099bbbd2015-09-02 11:18:32 +053063 for attribute, value in args.items():
Rushabh Mehta95383bb2016-07-15 15:11:46 +053064 if not value:
65 continue
66
67 if attribute.lower() in numeric_values:
68 numeric_attribute = numeric_values[attribute.lower()]
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053069 validate_is_incremental(numeric_attribute, attribute, value, item.name)
Anand Doshi099bbbd2015-09-02 11:18:32 +053070
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053071 else:
72 attributes_list = attribute_values.get(attribute.lower(), [])
73 validate_item_attribute_value(attributes_list, attribute, value, item.name)
Anand Doshi099bbbd2015-09-02 11:18:32 +053074
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053075def validate_is_incremental(numeric_attribute, attribute, value, item):
76 from_range = numeric_attribute.from_range
77 to_range = numeric_attribute.to_range
78 increment = numeric_attribute.increment
Anand Doshi099bbbd2015-09-02 11:18:32 +053079
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053080 if increment == 0:
81 # defensive validation to prevent ZeroDivisionError
82 frappe.throw(_("Increment for Attribute {0} cannot be 0").format(attribute))
Anand Doshi099bbbd2015-09-02 11:18:32 +053083
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053084 is_in_range = from_range <= flt(value) <= to_range
85 precision = max(len(cstr(v).split(".")[-1].rstrip("0")) for v in (value, increment))
86 #avoid precision error by rounding the remainder
87 remainder = flt((flt(value) - from_range) % increment, precision)
Anand Doshi099bbbd2015-09-02 11:18:32 +053088
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053089 is_incremental = remainder==0 or remainder==increment
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053090
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053091 if not (is_in_range and is_incremental):
92 frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3} for Item {4}")\
93 .format(attribute, from_range, to_range, increment, item),
94 InvalidItemAttributeValueError, title=_('Invalid Attribute'))
95
96def validate_item_attribute_value(attributes_list, attribute, attribute_value, item):
Vishal Dhayagude668ec252018-03-07 15:31:08 +053097 allow_rename_attribute_value = frappe.db.get_single_value('Item Variant Settings', 'allow_rename_attribute_value')
98 if allow_rename_attribute_value:
99 pass
100 elif attribute_value not in attributes_list:
Rohit Waghchaure6500ef42016-12-15 18:24:32 +0530101 frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values for Item {2}").format(
102 attribute_value, attribute, item), InvalidItemAttributeValueError, title=_('Invalid Attribute'))
Anand Doshi099bbbd2015-09-02 11:18:32 +0530103
Nabin Haitaaf378e2017-12-13 18:40:52 +0530104def get_attribute_values(item):
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530105 if not frappe.flags.attribute_values:
106 attribute_values = {}
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530107 numeric_values = {}
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530108 for t in frappe.get_all("Item Attribute Value", fields=["parent", "attribute_value"]):
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530109 attribute_values.setdefault(t.parent.lower(), []).append(t.attribute_value)
110
Nabin Haitaaf378e2017-12-13 18:40:52 +0530111 for t in frappe.get_all('Item Variant Attribute',
112 fields=["attribute", "from_range", "to_range", "increment"],
113 filters={'numeric_values': 1, 'parent': item.variant_of}):
114 numeric_values[t.attribute.lower()] = t
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530115
116 frappe.flags.attribute_values = attribute_values
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530117 frappe.flags.numeric_values = numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530118
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530119 return frappe.flags.attribute_values, frappe.flags.numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530120
Nabin Hait6b068e12015-12-31 13:20:32 +0530121def find_variant(template, args, variant_item_code=None):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530122 conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\
123 .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
124
125 conditions = " or ".join(conditions)
126
127 # use approximate match and shortlist possible variant matches
128 # it is approximate because we are matching using OR condition
129 # and it need not be exact match at this stage
130 # this uses a simpler query instead of using multiple exists conditions
131 possible_variants = frappe.db.sql_list("""select name from `tabItem` item
132 where variant_of=%s and exists (
133 select name from `tabItem Variant Attribute` iv_attribute
134 where iv_attribute.parent=item.name
Nabin Hait6626e322015-12-31 13:20:32 +0530135 and ({conditions}) and parent != %s
Nabin Hait6b068e12015-12-31 13:20:32 +0530136 )""".format(conditions=conditions), (template, cstr(variant_item_code)))
Anand Doshi099bbbd2015-09-02 11:18:32 +0530137
138 for variant in possible_variants:
139 variant = frappe.get_doc("Item", variant)
140
141 if len(args.keys()) == len(variant.get("attributes")):
142 # has the same number of attributes and values
143 # assuming no duplication as per the validation in Item
144 match_count = 0
145
146 for attribute, value in args.items():
147 for row in variant.attributes:
148 if row.attribute==attribute and row.attribute_value== cstr(value):
149 # this row matches
150 match_count += 1
151 break
152
153 if match_count == len(args.keys()):
154 return variant.name
155
156@frappe.whitelist()
157def create_variant(item, args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530158 if isinstance(args, string_types):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530159 args = json.loads(args)
160
161 template = frappe.get_doc("Item", item)
162 variant = frappe.new_doc("Item")
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100163 variant.variant_based_on = 'Item Attribute'
Anand Doshi099bbbd2015-09-02 11:18:32 +0530164 variant_attributes = []
165
166 for d in template.attributes:
167 variant_attributes.append({
168 "attribute": d.attribute,
169 "attribute_value": args.get(d.attribute)
170 })
171
172 variant.set("attributes", variant_attributes)
173 copy_attributes_to_variant(template, variant)
Prateeksha Singh89cec182017-05-19 12:35:36 +0530174 make_variant_item_code(template.item_code, template.item_name, variant)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530175
176 return variant
177
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530178@frappe.whitelist()
179def enqueue_multiple_variant_creation(item, args):
180 # There can be innumerable attribute combinations, enqueue
181 frappe.enqueue("erpnext.controllers.item_variant.create_multiple_variants",
182 item=item, args=args, now=frappe.flags.in_test);
183
184def create_multiple_variants(item, args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530185 if isinstance(args, string_types):
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530186 args = json.loads(args)
187
188 args_set = generate_keyed_value_combinations(args)
189
190 for attribute_values in args_set:
191 if not get_variant(item, args=attribute_values):
192 variant = create_variant(item, attribute_values)
193 variant.save()
194
195def generate_keyed_value_combinations(args):
196 """
197 From this:
198
199 args = {"attr1": ["a", "b", "c"], "attr2": ["1", "2"], "attr3": ["A"]}
200
201 To this:
202
203 [
204 {u'attr1': u'a', u'attr2': u'1', u'attr3': u'A'},
205 {u'attr1': u'b', u'attr2': u'1', u'attr3': u'A'},
206 {u'attr1': u'c', u'attr2': u'1', u'attr3': u'A'},
207 {u'attr1': u'a', u'attr2': u'2', u'attr3': u'A'},
208 {u'attr1': u'b', u'attr2': u'2', u'attr3': u'A'},
209 {u'attr1': u'c', u'attr2': u'2', u'attr3': u'A'}
210 ]
211
212 """
213 # Return empty list if empty
214 if not args:
215 return []
216
217 # Turn `args` into a list of lists of key-value tuples:
218 # [
219 # [(u'attr2', u'1'), (u'attr2', u'2')],
220 # [(u'attr3', u'A')],
221 # [(u'attr1', u'a'), (u'attr1', u'b'), (u'attr1', u'c')]
222 # ]
223 key_value_lists = [[(key, val) for val in args[key]] for key in args.keys()]
224
225 # Store the first, but as objects
226 # [{u'attr2': u'1'}, {u'attr2': u'2'}]
227 results = key_value_lists.pop(0)
228 results = [{d[0]: d[1]} for d in results]
229
230 # Iterate the remaining
231 # Take the next list to fuse with existing results
232 for l in key_value_lists:
233 new_results = []
234 for res in results:
235 for key_val in l:
236 # create a new clone of object in result
237 obj = copy.deepcopy(res)
238 # to be used with every incoming new value
239 obj[key_val[0]] = key_val[1]
240 # and pushed into new_results
241 new_results.append(obj)
242 results = new_results
243
244 return results
245
Anand Doshi099bbbd2015-09-02 11:18:32 +0530246def copy_attributes_to_variant(item, variant):
247 from frappe.model import no_value_fields
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100248
249 # copy non no-copy fields
250
Nabin Haitc3144852017-09-28 18:55:40 +0530251 exclude_fields = ["naming_series", "item_code", "item_name", "show_in_website",
Nabin Hait945f5022017-09-29 15:11:50 +0530252 "show_variant_in_website", "opening_stock", "variant_of", "valuation_rate"]
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100253
254 if item.variant_based_on=='Manufacturer':
255 # don't copy manufacturer values if based on part no
256 exclude_fields += ['manufacturer', 'manufacturer_part_no']
257
Rohit Waghchaure0e28fcc2017-08-29 18:15:57 +0530258 allow_fields = [d.field_name for d in frappe.get_all("Variant Field", fields = ['field_name'])]
Nabin Hait945f5022017-09-29 15:11:50 +0530259 if "variant_based_on" not in allow_fields:
260 allow_fields.append("variant_based_on")
Anand Doshi099bbbd2015-09-02 11:18:32 +0530261 for field in item.meta.fields:
tundebabzy6015f0f2017-07-04 11:13:02 +0100262 # "Table" is part of `no_value_field` but we shouldn't ignore tables
Rohit Waghchaure0e28fcc2017-08-29 18:15:57 +0530263 if (field.reqd or field.fieldname in allow_fields) and field.fieldname not in exclude_fields:
Anand Doshi099bbbd2015-09-02 11:18:32 +0530264 if variant.get(field.fieldname) != item.get(field.fieldname):
Nabin Hait945f5022017-09-29 15:11:50 +0530265 if field.fieldtype == "Table":
266 variant.set(field.fieldname, [])
267 for d in item.get(field.fieldname):
268 row = copy.deepcopy(d)
269 if row.get("name"):
270 row.name = None
271 variant.append(field.fieldname, row)
272 else:
273 variant.set(field.fieldname, item.get(field.fieldname))
Nabin Haitc3144852017-09-28 18:55:40 +0530274
hiousi38de9942018-04-24 08:40:45 +0200275 if 'description' in allow_fields:
276 variant.variant_of = item.name
277 variant.has_variants = 0
278 if not variant.description:
279 variant.description = ""
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100280
hiousi38de9942018-04-24 08:40:45 +0200281 if item.variant_based_on=='Item Attribute':
282 if variant.attributes:
283 attributes_description = ""
284 for d in variant.attributes:
285 attributes_description += "<div>" + d.attribute + ": " + cstr(d.attribute_value) + "</div>"
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530286
hiousi38de9942018-04-24 08:40:45 +0200287 if attributes_description not in variant.description:
Nabin Hait82c93522017-10-25 11:46:20 +0530288 variant.description += attributes_description
Anand Doshi099bbbd2015-09-02 11:18:32 +0530289
Prateeksha Singh89cec182017-05-19 12:35:36 +0530290def make_variant_item_code(template_item_code, template_item_name, variant):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530291 """Uses template's item code and abbreviations to make variant's item code"""
292 if variant.item_code:
293 return
294
295 abbreviations = []
296 for attr in variant.attributes:
297 item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr
298 from `tabItem Attribute` i left join `tabItem Attribute Value` v
299 on (i.name=v.parent)
Rohit Waghchaure01693412017-03-09 17:02:55 +0530300 where i.name=%(attribute)s and (v.attribute_value=%(attribute_value)s or i.numeric_values = 1)""", {
Anand Doshi099bbbd2015-09-02 11:18:32 +0530301 "attribute": attr.attribute,
302 "attribute_value": attr.attribute_value
303 }, as_dict=True)
304
305 if not item_attribute:
Anand Doshi099bbbd2015-09-02 11:18:32 +0530306 return
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530307 # frappe.throw(_('Invalid attribute {0} {1}').format(frappe.bold(attr.attribute),
308 # frappe.bold(attr.attribute_value)), title=_('Invalid Attribute'),
309 # exc=InvalidItemAttributeValueError)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530310
Rohit Waghchaure01693412017-03-09 17:02:55 +0530311 abbr_or_value = cstr(attr.attribute_value) if item_attribute[0].numeric_values else item_attribute[0].abbr
312 abbreviations.append(abbr_or_value)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530313
314 if abbreviations:
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530315 variant.item_code = "{0}-{1}".format(template_item_code, "-".join(abbreviations))
Prateeksha Singh89cec182017-05-19 12:35:36 +0530316 variant.item_name = "{0}-{1}".format(template_item_name, "-".join(abbreviations))
Rushabh Mehtad5c64162017-11-14 15:27:28 +0530317
318@frappe.whitelist()
319def create_variant_doc_for_quick_entry(template, args):
320 variant_based_on = frappe.db.get_value("Item", template, "variant_based_on")
321 args = json.loads(args)
322 if variant_based_on == "Manufacturer":
323 variant = get_variant(template, **args)
324 else:
325 existing_variant = get_variant(template, args)
326 if existing_variant:
327 return existing_variant
328 else:
329 variant = create_variant(template, args=args)
330 variant.name = variant.item_code
331 validate_item_variant_attributes(variant, args)
332 return variant.as_dict()
333