blob: 66780074893018c600cb1cae7a87de79e8408baf [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe 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
Nabin Haitadeb9762014-10-06 11:53:52 +053011from erpnext.accounts.general_ledger import make_gl_entries, delete_gl_entries, process_gl_map
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()
Nabin Haitadeb9762014-10-06 11:53:52 +053027 update_gl_entries_after(self.posting_date, self.posting_time, warehouses, items,
Nabin Haitf1a07ff2014-10-15 12:23:35 +053028 warehouse_account)
Anand Doshi2ce39cf2014-04-07 18:51:58 +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):
Nabin Haitadeb9762014-10-06 11:53:52 +053032
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()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053035
Anand Doshide1a97d2014-04-17 11:37:46 +053036 sle_map = self.get_stock_ledger_details()
37 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053038
Nabin Hait2e296fa2013-08-28 18:53:11 +053039 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +053040 warehouse_with_no_account = []
Nabin Hait2e296fa2013-08-28 18:53:11 +053041 for detail in voucher_details:
Anand Doshide1a97d2014-04-17 11:37:46 +053042 sle_list = sle_map.get(detail.name)
Nabin Hait2e296fa2013-08-28 18:53:11 +053043 if sle_list:
44 for sle in sle_list:
45 if warehouse_account.get(sle.warehouse):
Nabin Hait2e296fa2013-08-28 18:53:11 +053046 # from warehouse account
Rushabh Mehta052fe822014-04-16 19:20:11 +053047
Rushabh Mehtac38fc712014-04-16 17:21:25 +053048 self.check_expense_account(detail)
49
Nabin Hait2e296fa2013-08-28 18:53:11 +053050 gl_list.append(self.get_gl_dict({
51 "account": warehouse_account[sle.warehouse],
52 "against": detail.expense_account,
53 "cost_center": detail.cost_center,
Nabin Haitdc82d4f2014-04-07 12:02:57 +053054 "remarks": self.get("remarks") or "Accounting Entry for Stock",
Nabin Hait48bd4a12013-11-18 12:42:55 +053055 "debit": flt(sle.stock_value_difference, 2)
Nabin Hait2e296fa2013-08-28 18:53:11 +053056 }))
Nabin Hait27994c22013-08-26 16:53:30 +053057
Nabin Hait2e296fa2013-08-28 18:53:11 +053058 # to target warehouse / expense account
59 gl_list.append(self.get_gl_dict({
60 "account": detail.expense_account,
61 "against": warehouse_account[sle.warehouse],
62 "cost_center": detail.cost_center,
Nabin Haitdc82d4f2014-04-07 12:02:57 +053063 "remarks": self.get("remarks") or "Accounting Entry for Stock",
Nabin Hait48bd4a12013-11-18 12:42:55 +053064 "credit": flt(sle.stock_value_difference, 2)
Nabin Hait2e296fa2013-08-28 18:53:11 +053065 }))
Nabin Hait7a75e102013-09-17 10:21:20 +053066 elif sle.warehouse not in warehouse_with_no_account:
67 warehouse_with_no_account.append(sle.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053068
69 if warehouse_with_no_account:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053070 msgprint(_("No accounting entries for the following warehouses") + ": \n" +
Nabin Hait7a75e102013-09-17 10:21:20 +053071 "\n".join(warehouse_with_no_account))
Anand Doshi2ce39cf2014-04-07 18:51:58 +053072
Nabin Hait2e296fa2013-08-28 18:53:11 +053073 return process_gl_map(gl_list)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053074
Anand Doshide1a97d2014-04-17 11:37:46 +053075 def get_voucher_details(self, default_expense_account, default_cost_center, sle_map):
76 if self.doctype == "Stock Reconciliation":
77 return [frappe._dict({ "name": voucher_detail_no, "expense_account": default_expense_account,
78 "cost_center": default_cost_center }) for voucher_detail_no, sle in sle_map.items()]
79 else:
Nabin Haitdd38a262014-12-26 13:15:21 +053080 details = self.get("items")
Anand Doshi094610d2014-04-16 19:56:53 +053081
Anand Doshide1a97d2014-04-17 11:37:46 +053082 if default_expense_account or default_cost_center:
83 for d in details:
84 if default_expense_account and not d.get("expense_account"):
85 d.expense_account = default_expense_account
86 if default_cost_center and not d.get("cost_center"):
87 d.cost_center = default_cost_center
Anand Doshi2ce39cf2014-04-07 18:51:58 +053088
Anand Doshide1a97d2014-04-17 11:37:46 +053089 return details
Anand Doshi2ce39cf2014-04-07 18:51:58 +053090
Nabin Haitb9e04812014-09-26 14:22:18 +053091 def get_items_and_warehouses(self):
Nabin Haitbecf75d2014-03-27 17:18:29 +053092 items, warehouses = [], []
Anand Doshi2ce39cf2014-04-07 18:51:58 +053093
Nabin Haitdd38a262014-12-26 13:15:21 +053094 if hasattr(self, "items"):
95 item_doclist = self.get("items")
Anand Doshif78d1ae2014-03-28 13:55:00 +053096 elif self.doctype == "Stock Reconciliation":
Nabin Haitbecf75d2014-03-27 17:18:29 +053097 import json
98 item_doclist = []
Anand Doshif78d1ae2014-03-28 13:55:00 +053099 data = json.loads(self.reconciliation_json)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530100 for row in data[data.index(self.head_row)+1:]:
101 d = frappe._dict(zip(["item_code", "warehouse", "qty", "valuation_rate"], row))
102 item_doclist.append(d)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530103
Nabin Haitbecf75d2014-03-27 17:18:29 +0530104 if item_doclist:
105 for d in item_doclist:
106 if d.item_code and d.item_code not in items:
107 items.append(d.item_code)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530108
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530109 if d.get("warehouse") and d.warehouse not in warehouses:
Nabin Haitbecf75d2014-03-27 17:18:29 +0530110 warehouses.append(d.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530111
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530112 if self.doctype == "Stock Entry":
113 if d.get("s_warehouse") and d.s_warehouse not in warehouses:
114 warehouses.append(d.s_warehouse)
115 if d.get("t_warehouse") and d.t_warehouse not in warehouses:
116 warehouses.append(d.t_warehouse)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530117
Nabin Haitb9e04812014-09-26 14:22:18 +0530118 return items, warehouses
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530119
Nabin Hait2e296fa2013-08-28 18:53:11 +0530120 def get_stock_ledger_details(self):
121 stock_ledger = {}
Nabin Hait6c48ef72014-10-08 11:00:38 +0530122 for sle in frappe.db.sql("""select warehouse, stock_value_difference,
123 voucher_detail_no, item_code, posting_date, actual_qty
Nabin Hait27994c22013-08-26 16:53:30 +0530124 from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s""",
Anand Doshif78d1ae2014-03-28 13:55:00 +0530125 (self.doctype, self.name), as_dict=True):
Nabin Hait2e296fa2013-08-28 18:53:11 +0530126 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
127 return stock_ledger
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530128
Nabin Hait2e296fa2013-08-28 18:53:11 +0530129 def make_adjustment_entry(self, expected_gle, voucher_obj):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530130 from erpnext.accounts.utils import get_stock_and_account_difference
Nabin Hait27994c22013-08-26 16:53:30 +0530131 account_list = [d.account for d in expected_gle]
132 acc_diff = get_stock_and_account_difference(account_list, expected_gle[0].posting_date)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530133
Nabin Hait27994c22013-08-26 16:53:30 +0530134 cost_center = self.get_company_default("cost_center")
135 stock_adjustment_account = self.get_company_default("stock_adjustment_account")
136
Nabin Haitd4741942013-08-06 15:57:25 +0530137 gl_entries = []
138 for account, diff in acc_diff.items():
139 if diff:
Nabin Hait27994c22013-08-26 16:53:30 +0530140 gl_entries.append([
141 # stock in hand account
Nabin Hait2e296fa2013-08-28 18:53:11 +0530142 voucher_obj.get_gl_dict({
Nabin Hait27994c22013-08-26 16:53:30 +0530143 "account": account,
144 "against": stock_adjustment_account,
145 "debit": diff,
146 "remarks": "Adjustment Accounting Entry for Stock",
147 }),
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530148
Nabin Hait27994c22013-08-26 16:53:30 +0530149 # account against stock in hand
Nabin Hait2e296fa2013-08-28 18:53:11 +0530150 voucher_obj.get_gl_dict({
Nabin Hait27994c22013-08-26 16:53:30 +0530151 "account": stock_adjustment_account,
152 "against": account,
153 "credit": diff,
154 "cost_center": cost_center or None,
155 "remarks": "Adjustment Accounting Entry for Stock",
156 }),
157 ])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530158
Nabin Haitd4741942013-08-06 15:57:25 +0530159 if gl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +0530160 from erpnext.accounts.general_ledger import make_gl_entries
Nabin Haitd4741942013-08-06 15:57:25 +0530161 make_gl_entries(gl_entries)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530162
Nabin Hait27994c22013-08-26 16:53:30 +0530163 def check_expense_account(self, item):
Rushabh Mehta052fe822014-04-16 19:20:11 +0530164 if not item.get("expense_account"):
Nabin Haitd3412542014-05-01 17:42:21 +0530165 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 +0530166
Anand Doshi496123a2014-06-19 19:25:19 +0530167 else:
Nabin Hait00778c92014-06-25 19:12:24 +0530168 is_expense_account = frappe.db.get_value("Account",
169 item.get("expense_account"), "report_type")=="Profit and Loss"
Nabin Haitf40ce612015-01-02 14:36:46 +0530170 if self.doctype not in ("Purchase Receipt", "Stock Reconciliation", "Stock Entry") and not is_expense_account:
Nabin Hait00778c92014-06-25 19:12:24 +0530171 frappe.throw(_("Expense / Difference account ({0}) must be a 'Profit or Loss' account")
172 .format(item.get("expense_account")))
Anand Doshi496123a2014-06-19 19:25:19 +0530173 if is_expense_account and not item.get("cost_center"):
174 frappe.throw(_("{0} {1}: Cost Center is mandatory for Item {2}").format(
175 _(self.doctype), self.name, item.get("item_code")))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530176
177 def get_sl_entries(self, d, args):
Nabin Hait5288bde2014-11-03 15:08:21 +0530178 sl_dict = frappe._dict({
Nabin Hait296d6262014-05-02 17:36:13 +0530179 "item_code": d.get("item_code", None),
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530180 "warehouse": d.get("warehouse", None),
Anand Doshif78d1ae2014-03-28 13:55:00 +0530181 "posting_date": self.posting_date,
182 "posting_time": self.posting_time,
183 "voucher_type": self.doctype,
184 "voucher_no": self.name,
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530185 "voucher_detail_no": d.name,
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530186 "actual_qty": (self.docstatus==1 and 1 or -1)*flt(d.get("stock_qty")),
Nabin Hait296d6262014-05-02 17:36:13 +0530187 "stock_uom": d.get("stock_uom"),
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530188 "incoming_rate": 0,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530189 "company": self.company,
190 "fiscal_year": self.fiscal_year,
Nabin Hait296d6262014-05-02 17:36:13 +0530191 "batch_no": cstr(d.get("batch_no")).strip(),
192 "serial_no": d.get("serial_no"),
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530193 "project": d.get("project_name"),
Anand Doshif78d1ae2014-03-28 13:55:00 +0530194 "is_cancelled": self.docstatus==2 and "Yes" or "No"
Nabin Hait5288bde2014-11-03 15:08:21 +0530195 })
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530196
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530197 sl_dict.update(args)
198 return sl_dict
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530199
Anand Doshic3997092015-04-06 19:29:16 +0530200 def make_sl_entries(self, sl_entries, is_amended=None, allow_negative_stock=False,
Nabin Hait54c865e2015-03-27 15:38:31 +0530201 via_landed_cost_voucher=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530202 from erpnext.stock.stock_ledger import make_sl_entries
Nabin Hait54c865e2015-03-27 15:38:31 +0530203 make_sl_entries(sl_entries, is_amended, allow_negative_stock, via_landed_cost_voucher)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530204
nabinhait87f24012014-07-16 19:48:29 +0530205 def make_gl_entries_on_cancel(self):
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530206 if frappe.db.sql("""select name from `tabGL Entry` where voucher_type=%s
Anand Doshif78d1ae2014-03-28 13:55:00 +0530207 and voucher_no=%s""", (self.doctype, self.name)):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530208 self.make_gl_entries()
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530209
Anand Doshia740f752014-06-25 13:31:02 +0530210 def get_serialized_items(self):
211 serialized_items = []
Nabin Haitdd38a262014-12-26 13:15:21 +0530212 item_codes = list(set([d.item_code for d in self.get("items")]))
Anand Doshia740f752014-06-25 13:31:02 +0530213 if item_codes:
214 serialized_items = frappe.db.sql_list("""select name from `tabItem`
215 where has_serial_no='Yes' and name in ({})""".format(", ".join(["%s"]*len(item_codes))),
216 tuple(item_codes))
217
218 return serialized_items
219
Nabin Haitadeb9762014-10-06 11:53:52 +0530220def update_gl_entries_after(posting_date, posting_time, for_warehouses=None, for_items=None,
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530221 warehouse_account=None):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530222 def _delete_gl_entries(voucher_type, voucher_no):
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530223 frappe.db.sql("""delete from `tabGL Entry`
Nabin Haitbecf75d2014-03-27 17:18:29 +0530224 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530225
Nabin Haitbecf75d2014-03-27 17:18:29 +0530226 if not warehouse_account:
227 warehouse_account = get_warehouse_account()
Nabin Haitb9e04812014-09-26 14:22:18 +0530228
229 future_stock_vouchers = get_future_stock_vouchers(posting_date, posting_time, for_warehouses, for_items)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530230 gle = get_voucherwise_gl_entries(future_stock_vouchers, posting_date)
231
232 for voucher_type, voucher_no in future_stock_vouchers:
233 existing_gle = gle.get((voucher_type, voucher_no), [])
Rushabh Mehta0a0f2492014-03-31 17:27:06 +0530234 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530235 expected_gle = voucher_obj.get_gl_entries(warehouse_account)
236 if expected_gle:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530237 if not existing_gle or not compare_existing_and_expected_gle(existing_gle,
Nabin Haitbecf75d2014-03-27 17:18:29 +0530238 expected_gle):
239 _delete_gl_entries(voucher_type, voucher_no)
Anand Doshi03cf4072015-04-06 19:38:13 +0530240 voucher_obj.make_gl_entries(repost_future_gle=False)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530241 else:
242 _delete_gl_entries(voucher_type, voucher_no)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530243
Nabin Haitbecf75d2014-03-27 17:18:29 +0530244def compare_existing_and_expected_gle(existing_gle, expected_gle):
245 matched = True
246 for entry in expected_gle:
247 for e in existing_gle:
248 if entry.account==e.account and entry.against_account==e.against_account \
Nabin Hait7778b482015-01-07 15:44:35 +0530249 and (not entry.cost_center or not e.cost_center or entry.cost_center==e.cost_center) \
Nabin Haitbecf75d2014-03-27 17:18:29 +0530250 and (entry.debit != e.debit or entry.credit != e.credit):
251 matched = False
252 break
253 return matched
254
Nabin Haitb9e04812014-09-26 14:22:18 +0530255def get_future_stock_vouchers(posting_date, posting_time, for_warehouses=None, for_items=None):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530256 future_stock_vouchers = []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530257
Anand Doshi913c51b2014-08-27 22:09:03 +0530258 values = []
Nabin Haitbecf75d2014-03-27 17:18:29 +0530259 condition = ""
260 if for_items:
Anand Doshi913c51b2014-08-27 22:09:03 +0530261 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
262 values += for_items
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530263
Nabin Haitb9e04812014-09-26 14:22:18 +0530264 if for_warehouses:
265 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
266 values += for_warehouses
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530267
268 for d in frappe.db.sql("""select distinct sle.voucher_type, sle.voucher_no
Nabin Haitbecf75d2014-03-27 17:18:29 +0530269 from `tabStock Ledger Entry` sle
Anand Doshi913c51b2014-08-27 22:09:03 +0530270 where timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s) {condition}
271 order by timestamp(sle.posting_date, sle.posting_time) asc, name asc""".format(condition=condition),
272 tuple([posting_date, posting_time] + values), as_dict=True):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530273 future_stock_vouchers.append([d.voucher_type, d.voucher_no])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530274
Nabin Haitbecf75d2014-03-27 17:18:29 +0530275 return future_stock_vouchers
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530276
Nabin Haitbecf75d2014-03-27 17:18:29 +0530277def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
278 gl_entries = {}
279 if future_stock_vouchers:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530280 for d in frappe.db.sql("""select * from `tabGL Entry`
281 where posting_date >= %s and voucher_no in (%s)""" %
282 ('%s', ', '.join(['%s']*len(future_stock_vouchers))),
Nabin Haitbecf75d2014-03-27 17:18:29 +0530283 tuple([posting_date] + [d[1] for d in future_stock_vouchers]), as_dict=1):
284 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530285
Nabin Haitbecf75d2014-03-27 17:18:29 +0530286 return gl_entries
287
288def get_warehouse_account():
Nabin Haitbe8ec392014-08-27 12:05:48 +0530289 warehouse_account = dict(frappe.db.sql("""select warehouse, name from tabAccount
290 where account_type = 'Warehouse' and ifnull(warehouse, '') != ''"""))
Anand Doshi67d6a4e2014-03-28 13:41:59 +0530291 return warehouse_account