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