blob: e40549acae19deaf009e5a7ab7e507c14a4b739a [file] [log] [blame]
Rushabh Mehtaad45e312013-11-20 12:59:58 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Nabin Hait9d0f6362013-01-07 18:51:11 +05303
Anand Doshid57e7932015-02-24 12:24:53 +05304from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05306from frappe import _
Nabin Hait9d0f6362013-01-07 18:51:11 +05307import json
Rushabh Mehtaf8509872014-10-08 12:03:19 +05308from frappe.utils import flt, cstr, nowdate, nowtime
Nabin Hait9d0f6362013-01-07 18:51:11 +05309
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053010class InvalidWarehouseCompany(frappe.ValidationError): pass
Anand Doshi2ce39cf2014-04-07 18:51:58 +053011
Rushabh Mehtaf8509872014-10-08 12:03:19 +053012def get_stock_value_on(warehouse=None, posting_date=None, item_code=None):
Nabin Hait0dd7be12013-08-02 11:45:43 +053013 if not posting_date: posting_date = nowdate()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053014
Rushabh Mehtaf8509872014-10-08 12:03:19 +053015 values, condition = [posting_date], ""
16
17 if warehouse:
18 values.append(warehouse)
19 condition += " AND warehouse = %s"
20
21 if item_code:
22 values.append(item_code)
23 condition.append(" AND item_code = %s")
24
Anand Doshie9baaa62014-02-26 12:35:33 +053025 stock_ledger_entries = frappe.db.sql("""
Rushabh Mehtaf8509872014-10-08 12:03:19 +053026 SELECT item_code, stock_value
27 FROM `tabStock Ledger Entry`
28 WHERE posting_date <= %s {0}
Nabin Hait0dd7be12013-08-02 11:45:43 +053029 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
Rushabh Mehtaf8509872014-10-08 12:03:19 +053030 """.format(condition), values, as_dict=1)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053031
Nabin Hait0dd7be12013-08-02 11:45:43 +053032 sle_map = {}
33 for sle in stock_ledger_entries:
Nabin Hait625da792013-09-25 10:32:51 +053034 sle_map.setdefault(sle.item_code, flt(sle.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +053035
Nabin Hait625da792013-09-25 10:32:51 +053036 return sum(sle_map.values())
Anand Doshi2ce39cf2014-04-07 18:51:58 +053037
Rushabh Mehta2712e362015-02-17 12:50:20 +053038def get_stock_balance(item_code, warehouse, posting_date=None, posting_time=None, with_valuation_rate=False):
39 """Returns stock balance quantity at given warehouse on given posting date or current date.
40
41 If `with_valuation_rate` is True, will return tuple (qty, rate)"""
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053042
43 from erpnext.stock.stock_ledger import get_previous_sle
44
Rushabh Mehtaf8509872014-10-08 12:03:19 +053045 if not posting_date: posting_date = nowdate()
46 if not posting_time: posting_time = nowtime()
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053047
48 last_entry = get_previous_sle({
49 "item_code": item_code,
50 "warehouse":warehouse,
51 "posting_date": posting_date,
52 "posting_time": posting_time })
Rushabh Mehtaf8509872014-10-08 12:03:19 +053053
Rushabh Mehta2712e362015-02-17 12:50:20 +053054 if with_valuation_rate:
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053055 return (last_entry.qty_after_transaction, last_entry.valuation_rate) if last_entry else (0.0, 0.0)
Rushabh Mehtaf8509872014-10-08 12:03:19 +053056 else:
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053057 return last_entry.qty_after_transaction or 0.0
Rushabh Mehtaf8509872014-10-08 12:03:19 +053058
Nabin Hait47dc3182013-08-06 15:58:16 +053059def get_latest_stock_balance():
60 bin_map = {}
Anand Doshi2ce39cf2014-04-07 18:51:58 +053061 for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +053062 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +053063 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +053064
Nabin Hait47dc3182013-08-06 15:58:16 +053065 return bin_map
Anand Doshi2ce39cf2014-04-07 18:51:58 +053066
Nabin Hait74c281c2013-08-19 16:17:18 +053067def get_bin(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +053068 bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Nabin Hait74c281c2013-08-19 16:17:18 +053069 if not bin:
Rushabh Mehtaa504f062014-04-04 12:16:26 +053070 bin_obj = frappe.get_doc({
Nabin Hait74c281c2013-08-19 16:17:18 +053071 "doctype": "Bin",
72 "item_code": item_code,
73 "warehouse": warehouse,
Rushabh Mehtaa504f062014-04-04 12:16:26 +053074 })
Anand Doshi6dfd4302015-02-10 14:41:27 +053075 bin_obj.flags.ignore_permissions = 1
Rushabh Mehtaa504f062014-04-04 12:16:26 +053076 bin_obj.insert()
Nabin Hait74c281c2013-08-19 16:17:18 +053077 else:
Rushabh Mehtaa504f062014-04-04 12:16:26 +053078 bin_obj = frappe.get_doc('Bin', bin)
Anand Doshi6dfd4302015-02-10 14:41:27 +053079 bin_obj.flags.ignore_permissions = True
Nabin Hait74c281c2013-08-19 16:17:18 +053080 return bin_obj
81
Nabin Hait9c47efb2015-01-21 16:22:45 +053082def update_bin(args, allow_negative_stock=False):
Anand Doshie9baaa62014-02-26 12:35:33 +053083 is_stock_item = frappe.db.get_value('Item', args.get("item_code"), 'is_stock_item')
Nabin Hait74c281c2013-08-19 16:17:18 +053084 if is_stock_item == 'Yes':
85 bin = get_bin(args.get("item_code"), args.get("warehouse"))
Nabin Hait9c47efb2015-01-21 16:22:45 +053086 bin.update_stock(args, allow_negative_stock)
Nabin Hait74c281c2013-08-19 16:17:18 +053087 return bin
88 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053089 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
Nabin Hait0dd7be12013-08-02 11:45:43 +053090
Nabin Hait9d0f6362013-01-07 18:51:11 +053091def get_incoming_rate(args):
92 """Get Incoming Rate based on valuation method"""
Rushabh Mehta1f847992013-12-12 19:12:19 +053093 from erpnext.stock.stock_ledger import get_previous_sle
Anand Doshi2ce39cf2014-04-07 18:51:58 +053094
Nabin Hait9d0f6362013-01-07 18:51:11 +053095 in_rate = 0
Anand Doshi40a8ae22014-08-29 16:28:31 +053096 if (args.get("serial_no") or "").strip():
Nabin Hait9d0f6362013-01-07 18:51:11 +053097 in_rate = get_avg_purchase_rate(args.get("serial_no"))
Nabin Hait9d0f6362013-01-07 18:51:11 +053098 else:
99 valuation_method = get_valuation_method(args.get("item_code"))
100 previous_sle = get_previous_sle(args)
101 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +0530102 if not previous_sle:
103 return 0.0
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530104 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Nabin Hait227db762014-05-08 19:06:01 +0530105 in_rate = get_fifo_rate(previous_stock_queue, args.get("qty") or 0) if previous_stock_queue else 0
Nabin Hait9d0f6362013-01-07 18:51:11 +0530106 elif valuation_method == 'Moving Average':
107 in_rate = previous_sle.get('valuation_rate') or 0
Anand Doshi094610d2014-04-16 19:56:53 +0530108
Nabin Hait9d0f6362013-01-07 18:51:11 +0530109 return in_rate
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530110
Nabin Hait9d0f6362013-01-07 18:51:11 +0530111def get_avg_purchase_rate(serial_nos):
112 """get average value of serial numbers"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530113
Nabin Hait9d0f6362013-01-07 18:51:11 +0530114 serial_nos = get_valid_serial_nos(serial_nos)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530115 return flt(frappe.db.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
Nabin Hait9d0f6362013-01-07 18:51:11 +0530116 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
117 tuple(serial_nos))[0][0])
118
119def get_valuation_method(item_code):
120 """get valuation method from item or default"""
Anand Doshie9baaa62014-02-26 12:35:33 +0530121 val_method = frappe.db.get_value('Item', item_code, 'valuation_method')
Nabin Hait9d0f6362013-01-07 18:51:11 +0530122 if not val_method:
Nabin Hait4d742162014-10-09 19:25:03 +0530123 val_method = frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530124 return val_method
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530125
Nabin Hait831207f2013-01-16 14:15:48 +0530126def get_fifo_rate(previous_stock_queue, qty):
127 """get FIFO (average) Rate from Queue"""
128 if qty >= 0:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530129 total = sum(f[0] for f in previous_stock_queue)
Nabin Hait38265ef2014-10-21 20:23:39 +0530130 return sum(flt(f[0]) * flt(f[1]) for f in previous_stock_queue) / flt(total) if total else 0.0
Nabin Hait831207f2013-01-16 14:15:48 +0530131 else:
Nabin Hait227db762014-05-08 19:06:01 +0530132 available_qty_for_outgoing, outgoing_cost = 0, 0
Nabin Hait831207f2013-01-16 14:15:48 +0530133 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530134 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530135 batch = previous_stock_queue[0]
136 if 0 < batch[0] <= qty_to_pop:
137 # if batch qty > 0
138 # not enough or exactly same qty in current batch, clear batch
Nabin Hait227db762014-05-08 19:06:01 +0530139 available_qty_for_outgoing += flt(batch[0])
Nabin Hait831207f2013-01-16 14:15:48 +0530140 outgoing_cost += flt(batch[0]) * flt(batch[1])
141 qty_to_pop -= batch[0]
142 previous_stock_queue.pop(0)
143 else:
144 # all from current batch
Nabin Hait227db762014-05-08 19:06:01 +0530145 available_qty_for_outgoing += flt(qty_to_pop)
Nabin Hait831207f2013-01-16 14:15:48 +0530146 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
147 batch[0] -= qty_to_pop
148 qty_to_pop = 0
Anand Doshi094610d2014-04-16 19:56:53 +0530149
Nabin Hait227db762014-05-08 19:06:01 +0530150 return outgoing_cost / available_qty_for_outgoing
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530151
Nabin Hait9d0f6362013-01-07 18:51:11 +0530152def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
153 """split serial nos, validate and return list of valid serial nos"""
154 # TODO: remove duplicates in client side
155 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530156
Nabin Hait9d0f6362013-01-07 18:51:11 +0530157 valid_serial_nos = []
158 for val in serial_nos:
159 if val:
160 val = val.strip()
161 if val in valid_serial_nos:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530162 frappe.throw(_("Serial number {0} entered more than once").format(val))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530163 else:
164 valid_serial_nos.append(val)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530165
Nabin Hait9d0f6362013-01-07 18:51:11 +0530166 if qty and len(valid_serial_nos) != abs(qty):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530167 frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530168
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530169 return valid_serial_nos
Nabin Haita72c5122013-03-06 18:50:53 +0530170
Anand Doshi373680b2013-10-10 16:04:40 +0530171def validate_warehouse_company(warehouse, company):
Anand Doshie9baaa62014-02-26 12:35:33 +0530172 warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company")
Anand Doshi373680b2013-10-10 16:04:40 +0530173 if warehouse_company and warehouse_company != company:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530174 frappe.throw(_("Warehouse {0} does not belong to company {1}").format(warehouse, company),
175 InvalidWarehouseCompany)
Rushabh Mehtaa65253b2013-08-27 10:32:56 +0530176