blob: dba73872e26baf422a95bccd4221f1f71f3d7f06 [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
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05304import frappe
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05305from frappe import _
Nabin Hait9d0f6362013-01-07 18:51:11 +05306import json
Rushabh Mehtaf8509872014-10-08 12:03:19 +05307from frappe.utils import flt, cstr, nowdate, nowtime
Nabin Hait9d0f6362013-01-07 18:51:11 +05308
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05309class InvalidWarehouseCompany(frappe.ValidationError): pass
Anand Doshi2ce39cf2014-04-07 18:51:58 +053010
Rushabh Mehtaf8509872014-10-08 12:03:19 +053011def get_stock_value_on(warehouse=None, posting_date=None, item_code=None):
Nabin Hait0dd7be12013-08-02 11:45:43 +053012 if not posting_date: posting_date = nowdate()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053013
Rushabh Mehtaf8509872014-10-08 12:03:19 +053014 values, condition = [posting_date], ""
15
16 if warehouse:
17 values.append(warehouse)
18 condition += " AND warehouse = %s"
19
20 if item_code:
21 values.append(item_code)
22 condition.append(" AND item_code = %s")
23
Anand Doshie9baaa62014-02-26 12:35:33 +053024 stock_ledger_entries = frappe.db.sql("""
Rushabh Mehtaf8509872014-10-08 12:03:19 +053025 SELECT item_code, stock_value
26 FROM `tabStock Ledger Entry`
27 WHERE posting_date <= %s {0}
Nabin Hait0dd7be12013-08-02 11:45:43 +053028 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
Rushabh Mehtaf8509872014-10-08 12:03:19 +053029 """.format(condition), values, as_dict=1)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053030
Nabin Hait0dd7be12013-08-02 11:45:43 +053031 sle_map = {}
32 for sle in stock_ledger_entries:
Nabin Hait625da792013-09-25 10:32:51 +053033 sle_map.setdefault(sle.item_code, flt(sle.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +053034
Nabin Hait625da792013-09-25 10:32:51 +053035 return sum(sle_map.values())
Anand Doshi2ce39cf2014-04-07 18:51:58 +053036
Rushabh Mehtaf8509872014-10-08 12:03:19 +053037def get_stock_balance(item_code, warehouse, posting_date=None, posting_time=None):
38 if not posting_date: posting_date = nowdate()
39 if not posting_time: posting_time = nowtime()
40 last_entry = frappe.db.sql("""select qty_after_transaction from `tabStock Ledger Entry`
41 where item_code=%s and warehouse=%s
42 and timestamp(posting_date, posting_time) < timestamp(%s, %s)
43 order by timestamp(posting_date, posting_time) limit 1""",
44 (item_code, warehouse, posting_date, posting_time))
45
46 if last_entry:
47 return last_entry[0][0]
48 else:
49 return 0.0
50
Nabin Hait47dc3182013-08-06 15:58:16 +053051def get_latest_stock_balance():
52 bin_map = {}
Anand Doshi2ce39cf2014-04-07 18:51:58 +053053 for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +053054 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +053055 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +053056
Nabin Hait47dc3182013-08-06 15:58:16 +053057 return bin_map
Anand Doshi2ce39cf2014-04-07 18:51:58 +053058
Nabin Hait74c281c2013-08-19 16:17:18 +053059def get_bin(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +053060 bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Nabin Hait74c281c2013-08-19 16:17:18 +053061 if not bin:
Rushabh Mehtaa504f062014-04-04 12:16:26 +053062 bin_obj = frappe.get_doc({
Nabin Hait74c281c2013-08-19 16:17:18 +053063 "doctype": "Bin",
64 "item_code": item_code,
65 "warehouse": warehouse,
Rushabh Mehtaa504f062014-04-04 12:16:26 +053066 })
67 bin_obj.ignore_permissions = 1
68 bin_obj.insert()
Nabin Hait74c281c2013-08-19 16:17:18 +053069 else:
Rushabh Mehtaa504f062014-04-04 12:16:26 +053070 bin_obj = frappe.get_doc('Bin', bin)
Anand Doshi094610d2014-04-16 19:56:53 +053071 bin_obj.ignore_permissions = True
Nabin Hait74c281c2013-08-19 16:17:18 +053072 return bin_obj
73
74def update_bin(args):
Anand Doshie9baaa62014-02-26 12:35:33 +053075 is_stock_item = frappe.db.get_value('Item', args.get("item_code"), 'is_stock_item')
Nabin Hait74c281c2013-08-19 16:17:18 +053076 if is_stock_item == 'Yes':
77 bin = get_bin(args.get("item_code"), args.get("warehouse"))
78 bin.update_stock(args)
79 return bin
80 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053081 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
Nabin Hait0dd7be12013-08-02 11:45:43 +053082
Nabin Hait9d0f6362013-01-07 18:51:11 +053083def get_incoming_rate(args):
84 """Get Incoming Rate based on valuation method"""
Rushabh Mehta1f847992013-12-12 19:12:19 +053085 from erpnext.stock.stock_ledger import get_previous_sle
Anand Doshi2ce39cf2014-04-07 18:51:58 +053086
Nabin Hait9d0f6362013-01-07 18:51:11 +053087 in_rate = 0
Anand Doshi40a8ae22014-08-29 16:28:31 +053088 if (args.get("serial_no") or "").strip():
Nabin Hait9d0f6362013-01-07 18:51:11 +053089 in_rate = get_avg_purchase_rate(args.get("serial_no"))
Nabin Hait9d0f6362013-01-07 18:51:11 +053090 else:
91 valuation_method = get_valuation_method(args.get("item_code"))
92 previous_sle = get_previous_sle(args)
93 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +053094 if not previous_sle:
95 return 0.0
Rushabh Mehta4c17f942013-08-12 14:18:09 +053096 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Nabin Hait227db762014-05-08 19:06:01 +053097 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 +053098 elif valuation_method == 'Moving Average':
99 in_rate = previous_sle.get('valuation_rate') or 0
Anand Doshi094610d2014-04-16 19:56:53 +0530100
Nabin Hait9d0f6362013-01-07 18:51:11 +0530101 return in_rate
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530102
Nabin Hait9d0f6362013-01-07 18:51:11 +0530103def get_avg_purchase_rate(serial_nos):
104 """get average value of serial numbers"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530105
Nabin Hait9d0f6362013-01-07 18:51:11 +0530106 serial_nos = get_valid_serial_nos(serial_nos)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530107 return flt(frappe.db.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
Nabin Hait9d0f6362013-01-07 18:51:11 +0530108 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
109 tuple(serial_nos))[0][0])
110
111def get_valuation_method(item_code):
112 """get valuation method from item or default"""
Anand Doshie9baaa62014-02-26 12:35:33 +0530113 val_method = frappe.db.get_value('Item', item_code, 'valuation_method')
Nabin Hait9d0f6362013-01-07 18:51:11 +0530114 if not val_method:
Nabin Hait4d742162014-10-09 19:25:03 +0530115 val_method = frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530116 return val_method
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530117
Nabin Hait831207f2013-01-16 14:15:48 +0530118def get_fifo_rate(previous_stock_queue, qty):
119 """get FIFO (average) Rate from Queue"""
120 if qty >= 0:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530121 total = sum(f[0] for f in previous_stock_queue)
Nabin Hait38265ef2014-10-21 20:23:39 +0530122 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 +0530123 else:
Nabin Hait227db762014-05-08 19:06:01 +0530124 available_qty_for_outgoing, outgoing_cost = 0, 0
Nabin Hait831207f2013-01-16 14:15:48 +0530125 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530126 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530127 batch = previous_stock_queue[0]
128 if 0 < batch[0] <= qty_to_pop:
129 # if batch qty > 0
130 # not enough or exactly same qty in current batch, clear batch
Nabin Hait227db762014-05-08 19:06:01 +0530131 available_qty_for_outgoing += flt(batch[0])
Nabin Hait831207f2013-01-16 14:15:48 +0530132 outgoing_cost += flt(batch[0]) * flt(batch[1])
133 qty_to_pop -= batch[0]
134 previous_stock_queue.pop(0)
135 else:
136 # all from current batch
Nabin Hait227db762014-05-08 19:06:01 +0530137 available_qty_for_outgoing += flt(qty_to_pop)
Nabin Hait831207f2013-01-16 14:15:48 +0530138 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
139 batch[0] -= qty_to_pop
140 qty_to_pop = 0
Anand Doshi094610d2014-04-16 19:56:53 +0530141
Nabin Hait227db762014-05-08 19:06:01 +0530142 return outgoing_cost / available_qty_for_outgoing
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530143
Nabin Hait9d0f6362013-01-07 18:51:11 +0530144def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
145 """split serial nos, validate and return list of valid serial nos"""
146 # TODO: remove duplicates in client side
147 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530148
Nabin Hait9d0f6362013-01-07 18:51:11 +0530149 valid_serial_nos = []
150 for val in serial_nos:
151 if val:
152 val = val.strip()
153 if val in valid_serial_nos:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530154 frappe.throw(_("Serial number {0} entered more than once").format(val))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530155 else:
156 valid_serial_nos.append(val)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530157
Nabin Hait9d0f6362013-01-07 18:51:11 +0530158 if qty and len(valid_serial_nos) != abs(qty):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530159 frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530160
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530161 return valid_serial_nos
Nabin Haita72c5122013-03-06 18:50:53 +0530162
Anand Doshi373680b2013-10-10 16:04:40 +0530163def validate_warehouse_company(warehouse, company):
Anand Doshie9baaa62014-02-26 12:35:33 +0530164 warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company")
Anand Doshi373680b2013-10-10 16:04:40 +0530165 if warehouse_company and warehouse_company != company:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530166 frappe.throw(_("Warehouse {0} does not belong to company {1}").format(warehouse, company),
167 InvalidWarehouseCompany)
Rushabh Mehtaa65253b2013-08-27 10:32:56 +0530168
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530169def get_sales_bom_buying_amount(item_code, warehouse, voucher_type, voucher_no, voucher_detail_no,
Nabin Hait94c90bd2013-08-30 22:48:19 +0530170 stock_ledger_entries, item_sales_bom):
171 # sales bom item
172 buying_amount = 0.0
173 for bom_item in item_sales_bom[item_code]:
174 if bom_item.get("parent_detail_docname")==voucher_detail_no:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530175 buying_amount += get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
Nabin Hait94c90bd2013-08-30 22:48:19 +0530176 stock_ledger_entries.get((bom_item.item_code, warehouse), []))
177
178 return buying_amount
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530179
ankitjavalkarwork9aa11d22014-09-18 19:06:11 +0530180def get_buying_amount(item_code, item_qty, voucher_type, voucher_no, item_row, stock_ledger_entries):
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530181 # IMP NOTE
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530182 # stock_ledger_entries should already be filtered by item_code and warehouse and
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530183 # sorted by posting_date desc, posting_time desc
ankitjavalkarwork9aa11d22014-09-18 19:06:11 +0530184 if frappe.db.get_value("Item", item_code, "is_stock_item") == "Yes":
185 for i, sle in enumerate(stock_ledger_entries):
186 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
187 sle.voucher_detail_no == item_row:
188 previous_stock_value = len(stock_ledger_entries) > i+1 and \
189 flt(stock_ledger_entries[i+1].stock_value) or 0.0
190 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530191
ankitjavalkarwork9aa11d22014-09-18 19:06:11 +0530192 return buying_amount
193 else:
194 item_rate = frappe.db.sql("""select sum(base_amount) / sum(qty)
195 from `tabPurchase Invoice Item`
196 where item_code = %s and docstatus=1""" % ('%s'), item_code)
Nabin Hait5e080f92014-09-26 15:05:30 +0530197 buying_amount = flt(item_qty) * flt(item_rate[0][0]) if item_rate else 0
ankitjavalkarwork9aa11d22014-09-18 19:06:11 +0530198
199 return buying_amount
200
Nabin Hait62d06292013-05-22 16:19:10 +0530201 return 0.0
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530202