blob: 33b7fdb26bf8e0f735dda40b86aa8f40217e1fe3 [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 Haitc3afb252013-03-19 12:01:24 +05303
4from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
6from frappe.utils import cint, flt, cstr
7from frappe import msgprint, _
8import frappe.defaults
Nabin Haitd4741942013-08-06 15:57:25 +05309
Rushabh Mehta1f847992013-12-12 19:12:19 +053010from erpnext.controllers.accounts_controller import AccountsController
11from erpnext.accounts.general_ledger import make_gl_entries, delete_gl_entries
Nabin Haitc3afb252013-03-19 12:01:24 +053012
13class StockController(AccountsController):
Nabin Haitbecf75d2014-03-27 17:18:29 +053014 def make_gl_entries(self, repost_future_gle=True):
Anand Doshif78d1ae2014-03-28 13:55:00 +053015 if self.docstatus == 2:
16 delete_gl_entries(voucher_type=self.doctype, voucher_no=self.name)
Nabin Hait145e5e22013-10-22 23:51:41 +053017
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053018 if cint(frappe.defaults.get_global_default("auto_accounting_for_stock")):
Nabin Hait145e5e22013-10-22 23:51:41 +053019 warehouse_account = self.get_warehouse_account()
Nabin Hait2e296fa2013-08-28 18:53:11 +053020
Anand Doshif78d1ae2014-03-28 13:55:00 +053021 if self.docstatus==1:
Nabin Haite83069c2013-11-14 18:40:08 +053022 gl_entries = self.get_gl_entries(warehouse_account)
Nabin Hait145e5e22013-10-22 23:51:41 +053023 make_gl_entries(gl_entries)
24
Nabin Haitbecf75d2014-03-27 17:18:29 +053025 if repost_future_gle:
26 items, warehouse_account = self.get_items_and_warehouse_accounts(warehouse_account)
Anand Doshif78d1ae2014-03-28 13:55:00 +053027 update_gl_entries_after(self.posting_date, self.posting_time,
Nabin Haitbecf75d2014-03-27 17:18:29 +053028 warehouse_account, items)
Nabin Hait2e296fa2013-08-28 18:53:11 +053029
Nabin Haite83069c2013-11-14 18:40:08 +053030 def get_gl_entries(self, warehouse_account=None, default_expense_account=None,
Nabin Hait142007a2013-09-17 15:15:16 +053031 default_cost_center=None):
Rushabh Mehta1f847992013-12-12 19:12:19 +053032 from erpnext.accounts.general_ledger import process_gl_map
Nabin Hait142007a2013-09-17 15:15:16 +053033 if not warehouse_account:
Nabin Haitbecf75d2014-03-27 17:18:29 +053034 warehouse_account = get_warehouse_account()
Nabin Hait142007a2013-09-17 15:15:16 +053035
Nabin Hait2e296fa2013-08-28 18:53:11 +053036 stock_ledger = self.get_stock_ledger_details()
37 voucher_details = self.get_voucher_details(stock_ledger, default_expense_account,
38 default_cost_center)
39
40 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +053041 warehouse_with_no_account = []
Nabin Hait2e296fa2013-08-28 18:53:11 +053042 for detail in voucher_details:
43 sle_list = stock_ledger.get(detail.name)
44 if sle_list:
45 for sle in sle_list:
46 if warehouse_account.get(sle.warehouse):
Nabin Hait2e296fa2013-08-28 18:53:11 +053047 # from warehouse account
48 gl_list.append(self.get_gl_dict({
49 "account": warehouse_account[sle.warehouse],
50 "against": detail.expense_account,
51 "cost_center": detail.cost_center,
Anand Doshif78d1ae2014-03-28 13:55:00 +053052 "remarks": self.remarks or "Accounting Entry for Stock",
Nabin Hait48bd4a12013-11-18 12:42:55 +053053 "debit": flt(sle.stock_value_difference, 2)
Nabin Hait2e296fa2013-08-28 18:53:11 +053054 }))
Nabin Hait27994c22013-08-26 16:53:30 +053055
Nabin Hait2e296fa2013-08-28 18:53:11 +053056 # to target warehouse / expense account
57 gl_list.append(self.get_gl_dict({
58 "account": detail.expense_account,
59 "against": warehouse_account[sle.warehouse],
60 "cost_center": detail.cost_center,
Anand Doshif78d1ae2014-03-28 13:55:00 +053061 "remarks": self.remarks or "Accounting Entry for Stock",
Nabin Hait48bd4a12013-11-18 12:42:55 +053062 "credit": flt(sle.stock_value_difference, 2)
Nabin Hait2e296fa2013-08-28 18:53:11 +053063 }))
Nabin Hait7a75e102013-09-17 10:21:20 +053064 elif sle.warehouse not in warehouse_with_no_account:
65 warehouse_with_no_account.append(sle.warehouse)
66
67 if warehouse_with_no_account:
68 msgprint(_("No accounting entries for following warehouses") + ": \n" +
69 "\n".join(warehouse_with_no_account))
Nabin Hait27994c22013-08-26 16:53:30 +053070
Nabin Hait2e296fa2013-08-28 18:53:11 +053071 return process_gl_map(gl_list)
Nabin Hait27994c22013-08-26 16:53:30 +053072
Nabin Hait2e296fa2013-08-28 18:53:11 +053073 def get_voucher_details(self, stock_ledger, default_expense_account, default_cost_center):
74 if not default_expense_account:
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +053075 details = self.get(self.fname)
Nabin Hait2e296fa2013-08-28 18:53:11 +053076 for d in details:
77 self.check_expense_account(d)
78 else:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053079 details = [frappe._dict({
Nabin Hait2e296fa2013-08-28 18:53:11 +053080 "name":d,
81 "expense_account": default_expense_account,
82 "cost_center": default_cost_center
83 }) for d in stock_ledger.keys()]
84
85 return details
86
Nabin Haitbecf75d2014-03-27 17:18:29 +053087 def get_items_and_warehouse_accounts(self, warehouse_account=None):
88 items, warehouses = [], []
89 if not warehouse_account:
90 warehouse_account = get_warehouse_account()
91
92 if hasattr(self, "fname"):
93 item_doclist = self.doclist.get({"parentfield": self.fname})
Anand Doshif78d1ae2014-03-28 13:55:00 +053094 elif self.doctype == "Stock Reconciliation":
Nabin Haitbecf75d2014-03-27 17:18:29 +053095 import json
96 item_doclist = []
Anand Doshif78d1ae2014-03-28 13:55:00 +053097 data = json.loads(self.reconciliation_json)
Nabin Haitbecf75d2014-03-27 17:18:29 +053098 for row in data[data.index(self.head_row)+1:]:
99 d = frappe._dict(zip(["item_code", "warehouse", "qty", "valuation_rate"], row))
100 item_doclist.append(d)
101
102 if item_doclist:
103 for d in item_doclist:
104 if d.item_code and d.item_code not in items:
105 items.append(d.item_code)
106 if d.warehouse and d.warehouse not in warehouses:
107 warehouses.append(d.warehouse)
108
109 warehouse_account = {wh: warehouse_account[wh] for wh in warehouses
110 if warehouse_account.get(wh)}
111
112 return items, warehouse_account
113
Nabin Hait2e296fa2013-08-28 18:53:11 +0530114 def get_stock_ledger_details(self):
115 stock_ledger = {}
Anand Doshie9baaa62014-02-26 12:35:33 +0530116 for sle in frappe.db.sql("""select warehouse, stock_value_difference, voucher_detail_no
Nabin Hait27994c22013-08-26 16:53:30 +0530117 from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s""",
Anand Doshif78d1ae2014-03-28 13:55:00 +0530118 (self.doctype, self.name), as_dict=True):
Nabin Hait2e296fa2013-08-28 18:53:11 +0530119 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
120 return stock_ledger
Nabin Hait27994c22013-08-26 16:53:30 +0530121
Nabin Hait2e296fa2013-08-28 18:53:11 +0530122 def get_warehouse_account(self):
Anand Doshie9baaa62014-02-26 12:35:33 +0530123 warehouse_account = dict(frappe.db.sql("""select master_name, name from tabAccount
Nabin Hait7a75e102013-09-17 10:21:20 +0530124 where account_type = 'Warehouse' and ifnull(master_name, '') != ''"""))
Nabin Hait2e296fa2013-08-28 18:53:11 +0530125 return warehouse_account
Nabin Hait27994c22013-08-26 16:53:30 +0530126
Nabin Hait142007a2013-09-17 15:15:16 +0530127 def update_gl_entries_after(self, warehouse_account=None):
Nabin Hait27994c22013-08-26 16:53:30 +0530128 future_stock_vouchers = self.get_future_stock_vouchers()
129 gle = self.get_voucherwise_gl_entries(future_stock_vouchers)
Nabin Hait142007a2013-09-17 15:15:16 +0530130 if not warehouse_account:
131 warehouse_account = self.get_warehouse_account()
Nabin Hait27994c22013-08-26 16:53:30 +0530132 for voucher_type, voucher_no in future_stock_vouchers:
Nabin Hait2e296fa2013-08-28 18:53:11 +0530133 existing_gle = gle.get((voucher_type, voucher_no), [])
Rushabh Mehta0a0f2492014-03-31 17:27:06 +0530134 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
Nabin Haite83069c2013-11-14 18:40:08 +0530135 expected_gle = voucher_obj.get_gl_entries(warehouse_account)
Nabin Hait27994c22013-08-26 16:53:30 +0530136 if expected_gle:
Nabin Hait2e296fa2013-08-28 18:53:11 +0530137 matched = True
Nabin Hait27994c22013-08-26 16:53:30 +0530138 if existing_gle:
Nabin Hait27994c22013-08-26 16:53:30 +0530139 for entry in expected_gle:
Nabin Hait2e296fa2013-08-28 18:53:11 +0530140 for e in existing_gle:
141 if entry.account==e.account \
142 and entry.against_account==e.against_account\
143 and entry.cost_center==e.cost_center:
144 if entry.debit != e.debit or entry.credit != e.credit:
145 matched = False
146 break
Nabin Hait27994c22013-08-26 16:53:30 +0530147 else:
Nabin Hait2e296fa2013-08-28 18:53:11 +0530148 matched = False
149
150 if not matched:
151 self.delete_gl_entries(voucher_type, voucher_no)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530152 voucher_obj.make_gl_entries(repost_future_gle=False)
Nabin Hait2e296fa2013-08-28 18:53:11 +0530153 else:
154 self.delete_gl_entries(voucher_type, voucher_no)
Nabin Hait27994c22013-08-26 16:53:30 +0530155
156
157 def get_future_stock_vouchers(self):
158 future_stock_vouchers = []
Nabin Haitbf4d27e2013-09-04 17:55:45 +0530159
160 if hasattr(self, "fname"):
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530161 item_list = [d.item_code for d in self.get(self.fname)]
Nabin Haitbf4d27e2013-09-04 17:55:45 +0530162 condition = ''.join(['and item_code in (\'', '\', \''.join(item_list) ,'\')'])
163 else:
164 condition = ""
Nabin Hait2e296fa2013-08-28 18:53:11 +0530165
Anand Doshie9baaa62014-02-26 12:35:33 +0530166 for d in frappe.db.sql("""select distinct sle.voucher_type, sle.voucher_no
Nabin Hait2e296fa2013-08-28 18:53:11 +0530167 from `tabStock Ledger Entry` sle
Nabin Haitbf4d27e2013-09-04 17:55:45 +0530168 where timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s) %s
169 order by timestamp(sle.posting_date, sle.posting_time) asc, name asc""" %
Anand Doshif78d1ae2014-03-28 13:55:00 +0530170 ('%s', '%s', condition), (self.posting_date, self.posting_time),
Nabin Haitbf4d27e2013-09-04 17:55:45 +0530171 as_dict=True):
Nabin Hait27994c22013-08-26 16:53:30 +0530172 future_stock_vouchers.append([d.voucher_type, d.voucher_no])
Nabin Hait2e296fa2013-08-28 18:53:11 +0530173
Nabin Hait27994c22013-08-26 16:53:30 +0530174 return future_stock_vouchers
175
176 def get_voucherwise_gl_entries(self, future_stock_vouchers):
177 gl_entries = {}
178 if future_stock_vouchers:
Anand Doshie9baaa62014-02-26 12:35:33 +0530179 for d in frappe.db.sql("""select * from `tabGL Entry`
Nabin Hait27994c22013-08-26 16:53:30 +0530180 where posting_date >= %s and voucher_no in (%s)""" %
181 ('%s', ', '.join(['%s']*len(future_stock_vouchers))),
Anand Doshif78d1ae2014-03-28 13:55:00 +0530182 tuple([self.posting_date] + [d[1] for d in future_stock_vouchers]), as_dict=1):
Nabin Hait2e296fa2013-08-28 18:53:11 +0530183 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Nabin Hait27994c22013-08-26 16:53:30 +0530184
185 return gl_entries
Nabin Hait2e296fa2013-08-28 18:53:11 +0530186
187 def delete_gl_entries(self, voucher_type, voucher_no):
Anand Doshie9baaa62014-02-26 12:35:33 +0530188 frappe.db.sql("""delete from `tabGL Entry`
Nabin Hait2e296fa2013-08-28 18:53:11 +0530189 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Nabin Hait27994c22013-08-26 16:53:30 +0530190
Nabin Hait2e296fa2013-08-28 18:53:11 +0530191 def make_adjustment_entry(self, expected_gle, voucher_obj):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530192 from erpnext.accounts.utils import get_stock_and_account_difference
Nabin Hait27994c22013-08-26 16:53:30 +0530193 account_list = [d.account for d in expected_gle]
194 acc_diff = get_stock_and_account_difference(account_list, expected_gle[0].posting_date)
195
196 cost_center = self.get_company_default("cost_center")
197 stock_adjustment_account = self.get_company_default("stock_adjustment_account")
198
Nabin Haitd4741942013-08-06 15:57:25 +0530199 gl_entries = []
200 for account, diff in acc_diff.items():
201 if diff:
Nabin Hait27994c22013-08-26 16:53:30 +0530202 gl_entries.append([
203 # stock in hand account
Nabin Hait2e296fa2013-08-28 18:53:11 +0530204 voucher_obj.get_gl_dict({
Nabin Hait27994c22013-08-26 16:53:30 +0530205 "account": account,
206 "against": stock_adjustment_account,
207 "debit": diff,
208 "remarks": "Adjustment Accounting Entry for Stock",
209 }),
210
211 # account against stock in hand
Nabin Hait2e296fa2013-08-28 18:53:11 +0530212 voucher_obj.get_gl_dict({
Nabin Hait27994c22013-08-26 16:53:30 +0530213 "account": stock_adjustment_account,
214 "against": account,
215 "credit": diff,
216 "cost_center": cost_center or None,
217 "remarks": "Adjustment Accounting Entry for Stock",
218 }),
219 ])
220
Nabin Haitd4741942013-08-06 15:57:25 +0530221 if gl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +0530222 from erpnext.accounts.general_ledger import make_gl_entries
Nabin Haitd4741942013-08-06 15:57:25 +0530223 make_gl_entries(gl_entries)
Nabin Hait27994c22013-08-26 16:53:30 +0530224
225 def check_expense_account(self, item):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530226 if item.meta.has_field("expense_account") and not item.expense_account:
Nabin Hait678130f2013-09-02 18:10:36 +0530227 msgprint(_("""Expense/Difference account is mandatory for item: """) + item.item_code,
Nabin Hait27994c22013-08-26 16:53:30 +0530228 raise_exception=1)
229
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530230 if item.meta.has_field("expense_account") and not item.cost_center:
Nabin Hait27994c22013-08-26 16:53:30 +0530231 msgprint(_("""Cost Center is mandatory for item: """) + item.item_code,
232 raise_exception=1)
Nabin Haitd4741942013-08-06 15:57:25 +0530233
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530234 def get_sl_entries(self, d, args):
235 sl_dict = {
236 "item_code": d.item_code,
237 "warehouse": d.warehouse,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530238 "posting_date": self.posting_date,
239 "posting_time": self.posting_time,
240 "voucher_type": self.doctype,
241 "voucher_no": self.name,
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530242 "voucher_detail_no": d.name,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530243 "actual_qty": (self.docstatus==1 and 1 or -1)*flt(d.stock_qty),
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530244 "stock_uom": d.stock_uom,
245 "incoming_rate": 0,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530246 "company": self.company,
247 "fiscal_year": self.fiscal_year,
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530248 "batch_no": cstr(d.batch_no).strip(),
249 "serial_no": d.serial_no,
Nabin Hait74c281c2013-08-19 16:17:18 +0530250 "project": d.project_name,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530251 "is_cancelled": self.docstatus==2 and "Yes" or "No"
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530252 }
253
254 sl_dict.update(args)
255 return sl_dict
256
257 def make_sl_entries(self, sl_entries, is_amended=None):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530258 from erpnext.stock.stock_ledger import make_sl_entries
Nabin Hait74c281c2013-08-19 16:17:18 +0530259 make_sl_entries(sl_entries, is_amended)
260
Nabin Hait787c02e2013-03-29 16:42:33 +0530261 def make_cancel_gl_entries(self):
Anand Doshie9baaa62014-02-26 12:35:33 +0530262 if frappe.db.sql("""select name from `tabGL Entry` where voucher_type=%s
Anand Doshif78d1ae2014-03-28 13:55:00 +0530263 and voucher_no=%s""", (self.doctype, self.name)):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530264 self.make_gl_entries()
265
266def update_gl_entries_after(posting_date, posting_time, warehouse_account=None, for_items=None):
267 def _delete_gl_entries(voucher_type, voucher_no):
268 frappe.db.sql("""delete from `tabGL Entry`
269 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
270
271 if not warehouse_account:
272 warehouse_account = get_warehouse_account()
273 future_stock_vouchers = get_future_stock_vouchers(posting_date, posting_time,
274 warehouse_account, for_items)
275 gle = get_voucherwise_gl_entries(future_stock_vouchers, posting_date)
276
277 for voucher_type, voucher_no in future_stock_vouchers:
278 existing_gle = gle.get((voucher_type, voucher_no), [])
Rushabh Mehta0a0f2492014-03-31 17:27:06 +0530279 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530280 expected_gle = voucher_obj.get_gl_entries(warehouse_account)
281 if expected_gle:
282 if not existing_gle or not compare_existing_and_expected_gle(existing_gle,
283 expected_gle):
284 _delete_gl_entries(voucher_type, voucher_no)
285 voucher_obj.make_gl_entries(repost_future_gle=False)
286 else:
287 _delete_gl_entries(voucher_type, voucher_no)
288
289def compare_existing_and_expected_gle(existing_gle, expected_gle):
290 matched = True
291 for entry in expected_gle:
292 for e in existing_gle:
293 if entry.account==e.account and entry.against_account==e.against_account \
294 and entry.cost_center==e.cost_center \
295 and (entry.debit != e.debit or entry.credit != e.credit):
296 matched = False
297 break
298 return matched
299
300def get_future_stock_vouchers(posting_date, posting_time, warehouse_account=None, for_items=None):
301 future_stock_vouchers = []
302
303 condition = ""
304 if for_items:
305 condition = ''.join([' and item_code in (\'', '\', \''.join(for_items) ,'\')'])
306
307 if warehouse_account:
308 condition += ''.join([' and warehouse in (\'', '\', \''.join(warehouse_account.keys()) ,'\')'])
309
310 for d in frappe.db.sql("""select distinct sle.voucher_type, sle.voucher_no
311 from `tabStock Ledger Entry` sle
312 where timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s) %s
313 order by timestamp(sle.posting_date, sle.posting_time) asc, name asc""" %
314 ('%s', '%s', condition), (posting_date, posting_time),
315 as_dict=True):
316 future_stock_vouchers.append([d.voucher_type, d.voucher_no])
317
318 return future_stock_vouchers
319
320def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
321 gl_entries = {}
322 if future_stock_vouchers:
323 for d in frappe.db.sql("""select * from `tabGL Entry`
324 where posting_date >= %s and voucher_no in (%s)""" %
325 ('%s', ', '.join(['%s']*len(future_stock_vouchers))),
326 tuple([posting_date] + [d[1] for d in future_stock_vouchers]), as_dict=1):
327 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
328
329 return gl_entries
330
331def get_warehouse_account():
332 warehouse_account = dict(frappe.db.sql("""select master_name, name from tabAccount
333 where account_type = 'Warehouse' and ifnull(master_name, '') != ''"""))
Anand Doshi67d6a4e2014-03-28 13:41:59 +0530334 return warehouse_account