blob: fe596c4c7d6db60bb37e12c176a8524d0fc355e6 [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)
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053035 args = frappe._dict(args)
Nabin Hait0f231062014-02-20 11:27:47 +053036
Nabin Hait0aa71a52014-02-11 16:14:52 +053037 if not args.get("transaction_type"):
Nabin Hait0f231062014-02-20 11:27:47 +053038 args.transaction_type = "buying" if has_field(args.get("doctype"), "supplier") \
39 else "selling"
Nabin Hait139dc7b2014-02-12 14:53:18 +053040
41 if not args.get("price_list"):
42 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
Nabin Hait0aa71a52014-02-11 16:14:52 +053043
Nabin Hait436f5262014-02-10 14:47:54 +053044 if args.barcode:
45 args.item_code = get_item_code(barcode=args.barcode)
46 elif not args.item_code and args.serial_no:
47 args.item_code = get_item_code(serial_no=args.serial_no)
48
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053049 item_bean = frappe.bean("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053050 item = item_bean.doc
51
52 validate_item_details(args, item)
53
54 out = get_basic_details(args, item_bean)
55
56 get_party_item_code(args, item_bean, out)
57
58 if out.get("warehouse"):
59 out.update(get_available_qty(args.item_code, out.warehouse))
60 out.update(get_projected_qty(item.name, out.warehouse))
61
Nabin Hait436f5262014-02-10 14:47:54 +053062 get_price_list_rate(args, item_bean, out)
Nabin Hait436f5262014-02-10 14:47:54 +053063
64 if args.transaction_type == "selling" and cint(args.is_pos):
65 out.update(get_pos_settings_item_details(args.company, args))
Nabin Hait615d3422014-02-25 19:01:20 +053066
67 apply_pricing_rule(out, args)
Nabin Hait436f5262014-02-10 14:47:54 +053068
Nabin Hait139dc7b2014-02-12 14:53:18 +053069 if args.get("doctype") in ("Sales Invoice", "Delivery Note"):
Nabin Hait436f5262014-02-10 14:47:54 +053070 if item_bean.doc.has_serial_no == "Yes" and not args.serial_no:
Nabin Hait0aa71a52014-02-11 16:14:52 +053071 out.serial_no = get_serial_nos_by_fifo(args, item_bean)
Nabin Hait139dc7b2014-02-12 14:53:18 +053072
73 if args.transaction_date and item.lead_time_days:
74 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
75 item.lead_time_days)
Nabin Hait436f5262014-02-10 14:47:54 +053076
77 return out
78
Nabin Hait436f5262014-02-10 14:47:54 +053079def get_item_code(barcode=None, serial_no=None):
80 if barcode:
Anand Doshie9baaa62014-02-26 12:35:33 +053081 item_code = frappe.db.get_value("Item", {"barcode": barcode})
Nabin Hait436f5262014-02-10 14:47:54 +053082 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +053083 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Nabin Hait436f5262014-02-10 14:47:54 +053084
85 if not item_code:
86 throw(_("No Item found with ") + _("Barcode") if barcode else _("Serial No") +
87 ": %s" % (barcode or serial_no))
88
89 return item_code
90
91def validate_item_details(args, item):
92 if not args.company:
93 throw(_("Please specify Company"))
94
95 from erpnext.stock.doctype.item.item import validate_end_of_life
96 validate_end_of_life(item.name, item.end_of_life)
97
98 if args.transaction_type == "selling":
99 # validate if sales item or service item
Nabin Hait139dc7b2014-02-12 14:53:18 +0530100 if args.get("order_type") == "Maintenance":
Nabin Hait436f5262014-02-10 14:47:54 +0530101 if item.is_service_item != "Yes":
102 throw(_("Item") + (" %s: " % item.name) +
Nabin Hait08222152014-02-28 11:30:47 +0530103 _("is not a service item.") +
Nabin Hait436f5262014-02-10 14:47:54 +0530104 _("Please select a service item or change the order type to Sales."))
105
106 elif item.is_sales_item != "Yes":
Nabin Hait08222152014-02-28 11:30:47 +0530107 throw(_("Item") + (" %s: " % item.name) + _("is not a sales item"))
Nabin Hait436f5262014-02-10 14:47:54 +0530108
109 elif args.transaction_type == "buying":
110 # validate if purchase item or subcontracted item
111 if item.is_purchase_item != "Yes":
Nabin Hait08222152014-02-28 11:30:47 +0530112 throw(_("Item") + (" %s: " % item.name) + _("is not a purchase item"))
Nabin Hait436f5262014-02-10 14:47:54 +0530113
Nabin Hait139dc7b2014-02-12 14:53:18 +0530114 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != "Yes":
Nabin Hait436f5262014-02-10 14:47:54 +0530115 throw(_("Item") + (" %s: " % item.name) +
116 _("not a sub-contracted item.") +
117 _("Please select a sub-contracted item or do not sub-contract the transaction."))
118
119def get_basic_details(args, item_bean):
120 item = item_bean.doc
121
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530122 from frappe.defaults import get_user_default_as_list
Nabin Hait436f5262014-02-10 14:47:54 +0530123 user_default_warehouse_list = get_user_default_as_list('warehouse')
124 user_default_warehouse = user_default_warehouse_list[0] \
125 if len(user_default_warehouse_list)==1 else ""
Nabin Hait36028bf2014-02-12 19:09:28 +0530126
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530127 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530128 "item_code": item.name,
129 "item_name": item.item_name,
130 "description": item.description_html or item.description,
131 "warehouse": user_default_warehouse or args.warehouse or item.default_warehouse,
Nabin Haiteba1bdb2014-02-12 16:04:17 +0530132 "income_account": item.income_account or args.income_account \
Anand Doshie9baaa62014-02-26 12:35:33 +0530133 or frappe.db.get_value("Company", args.company, "default_income_account"),
Nabin Hait139dc7b2014-02-12 14:53:18 +0530134 "expense_account": item.expense_account or args.expense_account \
Anand Doshie9baaa62014-02-26 12:35:33 +0530135 or frappe.db.get_value("Company", args.company, "default_expense_account"),
Nabin Hait139dc7b2014-02-12 14:53:18 +0530136 "cost_center": item.selling_cost_center \
Nabin Hait36028bf2014-02-12 19:09:28 +0530137 if args.transaction_type == "selling" else item.buying_cost_center,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530138 "batch_no": None,
139 "item_tax_rate": json.dumps(dict(([d.tax_type, d.tax_rate] for d in
140 item_bean.doclist.get({"parentfield": "item_tax"})))),
141 "uom": item.stock_uom,
142 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
143 "conversion_factor": 1.0,
144 "qty": 1.0,
145 "price_list_rate": 0.0,
146 "base_price_list_rate": 0.0,
147 "rate": 0.0,
148 "base_rate": 0.0,
149 "amount": 0.0,
150 "base_amount": 0.0,
151 "discount_percentage": 0.0
152 })
Nabin Hait436f5262014-02-10 14:47:54 +0530153
154 for fieldname in ("item_name", "item_group", "barcode", "brand", "stock_uom"):
155 out[fieldname] = item.fields.get(fieldname)
156
157 return out
158
159def get_price_list_rate(args, item_bean, out):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530160 meta = frappe.get_doctype(args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530161
162 if meta.get_field("currency"):
163 validate_price_list(args)
164 validate_conversion_rate(args, meta)
165
Anand Doshie9baaa62014-02-26 12:35:33 +0530166 price_list_rate = frappe.db.get_value("Item Price",
Nabin Haita7f757a2014-02-10 17:54:04 +0530167 {"price_list": args.price_list, "item_code": args.item_code}, "price_list_rate")
Nabin Hait436f5262014-02-10 14:47:54 +0530168
169 if not price_list_rate: return {}
170
171 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
172 / flt(args.conversion_rate)
173
174 if not out.price_list_rate and args.transaction_type == "buying":
175 from erpnext.stock.doctype.item.item import get_last_purchase_details
176 out.update(get_last_purchase_details(item_bean.doc.name,
177 args.docname, args.conversion_rate))
178
179def validate_price_list(args):
180 if args.get("price_list"):
Anand Doshie9baaa62014-02-26 12:35:33 +0530181 if not frappe.db.get_value("Price List",
Nabin Hait436f5262014-02-10 14:47:54 +0530182 {"name": args.price_list, args.transaction_type: 1, "enabled": 1}):
183 throw(_("Price List is either disabled or for not ") + _(args.transaction_type))
184 else:
185 throw(_("Price List not selected"))
186
187def validate_conversion_rate(args, meta):
188 from erpnext.setup.doctype.currency.currency import validate_conversion_rate
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530189 from frappe.model.meta import get_field_precision
Nabin Hait436f5262014-02-10 14:47:54 +0530190
191 # validate currency conversion rate
192 validate_conversion_rate(args.currency, args.conversion_rate,
193 meta.get_label("conversion_rate"), args.company)
194
195 args.conversion_rate = flt(args.conversion_rate,
196 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530197 frappe._dict({"fields": args})))
Nabin Hait436f5262014-02-10 14:47:54 +0530198
199 # validate price list currency conversion rate
200 if not args.get("price_list_currency"):
201 throw(_("Price List Currency not selected"))
202 else:
203 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
204 meta.get_label("plc_conversion_rate"), args.company)
205
206 args.plc_conversion_rate = flt(args.plc_conversion_rate,
207 get_field_precision(meta.get_field("plc_conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530208 frappe._dict({"fields": args})))
Nabin Hait436f5262014-02-10 14:47:54 +0530209
210def get_party_item_code(args, item_bean, out):
211 if args.transaction_type == "selling":
212 customer_item_code = item_bean.doclist.get({"parentfield": "item_customer_details",
213 "customer_name": args.customer})
214 out.customer_item_code = customer_item_code[0].ref_code if customer_item_code else None
215 else:
216 item_supplier = item_bean.doclist.get({"parentfield": "item_supplier_details",
217 "supplier": args.supplier})
218 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
219
220
221def get_pos_settings_item_details(company, args, pos_settings=None):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530222 res = frappe._dict()
Nabin Hait436f5262014-02-10 14:47:54 +0530223
224 if not pos_settings:
225 pos_settings = get_pos_settings(company)
226
227 if pos_settings:
228 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
229 if not args.get(fieldname):
230 res[fieldname] = pos_settings.get(fieldname)
231
232 if res.get("warehouse"):
233 res.actual_qty = get_available_qty(args.item_code,
234 res.warehouse).get("actual_qty")
235
236 return res
237
238def get_pos_settings(company):
Anand Doshie9baaa62014-02-26 12:35:33 +0530239 pos_settings = frappe.db.sql("""select * from `tabPOS Setting` where user = %s
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530240 and company = %s""", (frappe.session['user'], company), as_dict=1)
Nabin Hait436f5262014-02-10 14:47:54 +0530241
242 if not pos_settings:
Anand Doshie9baaa62014-02-26 12:35:33 +0530243 pos_settings = frappe.db.sql("""select * from `tabPOS Setting`
Nabin Hait436f5262014-02-10 14:47:54 +0530244 where ifnull(user,'') = '' and company = %s""", company, as_dict=1)
245
246 return pos_settings and pos_settings[0] or None
Nabin Hait139dc7b2014-02-12 14:53:18 +0530247
Nabin Hait615d3422014-02-25 19:01:20 +0530248def apply_pricing_rule(out, args):
249 args_dict = frappe._dict().update(args)
250 args_dict.update(out)
Nabin Hait08222152014-02-28 11:30:47 +0530251 all_pricing_rules = get_pricing_rules(args_dict)
252
253 for rule_for in ["price", "discount_percentage"]:
254 pricing_rules = filter(lambda x: x[rule_for] > 0.0, all_pricing_rules)
255 pricing_rules = filter_pricing_rules(args_dict, pricing_rules, rule_for)
Nabin Hait615d3422014-02-25 19:01:20 +0530256 if pricing_rules:
Nabin Hait08222152014-02-28 11:30:47 +0530257 if rule_for == "discount_percentage":
258 out["discount_percentage"] = pricing_rules[-1]["discount_percentage"]
259 out["pricing_rule_for_discount"] = pricing_rules[-1]["name"]
Nabin Hait615d3422014-02-25 19:01:20 +0530260 else:
261 out["base_price_list_rate"] = pricing_rules[0]["price"]
262 out["price_list_rate"] = pricing_rules[0]["price"] * \
263 flt(args_dict.plc_conversion_rate) / flt(args_dict.conversion_rate)
Nabin Hait08222152014-02-28 11:30:47 +0530264 out["pricing_rule_for_price"] = pricing_rules[-1]["name"]
Nabin Hait615d3422014-02-25 19:01:20 +0530265
Nabin Haited5f4232014-02-28 12:52:06 +0530266def get_pricing_rules(args_dict):
Nabin Hait177b86a2014-02-28 15:47:22 +0530267 def _get_tree_conditions(doctype, allow_blank=True):
Nabin Haited5f4232014-02-28 12:52:06 +0530268 field = frappe.scrub(doctype)
269 condition = ""
270 if args_dict.get(field):
271 lft, rgt = frappe.db.get_value(doctype, args_dict[field], ["lft", "rgt"])
272 parent_groups = frappe.db.sql_list("""select name from `tab%s`
Nabin Hait177b86a2014-02-28 15:47:22 +0530273 where lft<=%s and rgt>=%s""" % (doctype, '%s', '%s'), (lft, rgt))
Nabin Haited5f4232014-02-28 12:52:06 +0530274
275 if parent_groups:
Nabin Hait177b86a2014-02-28 15:47:22 +0530276 if allow_blank: parent_groups.append('')
277 condition = " ifnull("+field+", '') in ('" + "', '".join(parent_groups)+"')"
Nabin Haited5f4232014-02-28 12:52:06 +0530278
279 return condition
280
281
Nabin Hait7e8e8ba2014-02-26 15:13:44 +0530282 conditions = ""
Nabin Hait33191702014-02-28 13:01:33 +0530283 for field in ["customer", "supplier", "supplier_type", "campaign", "sales_partner"]:
Nabin Hait615d3422014-02-25 19:01:20 +0530284 if args_dict.get(field):
285 conditions += " and ifnull("+field+", '') in (%("+field+")s, '')"
Nabin Hait08222152014-02-28 11:30:47 +0530286 else:
287 conditions += " and ifnull("+field+", '') = ''"
288
Nabin Hait33191702014-02-28 13:01:33 +0530289 for doctype in ["Customer Group", "Territory"]:
290 group_condition = _get_tree_conditions(doctype)
291 if group_condition:
292 conditions += " and " + group_condition
Nabin Haited5f4232014-02-28 12:52:06 +0530293
Nabin Hait08222152014-02-28 11:30:47 +0530294 conditions += " and ifnull(for_price_list, '') in (%(price_list)s, '')"
Nabin Haited5f4232014-02-28 12:52:06 +0530295
Nabin Hait08222152014-02-28 11:30:47 +0530296
Nabin Hait615d3422014-02-25 19:01:20 +0530297 if args_dict.get("transaction_date"):
298 conditions += """ and %(transaction_date)s between ifnull(valid_from, '2000-01-01')
299 and ifnull(valid_upto, '2500-12-31')"""
300
Nabin Hait08222152014-02-28 11:30:47 +0530301 return frappe.db.sql("""select * from `tabPricing Rule`
Nabin Haited5f4232014-02-28 12:52:06 +0530302 where (item_code=%(item_code)s or {item_group_condition} or brand=%(brand)s)
303 and docstatus < 2 and ifnull(disable, 0) = 0 {conditions}
304 order by priority desc, name desc""".format(
Nabin Hait177b86a2014-02-28 15:47:22 +0530305 item_group_condition=_get_tree_conditions("Item Group", False), conditions=conditions),
Nabin Haited5f4232014-02-28 12:52:06 +0530306 args_dict, as_dict=1)
Nabin Hait08222152014-02-28 11:30:47 +0530307
308def filter_pricing_rules(args_dict, pricing_rules, price_or_discount):
309 # filter for qty
310 if pricing_rules and args_dict.get("qty"):
311 pricing_rules = filter(lambda x: (args_dict.qty>=flt(x.min_qty)
312 and (args_dict.qty<=x.max_qty if x.max_qty else True)), pricing_rules)
313
314 # find pricing rule with highest priority
315 if pricing_rules:
316 max_priority = max([cint(p.priority) for p in pricing_rules])
317 if max_priority:
318 pricing_rules = filter(lambda x: cint(x.priority)==max_priority, pricing_rules)
319
320 # apply internal priority
321 all_fields = ["item_code", "item_group", "brand", "customer", "customer_group", "territory",
322 "supplier", "supplier_type", "campaign", "for_price_list", "sales_partner"]
Nabin Hait615d3422014-02-25 19:01:20 +0530323
Nabin Hait08222152014-02-28 11:30:47 +0530324 if len(pricing_rules) > 1:
325 for field_set in [["item_code", "item_group", "brand"],
326 ["customer", "customer_group", "territory"], ["supplier", "supplier_type"]]:
327 remaining_fields = list(set(all_fields) - set(field_set))
328 if if_all_rules_same(pricing_rules, remaining_fields):
329 pricing_rules = apply_internal_priority(pricing_rules, field_set, args_dict)
330 break
331
332 if len(pricing_rules) > 1:
333 pricing_rules = sorted(pricing_rules, key=lambda x: x[price_or_discount])
334
335 return pricing_rules
336
337def if_all_rules_same(pricing_rules, fields):
338 all_rules_same = True
339 val = [pricing_rules[0][k] for k in fields]
340 for p in pricing_rules[1:]:
341 if val != [p[k] for k in fields]:
342 all_rules_same = False
343 break
344
345 return all_rules_same
346
347def apply_internal_priority(pricing_rules, field_set, args_dict):
348 filtered_rules = []
349 for field in field_set:
350 if args_dict.get(field):
351 filtered_rules = filter(lambda x: x[field]==args_dict[field], pricing_rules)
352 if filtered_rules: break
353
354 return filtered_rules or pricing_rules
355
Nabin Hait139dc7b2014-02-12 14:53:18 +0530356def get_serial_nos_by_fifo(args, item_bean):
Anand Doshie9baaa62014-02-26 12:35:33 +0530357 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Nabin Hait139dc7b2014-02-12 14:53:18 +0530358 where item_code=%(item_code)s and warehouse=%(warehouse)s and status='Available'
359 order by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
360 "item_code": args.item_code,
361 "warehouse": args.warehouse,
362 "qty": cint(args.qty)
363 }))
Nabin Hait08222152014-02-28 11:30:47 +0530364
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530365@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530366def get_conversion_factor(item_code, uom):
Anand Doshie9baaa62014-02-26 12:35:33 +0530367 return {"conversion_factor": frappe.db.get_value("UOM Conversion Detail",
Nabin Hait436f5262014-02-10 14:47:54 +0530368 {"parent": item_code, "uom": uom}, "conversion_factor")}
Nabin Hait08222152014-02-28 11:30:47 +0530369
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530370@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530371def get_projected_qty(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530372 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530373 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530374
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530375@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530376def get_available_qty(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530377 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Hait436f5262014-02-10 14:47:54 +0530378 ["projected_qty", "actual_qty"], as_dict=True) or {}