Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 1 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors |
| 2 | # License: GNU General Public License v3. See license.txt |
| 3 | |
| 4 | from __future__ import unicode_literals |
| 5 | import frappe |
| 6 | from frappe import _ |
| 7 | from frappe.utils import cstr, flt |
| 8 | import json |
| 9 | |
| 10 | class ItemVariantExistsError(frappe.ValidationError): pass |
| 11 | class InvalidItemAttributeValueError(frappe.ValidationError): pass |
| 12 | class ItemTemplateCannotHaveStock(frappe.ValidationError): pass |
| 13 | |
| 14 | @frappe.whitelist() |
Nabin Hait | 6b068e1 | 2015-12-31 13:20:32 +0530 | [diff] [blame] | 15 | def get_variant(template, args, variant=None): |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 16 | """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 Hait | 6626e32 | 2015-12-31 13:20:32 +0530 | [diff] [blame] | 27 | validate_item_variant_attributes(template, args) |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 28 | |
Nabin Hait | 6b068e1 | 2015-12-31 13:20:32 +0530 | [diff] [blame] | 29 | return find_variant(template, args, variant) |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 30 | |
Rushabh Mehta | b8bdfbc | 2016-07-15 12:40:47 +0530 | [diff] [blame] | 31 | def validate_item_variant_attributes(item, args=None): |
| 32 | if not args: |
Rushabh Mehta | 20122ae | 2016-07-15 12:42:41 +0530 | [diff] [blame^] | 33 | args = {d.attribute.lower():d.attribute_value for d in item.attributes} |
Rushabh Mehta | aed79e9 | 2016-06-02 17:49:16 +0530 | [diff] [blame] | 34 | |
Rushabh Mehta | b8bdfbc | 2016-07-15 12:40:47 +0530 | [diff] [blame] | 35 | attribute_values = get_attribute_values() |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 36 | |
Rushabh Mehta | 20122ae | 2016-07-15 12:42:41 +0530 | [diff] [blame^] | 37 | numeric_attributes = frappe._dict({d.attribute.lower(): d for d |
Rushabh Mehta | b8bdfbc | 2016-07-15 12:40:47 +0530 | [diff] [blame] | 38 | in item.attributes if d.numeric_values==1}) |
Rushabh Mehta | aed79e9 | 2016-06-02 17:49:16 +0530 | [diff] [blame] | 39 | |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 40 | for attribute, value in args.items(): |
Saurabh | 47fd5e0 | 2016-01-21 15:46:55 +0530 | [diff] [blame] | 41 | if attribute.lower() in numeric_attributes: |
| 42 | numeric_attribute = numeric_attributes[attribute.lower()] |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 43 | |
| 44 | from_range = numeric_attribute.from_range |
| 45 | to_range = numeric_attribute.to_range |
| 46 | increment = numeric_attribute.increment |
| 47 | |
| 48 | if increment == 0: |
| 49 | # defensive validation to prevent ZeroDivisionError |
| 50 | frappe.throw(_("Increment for Attribute {0} cannot be 0").format(attribute)) |
| 51 | |
| 52 | is_in_range = from_range <= flt(value) <= to_range |
Neil Trini Lasrado | a4fad72 | 2015-10-20 11:58:07 +0530 | [diff] [blame] | 53 | precision = max(len(cstr(v).split(".")[-1].rstrip("0")) for v in (value, increment)) |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 54 | #avoid precision error by rounding the remainder |
| 55 | remainder = flt((flt(value) - from_range) % increment, precision) |
| 56 | |
Rushabh Mehta | b8bdfbc | 2016-07-15 12:40:47 +0530 | [diff] [blame] | 57 | is_incremental = remainder==0 or remainder==increment |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 58 | |
| 59 | if not (is_in_range and is_incremental): |
| 60 | frappe.throw(_("Value for Attribute {0} must be within the range of {1} to {2} in the increments of {3}")\ |
| 61 | .format(attribute, from_range, to_range, increment), InvalidItemAttributeValueError) |
Rushabh Mehta | aed79e9 | 2016-06-02 17:49:16 +0530 | [diff] [blame] | 62 | |
Saurabh | 47fd5e0 | 2016-01-21 15:46:55 +0530 | [diff] [blame] | 63 | elif value not in attribute_values.get(attribute.lower(), []): |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 64 | frappe.throw(_("Value {0} for Attribute {1} does not exist in the list of valid Item Attribute Values").format( |
Rushabh Mehta | aed79e9 | 2016-06-02 17:49:16 +0530 | [diff] [blame] | 65 | value, attribute), InvalidItemAttributeValueError) |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 66 | |
Rushabh Mehta | b8bdfbc | 2016-07-15 12:40:47 +0530 | [diff] [blame] | 67 | def get_attribute_values(): |
| 68 | if not frappe.flags.attribute_values: |
| 69 | attribute_values = {} |
| 70 | for t in frappe.get_all("Item Attribute Value", fields=["parent", "attribute_value"]): |
| 71 | (attribute_values.setdefault(t.parent.lower(), [])).append(t.attribute_value) |
| 72 | |
| 73 | frappe.flags.attribute_values = attribute_values |
| 74 | |
| 75 | return frappe.flags.attribute_values |
| 76 | |
Nabin Hait | 6b068e1 | 2015-12-31 13:20:32 +0530 | [diff] [blame] | 77 | def find_variant(template, args, variant_item_code=None): |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 78 | conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\ |
| 79 | .format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()] |
| 80 | |
| 81 | conditions = " or ".join(conditions) |
| 82 | |
| 83 | # use approximate match and shortlist possible variant matches |
| 84 | # it is approximate because we are matching using OR condition |
| 85 | # and it need not be exact match at this stage |
| 86 | # this uses a simpler query instead of using multiple exists conditions |
| 87 | possible_variants = frappe.db.sql_list("""select name from `tabItem` item |
| 88 | where variant_of=%s and exists ( |
| 89 | select name from `tabItem Variant Attribute` iv_attribute |
| 90 | where iv_attribute.parent=item.name |
Nabin Hait | 6626e32 | 2015-12-31 13:20:32 +0530 | [diff] [blame] | 91 | and ({conditions}) and parent != %s |
Nabin Hait | 6b068e1 | 2015-12-31 13:20:32 +0530 | [diff] [blame] | 92 | )""".format(conditions=conditions), (template, cstr(variant_item_code))) |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 93 | |
| 94 | for variant in possible_variants: |
| 95 | variant = frappe.get_doc("Item", variant) |
| 96 | |
| 97 | if len(args.keys()) == len(variant.get("attributes")): |
| 98 | # has the same number of attributes and values |
| 99 | # assuming no duplication as per the validation in Item |
| 100 | match_count = 0 |
| 101 | |
| 102 | for attribute, value in args.items(): |
| 103 | for row in variant.attributes: |
| 104 | if row.attribute==attribute and row.attribute_value== cstr(value): |
| 105 | # this row matches |
| 106 | match_count += 1 |
| 107 | break |
| 108 | |
| 109 | if match_count == len(args.keys()): |
| 110 | return variant.name |
| 111 | |
| 112 | @frappe.whitelist() |
| 113 | def create_variant(item, args): |
| 114 | if isinstance(args, basestring): |
| 115 | args = json.loads(args) |
| 116 | |
| 117 | template = frappe.get_doc("Item", item) |
| 118 | variant = frappe.new_doc("Item") |
| 119 | variant_attributes = [] |
| 120 | |
| 121 | for d in template.attributes: |
| 122 | variant_attributes.append({ |
| 123 | "attribute": d.attribute, |
| 124 | "attribute_value": args.get(d.attribute) |
| 125 | }) |
| 126 | |
| 127 | variant.set("attributes", variant_attributes) |
| 128 | copy_attributes_to_variant(template, variant) |
| 129 | make_variant_item_code(template, variant) |
| 130 | |
| 131 | return variant |
| 132 | |
| 133 | def copy_attributes_to_variant(item, variant): |
| 134 | from frappe.model import no_value_fields |
| 135 | for field in item.meta.fields: |
| 136 | if field.fieldtype not in no_value_fields and (not field.no_copy)\ |
Anand Doshi | 7c0eadb | 2015-10-20 17:30:02 +0530 | [diff] [blame] | 137 | and field.fieldname not in ("item_code", "item_name", "show_in_website"): |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 138 | if variant.get(field.fieldname) != item.get(field.fieldname): |
| 139 | variant.set(field.fieldname, item.get(field.fieldname)) |
| 140 | variant.variant_of = item.name |
| 141 | variant.has_variants = 0 |
Anand Doshi | 099bbbd | 2015-09-02 11:18:32 +0530 | [diff] [blame] | 142 | if variant.attributes: |
| 143 | variant.description += "\n" |
| 144 | for d in variant.attributes: |
| 145 | variant.description += "<p>" + d.attribute + ": " + cstr(d.attribute_value) + "</p>" |
| 146 | |
| 147 | def make_variant_item_code(template, variant): |
| 148 | """Uses template's item code and abbreviations to make variant's item code""" |
| 149 | if variant.item_code: |
| 150 | return |
| 151 | |
| 152 | abbreviations = [] |
| 153 | for attr in variant.attributes: |
| 154 | item_attribute = frappe.db.sql("""select i.numeric_values, v.abbr |
| 155 | from `tabItem Attribute` i left join `tabItem Attribute Value` v |
| 156 | on (i.name=v.parent) |
| 157 | where i.name=%(attribute)s and v.attribute_value=%(attribute_value)s""", { |
| 158 | "attribute": attr.attribute, |
| 159 | "attribute_value": attr.attribute_value |
| 160 | }, as_dict=True) |
| 161 | |
| 162 | if not item_attribute: |
| 163 | # somehow an invalid item attribute got used |
| 164 | return |
| 165 | |
| 166 | if item_attribute[0].numeric_values: |
| 167 | # don't generate item code if one of the attributes is numeric |
| 168 | return |
| 169 | |
| 170 | abbreviations.append(item_attribute[0].abbr) |
| 171 | |
| 172 | if abbreviations: |
| 173 | variant.item_code = "{0}-{1}".format(template.item_code, "-".join(abbreviations)) |
| 174 | |
| 175 | if variant.item_code: |
| 176 | variant.item_name = variant.item_code |