blob: 3649cc119d1b0165e4d7b78ef4bba090101b5f96 [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
Rushabh Mehtaffd80a62017-01-16 17:23:20 +05306from frappe.utils import cint, flt, cstr
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05307from frappe import msgprint, _
8import frappe.defaults
Valmik Janglad89dcf62016-03-04 14:33:49 +05309from erpnext.accounts.utils import get_fiscal_year
Nabin Hait1f94fa22015-08-24 14:32:38 +053010from erpnext.accounts.general_ledger import make_gl_entries, delete_gl_entries, process_gl_map
Rushabh Mehta1f847992013-12-12 19:12:19 +053011from erpnext.controllers.accounts_controller import AccountsController
Rohit Waghchaure3899d742017-01-25 18:47:53 +053012from erpnext.stock.stock_ledger import get_valuation_rate
Nabin Haitc3afb252013-03-19 12:01:24 +053013
14class StockController(AccountsController):
Nabin Hait8af429d2016-11-16 17:21:59 +053015 def validate(self):
16 super(StockController, self).validate()
17 self.validate_inspection()
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053018
Nabin Hait9784d272016-12-30 16:21:35 +053019 def make_gl_entries(self, gl_entries=None, repost_future_gle=True, from_repost=False):
Anand Doshif78d1ae2014-03-28 13:55:00 +053020 if self.docstatus == 2:
21 delete_gl_entries(voucher_type=self.doctype, voucher_no=self.name)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053022
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053023 if cint(frappe.defaults.get_global_default("auto_accounting_for_stock")):
Nabin Haitb9e04812014-09-26 14:22:18 +053024 warehouse_account = get_warehouse_account()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053025
Anand Doshif78d1ae2014-03-28 13:55:00 +053026 if self.docstatus==1:
Nabin Hait9784d272016-12-30 16:21:35 +053027 if not gl_entries:
28 gl_entries = self.get_gl_entries(warehouse_account)
29 make_gl_entries(gl_entries, from_repost=from_repost)
Nabin Hait145e5e22013-10-22 23:51:41 +053030
Nabin Haitbecf75d2014-03-27 17:18:29 +053031 if repost_future_gle:
Nabin Haitb9e04812014-09-26 14:22:18 +053032 items, warehouses = self.get_items_and_warehouses()
Nabin Haitadeb9762014-10-06 11:53:52 +053033 update_gl_entries_after(self.posting_date, self.posting_time, warehouses, items,
Nabin Haitf1a07ff2014-10-15 12:23:35 +053034 warehouse_account)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053035
Nabin Haite83069c2013-11-14 18:40:08 +053036 def get_gl_entries(self, warehouse_account=None, default_expense_account=None,
Nabin Hait142007a2013-09-17 15:15:16 +053037 default_cost_center=None):
Nabin Haitadeb9762014-10-06 11:53:52 +053038
Nabin Hait142007a2013-09-17 15:15:16 +053039 if not warehouse_account:
Nabin Haitbecf75d2014-03-27 17:18:29 +053040 warehouse_account = get_warehouse_account()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053041
Anand Doshide1a97d2014-04-17 11:37:46 +053042 sle_map = self.get_stock_ledger_details()
43 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053044
Nabin Hait2e296fa2013-08-28 18:53:11 +053045 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +053046 warehouse_with_no_account = []
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053047
Nabin Hait8c61f342016-12-15 13:46:03 +053048 for item_row in voucher_details:
49 sle_list = sle_map.get(item_row.name)
Nabin Hait2e296fa2013-08-28 18:53:11 +053050 if sle_list:
51 for sle in sle_list:
52 if warehouse_account.get(sle.warehouse):
Nabin Hait2e296fa2013-08-28 18:53:11 +053053 # from warehouse account
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053054
Nabin Hait8c61f342016-12-15 13:46:03 +053055 self.check_expense_account(item_row)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053056
Javier Wong9b11d9b2017-04-14 18:24:04 +080057 # If the item does not have the allow zero valuation rate flag set
Nabin Haitea8fab52017-02-06 17:13:39 +053058 # and ( valuation rate not mentioned in an incoming entry
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053059 # or incoming entry not found while delivering the item),
Nabin Haitea8fab52017-02-06 17:13:39 +053060 # try to pick valuation rate from previous sle or Item master and update in SLE
61 # Otherwise, throw an exception
Nabin Hait0a6aaf42017-02-07 01:23:26 +053062
63 if not sle.stock_value_difference and self.doctype != "Stock Reconciliation" \
Javier Wong9b11d9b2017-04-14 18:24:04 +080064 and not item_row.get("allow_zero_valuation_rate"):
Nabin Hait0a6aaf42017-02-07 01:23:26 +053065
Nabin Haitea8fab52017-02-06 17:13:39 +053066 sle = self.update_stock_ledger_entries(sle)
Rushabh Mehta14a908b2015-10-15 12:28:20 +053067
Nabin Hait2e296fa2013-08-28 18:53:11 +053068 gl_list.append(self.get_gl_dict({
Nabin Hait46bcbaf2015-08-19 13:49:10 +053069 "account": warehouse_account[sle.warehouse]["name"],
Nabin Hait8c61f342016-12-15 13:46:03 +053070 "against": item_row.expense_account,
71 "cost_center": item_row.cost_center,
Nabin Haitdc82d4f2014-04-07 12:02:57 +053072 "remarks": self.get("remarks") or "Accounting Entry for Stock",
Nabin Hait46bcbaf2015-08-19 13:49:10 +053073 "debit": flt(sle.stock_value_difference, 2),
Nabin Hait6e439a52015-08-28 19:24:22 +053074 }, warehouse_account[sle.warehouse]["account_currency"]))
Nabin Hait27994c22013-08-26 16:53:30 +053075
Rushabh Mehta14a908b2015-10-15 12:28:20 +053076 # to target warehouse / expense account
Nabin Hait2e296fa2013-08-28 18:53:11 +053077 gl_list.append(self.get_gl_dict({
Nabin Hait8c61f342016-12-15 13:46:03 +053078 "account": item_row.expense_account,
Nabin Hait46bcbaf2015-08-19 13:49:10 +053079 "against": warehouse_account[sle.warehouse]["name"],
Nabin Hait8c61f342016-12-15 13:46:03 +053080 "cost_center": item_row.cost_center,
Nabin Haitdc82d4f2014-04-07 12:02:57 +053081 "remarks": self.get("remarks") or "Accounting Entry for Stock",
Nabin Hait46bcbaf2015-08-19 13:49:10 +053082 "credit": flt(sle.stock_value_difference, 2),
Nabin Hait8c61f342016-12-15 13:46:03 +053083 "project": item_row.get("project") or self.get("project")
Nabin Hait2e296fa2013-08-28 18:53:11 +053084 }))
Nabin Hait7a75e102013-09-17 10:21:20 +053085 elif sle.warehouse not in warehouse_with_no_account:
86 warehouse_with_no_account.append(sle.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053087
88 if warehouse_with_no_account:
Nabin Haitd6625022016-10-24 18:17:57 +053089 for wh in warehouse_with_no_account:
90 if frappe.db.get_value("Warehouse", wh, "company"):
91 frappe.throw(_("Warehouse {0} is not linked to any account, please create/link the corresponding (Asset) account for the warehouse.").format(wh))
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053092
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053093 msgprint(_("No accounting entries for the following warehouses") + ": \n" +
Nabin Hait7a75e102013-09-17 10:21:20 +053094 "\n".join(warehouse_with_no_account))
Rushabh Mehta14a908b2015-10-15 12:28:20 +053095
Nabin Hait2e296fa2013-08-28 18:53:11 +053096 return process_gl_map(gl_list)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053097
Rohit Waghchaure3899d742017-01-25 18:47:53 +053098 def update_stock_ledger_entries(self, sle):
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053099 sle.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
100 self.doctype, self.name, currency=self.company_currency)
Nabin Haitea8fab52017-02-06 17:13:39 +0530101
Nabin Haitcb19f522017-01-25 19:20:35 +0530102 sle.stock_value = flt(sle.qty_after_transaction) * flt(sle.valuation_rate)
Nabin Haitea8fab52017-02-06 17:13:39 +0530103 sle.stock_value_difference = flt(sle.actual_qty) * flt(sle.valuation_rate)
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530104
Kanchan Chauhanb77eaf72017-01-28 13:18:49 +0530105 if sle.name:
Nabin Haitea8fab52017-02-06 17:13:39 +0530106 frappe.db.sql("""
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530107 update
108 `tabStock Ledger Entry`
109 set
Nabin Haitea8fab52017-02-06 17:13:39 +0530110 stock_value = %(stock_value)s,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530111 valuation_rate = %(valuation_rate)s,
112 stock_value_difference = %(stock_value_difference)s
113 where
Nabin Haitea8fab52017-02-06 17:13:39 +0530114 name = %(name)s""", (sle))
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530115
Nabin Haitea8fab52017-02-06 17:13:39 +0530116 return sle
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530117
Anand Doshide1a97d2014-04-17 11:37:46 +0530118 def get_voucher_details(self, default_expense_account, default_cost_center, sle_map):
119 if self.doctype == "Stock Reconciliation":
120 return [frappe._dict({ "name": voucher_detail_no, "expense_account": default_expense_account,
121 "cost_center": default_cost_center }) for voucher_detail_no, sle in sle_map.items()]
122 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530123 details = self.get("items")
Anand Doshi094610d2014-04-16 19:56:53 +0530124
Anand Doshide1a97d2014-04-17 11:37:46 +0530125 if default_expense_account or default_cost_center:
126 for d in details:
127 if default_expense_account and not d.get("expense_account"):
128 d.expense_account = default_expense_account
129 if default_cost_center and not d.get("cost_center"):
130 d.cost_center = default_cost_center
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530131
Anand Doshide1a97d2014-04-17 11:37:46 +0530132 return details
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530133
Nabin Haitb9e04812014-09-26 14:22:18 +0530134 def get_items_and_warehouses(self):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530135 items, warehouses = [], []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530136
Nabin Haitdd38a262014-12-26 13:15:21 +0530137 if hasattr(self, "items"):
138 item_doclist = self.get("items")
Anand Doshif78d1ae2014-03-28 13:55:00 +0530139 elif self.doctype == "Stock Reconciliation":
Nabin Haitbecf75d2014-03-27 17:18:29 +0530140 import json
141 item_doclist = []
Anand Doshif78d1ae2014-03-28 13:55:00 +0530142 data = json.loads(self.reconciliation_json)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530143 for row in data[data.index(self.head_row)+1:]:
144 d = frappe._dict(zip(["item_code", "warehouse", "qty", "valuation_rate"], row))
145 item_doclist.append(d)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530146
Nabin Haitbecf75d2014-03-27 17:18:29 +0530147 if item_doclist:
148 for d in item_doclist:
149 if d.item_code and d.item_code not in items:
150 items.append(d.item_code)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530151
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530152 if d.get("warehouse") and d.warehouse not in warehouses:
Nabin Haitbecf75d2014-03-27 17:18:29 +0530153 warehouses.append(d.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530154
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530155 if self.doctype == "Stock Entry":
156 if d.get("s_warehouse") and d.s_warehouse not in warehouses:
157 warehouses.append(d.s_warehouse)
158 if d.get("t_warehouse") and d.t_warehouse not in warehouses:
159 warehouses.append(d.t_warehouse)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530160
Nabin Haitb9e04812014-09-26 14:22:18 +0530161 return items, warehouses
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530162
Nabin Hait2e296fa2013-08-28 18:53:11 +0530163 def get_stock_ledger_details(self):
164 stock_ledger = {}
Nabin Haitea8fab52017-02-06 17:13:39 +0530165 stock_ledger_entries = frappe.db.sql("""
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530166 select
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530167 name, warehouse, stock_value_difference, valuation_rate,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530168 voucher_detail_no, item_code, posting_date, posting_time,
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530169 actual_qty, qty_after_transaction
Nabin Haitea8fab52017-02-06 17:13:39 +0530170 from
171 `tabStock Ledger Entry`
172 where
173 voucher_type=%s and voucher_no=%s
174 """, (self.doctype, self.name), as_dict=True)
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530175
Nabin Haitea8fab52017-02-06 17:13:39 +0530176 for sle in stock_ledger_entries:
Nabin Hait2e296fa2013-08-28 18:53:11 +0530177 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
178 return stock_ledger
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530179
Rushabh Mehta551406a2017-04-21 12:40:19 +0530180 def make_batches(self, warehouse_field):
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530181 '''Create batches if required. Called before submit'''
182 for d in self.items:
Rushabh Mehta551406a2017-04-21 12:40:19 +0530183 if d.get(warehouse_field) and not d.batch_no:
184 has_batch_no, create_new_batch = frappe.db.get_value('Item', d.item_code, ['has_batch_no', 'create_new_batch'])
185 if has_batch_no and create_new_batch:
186 d.batch_no = frappe.get_doc(dict(
187 doctype='Batch',
188 item=d.item_code,
189 supplier=getattr(self, 'supplier', None),
190 reference_doctype=self.doctype,
191 reference_name=self.name)).insert().name
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530192
Nabin Hait2e296fa2013-08-28 18:53:11 +0530193 def make_adjustment_entry(self, expected_gle, voucher_obj):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530194 from erpnext.accounts.utils import get_stock_and_account_difference
Nabin Hait27994c22013-08-26 16:53:30 +0530195 account_list = [d.account for d in expected_gle]
196 acc_diff = get_stock_and_account_difference(account_list, expected_gle[0].posting_date)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530197
Nabin Hait27994c22013-08-26 16:53:30 +0530198 cost_center = self.get_company_default("cost_center")
199 stock_adjustment_account = self.get_company_default("stock_adjustment_account")
200
Nabin Haitd4741942013-08-06 15:57:25 +0530201 gl_entries = []
202 for account, diff in acc_diff.items():
203 if diff:
Nabin Hait27994c22013-08-26 16:53:30 +0530204 gl_entries.append([
205 # stock in hand account
Nabin Hait2e296fa2013-08-28 18:53:11 +0530206 voucher_obj.get_gl_dict({
Nabin Hait27994c22013-08-26 16:53:30 +0530207 "account": account,
208 "against": stock_adjustment_account,
209 "debit": diff,
210 "remarks": "Adjustment Accounting Entry for Stock",
211 }),
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530212
Nabin Hait27994c22013-08-26 16:53:30 +0530213 # account against stock in hand
Nabin Hait2e296fa2013-08-28 18:53:11 +0530214 voucher_obj.get_gl_dict({
Nabin Hait27994c22013-08-26 16:53:30 +0530215 "account": stock_adjustment_account,
216 "against": account,
217 "credit": diff,
218 "cost_center": cost_center or None,
219 "remarks": "Adjustment Accounting Entry for Stock",
220 }),
221 ])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530222
Nabin Haitd4741942013-08-06 15:57:25 +0530223 if gl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +0530224 from erpnext.accounts.general_ledger import make_gl_entries
Nabin Haitd4741942013-08-06 15:57:25 +0530225 make_gl_entries(gl_entries)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530226
Nabin Hait27994c22013-08-26 16:53:30 +0530227 def check_expense_account(self, item):
Rushabh Mehta052fe822014-04-16 19:20:11 +0530228 if not item.get("expense_account"):
Nabin Haitd3412542014-05-01 17:42:21 +0530229 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 +0530230
Anand Doshi496123a2014-06-19 19:25:19 +0530231 else:
Nabin Hait00778c92014-06-25 19:12:24 +0530232 is_expense_account = frappe.db.get_value("Account",
233 item.get("expense_account"), "report_type")=="Profit and Loss"
jof2jc524ebbc2016-02-08 23:44:55 +0700234 if self.doctype not in ("Purchase Receipt", "Purchase Invoice", "Stock Reconciliation", "Stock Entry") and not is_expense_account:
Nabin Hait00778c92014-06-25 19:12:24 +0530235 frappe.throw(_("Expense / Difference account ({0}) must be a 'Profit or Loss' account")
236 .format(item.get("expense_account")))
Anand Doshi496123a2014-06-19 19:25:19 +0530237 if is_expense_account and not item.get("cost_center"):
238 frappe.throw(_("{0} {1}: Cost Center is mandatory for Item {2}").format(
239 _(self.doctype), self.name, item.get("item_code")))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530240
241 def get_sl_entries(self, d, args):
Nabin Hait5288bde2014-11-03 15:08:21 +0530242 sl_dict = frappe._dict({
Nabin Hait296d6262014-05-02 17:36:13 +0530243 "item_code": d.get("item_code", None),
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530244 "warehouse": d.get("warehouse", None),
Anand Doshif78d1ae2014-03-28 13:55:00 +0530245 "posting_date": self.posting_date,
246 "posting_time": self.posting_time,
Valmik Janglad89dcf62016-03-04 14:33:49 +0530247 'fiscal_year': get_fiscal_year(self.posting_date, company=self.company)[0],
Anand Doshif78d1ae2014-03-28 13:55:00 +0530248 "voucher_type": self.doctype,
249 "voucher_no": self.name,
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530250 "voucher_detail_no": d.name,
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530251 "actual_qty": (self.docstatus==1 and 1 or -1)*flt(d.get("stock_qty")),
Nabin Haitc865f222015-09-21 09:18:43 +0530252 "stock_uom": frappe.db.get_value("Item", args.get("item_code") or d.get("item_code"), "stock_uom"),
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530253 "incoming_rate": 0,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530254 "company": self.company,
Nabin Hait296d6262014-05-02 17:36:13 +0530255 "batch_no": cstr(d.get("batch_no")).strip(),
256 "serial_no": d.get("serial_no"),
Neil Trini Lasrado6e343e22016-03-09 17:02:59 +0530257 "project": d.get("project"),
Anand Doshif78d1ae2014-03-28 13:55:00 +0530258 "is_cancelled": self.docstatus==2 and "Yes" or "No"
Nabin Hait5288bde2014-11-03 15:08:21 +0530259 })
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530260
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530261 sl_dict.update(args)
262 return sl_dict
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530263
Anand Doshic3997092015-04-06 19:29:16 +0530264 def make_sl_entries(self, sl_entries, is_amended=None, allow_negative_stock=False,
Nabin Hait54c865e2015-03-27 15:38:31 +0530265 via_landed_cost_voucher=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530266 from erpnext.stock.stock_ledger import make_sl_entries
Nabin Hait54c865e2015-03-27 15:38:31 +0530267 make_sl_entries(sl_entries, is_amended, allow_negative_stock, via_landed_cost_voucher)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530268
Nabin Hait3b6dc142016-08-19 16:39:33 +0530269 def make_gl_entries_on_cancel(self, repost_future_gle=True):
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530270 if frappe.db.sql("""select name from `tabGL Entry` where voucher_type=%s
Anand Doshif78d1ae2014-03-28 13:55:00 +0530271 and voucher_no=%s""", (self.doctype, self.name)):
Nabin Hait9784d272016-12-30 16:21:35 +0530272 self.make_gl_entries(repost_future_gle=repost_future_gle)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530273
Anand Doshia740f752014-06-25 13:31:02 +0530274 def get_serialized_items(self):
275 serialized_items = []
Nabin Haitdd38a262014-12-26 13:15:21 +0530276 item_codes = list(set([d.item_code for d in self.get("items")]))
Anand Doshia740f752014-06-25 13:31:02 +0530277 if item_codes:
278 serialized_items = frappe.db.sql_list("""select name from `tabItem`
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530279 where has_serial_no=1 and name in ({})""".format(", ".join(["%s"]*len(item_codes))),
Anand Doshia740f752014-06-25 13:31:02 +0530280 tuple(item_codes))
281
282 return serialized_items
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530283
Nabin Hait20105d82016-01-19 18:05:28 +0530284 def get_incoming_rate_for_sales_return(self, item_code, against_document):
Nabin Hait1d218422015-07-17 15:19:02 +0530285 incoming_rate = 0.0
286 if against_document and item_code:
Anand Doshi602e8252015-11-16 19:05:46 +0530287 incoming_rate = frappe.db.sql("""select abs(stock_value_difference / actual_qty)
Nabin Hait1d218422015-07-17 15:19:02 +0530288 from `tabStock Ledger Entry`
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530289 where voucher_type = %s and voucher_no = %s
Nabin Hait20105d82016-01-19 18:05:28 +0530290 and item_code = %s limit 1""",
291 (self.doctype, against_document, item_code))
Nabin Hait1d218422015-07-17 15:19:02 +0530292 incoming_rate = incoming_rate[0][0] if incoming_rate else 0.0
293
294 return incoming_rate
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530295
Saurabh2e292062015-11-18 17:03:33 +0530296 def validate_warehouse(self):
297 from erpnext.stock.utils import validate_warehouse_company
298
299 warehouses = list(set([d.warehouse for d in
300 self.get("items") if getattr(d, "warehouse", None)]))
301
302 for w in warehouses:
303 validate_warehouse_company(w, self.company)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530304
Anand Doshi6b71ef52016-01-06 16:32:06 +0530305 def update_billing_percentage(self, update_modified=True):
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530306 self._update_percent_field({
307 "target_dt": self.doctype + " Item",
308 "target_parent_dt": self.doctype,
309 "target_parent_field": "per_billed",
310 "target_ref_field": "amount",
311 "target_field": "billed_amt",
312 "name": self.name,
Anand Doshi6b71ef52016-01-06 16:32:06 +0530313 }, update_modified)
Anand Doshia740f752014-06-25 13:31:02 +0530314
Nabin Hait8af429d2016-11-16 17:21:59 +0530315 def validate_inspection(self):
Manas Solankicc902412016-11-10 19:15:11 +0530316 '''Checks if quality inspection is set for Items that require inspection.
317 On submit, throw an exception'''
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530318
Manas Solanki60db98a2016-11-18 14:52:13 +0530319 inspection_required_fieldname = None
Nabin Hait8af429d2016-11-16 17:21:59 +0530320 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
321 inspection_required_fieldname = "inspection_required_before_purchase"
322 elif self.doctype in ["Delivery Note", "Sales Invoice"]:
323 inspection_required_fieldname = "inspection_required_before_delivery"
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530324
Nabin Hait8af429d2016-11-16 17:21:59 +0530325 if not inspection_required_fieldname or \
326 (self.doctype in ["Sales Invoice", "Purchase Invoice"] and not self.update_stock):
327 return
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530328
Manas Solankicc902412016-11-10 19:15:11 +0530329 for d in self.get('items'):
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530330 if (frappe.db.get_value("Item", d.item_code, inspection_required_fieldname)
Manas Solankicc902412016-11-10 19:15:11 +0530331 and not d.quality_inspection):
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530332
Manas Solankicc902412016-11-10 19:15:11 +0530333 frappe.msgprint(_("Quality Inspection required for Item {0}").format(d.item_code))
334 if self.docstatus==1:
335 raise frappe.ValidationError
336
Nabin Haitadeb9762014-10-06 11:53:52 +0530337def update_gl_entries_after(posting_date, posting_time, for_warehouses=None, for_items=None,
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530338 warehouse_account=None):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530339 def _delete_gl_entries(voucher_type, voucher_no):
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530340 frappe.db.sql("""delete from `tabGL Entry`
Nabin Haitbecf75d2014-03-27 17:18:29 +0530341 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530342
Nabin Haitbecf75d2014-03-27 17:18:29 +0530343 if not warehouse_account:
344 warehouse_account = get_warehouse_account()
Nabin Haitb9e04812014-09-26 14:22:18 +0530345
346 future_stock_vouchers = get_future_stock_vouchers(posting_date, posting_time, for_warehouses, for_items)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530347 gle = get_voucherwise_gl_entries(future_stock_vouchers, posting_date)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530348
Nabin Haitbecf75d2014-03-27 17:18:29 +0530349 for voucher_type, voucher_no in future_stock_vouchers:
350 existing_gle = gle.get((voucher_type, voucher_no), [])
Rushabh Mehta0a0f2492014-03-31 17:27:06 +0530351 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530352 expected_gle = voucher_obj.get_gl_entries(warehouse_account)
353 if expected_gle:
Nabin Hait99d4ff42016-08-08 14:12:16 +0530354 if not existing_gle or not compare_existing_and_expected_gle(existing_gle, expected_gle):
355 _delete_gl_entries(voucher_type, voucher_no)
Nabin Hait9784d272016-12-30 16:21:35 +0530356 voucher_obj.make_gl_entries(gl_entries=expected_gle, repost_future_gle=False, from_repost=True)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530357 else:
358 _delete_gl_entries(voucher_type, voucher_no)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530359
Nabin Haitbecf75d2014-03-27 17:18:29 +0530360def compare_existing_and_expected_gle(existing_gle, expected_gle):
361 matched = True
362 for entry in expected_gle:
robert schouten64657112016-09-12 11:17:14 +0800363 account_existed = False
Nabin Haitbecf75d2014-03-27 17:18:29 +0530364 for e in existing_gle:
robert schouten64657112016-09-12 11:17:14 +0800365 if entry.account == e.account:
366 account_existed = True
367 if entry.account == e.account and entry.against_account == e.against_account \
368 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center) \
369 and (entry.debit != e.debit or entry.credit != e.credit):
370 matched = False
371 break
372 if not account_existed:
373 matched = False
374 break
Nabin Haitbecf75d2014-03-27 17:18:29 +0530375 return matched
376
Nabin Haitb9e04812014-09-26 14:22:18 +0530377def get_future_stock_vouchers(posting_date, posting_time, for_warehouses=None, for_items=None):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530378 future_stock_vouchers = []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530379
Anand Doshi913c51b2014-08-27 22:09:03 +0530380 values = []
Nabin Haitbecf75d2014-03-27 17:18:29 +0530381 condition = ""
382 if for_items:
Anand Doshi913c51b2014-08-27 22:09:03 +0530383 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
384 values += for_items
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530385
Nabin Haitb9e04812014-09-26 14:22:18 +0530386 if for_warehouses:
387 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
388 values += for_warehouses
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530389
390 for d in frappe.db.sql("""select distinct sle.voucher_type, sle.voucher_no
Nabin Haitbecf75d2014-03-27 17:18:29 +0530391 from `tabStock Ledger Entry` sle
Anand Doshi913c51b2014-08-27 22:09:03 +0530392 where timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s) {condition}
393 order by timestamp(sle.posting_date, sle.posting_time) asc, name asc""".format(condition=condition),
394 tuple([posting_date, posting_time] + values), as_dict=True):
Nabin Haitbecf75d2014-03-27 17:18:29 +0530395 future_stock_vouchers.append([d.voucher_type, d.voucher_no])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530396
Nabin Haitbecf75d2014-03-27 17:18:29 +0530397 return future_stock_vouchers
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530398
Nabin Haitbecf75d2014-03-27 17:18:29 +0530399def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
400 gl_entries = {}
401 if future_stock_vouchers:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530402 for d in frappe.db.sql("""select * from `tabGL Entry`
403 where posting_date >= %s and voucher_no in (%s)""" %
404 ('%s', ', '.join(['%s']*len(future_stock_vouchers))),
Nabin Haitbecf75d2014-03-27 17:18:29 +0530405 tuple([posting_date] + [d[1] for d in future_stock_vouchers]), as_dict=1):
406 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530407
Nabin Haitbecf75d2014-03-27 17:18:29 +0530408 return gl_entries
409
410def get_warehouse_account():
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530411 if not frappe.flags.warehouse_account_map or frappe.flags.in_test:
Nabin Hait9784d272016-12-30 16:21:35 +0530412 warehouse_account = frappe._dict()
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530413
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530414 for d in frappe.db.sql("""select
415 warehouse, name, account_currency
416 from
417 tabAccount
418 where
419 account_type = 'Stock'
420 and (warehouse is not null and warehouse != '')
421 and is_group=0 """, as_dict=1):
422 warehouse_account.setdefault(d.warehouse, d)
423
Nabin Hait9784d272016-12-30 16:21:35 +0530424 frappe.flags.warehouse_account_map = warehouse_account
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530425
Nabin Hait9784d272016-12-30 16:21:35 +0530426 return frappe.flags.warehouse_account_map