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