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