blob: 3cd49d94b389961437840a25580121c3b95e48f4 [file] [log] [blame]
Nabin Hait436f5262014-02-10 14:47:54 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
2# License: GNU General Public License v3. See license.txt
3
4from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
6from frappe import _, throw
7from frappe.utils import flt, cint, add_days
Nabin Hait0f231062014-02-20 11:27:47 +05308from frappe.model.meta import has_field
Nabin Hait436f5262014-02-10 14:47:54 +05309import json
10
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053011@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +053012def get_item_details(args):
13 """
14 args = {
15 "item_code": "",
16 "warehouse": None,
17 "customer": "",
18 "conversion_rate": 1.0,
19 "selling_price_list": None,
20 "price_list_currency": None,
Nabin Hait615d3422014-02-25 19:01:20 +053021 "plc_conversion_rate": 1.0,
Nabin Hait436f5262014-02-10 14:47:54 +053022 "doctype": "",
23 "docname": "",
24 "supplier": None,
25 "transaction_date": None,
26 "conversion_rate": 1.0,
27 "buying_price_list": None,
28 "is_subcontracted": "Yes" / "No",
29 "transaction_type": "selling"
30 }
31 """
32
33 if isinstance(args, basestring):
34 args = json.loads(args)
Anand Doshi4b269212014-03-19 16:58:42 +053035
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053036 args = frappe._dict(args)
Nabin Hait0f231062014-02-20 11:27:47 +053037
Nabin Hait0aa71a52014-02-11 16:14:52 +053038 if not args.get("transaction_type"):
Nabin Hait0f231062014-02-20 11:27:47 +053039 args.transaction_type = "buying" if has_field(args.get("doctype"), "supplier") \
40 else "selling"
Nabin Hait139dc7b2014-02-12 14:53:18 +053041
42 if not args.get("price_list"):
43 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
Nabin Hait0aa71a52014-02-11 16:14:52 +053044
Nabin Hait436f5262014-02-10 14:47:54 +053045 if args.barcode:
46 args.item_code = get_item_code(barcode=args.barcode)
47 elif not args.item_code and args.serial_no:
48 args.item_code = get_item_code(serial_no=args.serial_no)
49
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053050 item_bean = frappe.bean("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053051 item = item_bean.doc
52
53 validate_item_details(args, item)
54
55 out = get_basic_details(args, item_bean)
56
57 get_party_item_code(args, item_bean, out)
58
59 if out.get("warehouse"):
60 out.update(get_available_qty(args.item_code, out.warehouse))
61 out.update(get_projected_qty(item.name, out.warehouse))
62
Nabin Hait436f5262014-02-10 14:47:54 +053063 get_price_list_rate(args, item_bean, out)
Nabin Hait436f5262014-02-10 14:47:54 +053064
65 if args.transaction_type == "selling" and cint(args.is_pos):
66 out.update(get_pos_settings_item_details(args.company, args))
Nabin Hait615d3422014-02-25 19:01:20 +053067
68 apply_pricing_rule(out, args)
Nabin Hait436f5262014-02-10 14:47:54 +053069
Nabin Hait139dc7b2014-02-12 14:53:18 +053070 if args.get("doctype") in ("Sales Invoice", "Delivery Note"):
Nabin Hait436f5262014-02-10 14:47:54 +053071 if item_bean.doc.has_serial_no == "Yes" and not args.serial_no:
Nabin Hait0aa71a52014-02-11 16:14:52 +053072 out.serial_no = get_serial_nos_by_fifo(args, item_bean)
Nabin Hait139dc7b2014-02-12 14:53:18 +053073
74 if args.transaction_date and item.lead_time_days:
75 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
76 item.lead_time_days)
Nabin Hait436f5262014-02-10 14:47:54 +053077
78 return out
79
Nabin Hait436f5262014-02-10 14:47:54 +053080def get_item_code(barcode=None, serial_no=None):
81 if barcode:
Anand Doshie9baaa62014-02-26 12:35:33 +053082 item_code = frappe.db.get_value("Item", {"barcode": barcode})
Nabin Hait436f5262014-02-10 14:47:54 +053083 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +053084 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Nabin Hait436f5262014-02-10 14:47:54 +053085
86 if not item_code:
87 throw(_("No Item found with ") + _("Barcode") if barcode else _("Serial No") +
88 ": %s" % (barcode or serial_no))
89
90 return item_code
91
92def validate_item_details(args, item):
93 if not args.company:
94 throw(_("Please specify Company"))
95
96 from erpnext.stock.doctype.item.item import validate_end_of_life
97 validate_end_of_life(item.name, item.end_of_life)
98
99 if args.transaction_type == "selling":
100 # validate if sales item or service item
Nabin Hait139dc7b2014-02-12 14:53:18 +0530101 if args.get("order_type") == "Maintenance":
Nabin Hait436f5262014-02-10 14:47:54 +0530102 if item.is_service_item != "Yes":
103 throw(_("Item") + (" %s: " % item.name) +
Nabin Hait08222152014-02-28 11:30:47 +0530104 _("is not a service item.") +
Nabin Hait436f5262014-02-10 14:47:54 +0530105 _("Please select a service item or change the order type to Sales."))
106
107 elif item.is_sales_item != "Yes":
Nabin Hait08222152014-02-28 11:30:47 +0530108 throw(_("Item") + (" %s: " % item.name) + _("is not a sales item"))
Nabin Hait436f5262014-02-10 14:47:54 +0530109
110 elif args.transaction_type == "buying":
111 # validate if purchase item or subcontracted item
112 if item.is_purchase_item != "Yes":
Nabin Hait08222152014-02-28 11:30:47 +0530113 throw(_("Item") + (" %s: " % item.name) + _("is not a purchase item"))
Nabin Hait436f5262014-02-10 14:47:54 +0530114
Nabin Hait139dc7b2014-02-12 14:53:18 +0530115 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != "Yes":
Nabin Hait436f5262014-02-10 14:47:54 +0530116 throw(_("Item") + (" %s: " % item.name) +
117 _("not a sub-contracted item.") +
118 _("Please select a sub-contracted item or do not sub-contract the transaction."))
119
120def get_basic_details(args, item_bean):
121 item = item_bean.doc
122
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530123 from frappe.defaults import get_user_default_as_list
Nabin Hait436f5262014-02-10 14:47:54 +0530124 user_default_warehouse_list = get_user_default_as_list('warehouse')
125 user_default_warehouse = user_default_warehouse_list[0] \
126 if len(user_default_warehouse_list)==1 else ""
Nabin Hait36028bf2014-02-12 19:09:28 +0530127
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530128 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530129 "item_code": item.name,
130 "item_name": item.item_name,
131 "description": item.description_html or item.description,
132 "warehouse": user_default_warehouse or args.warehouse or item.default_warehouse,
Nabin Haiteba1bdb2014-02-12 16:04:17 +0530133 "income_account": item.income_account or args.income_account \
Anand Doshie9baaa62014-02-26 12:35:33 +0530134 or frappe.db.get_value("Company", args.company, "default_income_account"),
Nabin Hait139dc7b2014-02-12 14:53:18 +0530135 "expense_account": item.expense_account or args.expense_account \
Anand Doshie9baaa62014-02-26 12:35:33 +0530136 or frappe.db.get_value("Company", args.company, "default_expense_account"),
Nabin Hait139dc7b2014-02-12 14:53:18 +0530137 "cost_center": item.selling_cost_center \
Nabin Hait36028bf2014-02-12 19:09:28 +0530138 if args.transaction_type == "selling" else item.buying_cost_center,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530139 "batch_no": None,
140 "item_tax_rate": json.dumps(dict(([d.tax_type, d.tax_rate] for d in
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530141 item_bean.get("item_tax")))),
Nabin Hait139dc7b2014-02-12 14:53:18 +0530142 "uom": item.stock_uom,
143 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
144 "conversion_factor": 1.0,
145 "qty": 1.0,
146 "price_list_rate": 0.0,
147 "base_price_list_rate": 0.0,
148 "rate": 0.0,
149 "base_rate": 0.0,
150 "amount": 0.0,
151 "base_amount": 0.0,
152 "discount_percentage": 0.0
153 })
Nabin Hait436f5262014-02-10 14:47:54 +0530154
155 for fieldname in ("item_name", "item_group", "barcode", "brand", "stock_uom"):
156 out[fieldname] = item.fields.get(fieldname)
157
158 return out
159
160def get_price_list_rate(args, item_bean, out):
Rushabh Mehtae88bc8b2014-03-27 17:51:41 +0530161 meta = frappe.get_meta(args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530162
163 if meta.get_field("currency"):
164 validate_price_list(args)
165 validate_conversion_rate(args, meta)
166
Anand Doshie9baaa62014-02-26 12:35:33 +0530167 price_list_rate = frappe.db.get_value("Item Price",
Nabin Haita7f757a2014-02-10 17:54:04 +0530168 {"price_list": args.price_list, "item_code": args.item_code}, "price_list_rate")
Nabin Hait436f5262014-02-10 14:47:54 +0530169
170 if not price_list_rate: return {}
171
172 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
173 / flt(args.conversion_rate)
174
175 if not out.price_list_rate and args.transaction_type == "buying":
176 from erpnext.stock.doctype.item.item import get_last_purchase_details
177 out.update(get_last_purchase_details(item_bean.doc.name,
178 args.docname, args.conversion_rate))
179
180def validate_price_list(args):
181 if args.get("price_list"):
Anand Doshie9baaa62014-02-26 12:35:33 +0530182 if not frappe.db.get_value("Price List",
Nabin Hait436f5262014-02-10 14:47:54 +0530183 {"name": args.price_list, args.transaction_type: 1, "enabled": 1}):
184 throw(_("Price List is either disabled or for not ") + _(args.transaction_type))
185 else:
186 throw(_("Price List not selected"))
187
188def validate_conversion_rate(args, meta):
189 from erpnext.setup.doctype.currency.currency import validate_conversion_rate
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530190 from frappe.model.meta import get_field_precision
Nabin Hait436f5262014-02-10 14:47:54 +0530191
192 # validate currency conversion rate
193 validate_conversion_rate(args.currency, args.conversion_rate,
194 meta.get_label("conversion_rate"), args.company)
195
196 args.conversion_rate = flt(args.conversion_rate,
197 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530198 frappe._dict({"fields": args})))
Nabin Hait436f5262014-02-10 14:47:54 +0530199
200 # validate price list currency conversion rate
201 if not args.get("price_list_currency"):
202 throw(_("Price List Currency not selected"))
203 else:
204 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
205 meta.get_label("plc_conversion_rate"), args.company)
206
207 args.plc_conversion_rate = flt(args.plc_conversion_rate,
208 get_field_precision(meta.get_field("plc_conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530209 frappe._dict({"fields": args})))
Nabin Hait436f5262014-02-10 14:47:54 +0530210
211def get_party_item_code(args, item_bean, out):
212 if args.transaction_type == "selling":
213 customer_item_code = item_bean.doclist.get({"parentfield": "item_customer_details",
214 "customer_name": args.customer})
215 out.customer_item_code = customer_item_code[0].ref_code if customer_item_code else None
216 else:
217 item_supplier = item_bean.doclist.get({"parentfield": "item_supplier_details",
218 "supplier": args.supplier})
219 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
220
221
222def get_pos_settings_item_details(company, args, pos_settings=None):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530223 res = frappe._dict()
Nabin Hait436f5262014-02-10 14:47:54 +0530224
225 if not pos_settings:
226 pos_settings = get_pos_settings(company)
227
228 if pos_settings:
229 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
230 if not args.get(fieldname):
231 res[fieldname] = pos_settings.get(fieldname)
232
233 if res.get("warehouse"):
234 res.actual_qty = get_available_qty(args.item_code,
235 res.warehouse).get("actual_qty")
236
237 return res
238
239def get_pos_settings(company):
Anand Doshie9baaa62014-02-26 12:35:33 +0530240 pos_settings = frappe.db.sql("""select * from `tabPOS Setting` where user = %s
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530241 and company = %s""", (frappe.session['user'], company), as_dict=1)
Nabin Hait436f5262014-02-10 14:47:54 +0530242
243 if not pos_settings:
Anand Doshie9baaa62014-02-26 12:35:33 +0530244 pos_settings = frappe.db.sql("""select * from `tabPOS Setting`
Nabin Hait436f5262014-02-10 14:47:54 +0530245 where ifnull(user,'') = '' and company = %s""", company, as_dict=1)
246
247 return pos_settings and pos_settings[0] or None
Nabin Hait139dc7b2014-02-12 14:53:18 +0530248
Nabin Hait615d3422014-02-25 19:01:20 +0530249def apply_pricing_rule(out, args):
250 args_dict = frappe._dict().update(args)
251 args_dict.update(out)
Nabin Hait08222152014-02-28 11:30:47 +0530252 all_pricing_rules = get_pricing_rules(args_dict)
253
254 for rule_for in ["price", "discount_percentage"]:
255 pricing_rules = filter(lambda x: x[rule_for] > 0.0, all_pricing_rules)
256 pricing_rules = filter_pricing_rules(args_dict, pricing_rules, rule_for)
Nabin Hait615d3422014-02-25 19:01:20 +0530257 if pricing_rules:
Nabin Hait08222152014-02-28 11:30:47 +0530258 if rule_for == "discount_percentage":
259 out["discount_percentage"] = pricing_rules[-1]["discount_percentage"]
260 out["pricing_rule_for_discount"] = pricing_rules[-1]["name"]
Nabin Hait615d3422014-02-25 19:01:20 +0530261 else:
262 out["base_price_list_rate"] = pricing_rules[0]["price"]
263 out["price_list_rate"] = pricing_rules[0]["price"] * \
264 flt(args_dict.plc_conversion_rate) / flt(args_dict.conversion_rate)
Nabin Hait08222152014-02-28 11:30:47 +0530265 out["pricing_rule_for_price"] = pricing_rules[-1]["name"]
Nabin Hait615d3422014-02-25 19:01:20 +0530266
Nabin Haited5f4232014-02-28 12:52:06 +0530267def get_pricing_rules(args_dict):
Nabin Hait177b86a2014-02-28 15:47:22 +0530268 def _get_tree_conditions(doctype, allow_blank=True):
Nabin Haited5f4232014-02-28 12:52:06 +0530269 field = frappe.scrub(doctype)
270 condition = ""
271 if args_dict.get(field):
272 lft, rgt = frappe.db.get_value(doctype, args_dict[field], ["lft", "rgt"])
273 parent_groups = frappe.db.sql_list("""select name from `tab%s`
Nabin Hait177b86a2014-02-28 15:47:22 +0530274 where lft<=%s and rgt>=%s""" % (doctype, '%s', '%s'), (lft, rgt))
Nabin Haited5f4232014-02-28 12:52:06 +0530275
276 if parent_groups:
Nabin Hait177b86a2014-02-28 15:47:22 +0530277 if allow_blank: parent_groups.append('')
278 condition = " ifnull("+field+", '') in ('" + "', '".join(parent_groups)+"')"
Nabin Haited5f4232014-02-28 12:52:06 +0530279
280 return condition
281
282
Nabin Hait7e8e8ba2014-02-26 15:13:44 +0530283 conditions = ""
Nabin Hait33191702014-02-28 13:01:33 +0530284 for field in ["customer", "supplier", "supplier_type", "campaign", "sales_partner"]:
Nabin Hait615d3422014-02-25 19:01:20 +0530285 if args_dict.get(field):
286 conditions += " and ifnull("+field+", '') in (%("+field+")s, '')"
Nabin Hait08222152014-02-28 11:30:47 +0530287 else:
288 conditions += " and ifnull("+field+", '') = ''"
289
Nabin Hait33191702014-02-28 13:01:33 +0530290 for doctype in ["Customer Group", "Territory"]:
291 group_condition = _get_tree_conditions(doctype)
292 if group_condition:
293 conditions += " and " + group_condition
Nabin Haited5f4232014-02-28 12:52:06 +0530294
Nabin Hait08222152014-02-28 11:30:47 +0530295 conditions += " and ifnull(for_price_list, '') in (%(price_list)s, '')"
Nabin Haited5f4232014-02-28 12:52:06 +0530296
Nabin Hait08222152014-02-28 11:30:47 +0530297
Nabin Hait615d3422014-02-25 19:01:20 +0530298 if args_dict.get("transaction_date"):
299 conditions += """ and %(transaction_date)s between ifnull(valid_from, '2000-01-01')
300 and ifnull(valid_upto, '2500-12-31')"""
301
Nabin Hait08222152014-02-28 11:30:47 +0530302 return frappe.db.sql("""select * from `tabPricing Rule`
Nabin Haited5f4232014-02-28 12:52:06 +0530303 where (item_code=%(item_code)s or {item_group_condition} or brand=%(brand)s)
304 and docstatus < 2 and ifnull(disable, 0) = 0 {conditions}
305 order by priority desc, name desc""".format(
Nabin Hait177b86a2014-02-28 15:47:22 +0530306 item_group_condition=_get_tree_conditions("Item Group", False), conditions=conditions),
Nabin Haited5f4232014-02-28 12:52:06 +0530307 args_dict, as_dict=1)
Nabin Hait08222152014-02-28 11:30:47 +0530308
309def filter_pricing_rules(args_dict, pricing_rules, price_or_discount):
310 # filter for qty
311 if pricing_rules and args_dict.get("qty"):
312 pricing_rules = filter(lambda x: (args_dict.qty>=flt(x.min_qty)
313 and (args_dict.qty<=x.max_qty if x.max_qty else True)), pricing_rules)
314
315 # find pricing rule with highest priority
316 if pricing_rules:
317 max_priority = max([cint(p.priority) for p in pricing_rules])
318 if max_priority:
319 pricing_rules = filter(lambda x: cint(x.priority)==max_priority, pricing_rules)
320
321 # apply internal priority
322 all_fields = ["item_code", "item_group", "brand", "customer", "customer_group", "territory",
323 "supplier", "supplier_type", "campaign", "for_price_list", "sales_partner"]
Nabin Hait615d3422014-02-25 19:01:20 +0530324
Nabin Hait08222152014-02-28 11:30:47 +0530325 if len(pricing_rules) > 1:
326 for field_set in [["item_code", "item_group", "brand"],
327 ["customer", "customer_group", "territory"], ["supplier", "supplier_type"]]:
328 remaining_fields = list(set(all_fields) - set(field_set))
329 if if_all_rules_same(pricing_rules, remaining_fields):
330 pricing_rules = apply_internal_priority(pricing_rules, field_set, args_dict)
331 break
332
333 if len(pricing_rules) > 1:
334 pricing_rules = sorted(pricing_rules, key=lambda x: x[price_or_discount])
335
336 return pricing_rules
337
338def if_all_rules_same(pricing_rules, fields):
339 all_rules_same = True
340 val = [pricing_rules[0][k] for k in fields]
341 for p in pricing_rules[1:]:
342 if val != [p[k] for k in fields]:
343 all_rules_same = False
344 break
345
346 return all_rules_same
347
348def apply_internal_priority(pricing_rules, field_set, args_dict):
349 filtered_rules = []
350 for field in field_set:
351 if args_dict.get(field):
352 filtered_rules = filter(lambda x: x[field]==args_dict[field], pricing_rules)
353 if filtered_rules: break
354
355 return filtered_rules or pricing_rules
356
Nabin Hait139dc7b2014-02-12 14:53:18 +0530357def get_serial_nos_by_fifo(args, item_bean):
Anand Doshie9baaa62014-02-26 12:35:33 +0530358 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Nabin Hait139dc7b2014-02-12 14:53:18 +0530359 where item_code=%(item_code)s and warehouse=%(warehouse)s and status='Available'
360 order by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
361 "item_code": args.item_code,
362 "warehouse": args.warehouse,
363 "qty": cint(args.qty)
364 }))
Nabin Hait08222152014-02-28 11:30:47 +0530365
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530366@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530367def get_conversion_factor(item_code, uom):
Anand Doshie9baaa62014-02-26 12:35:33 +0530368 return {"conversion_factor": frappe.db.get_value("UOM Conversion Detail",
Nabin Hait436f5262014-02-10 14:47:54 +0530369 {"parent": item_code, "uom": uom}, "conversion_factor")}
Nabin Hait08222152014-02-28 11:30:47 +0530370
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530371@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530372def get_projected_qty(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530373 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530374 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530375
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530376@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530377def get_available_qty(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530378 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Hait436f5262014-02-10 14:47:54 +0530379 ["projected_qty", "actual_qty"], as_dict=True) or {}