blob: 575525399fc1f00a048e170ee449ea458463b08a [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)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053017
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053018 if cint(frappe.defaults.get_global_default("auto_accounting_for_stock")):
Nabin Haitb9e04812014-09-26 14:22:18 +053019 warehouse_account = get_warehouse_account()
Anand Doshi2ce39cf2014-04-07 18:51:58 +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:
Nabin Haitb9e04812014-09-26 14:22:18 +053026 items, warehouses = self.get_items_and_warehouses()
27 update_gl_entries_after(self.posting_date, self.posting_time, warehouses, items, warehouse_account)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053028
Nabin Haite83069c2013-11-14 18:40:08 +053029 def get_gl_entries(self, warehouse_account=None, default_expense_account=None,
Nabin Hait142007a2013-09-17 15:15:16 +053030 default_cost_center=None):
Rushabh Mehta1f847992013-12-12 19:12:19 +053031 from erpnext.accounts.general_ledger import process_gl_map
Nabin Hait142007a2013-09-17 15:15:16 +053032 if not warehouse_account:
Nabin Haitbecf75d2014-03-27 17:18:29 +053033 warehouse_account = get_warehouse_account()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053034
Anand Doshide1a97d2014-04-17 11:37:46 +053035 sle_map = self.get_stock_ledger_details()
36 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053037
Nabin Hait2e296fa2013-08-28 18:53:11 +053038 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +053039 warehouse_with_no_account = []
Nabin Hait2e296fa2013-08-28 18:53:11 +053040 for detail in voucher_details:
Anand Doshide1a97d2014-04-17 11:37:46 +053041 sle_list = sle_map.get(detail.name)
Nabin Hait2e296fa2013-08-28 18:53:11 +053042 if sle_list:
43 for sle in sle_list:
44 if warehouse_account.get(sle.warehouse):
Nabin Hait2e296fa2013-08-28 18:53:11 +053045 # from warehouse account
Rushabh Mehta052fe822014-04-16 19:20:11 +053046
Rushabh Mehtac38fc712014-04-16 17:21:25 +053047 self.check_expense_account(detail)
48
Nabin Hait2e296fa2013-08-28 18:53:11 +053049 gl_list.append(self.get_gl_dict({
50 "account": warehouse_account[sle.warehouse],
51 "against": detail.expense_account,
52 "cost_center": detail.cost_center,
Nabin Haitdc82d4f2014-04-07 12:02:57 +053053 "remarks": self.get("remarks") or "Accounting Entry for Stock",
Nabin Hait48bd4a12013-11-18 12:42:55 +053054 "debit": flt(sle.stock_value_difference, 2)
Nabin Hait2e296fa2013-08-28 18:53:11 +053055 }))
Nabin Hait27994c22013-08-26 16:53:30 +053056
Nabin Hait2e296fa2013-08-28 18:53:11 +053057 # to target warehouse / expense account
58 gl_list.append(self.get_gl_dict({
59 "account": detail.expense_account,
60 "against": warehouse_account[sle.warehouse],
61 "cost_center": detail.cost_center,
Nabin Haitdc82d4f2014-04-07 12:02:57 +053062 "remarks": self.get("remarks") or "Accounting Entry for Stock",
Nabin Hait48bd4a12013-11-18 12:42:55 +053063 "credit": flt(sle.stock_value_difference, 2)
Nabin Hait2e296fa2013-08-28 18:53:11 +053064 }))
Nabin Hait7a75e102013-09-17 10:21:20 +053065 elif sle.warehouse not in warehouse_with_no_account:
66 warehouse_with_no_account.append(sle.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053067
68 if warehouse_with_no_account:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053069 msgprint(_("No accounting entries for the following warehouses") + ": \n" +
Nabin Hait7a75e102013-09-17 10:21:20 +053070 "\n".join(warehouse_with_no_account))
Anand Doshi2ce39cf2014-04-07 18:51:58 +053071
Nabin Hait2e296fa2013-08-28 18:53:11 +053072 return process_gl_map(gl_list)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053073
Anand Doshide1a97d2014-04-17 11:37:46 +053074 def get_voucher_details(self, default_expense_account, default_cost_center, sle_map):
75 if self.doctype == "Stock Reconciliation":
76 return [frappe._dict({ "name": voucher_detail_no, "expense_account": default_expense_account,
77 "cost_center": default_cost_center }) for voucher_detail_no, sle in sle_map.items()]
78 else:
79 details = self.get(self.fname)
Anand Doshi094610d2014-04-16 19:56:53 +053080
Anand Doshide1a97d2014-04-17 11:37:46 +053081 if default_expense_account or default_cost_center:
82 for d in details:
83 if default_expense_account and not d.get("expense_account"):
84 d.expense_account = default_expense_account
85 if default_cost_center and not d.get("cost_center"):
86 d.cost_center = default_cost_center
Anand Doshi2ce39cf2014-04-07 18:51:58 +053087
Anand Doshide1a97d2014-04-17 11:37:46 +053088 return details
Anand Doshi2ce39cf2014-04-07 18:51:58 +053089
Nabin Haitb9e04812014-09-26 14:22:18 +053090 def get_items_and_warehouses(self):
Nabin Haitbecf75d2014-03-27 17:18:29 +053091 items, warehouses = [], []
Anand Doshi2ce39cf2014-04-07 18:51:58 +053092
Nabin Haitbecf75d2014-03-27 17:18:29 +053093 if hasattr(self, "fname"):
Rushabh Mehtaf191f852014-04-02 18:09:34 +053094 item_doclist = self.get(self.fname)
Anand Doshif78d1ae2014-03-28 13:55:00 +053095 elif self.doctype == "Stock Reconciliation":
Nabin Haitbecf75d2014-03-27 17:18:29 +053096 import json
97 item_doclist = []
Anand Doshif78d1ae2014-03-28 13:55:00 +053098 data = json.loads(self.reconciliation_json)
Nabin Haitbecf75d2014-03-27 17:18:29 +053099 for row in data[data.index(self.head_row)+1:]:
100 d = frappe._dict(zip(["item_code", "warehouse", "qty", "valuation_rate"], row))
101 item_doclist.append(d)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530102
Nabin Haitbecf75d2014-03-27 17:18:29 +0530103 if item_doclist:
104 for d in item_doclist:
105 if d.item_code and d.item_code not in items:
106 items.append(d.item_code)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530107
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530108 if d.get("warehouse") and d.warehouse not in warehouses:
Nabin Haitbecf75d2014-03-27 17:18:29 +0530109 warehouses.append(d.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530110
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530111 if self.doctype == "Stock Entry":
112 if d.get("s_warehouse") and d.s_warehouse not in warehouses:
113 warehouses.append(d.s_warehouse)
114 if d.get("t_warehouse") and d.t_warehouse not in warehouses:
115 warehouses.append(d.t_warehouse)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530116
Nabin Haitb9e04812014-09-26 14:22:18 +0530117 return items, warehouses
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530118
Nabin Hait2e296fa2013-08-28 18:53:11 +0530119 def get_stock_ledger_details(self):
120 stock_ledger = {}
Anand Doshie9baaa62014-02-26 12:35:33 +0530121 for sle in frappe.db.sql("""select warehouse, stock_value_difference, voucher_detail_no
Nabin Hait27994c22013-08-26 16:53:30 +0530122 from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s""",
Anand Doshif78d1ae2014-03-28 13:55:00 +0530123 (self.doctype, self.name), as_dict=True):
Nabin Hait2e296fa2013-08-28 18:53:11 +0530124 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
125 return stock_ledger
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530126
Nabin Hait2e296fa2013-08-28 18:53:11 +0530127 def make_adjustment_entry(self, expected_gle, voucher_obj):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530128 from erpnext.accounts.utils import get_stock_and_account_difference
Nabin Hait27994c22013-08-26 16:53:30 +0530129 account_list = [d.account for d in expected_gle]
130 acc_diff = get_stock_and_account_difference(account_list, expected_gle[0].posting_date)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530131
Nabin Hait27994c22013-08-26 16:53:30 +0530132 cost_center = self.get_company_default("cost_center")
133 stock_adjustment_account = self.get_company_default("stock_adjustment_account")
134
Nabin Haitd4741942013-08-06 15:57:25 +0530135 gl_entries = []
136 for account, diff in acc_diff.items():
137 if diff:
Nabin Hait27994c22013-08-26 16:53:30 +0530138 gl_entries.append([
139 # stock in hand account
Nabin Hait2e296fa2013-08-28 18:53:11 +0530140 voucher_obj.get_gl_dict({
Nabin Hait27994c22013-08-26 16:53:30 +0530141 "account": account,
142 "against": stock_adjustment_account,
143 "debit": diff,
144 "remarks": "Adjustment Accounting Entry for Stock",
145 }),
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530146
Nabin Hait27994c22013-08-26 16:53:30 +0530147 # account against stock in hand
Nabin Hait2e296fa2013-08-28 18:53:11 +0530148 voucher_obj.get_gl_dict({
Nabin Hait27994c22013-08-26 16:53:30 +0530149 "account": stock_adjustment_account,
150 "against": account,
151 "credit": diff,
152 "cost_center": cost_center or None,
153 "remarks": "Adjustment Accounting Entry for Stock",
154 }),
155 ])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530156
Nabin Haitd4741942013-08-06 15:57:25 +0530157 if gl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +0530158 from erpnext.accounts.general_ledger import make_gl_entries
Nabin Haitd4741942013-08-06 15:57:25 +0530159 make_gl_entries(gl_entries)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530160
Nabin Hait27994c22013-08-26 16:53:30 +0530161 def check_expense_account(self, item):
Rushabh Mehta052fe822014-04-16 19:20:11 +0530162 if not item.get("expense_account"):
Nabin Haitd3412542014-05-01 17:42:21 +0530163 frappe.throw(_("Expense or Difference account is mandatory for Item {0} as it impacts overall stock value").format(item.item_code))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530164
Anand Doshi496123a2014-06-19 19:25:19 +0530165 else:
Nabin Hait00778c92014-06-25 19:12:24 +0530166 is_expense_account = frappe.db.get_value("Account",
167 item.get("expense_account"), "report_type")=="Profit and Loss"
nabinhaite6cee7b2014-07-10 19:06:39 +0530168 if self.doctype not in ("Purchase Receipt", "Stock Reconciliation") and not is_expense_account:
Nabin Hait00778c92014-06-25 19:12:24 +0530169 frappe.throw(_("Expense / Difference account ({0}) must be a 'Profit or Loss' account")
170 .format(item.get("expense_account")))
Anand Doshi496123a2014-06-19 19:25:19 +0530171 if is_expense_account and not item.get("cost_center"):
172 frappe.throw(_("{0} {1}: Cost Center is mandatory for Item {2}").format(
173 _(self.doctype), self.name, item.get("item_code")))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530174
175 def get_sl_entries(self, d, args):
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530176 sl_dict = {
Nabin Hait296d6262014-05-02 17:36:13 +0530177 "item_code": d.get("item_code", None),
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530178 "warehouse": d.get("warehouse", None),
Anand Doshif78d1ae2014-03-28 13:55:00 +0530179 "posting_date": self.posting_date,
180 "posting_time": self.posting_time,
181 "voucher_type": self.doctype,
182 "voucher_no": self.name,
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530183 "voucher_detail_no": d.name,
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530184 "actual_qty": (self.docstatus==1 and 1 or -1)*flt(d.get("stock_qty")),
Nabin Hait296d6262014-05-02 17:36:13 +0530185 "stock_uom": d.get("stock_uom"),
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530186 "incoming_rate": 0,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530187 "company": self.company,
188 "fiscal_year": self.fiscal_year,
Nabin Hait296d6262014-05-02 17:36:13 +0530189 "batch_no": cstr(d.get("batch_no")).strip(),
190 "serial_no": d.get("serial_no"),
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530191 "project": d.get("project_name"),
Anand Doshif78d1ae2014-03-28 13:55:00 +0530192 "is_cancelled": self.docstatus==2 and "Yes" or "No"
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530193 }
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530194
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530195 sl_dict.update(args)
196 return sl_dict
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530197
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530198 def make_sl_entries(self, sl_entries, is_amended=None):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530199 from erpnext.stock.stock_ledger import make_sl_entries
Nabin Hait74c281c2013-08-19 16:17:18 +0530200 make_sl_entries(sl_entries, is_amended)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530201
nabinhait87f24012014-07-16 19:48:29 +0530202 def make_gl_entries_on_cancel(self):
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530203 if frappe.db.sql("""select name from `tabGL Entry` where voucher_type=%s
Anand Doshif78d1ae2014-03-28 13:55:00 +0530204 and voucher_no=%s""", (self.doctype, self.name)):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530205 self.make_gl_entries()
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530206
Anand Doshia740f752014-06-25 13:31:02 +0530207 def get_serialized_items(self):
208 serialized_items = []
209 item_codes = list(set([d.item_code for d in self.get(self.fname)]))
210 if item_codes:
211 serialized_items = frappe.db.sql_list("""select name from `tabItem`
212 where has_serial_no='Yes' and name in ({})""".format(", ".join(["%s"]*len(item_codes))),
213 tuple(item_codes))
214
215 return serialized_items
216
Nabin Haitb9e04812014-09-26 14:22:18 +0530217def update_gl_entries_after(posting_date, posting_time, for_warehouses=None, for_items=None, warehouse_account=None):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530218 def _delete_gl_entries(voucher_type, voucher_no):
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530219 frappe.db.sql("""delete from `tabGL Entry`
Nabin Haitbecf75d2014-03-27 17:18:29 +0530220 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530221
Nabin Haitbecf75d2014-03-27 17:18:29 +0530222 if not warehouse_account:
223 warehouse_account = get_warehouse_account()
Nabin Haitb9e04812014-09-26 14:22:18 +0530224
225 future_stock_vouchers = get_future_stock_vouchers(posting_date, posting_time, for_warehouses, for_items)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530226 gle = get_voucherwise_gl_entries(future_stock_vouchers, posting_date)
227
228 for voucher_type, voucher_no in future_stock_vouchers:
229 existing_gle = gle.get((voucher_type, voucher_no), [])
Rushabh Mehta0a0f2492014-03-31 17:27:06 +0530230 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530231 expected_gle = voucher_obj.get_gl_entries(warehouse_account)
232 if expected_gle:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530233 if not existing_gle or not compare_existing_and_expected_gle(existing_gle,
Nabin Haitbecf75d2014-03-27 17:18:29 +0530234 expected_gle):
235 _delete_gl_entries(voucher_type, voucher_no)
236 voucher_obj.make_gl_entries(repost_future_gle=False)
237 else:
238 _delete_gl_entries(voucher_type, voucher_no)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530239
Nabin Haitbecf75d2014-03-27 17:18:29 +0530240def compare_existing_and_expected_gle(existing_gle, expected_gle):
241 matched = True
242 for entry in expected_gle:
243 for e in existing_gle:
244 if entry.account==e.account and entry.against_account==e.against_account \
245 and entry.cost_center==e.cost_center \
246 and (entry.debit != e.debit or entry.credit != e.credit):
247 matched = False
248 break
249 return matched
250
Nabin Haitb9e04812014-09-26 14:22:18 +0530251def get_future_stock_vouchers(posting_date, posting_time, for_warehouses=None, for_items=None):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530252 future_stock_vouchers = []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530253
Anand Doshi913c51b2014-08-27 22:09:03 +0530254 values = []
Nabin Haitbecf75d2014-03-27 17:18:29 +0530255 condition = ""
256 if for_items:
Anand Doshi913c51b2014-08-27 22:09:03 +0530257 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
258 values += for_items
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530259
Nabin Haitb9e04812014-09-26 14:22:18 +0530260 if for_warehouses:
261 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
262 values += for_warehouses
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530263
264 for d in frappe.db.sql("""select distinct sle.voucher_type, sle.voucher_no
Nabin Haitbecf75d2014-03-27 17:18:29 +0530265 from `tabStock Ledger Entry` sle
Anand Doshi913c51b2014-08-27 22:09:03 +0530266 where timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s) {condition}
267 order by timestamp(sle.posting_date, sle.posting_time) asc, name asc""".format(condition=condition),
268 tuple([posting_date, posting_time] + values), as_dict=True):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530269 future_stock_vouchers.append([d.voucher_type, d.voucher_no])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530270
Nabin Haitbecf75d2014-03-27 17:18:29 +0530271 return future_stock_vouchers
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530272
Nabin Haitbecf75d2014-03-27 17:18:29 +0530273def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
274 gl_entries = {}
275 if future_stock_vouchers:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530276 for d in frappe.db.sql("""select * from `tabGL Entry`
277 where posting_date >= %s and voucher_no in (%s)""" %
278 ('%s', ', '.join(['%s']*len(future_stock_vouchers))),
Nabin Haitbecf75d2014-03-27 17:18:29 +0530279 tuple([posting_date] + [d[1] for d in future_stock_vouchers]), as_dict=1):
280 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530281
Nabin Haitbecf75d2014-03-27 17:18:29 +0530282 return gl_entries
283
284def get_warehouse_account():
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530285 warehouse_account = dict(frappe.db.sql("""select master_name, name from tabAccount
Nabin Haitbecf75d2014-03-27 17:18:29 +0530286 where account_type = 'Warehouse' and ifnull(master_name, '') != ''"""))
Anand Doshi67d6a4e2014-03-28 13:41:59 +0530287 return warehouse_account