blob: 29f8dd57026fbbcfe083b95ad3ab19dfccd21683 [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:
Shivam Mishra7dedd9a2019-07-03 17:29:29 +0530101 frappe.throw(_("The value {0} is already assigned to an exisiting Item {2}.").format(
102 attribute_value, attribute, item), InvalidItemAttributeValueError, title=_('Rename Not Allowed'))
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):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530122 conditions = ["""(iv_attribute.attribute={0} and iv_attribute.attribute_value={1})"""\
Anand Doshi099bbbd2015-09-02 11:18:32 +0530123 .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
124
125 conditions = " or ".join(conditions)
126
Faris Ansaricb03bb12019-05-03 13:41:50 +0530127 from erpnext.portal.product_configurator.utils import get_item_codes_by_attributes
128 possible_variants = [i for i in get_item_codes_by_attributes(args, template) if i != variant_item_code]
Anand Doshi099bbbd2015-09-02 11:18:32 +0530129
130 for variant in possible_variants:
131 variant = frappe.get_doc("Item", variant)
132
133 if len(args.keys()) == len(variant.get("attributes")):
134 # has the same number of attributes and values
135 # assuming no duplication as per the validation in Item
136 match_count = 0
137
138 for attribute, value in args.items():
139 for row in variant.attributes:
140 if row.attribute==attribute and row.attribute_value== cstr(value):
141 # this row matches
142 match_count += 1
143 break
144
145 if match_count == len(args.keys()):
146 return variant.name
147
148@frappe.whitelist()
149def create_variant(item, args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530150 if isinstance(args, string_types):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530151 args = json.loads(args)
152
153 template = frappe.get_doc("Item", item)
154 variant = frappe.new_doc("Item")
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100155 variant.variant_based_on = 'Item Attribute'
Anand Doshi099bbbd2015-09-02 11:18:32 +0530156 variant_attributes = []
157
158 for d in template.attributes:
159 variant_attributes.append({
160 "attribute": d.attribute,
161 "attribute_value": args.get(d.attribute)
162 })
163
164 variant.set("attributes", variant_attributes)
165 copy_attributes_to_variant(template, variant)
Prateeksha Singh89cec182017-05-19 12:35:36 +0530166 make_variant_item_code(template.item_code, template.item_name, variant)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530167
168 return variant
169
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530170@frappe.whitelist()
171def enqueue_multiple_variant_creation(item, args):
172 # There can be innumerable attribute combinations, enqueue
Charles-Henri Decultotbd06a5b2018-08-16 07:02:49 +0200173 if isinstance(args, string_types):
Ameya Shenoy935f4a42018-07-03 10:48:59 +0530174 variants = json.loads(args)
175 total_variants = 1
176 for key in variants:
177 total_variants *= len(variants[key])
178 if total_variants >= 600:
Anurag Mishra841d8522019-07-03 15:15:08 +0530179 frappe.throw(_("Please do not create more than 500 items at a time"))
Ameya Shenoy935f4a42018-07-03 10:48:59 +0530180 return
Rushabh Mehta87053712018-08-16 09:22:33 +0530181 if total_variants < 10:
182 return create_multiple_variants(item, args)
183 else:
184 frappe.enqueue("erpnext.controllers.item_variant.create_multiple_variants",
185 item=item, args=args, now=frappe.flags.in_test);
186 return 'queued'
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530187
188def create_multiple_variants(item, args):
Rushabh Mehta87053712018-08-16 09:22:33 +0530189 count = 0
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530190 if isinstance(args, string_types):
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530191 args = json.loads(args)
192
193 args_set = generate_keyed_value_combinations(args)
194
195 for attribute_values in args_set:
196 if not get_variant(item, args=attribute_values):
197 variant = create_variant(item, attribute_values)
198 variant.save()
Rushabh Mehta87053712018-08-16 09:22:33 +0530199 count +=1
200
201 return count
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530202
203def generate_keyed_value_combinations(args):
204 """
205 From this:
206
207 args = {"attr1": ["a", "b", "c"], "attr2": ["1", "2"], "attr3": ["A"]}
208
209 To this:
210
211 [
212 {u'attr1': u'a', u'attr2': u'1', u'attr3': u'A'},
213 {u'attr1': u'b', u'attr2': u'1', u'attr3': u'A'},
214 {u'attr1': u'c', u'attr2': u'1', u'attr3': u'A'},
215 {u'attr1': u'a', u'attr2': u'2', u'attr3': u'A'},
216 {u'attr1': u'b', u'attr2': u'2', u'attr3': u'A'},
217 {u'attr1': u'c', u'attr2': u'2', u'attr3': u'A'}
218 ]
219
220 """
221 # Return empty list if empty
222 if not args:
223 return []
224
225 # Turn `args` into a list of lists of key-value tuples:
226 # [
227 # [(u'attr2', u'1'), (u'attr2', u'2')],
228 # [(u'attr3', u'A')],
229 # [(u'attr1', u'a'), (u'attr1', u'b'), (u'attr1', u'c')]
230 # ]
231 key_value_lists = [[(key, val) for val in args[key]] for key in args.keys()]
232
233 # Store the first, but as objects
234 # [{u'attr2': u'1'}, {u'attr2': u'2'}]
235 results = key_value_lists.pop(0)
236 results = [{d[0]: d[1]} for d in results]
237
238 # Iterate the remaining
239 # Take the next list to fuse with existing results
240 for l in key_value_lists:
241 new_results = []
242 for res in results:
243 for key_val in l:
244 # create a new clone of object in result
245 obj = copy.deepcopy(res)
246 # to be used with every incoming new value
247 obj[key_val[0]] = key_val[1]
248 # and pushed into new_results
249 new_results.append(obj)
250 results = new_results
251
252 return results
253
Anand Doshi099bbbd2015-09-02 11:18:32 +0530254def copy_attributes_to_variant(item, variant):
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100255 # copy non no-copy fields
256
Nabin Haitc3144852017-09-28 18:55:40 +0530257 exclude_fields = ["naming_series", "item_code", "item_name", "show_in_website",
Nabin Hait945f5022017-09-29 15:11:50 +0530258 "show_variant_in_website", "opening_stock", "variant_of", "valuation_rate"]
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100259
260 if item.variant_based_on=='Manufacturer':
261 # don't copy manufacturer values if based on part no
262 exclude_fields += ['manufacturer', 'manufacturer_part_no']
263
Rohit Waghchaure0e28fcc2017-08-29 18:15:57 +0530264 allow_fields = [d.field_name for d in frappe.get_all("Variant Field", fields = ['field_name'])]
Nabin Hait945f5022017-09-29 15:11:50 +0530265 if "variant_based_on" not in allow_fields:
266 allow_fields.append("variant_based_on")
Anand Doshi099bbbd2015-09-02 11:18:32 +0530267 for field in item.meta.fields:
tundebabzy6015f0f2017-07-04 11:13:02 +0100268 # "Table" is part of `no_value_field` but we shouldn't ignore tables
Rohit Waghchaure0e28fcc2017-08-29 18:15:57 +0530269 if (field.reqd or field.fieldname in allow_fields) and field.fieldname not in exclude_fields:
Anand Doshi099bbbd2015-09-02 11:18:32 +0530270 if variant.get(field.fieldname) != item.get(field.fieldname):
Nabin Hait945f5022017-09-29 15:11:50 +0530271 if field.fieldtype == "Table":
272 variant.set(field.fieldname, [])
273 for d in item.get(field.fieldname):
274 row = copy.deepcopy(d)
275 if row.get("name"):
276 row.name = None
277 variant.append(field.fieldname, row)
278 else:
279 variant.set(field.fieldname, item.get(field.fieldname))
Nabin Haitc3144852017-09-28 18:55:40 +0530280
Rohit Waghchaure0eef3f62018-06-13 13:06:25 +0530281 variant.variant_of = item.name
Anurag Mishra62d58ac2019-05-30 14:04:08 +0530282
283 if 'description' not in allow_fields:
hiousi38de9942018-04-24 08:40:45 +0200284 if not variant.description:
Nabin Hait34c551d2019-07-03 10:34:31 +0530285 variant.description = ""
Rucha Mahabalc6b548b2019-09-24 19:17:13 +0530286 else:
hiousi38de9942018-04-24 08:40:45 +0200287 if item.variant_based_on=='Item Attribute':
288 if variant.attributes:
Anurag Mishra62d58ac2019-05-30 14:04:08 +0530289 attributes_description = item.description + " "
hiousi38de9942018-04-24 08:40:45 +0200290 for d in variant.attributes:
291 attributes_description += "<div>" + d.attribute + ": " + cstr(d.attribute_value) + "</div>"
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530292
hiousi38de9942018-04-24 08:40:45 +0200293 if attributes_description not in variant.description:
Rucha Mahabalc6b548b2019-09-24 19:17:13 +0530294 variant.description = attributes_description
Anand Doshi099bbbd2015-09-02 11:18:32 +0530295
Prateeksha Singh89cec182017-05-19 12:35:36 +0530296def make_variant_item_code(template_item_code, template_item_name, variant):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530297 """Uses template's item code and abbreviations to make variant's item code"""
298 if variant.item_code:
299 return
300
301 abbreviations = []
302 for attr in variant.attributes:
303 item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr
304 from `tabItem Attribute` i left join `tabItem Attribute Value` v
305 on (i.name=v.parent)
Rohit Waghchaure01693412017-03-09 17:02:55 +0530306 where i.name=%(attribute)s and (v.attribute_value=%(attribute_value)s or i.numeric_values = 1)""", {
Anand Doshi099bbbd2015-09-02 11:18:32 +0530307 "attribute": attr.attribute,
308 "attribute_value": attr.attribute_value
309 }, as_dict=True)
310
311 if not item_attribute:
Faris Ansariab148922019-05-03 13:57:20 +0530312 continue
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530313 # frappe.throw(_('Invalid attribute {0} {1}').format(frappe.bold(attr.attribute),
314 # frappe.bold(attr.attribute_value)), title=_('Invalid Attribute'),
315 # exc=InvalidItemAttributeValueError)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530316
Rohit Waghchaure01693412017-03-09 17:02:55 +0530317 abbr_or_value = cstr(attr.attribute_value) if item_attribute[0].numeric_values else item_attribute[0].abbr
318 abbreviations.append(abbr_or_value)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530319
320 if abbreviations:
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530321 variant.item_code = "{0}-{1}".format(template_item_code, "-".join(abbreviations))
Prateeksha Singh89cec182017-05-19 12:35:36 +0530322 variant.item_name = "{0}-{1}".format(template_item_name, "-".join(abbreviations))
Rushabh Mehtad5c64162017-11-14 15:27:28 +0530323
324@frappe.whitelist()
325def create_variant_doc_for_quick_entry(template, args):
326 variant_based_on = frappe.db.get_value("Item", template, "variant_based_on")
327 args = json.loads(args)
328 if variant_based_on == "Manufacturer":
329 variant = get_variant(template, **args)
330 else:
331 existing_variant = get_variant(template, args)
332 if existing_variant:
333 return existing_variant
334 else:
335 variant = create_variant(template, args=args)
336 variant.name = variant.item_code
337 validate_item_variant_attributes(variant, args)
338 return variant.as_dict()
339