blob: 2d6510854ed891427090c051e7de242cb1509a4a [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
Chillar Anand915b3432021-09-02 16:44:59 +05304
5import copy
6import json
7
Anand Doshi099bbbd2015-09-02 11:18:32 +05308import frappe
9from frappe import _
10from frappe.utils import cstr, flt
Achilles Rasquinha56b2e122018-02-13 14:42:40 +053011from six import string_types
12
Chillar Anand915b3432021-09-02 16:44:59 +053013
Anand Doshi099bbbd2015-09-02 11:18:32 +053014class ItemVariantExistsError(frappe.ValidationError): pass
15class InvalidItemAttributeValueError(frappe.ValidationError): pass
16class ItemTemplateCannotHaveStock(frappe.ValidationError): pass
17
18@frappe.whitelist()
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010019def get_variant(template, args=None, variant=None, manufacturer=None,
20 manufacturer_part_no=None):
21 """Validates Attributes and their Values, then looks for an exactly
22 matching Item Variant
Anand Doshi099bbbd2015-09-02 11:18:32 +053023
24 :param item: Template Item
25 :param args: A dictionary with "Attribute" as key and "Attribute Value" as value
26 """
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010027 item_template = frappe.get_doc('Item', template)
Anand Doshi099bbbd2015-09-02 11:18:32 +053028
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010029 if item_template.variant_based_on=='Manufacturer' and manufacturer:
30 return make_variant_based_on_manufacturer(item_template, manufacturer,
31 manufacturer_part_no)
32 else:
Achilles Rasquinha56b2e122018-02-13 14:42:40 +053033 if isinstance(args, string_types):
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010034 args = json.loads(args)
Anand Doshi099bbbd2015-09-02 11:18:32 +053035
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010036 if not args:
37 frappe.throw(_("Please specify at least one attribute in the Attributes table"))
38 return find_variant(template, args, variant)
39
40def make_variant_based_on_manufacturer(template, manufacturer, manufacturer_part_no):
41 '''Make and return a new variant based on manufacturer and
42 manufacturer part no'''
43 from frappe.model.naming import append_number_if_name_exists
44
45 variant = frappe.new_doc('Item')
46
47 copy_attributes_to_variant(template, variant)
48
Nabin Haitb6a89202017-04-25 17:27:53 +053049 variant.manufacturer = manufacturer
50 variant.manufacturer_part_no = manufacturer_part_no
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +010051
52 variant.item_code = append_number_if_name_exists('Item', template.name)
53
54 return variant
Anand Doshi099bbbd2015-09-02 11:18:32 +053055
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053056def validate_item_variant_attributes(item, args=None):
Achilles Rasquinha1697a7a2018-02-15 11:39:45 +053057 if isinstance(item, string_types):
Rushabh Mehta95383bb2016-07-15 15:11:46 +053058 item = frappe.get_doc('Item', item)
59
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +053060 if not args:
Rushabh Mehta20122ae2016-07-15 12:42:41 +053061 args = {d.attribute.lower():d.attribute_value for d in item.attributes}
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053062
Nabin Haitaaf378e2017-12-13 18:40:52 +053063 attribute_values, numeric_values = get_attribute_values(item)
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053064
Anand Doshi099bbbd2015-09-02 11:18:32 +053065 for attribute, value in args.items():
Rushabh Mehta95383bb2016-07-15 15:11:46 +053066 if not value:
67 continue
68
69 if attribute.lower() in numeric_values:
70 numeric_attribute = numeric_values[attribute.lower()]
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053071 validate_is_incremental(numeric_attribute, attribute, value, item.name)
Anand Doshi099bbbd2015-09-02 11:18:32 +053072
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053073 else:
74 attributes_list = attribute_values.get(attribute.lower(), [])
marination0df7f0f2020-06-01 11:56:33 +053075 validate_item_attribute_value(attributes_list, attribute, value, item.name, from_variant=True)
Anand Doshi099bbbd2015-09-02 11:18:32 +053076
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053077def validate_is_incremental(numeric_attribute, attribute, value, item):
78 from_range = numeric_attribute.from_range
79 to_range = numeric_attribute.to_range
80 increment = numeric_attribute.increment
Anand Doshi099bbbd2015-09-02 11:18:32 +053081
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053082 if increment == 0:
83 # defensive validation to prevent ZeroDivisionError
84 frappe.throw(_("Increment for Attribute {0} cannot be 0").format(attribute))
Anand Doshi099bbbd2015-09-02 11:18:32 +053085
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053086 is_in_range = from_range <= flt(value) <= to_range
87 precision = max(len(cstr(v).split(".")[-1].rstrip("0")) for v in (value, increment))
88 #avoid precision error by rounding the remainder
89 remainder = flt((flt(value) - from_range) % increment, precision)
Anand Doshi099bbbd2015-09-02 11:18:32 +053090
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053091 is_incremental = remainder==0 or remainder==increment
Rushabh Mehtaaed79e92016-06-02 17:49:16 +053092
Rohit Waghchaure6500ef42016-12-15 18:24:32 +053093 if not (is_in_range and is_incremental):
94 frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3} for Item {4}")\
95 .format(attribute, from_range, to_range, increment, item),
96 InvalidItemAttributeValueError, title=_('Invalid Attribute'))
97
marination0df7f0f2020-06-01 11:56:33 +053098def validate_item_attribute_value(attributes_list, attribute, attribute_value, item, from_variant=True):
Vishal Dhayagude668ec252018-03-07 15:31:08 +053099 allow_rename_attribute_value = frappe.db.get_single_value('Item Variant Settings', 'allow_rename_attribute_value')
100 if allow_rename_attribute_value:
101 pass
102 elif attribute_value not in attributes_list:
marination0df7f0f2020-06-01 11:56:33 +0530103 if from_variant:
104 frappe.throw(_("{0} is not a valid Value for Attribute {1} of Item {2}.").format(
105 frappe.bold(attribute_value), frappe.bold(attribute), frappe.bold(item)), InvalidItemAttributeValueError, title=_("Invalid Value"))
106 else:
marination91dfd002020-06-17 19:05:40 +0530107 msg = _("The value {0} is already assigned to an existing Item {1}.").format(
marination0df7f0f2020-06-01 11:56:33 +0530108 frappe.bold(attribute_value), frappe.bold(item))
109 msg += "<br>" + _("To still proceed with editing this Attribute Value, enable {0} in Item Variant Settings.").format(frappe.bold("Allow Rename Attribute Value"))
110
111 frappe.throw(msg, InvalidItemAttributeValueError, title=_('Edit Not Allowed'))
Anand Doshi099bbbd2015-09-02 11:18:32 +0530112
Nabin Haitaaf378e2017-12-13 18:40:52 +0530113def get_attribute_values(item):
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530114 if not frappe.flags.attribute_values:
115 attribute_values = {}
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530116 numeric_values = {}
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530117 for t in frappe.get_all("Item Attribute Value", fields=["parent", "attribute_value"]):
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530118 attribute_values.setdefault(t.parent.lower(), []).append(t.attribute_value)
119
Nabin Haitaaf378e2017-12-13 18:40:52 +0530120 for t in frappe.get_all('Item Variant Attribute',
121 fields=["attribute", "from_range", "to_range", "increment"],
122 filters={'numeric_values': 1, 'parent': item.variant_of}):
123 numeric_values[t.attribute.lower()] = t
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530124
125 frappe.flags.attribute_values = attribute_values
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530126 frappe.flags.numeric_values = numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530127
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530128 return frappe.flags.attribute_values, frappe.flags.numeric_values
Rushabh Mehtab8bdfbc2016-07-15 12:40:47 +0530129
Nabin Hait6b068e12015-12-31 13:20:32 +0530130def find_variant(template, args, variant_item_code=None):
Suraj Shettybfc195d2018-09-21 10:20:52 +0530131 conditions = ["""(iv_attribute.attribute={0} and iv_attribute.attribute_value={1})"""\
Anand Doshi099bbbd2015-09-02 11:18:32 +0530132 .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
133
134 conditions = " or ".join(conditions)
135
Faris Ansaricb03bb12019-05-03 13:41:50 +0530136 from erpnext.portal.product_configurator.utils import get_item_codes_by_attributes
137 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 +0530138
139 for variant in possible_variants:
140 variant = frappe.get_doc("Item", variant)
141
142 if len(args.keys()) == len(variant.get("attributes")):
143 # has the same number of attributes and values
144 # assuming no duplication as per the validation in Item
145 match_count = 0
146
147 for attribute, value in args.items():
148 for row in variant.attributes:
149 if row.attribute==attribute and row.attribute_value== cstr(value):
150 # this row matches
151 match_count += 1
152 break
153
154 if match_count == len(args.keys()):
155 return variant.name
156
157@frappe.whitelist()
158def create_variant(item, args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530159 if isinstance(args, string_types):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530160 args = json.loads(args)
161
162 template = frappe.get_doc("Item", item)
163 variant = frappe.new_doc("Item")
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100164 variant.variant_based_on = 'Item Attribute'
Anand Doshi099bbbd2015-09-02 11:18:32 +0530165 variant_attributes = []
166
167 for d in template.attributes:
168 variant_attributes.append({
169 "attribute": d.attribute,
170 "attribute_value": args.get(d.attribute)
171 })
172
173 variant.set("attributes", variant_attributes)
174 copy_attributes_to_variant(template, variant)
Prateeksha Singh89cec182017-05-19 12:35:36 +0530175 make_variant_item_code(template.item_code, template.item_name, variant)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530176
177 return variant
178
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530179@frappe.whitelist()
180def enqueue_multiple_variant_creation(item, args):
181 # There can be innumerable attribute combinations, enqueue
Charles-Henri Decultotbd06a5b2018-08-16 07:02:49 +0200182 if isinstance(args, string_types):
Ameya Shenoy935f4a42018-07-03 10:48:59 +0530183 variants = json.loads(args)
184 total_variants = 1
185 for key in variants:
186 total_variants *= len(variants[key])
187 if total_variants >= 600:
Anurag Mishra841d8522019-07-03 15:15:08 +0530188 frappe.throw(_("Please do not create more than 500 items at a time"))
Ameya Shenoy935f4a42018-07-03 10:48:59 +0530189 return
Rushabh Mehta87053712018-08-16 09:22:33 +0530190 if total_variants < 10:
191 return create_multiple_variants(item, args)
192 else:
193 frappe.enqueue("erpnext.controllers.item_variant.create_multiple_variants",
194 item=item, args=args, now=frappe.flags.in_test);
195 return 'queued'
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530196
197def create_multiple_variants(item, args):
Rushabh Mehta87053712018-08-16 09:22:33 +0530198 count = 0
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530199 if isinstance(args, string_types):
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530200 args = json.loads(args)
201
202 args_set = generate_keyed_value_combinations(args)
203
204 for attribute_values in args_set:
205 if not get_variant(item, args=attribute_values):
206 variant = create_variant(item, attribute_values)
207 variant.save()
Rushabh Mehta87053712018-08-16 09:22:33 +0530208 count +=1
209
210 return count
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530211
212def generate_keyed_value_combinations(args):
213 """
214 From this:
215
216 args = {"attr1": ["a", "b", "c"], "attr2": ["1", "2"], "attr3": ["A"]}
217
218 To this:
219
220 [
221 {u'attr1': u'a', u'attr2': u'1', u'attr3': u'A'},
222 {u'attr1': u'b', u'attr2': u'1', u'attr3': u'A'},
223 {u'attr1': u'c', u'attr2': u'1', u'attr3': u'A'},
224 {u'attr1': u'a', u'attr2': u'2', u'attr3': u'A'},
225 {u'attr1': u'b', u'attr2': u'2', u'attr3': u'A'},
226 {u'attr1': u'c', u'attr2': u'2', u'attr3': u'A'}
227 ]
228
229 """
230 # Return empty list if empty
231 if not args:
232 return []
233
234 # Turn `args` into a list of lists of key-value tuples:
235 # [
236 # [(u'attr2', u'1'), (u'attr2', u'2')],
237 # [(u'attr3', u'A')],
238 # [(u'attr1', u'a'), (u'attr1', u'b'), (u'attr1', u'c')]
239 # ]
240 key_value_lists = [[(key, val) for val in args[key]] for key in args.keys()]
241
242 # Store the first, but as objects
243 # [{u'attr2': u'1'}, {u'attr2': u'2'}]
244 results = key_value_lists.pop(0)
245 results = [{d[0]: d[1]} for d in results]
246
247 # Iterate the remaining
248 # Take the next list to fuse with existing results
249 for l in key_value_lists:
250 new_results = []
251 for res in results:
252 for key_val in l:
253 # create a new clone of object in result
254 obj = copy.deepcopy(res)
255 # to be used with every incoming new value
256 obj[key_val[0]] = key_val[1]
257 # and pushed into new_results
258 new_results.append(obj)
259 results = new_results
260
261 return results
262
Anand Doshi099bbbd2015-09-02 11:18:32 +0530263def copy_attributes_to_variant(item, variant):
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100264 # copy non no-copy fields
265
Nabin Haitc3144852017-09-28 18:55:40 +0530266 exclude_fields = ["naming_series", "item_code", "item_name", "show_in_website",
Ankush Menat9178d952021-04-26 15:37:17 +0530267 "show_variant_in_website", "opening_stock", "variant_of", "valuation_rate",
268 "has_variants", "attributes"]
Rushabh Mehtaa07c43f2017-03-21 17:48:34 +0100269
270 if item.variant_based_on=='Manufacturer':
271 # don't copy manufacturer values if based on part no
272 exclude_fields += ['manufacturer', 'manufacturer_part_no']
273
Rohit Waghchaure0e28fcc2017-08-29 18:15:57 +0530274 allow_fields = [d.field_name for d in frappe.get_all("Variant Field", fields = ['field_name'])]
Nabin Hait945f5022017-09-29 15:11:50 +0530275 if "variant_based_on" not in allow_fields:
276 allow_fields.append("variant_based_on")
Anand Doshi099bbbd2015-09-02 11:18:32 +0530277 for field in item.meta.fields:
tundebabzy6015f0f2017-07-04 11:13:02 +0100278 # "Table" is part of `no_value_field` but we shouldn't ignore tables
Rohit Waghchaure0e28fcc2017-08-29 18:15:57 +0530279 if (field.reqd or field.fieldname in allow_fields) and field.fieldname not in exclude_fields:
Anand Doshi099bbbd2015-09-02 11:18:32 +0530280 if variant.get(field.fieldname) != item.get(field.fieldname):
Nabin Hait945f5022017-09-29 15:11:50 +0530281 if field.fieldtype == "Table":
282 variant.set(field.fieldname, [])
283 for d in item.get(field.fieldname):
284 row = copy.deepcopy(d)
285 if row.get("name"):
286 row.name = None
287 variant.append(field.fieldname, row)
288 else:
289 variant.set(field.fieldname, item.get(field.fieldname))
Nabin Haitc3144852017-09-28 18:55:40 +0530290
Rohit Waghchaure0eef3f62018-06-13 13:06:25 +0530291 variant.variant_of = item.name
Anurag Mishra62d58ac2019-05-30 14:04:08 +0530292
293 if 'description' not in allow_fields:
hiousi38de9942018-04-24 08:40:45 +0200294 if not variant.description:
Nabin Hait34c551d2019-07-03 10:34:31 +0530295 variant.description = ""
Rucha Mahabalc6b548b2019-09-24 19:17:13 +0530296 else:
hiousi38de9942018-04-24 08:40:45 +0200297 if item.variant_based_on=='Item Attribute':
298 if variant.attributes:
Anurag Mishra62d58ac2019-05-30 14:04:08 +0530299 attributes_description = item.description + " "
hiousi38de9942018-04-24 08:40:45 +0200300 for d in variant.attributes:
301 attributes_description += "<div>" + d.attribute + ": " + cstr(d.attribute_value) + "</div>"
Prateeksha Singh8f43d252017-11-16 18:06:26 +0530302
hiousi38de9942018-04-24 08:40:45 +0200303 if attributes_description not in variant.description:
Rucha Mahabalc6b548b2019-09-24 19:17:13 +0530304 variant.description = attributes_description
Anand Doshi099bbbd2015-09-02 11:18:32 +0530305
Prateeksha Singh89cec182017-05-19 12:35:36 +0530306def make_variant_item_code(template_item_code, template_item_name, variant):
Anand Doshi099bbbd2015-09-02 11:18:32 +0530307 """Uses template's item code and abbreviations to make variant's item code"""
308 if variant.item_code:
309 return
310
311 abbreviations = []
312 for attr in variant.attributes:
313 item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr
314 from `tabItem Attribute` i left join `tabItem Attribute Value` v
315 on (i.name=v.parent)
Rohit Waghchaure01693412017-03-09 17:02:55 +0530316 where i.name=%(attribute)s and (v.attribute_value=%(attribute_value)s or i.numeric_values = 1)""", {
Anand Doshi099bbbd2015-09-02 11:18:32 +0530317 "attribute": attr.attribute,
318 "attribute_value": attr.attribute_value
319 }, as_dict=True)
320
321 if not item_attribute:
Faris Ansariab148922019-05-03 13:57:20 +0530322 continue
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530323 # frappe.throw(_('Invalid attribute {0} {1}').format(frappe.bold(attr.attribute),
324 # frappe.bold(attr.attribute_value)), title=_('Invalid Attribute'),
325 # exc=InvalidItemAttributeValueError)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530326
Rohit Waghchaure01693412017-03-09 17:02:55 +0530327 abbr_or_value = cstr(attr.attribute_value) if item_attribute[0].numeric_values else item_attribute[0].abbr
328 abbreviations.append(abbr_or_value)
Anand Doshi099bbbd2015-09-02 11:18:32 +0530329
330 if abbreviations:
Rushabh Mehta95383bb2016-07-15 15:11:46 +0530331 variant.item_code = "{0}-{1}".format(template_item_code, "-".join(abbreviations))
Prateeksha Singh89cec182017-05-19 12:35:36 +0530332 variant.item_name = "{0}-{1}".format(template_item_name, "-".join(abbreviations))
Rushabh Mehtad5c64162017-11-14 15:27:28 +0530333
334@frappe.whitelist()
335def create_variant_doc_for_quick_entry(template, args):
336 variant_based_on = frappe.db.get_value("Item", template, "variant_based_on")
337 args = json.loads(args)
338 if variant_based_on == "Manufacturer":
339 variant = get_variant(template, **args)
340 else:
341 existing_variant = get_variant(template, args)
342 if existing_variant:
343 return existing_variant
344 else:
345 variant = create_variant(template, args=args)
346 variant.name = variant.item_code
347 validate_item_variant_attributes(variant, args)
348 return variant.as_dict()