blob: fdd8d092ebb543e3b5d9f11cc9161cc4b33ab2c8 [file] [log] [blame]
Charles-Henri Decultota774f3d2018-06-06 06:52:13 +02001# -*- coding: utf-8 -*-
Anand Doshi885e0742015-03-03 14:55:30 +05302# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05303# License: GNU General Public License v3. See license.txt
Nabin Hait23941aa2013-01-29 11:32:38 +05304
IOWEB TECHNOLOGIES62805e22018-06-14 06:44:07 +03005from __future__ import unicode_literals
Nabin Hait23941aa2013-01-29 11:32:38 +05306
Saqib90517352021-10-04 11:44:46 +05307from json import loads
8
Chillar Anand915b3432021-09-02 16:44:59 +05309import frappe
Nabin Hait9b20e072017-04-25 12:10:24 +053010import frappe.defaults
Chillar Anand915b3432021-09-02 16:44:59 +053011from frappe import _, throw
Nabin Haitb99c77b2020-12-25 18:12:35 +053012from frappe.model.meta import get_field_precision
Chillar Anand915b3432021-09-02 16:44:59 +053013from frappe.utils import cint, cstr, flt, formatdate, get_number_format_info, getdate, now, nowdate
Saqib90517352021-10-04 11:44:46 +053014from six import string_types
Anand Doshicd0989e2015-09-28 13:31:17 +053015
Chillar Anand915b3432021-09-02 16:44:59 +053016import erpnext
17
18# imported to enable erpnext.accounts.utils.get_account_currency
19from erpnext.accounts.doctype.account.account import get_account_currency # noqa
Anurag Mishraa11e7382019-10-31 15:55:03 +053020from erpnext.stock import get_warehouse_account_map
Chillar Anand915b3432021-09-02 16:44:59 +053021from erpnext.stock.utils import get_stock_value_on
22
Anurag Mishraa11e7382019-10-31 15:55:03 +053023
Nabin Haitb99c77b2020-12-25 18:12:35 +053024class StockValueAndAccountBalanceOutOfSync(frappe.ValidationError): pass
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053025class FiscalYearError(frappe.ValidationError): pass
Deepesh Garg71418602021-08-10 22:21:28 +053026class PaymentEntryUnlinkError(frappe.ValidationError): pass
Nabin Hait2b06aaa2013-08-22 18:25:43 +053027
Neil Trini Lasrado78fa6952014-10-03 17:43:02 +053028@frappe.whitelist()
Anand Doshic75c1d72016-03-11 14:56:19 +053029def get_fiscal_year(date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False):
30 return get_fiscal_years(date, fiscal_year, label, verbose, company, as_dict=as_dict)[0]
Nabin Hait23941aa2013-01-29 11:32:38 +053031
Anand Doshic75c1d72016-03-11 14:56:19 +053032def get_fiscal_years(transaction_date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False):
Nabin Hait9784d272016-12-30 16:21:35 +053033 fiscal_years = frappe.cache().hget("fiscal_years", company) or []
Rushabh Mehtad50da782017-07-28 11:39:01 +053034
35 if not fiscal_years:
Nabin Hait9784d272016-12-30 16:21:35 +053036 # if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
37 cond = ""
38 if fiscal_year:
39 cond += " and fy.name = {0}".format(frappe.db.escape(fiscal_year))
40 if company:
41 cond += """
Rushabh Mehtad50da782017-07-28 11:39:01 +053042 and (not exists (select name
43 from `tabFiscal Year Company` fyc
44 where fyc.parent = fy.name)
45 or exists(select company
46 from `tabFiscal Year Company` fyc
47 where fyc.parent = fy.name
Nabin Hait9784d272016-12-30 16:21:35 +053048 and fyc.company=%(company)s)
49 )
50 """
Nabin Haitfff3ab72015-01-14 16:27:13 +053051
Nabin Hait9784d272016-12-30 16:21:35 +053052 fiscal_years = frappe.db.sql("""
Rushabh Mehtad50da782017-07-28 11:39:01 +053053 select
54 fy.name, fy.year_start_date, fy.year_end_date
55 from
Nabin Hait9784d272016-12-30 16:21:35 +053056 `tabFiscal Year` fy
Rushabh Mehtad50da782017-07-28 11:39:01 +053057 where
Nabin Hait9784d272016-12-30 16:21:35 +053058 disabled = 0 {0}
Rushabh Mehtad50da782017-07-28 11:39:01 +053059 order by
Nabin Hait9784d272016-12-30 16:21:35 +053060 fy.year_start_date desc""".format(cond), {
61 "company": company
62 }, as_dict=True)
Rushabh Mehtad50da782017-07-28 11:39:01 +053063
Nabin Hait9784d272016-12-30 16:21:35 +053064 frappe.cache().hset("fiscal_years", company, fiscal_years)
Nabin Haitfff3ab72015-01-14 16:27:13 +053065
Prssanna Desai82ddef52020-06-18 18:18:41 +053066 if not transaction_date and not fiscal_year:
67 return fiscal_years
68
Nabin Hait9784d272016-12-30 16:21:35 +053069 if transaction_date:
70 transaction_date = getdate(transaction_date)
Anand Doshicd71e1d2014-04-08 13:53:35 +053071
Nabin Hait9784d272016-12-30 16:21:35 +053072 for fy in fiscal_years:
73 matched = False
74 if fiscal_year and fy.name == fiscal_year:
75 matched = True
Anand Doshicd71e1d2014-04-08 13:53:35 +053076
Rushabh Mehtad50da782017-07-28 11:39:01 +053077 if (transaction_date and getdate(fy.year_start_date) <= transaction_date
Nabin Hait9784d272016-12-30 16:21:35 +053078 and getdate(fy.year_end_date) >= transaction_date):
79 matched = True
Rushabh Mehtad50da782017-07-28 11:39:01 +053080
Nabin Hait9784d272016-12-30 16:21:35 +053081 if matched:
82 if as_dict:
83 return (fy,)
84 else:
85 return ((fy.name, fy.year_start_date, fy.year_end_date),)
86
Anuja P550cb9c2020-12-07 11:11:00 +053087 error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(label, formatdate(transaction_date))
Anuja P2e4faf92020-12-05 13:36:43 +053088 if company:
Anuja P550cb9c2020-12-07 11:11:00 +053089 error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company))
rohitwaghchaured60ff832021-02-16 09:12:27 +053090
Nabin Hait9784d272016-12-30 16:21:35 +053091 if verbose==1: frappe.msgprint(error_msg)
cclauss68487082017-07-27 07:08:35 +020092 raise FiscalYearError(error_msg)
Nabin Hait9784d272016-12-30 16:21:35 +053093
Prssanna Desai82ddef52020-06-18 18:18:41 +053094@frappe.whitelist()
95def get_fiscal_year_filter_field(company=None):
96 field = {
97 "fieldtype": "Select",
98 "options": [],
99 "operator": "Between",
100 "query_value": True
101 }
102 fiscal_years = get_fiscal_years(company=company)
103 for fiscal_year in fiscal_years:
104 field["options"].append({
105 "label": fiscal_year.name,
106 "value": fiscal_year.name,
107 "query_value": [fiscal_year.year_start_date.strftime("%Y-%m-%d"), fiscal_year.year_end_date.strftime("%Y-%m-%d")]
108 })
109 return field
110
Nabin Hait8bf58362017-03-27 12:30:01 +0530111def validate_fiscal_year(date, fiscal_year, company, label="Date", doc=None):
112 years = [f[0] for f in get_fiscal_years(date, label=_(label), company=company)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +0530113 if fiscal_year not in years:
Rushabh Mehtad60acb92015-02-19 14:51:58 +0530114 if doc:
115 doc.fiscal_year = years[0]
116 else:
117 throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
Nabin Hait23941aa2013-01-29 11:32:38 +0530118
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530119@frappe.whitelist()
Suraj Shetty1a2600c2019-08-13 12:05:22 +0530120def get_balance_on(account=None, date=None, party_type=None, party=None, company=None,
121 in_account_currency=True, cost_center=None, ignore_account_permission=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530122 if not account and frappe.form_dict.get("account"):
123 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530124 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530125 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530126 if not party_type and frappe.form_dict.get("party_type"):
127 party_type = frappe.form_dict.get("party_type")
128 if not party and frappe.form_dict.get("party"):
129 party = frappe.form_dict.get("party")
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400130 if not cost_center and frappe.form_dict.get("cost_center"):
131 cost_center = frappe.form_dict.get("cost_center")
132
Anand Doshi9365b612014-04-21 12:42:21 +0530133
Nabin Hait98372852020-07-30 20:52:20 +0530134 cond = ["is_cancelled=0"]
Nabin Hait23941aa2013-01-29 11:32:38 +0530135 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530136 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530137 else:
138 # get balance of all entries that exist
139 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530140
Deepesh Garg8c217032019-07-16 09:41:01 +0530141 if account:
142 acc = frappe.get_doc("Account", account)
143
Nabin Hait23941aa2013-01-29 11:32:38 +0530144 try:
Deepesh Garg96d40ec2020-07-03 22:59:00 +0530145 year_start_date = get_fiscal_year(date, company=company, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530146 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +0530147 if getdate(date) > getdate(nowdate()):
148 # if fiscal year not found and the date is greater than today
149 # get fiscal year for today's date and its corresponding year start date
150 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
151 else:
152 # this indicates that it is a date older than any existing fiscal year.
153 # hence, assuming balance as 0.0
154 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530155
deepeshgarg0072ddbebf2019-07-20 14:52:59 +0530156 if account:
deepeshgarg007e097d4f2019-07-20 14:49:32 +0530157 report_type = acc.report_type
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530158 else:
159 report_type = ""
160
Saqib Ansari91b307e2020-03-11 13:59:15 +0530161 if cost_center and report_type == 'Profit and Loss':
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400162 cc = frappe.get_doc("Cost Center", cost_center)
163 if cc.is_group:
164 cond.append(""" exists (
165 select 1 from `tabCost Center` cc where cc.name = gle.cost_center
166 and cc.lft >= %s and cc.rgt <= %s
167 )""" % (cc.lft, cc.rgt))
168
169 else:
Suraj Shettydabaec02018-09-21 15:46:44 +0530170 cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center, percent=False), ))
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400171
172
Nabin Hait6f17cf92014-09-17 14:11:22 +0530173 if account:
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400174
Suraj Shetty1a2600c2019-08-13 12:05:22 +0530175 if not (frappe.flags.ignore_account_permission
176 or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530177 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530178
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530179 if report_type == 'Profit and Loss':
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400180 # for pl accounts, get balance within a fiscal year
Nabin Hait6f17cf92014-09-17 14:11:22 +0530181 cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
182 % year_start_date)
Nabin Hait6f17cf92014-09-17 14:11:22 +0530183 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530184 if acc.is_group:
Nabin Hait6f17cf92014-09-17 14:11:22 +0530185 cond.append("""exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530186 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530187 and ac.lft >= %s and ac.rgt <= %s
188 )""" % (acc.lft, acc.rgt))
Anand Doshicd0989e2015-09-28 13:31:17 +0530189
190 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530191 # always return balance based on debit and credit in company currency
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530192 if acc.account_currency == frappe.get_cached_value('Company', acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530193 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530194 else:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530195 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False), ))
Anand Doshic75c1d72016-03-11 14:56:19 +0530196
Nabin Hait6f17cf92014-09-17 14:11:22 +0530197 if party_type and party:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530198 cond.append("""gle.party_type = %s and gle.party = %s """ %
Nabin Hait1a99cb82016-02-19 12:45:57 +0530199 (frappe.db.escape(party_type), frappe.db.escape(party, percent=False)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530200
Nabin Hait85648d92016-07-20 11:26:45 +0530201 if company:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530202 cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530203
Nabin Haitdc768232015-08-17 11:27:00 +0530204 if account or (party_type and party):
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530205 if in_account_currency:
Anand Doshi602e8252015-11-16 19:05:46 +0530206 select_field = "sum(debit_in_account_currency) - sum(credit_in_account_currency)"
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530207 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530208 select_field = "sum(debit) - sum(credit)"
Nabin Haitdc768232015-08-17 11:27:00 +0530209 bal = frappe.db.sql("""
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530210 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530211 FROM `tabGL Entry` gle
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530212 WHERE {1}""".format(select_field, " and ".join(cond)))[0][0]
Anand Doshicd71e1d2014-04-08 13:53:35 +0530213
Nabin Haitdc768232015-08-17 11:27:00 +0530214 # if bal is None, return 0
215 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530216
RobertSchouten8d43b322016-09-20 13:41:39 +0800217def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530218 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800219 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530220 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800221 else:
222 # get balance of all entries that exist
223 date = nowdate()
224
225 try:
226 year_start_date = get_fiscal_year(date, verbose=0)[1]
227 except FiscalYearError:
228 if getdate(date) > getdate(nowdate()):
229 # if fiscal year not found and the date is greater than today
230 # get fiscal year for today's date and its corresponding year start date
231 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
232 else:
233 # this indicates that it is a date older than any existing fiscal year.
234 # hence, assuming balance as 0.0
235 return 0.0
236
237 if account:
238 acc = frappe.get_doc("Account", account)
239
240 if not frappe.flags.ignore_account_permission:
241 acc.check_permission("read")
242
243 # for pl accounts, get balance within a fiscal year
244 if acc.report_type == 'Profit and Loss':
245 cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
246 % year_start_date)
247
248 # different filter for group and ledger - improved performance
249 if acc.is_group:
250 cond.append("""exists (
251 select name from `tabAccount` ac where ac.name = gle.account
252 and ac.lft >= %s and ac.rgt <= %s
253 )""" % (acc.lft, acc.rgt))
RobertSchouten8d43b322016-09-20 13:41:39 +0800254 else:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530255 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False), ))
RobertSchouten8d43b322016-09-20 13:41:39 +0800256
257 entries = frappe.db.sql("""
258 SELECT name, posting_date, account, party_type, party,debit,credit,
259 voucher_type, voucher_no, against_voucher_type, against_voucher
260 FROM `tabGL Entry` gle
261 WHERE {0}""".format(" and ".join(cond)), as_dict=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530262
RobertSchouten8d43b322016-09-20 13:41:39 +0800263 count = 0
264 for gle in entries:
265 if fieldname not in ('invoiced_amount','payables'):
266 count += 1
267 else:
268 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
269 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Nabin Hait6d7b0ce2017-06-15 11:09:27 +0530270 select_fields = "ifnull(sum(credit-debit),0)" \
271 if fieldname == "invoiced_amount" else "ifnull(sum(debit-credit),0)"
RobertSchouten8d43b322016-09-20 13:41:39 +0800272
273 if ((not gle.against_voucher) or (gle.against_voucher_type in ["Sales Order", "Purchase Order"]) or
274 (gle.against_voucher==gle.voucher_no and gle.get(dr_or_cr) > 0)):
275 payment_amount = frappe.db.sql("""
276 SELECT {0}
277 FROM `tabGL Entry` gle
278 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Nabin Hait6d7b0ce2017-06-15 11:09:27 +0530279 and party = %(party)s and name != %(name)s"""
280 .format(select_fields),
Rushabh Mehtad50da782017-07-28 11:39:01 +0530281 {"date": date, "voucher_no": gle.voucher_no,
Nabin Hait6d7b0ce2017-06-15 11:09:27 +0530282 "party": gle.party, "name": gle.name})[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530283
RobertSchouten8d43b322016-09-20 13:41:39 +0800284 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
285 currency_precision = get_currency_precision() or 2
286 if abs(flt(outstanding_amount)) > 0.1/10**currency_precision:
287 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530288
RobertSchouten8d43b322016-09-20 13:41:39 +0800289 return count
290
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530291@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530292def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530293 from frappe.desk.treeview import make_tree_args
294
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530295 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530296 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530297
Nabin Hait02d987e2017-02-17 15:50:26 +0530298 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530299 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530300
Anand Doshi3e41fd12014-04-22 18:54:54 +0530301 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530302
Nabin Hait665568d2016-05-13 15:56:00 +0530303 if args.get("ignore_permissions"):
304 ac.flags.ignore_permissions = True
305 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530306
Anand Doshi3e41fd12014-04-22 18:54:54 +0530307 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530308
309 if not ac.parent_account:
310 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530311
Anand Doshif78d1ae2014-03-28 13:55:00 +0530312 ac.old_parent = ""
313 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530314 if cint(ac.get("is_root")):
315 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530316 ac.flags.ignore_mandatory = True
317
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530318 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530319
Anand Doshif78d1ae2014-03-28 13:55:00 +0530320 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530321
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530322@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530323def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530324 from frappe.desk.treeview import make_tree_args
325
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530326 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530327 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530328
Nabin Hait02d987e2017-02-17 15:50:26 +0530329 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530330 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530331
Zarrar7ab70ca2018-06-08 14:33:15 +0530332 if args.parent_cost_center == args.company:
333 args.parent_cost_center = "{0} - {1}".format(args.parent_cost_center,
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530334 frappe.get_cached_value('Company', args.company, 'abbr'))
Zarrar7ab70ca2018-06-08 14:33:15 +0530335
Anand Doshi3e41fd12014-04-22 18:54:54 +0530336 cc = frappe.new_doc("Cost Center")
337 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530338
339 if not cc.parent_cost_center:
340 cc.parent_cost_center = args.get("parent")
341
Anand Doshif78d1ae2014-03-28 13:55:00 +0530342 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530343 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530344 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530345
346def reconcile_against_document(args):
347 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530348 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530349 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530350 # To optimize making GL Entry for PE or JV with multiple references
351 reconciled_entries = {}
352 for row in args:
353 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
354 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530355
Anuja Pawar3e404f12021-08-31 18:59:29 +0530356 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
357
358 for key, entries in reconciled_entries.items():
359 voucher_type = key[0]
360 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530361
Nabin Hait28a05282016-06-27 17:41:39 +0530362 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530363 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530364 frappe.flags.ignore_party_validation = True
Nabin Hait28a05282016-06-27 17:41:39 +0530365 doc.make_gl_entries(cancel=1, adv_adj=1)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530366
Anuja Pawar3e404f12021-08-31 18:59:29 +0530367 for entry in entries:
368 check_if_advance_entry_modified(entry)
369 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530370
Anuja Pawar3e404f12021-08-31 18:59:29 +0530371 # update ref in advance entry
372 if voucher_type == "Journal Entry":
373 update_reference_in_journal_entry(entry, doc, do_not_save=True)
374 else:
375 update_reference_in_payment_entry(entry, doc, do_not_save=True)
376
377 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530378 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530379 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
Nabin Hait28a05282016-06-27 17:41:39 +0530380 doc.make_gl_entries(cancel = 0, adv_adj =1)
Subin Tomb8845b92021-07-30 16:30:18 +0530381 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530382
Anuja Pawar3e404f12021-08-31 18:59:29 +0530383 if entry.voucher_type in ('Payment Entry', 'Journal Entry'):
Nabin Hait5cd04a62019-05-27 11:44:06 +0530384 doc.update_expense_claim()
385
Nabin Hait28a05282016-06-27 17:41:39 +0530386def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530387 """
388 check if there is already a voucher reference
389 check if amount is same
390 check if jv is submitted
391 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530392 if not args.get('unreconciled_amount'):
393 args.update({'unreconciled_amount': args.get('unadjusted_amount')})
394
Nabin Hait28a05282016-06-27 17:41:39 +0530395 ret = None
396 if args.voucher_type == "Journal Entry":
397 ret = frappe.db.sql("""
398 select t2.{dr_or_cr} from `tabJournal Entry` t1, `tabJournal Entry Account` t2
399 where t1.name = t2.parent and t2.account = %(account)s
400 and t2.party_type = %(party_type)s and t2.party = %(party)s
401 and (t2.reference_type is null or t2.reference_type in ("", "Sales Order", "Purchase Order"))
402 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
403 and t1.docstatus=1 """.format(dr_or_cr = args.get("dr_or_cr")), args)
404 else:
rohitwaghchauree8358f32018-05-16 11:02:26 +0530405 party_account_field = ("paid_from"
406 if erpnext.get_party_account_type(args.party_type) == 'Receivable' else "paid_to")
407
Nabin Hait28a05282016-06-27 17:41:39 +0530408 if args.voucher_detail_no:
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530409 ret = frappe.db.sql("""select t1.name
410 from `tabPayment Entry` t1, `tabPayment Entry Reference` t2
Nabin Hait28a05282016-06-27 17:41:39 +0530411 where
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530412 t1.name = t2.parent and t1.docstatus = 1
Nabin Hait28a05282016-06-27 17:41:39 +0530413 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
414 and t1.party_type = %(party_type)s and t1.party = %(party)s and t1.{0} = %(account)s
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530415 and t2.reference_doctype in ("", "Sales Order", "Purchase Order")
Anuja Pawar3e404f12021-08-31 18:59:29 +0530416 and t2.allocated_amount = %(unreconciled_amount)s
Nabin Hait28a05282016-06-27 17:41:39 +0530417 """.format(party_account_field), args)
418 else:
419 ret = frappe.db.sql("""select name from `tabPayment Entry`
420 where
421 name = %(voucher_no)s and docstatus = 1
422 and party_type = %(party_type)s and party = %(party)s and {0} = %(account)s
Anuja Pawar3e404f12021-08-31 18:59:29 +0530423 and unallocated_amount = %(unreconciled_amount)s
Nabin Hait28a05282016-06-27 17:41:39 +0530424 """.format(party_account_field), args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530425
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530426 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530427 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530428
Nabin Hait576f0252014-04-30 19:30:50 +0530429def validate_allocated_amount(args):
Deepesh Gargf54d5962021-03-31 14:06:02 +0530430 precision = args.get('precision') or frappe.db.get_single_value("System Settings", "currency_precision")
Nabin Hait28a05282016-06-27 17:41:39 +0530431 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530432 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530433 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530434 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530435
Anuja Pawar3e404f12021-08-31 18:59:29 +0530436def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530437 """
438 Updates against document, if partial amount splits into rows
439 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530440 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530441
Anuja Pawar3e404f12021-08-31 18:59:29 +0530442 if flt(d['unadjusted_amount']) - flt(d['allocated_amount']) != 0:
443 # adjust the unreconciled balance
Nabin Hait28a05282016-06-27 17:41:39 +0530444 amount_in_account_currency = flt(d['unadjusted_amount']) - flt(d['allocated_amount'])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530445 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
446 jv_detail.set(d['dr_or_cr'], amount_in_account_currency)
447 jv_detail.set('debit' if d['dr_or_cr'] == 'debit_in_account_currency' else 'credit', amount_in_company_currency)
448 else:
449 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530450
Anuja Pawar3e404f12021-08-31 18:59:29 +0530451 # new row with references
452 new_row = journal_entry.append("accounts")
453 new_row.update(jv_detail.as_dict().copy())
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530454
Anuja Pawar3e404f12021-08-31 18:59:29 +0530455 new_row.set(d["dr_or_cr"], d["allocated_amount"])
456 new_row.set('debit' if d['dr_or_cr'] == 'debit_in_account_currency' else 'credit',
457 d["allocated_amount"] * flt(jv_detail.exchange_rate))
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530458
Anuja Pawar3e404f12021-08-31 18:59:29 +0530459 new_row.set('credit_in_account_currency' if d['dr_or_cr'] == 'debit_in_account_currency'
460 else 'debit_in_account_currency', 0)
461 new_row.set('credit' if d['dr_or_cr'] == 'debit_in_account_currency' else 'debit', 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530462
Anuja Pawar3e404f12021-08-31 18:59:29 +0530463 new_row.set("reference_type", d["against_voucher_type"])
464 new_row.set("reference_name", d["against_voucher"])
465
466 new_row.against_account = cstr(jv_detail.against_account)
467 new_row.is_advance = cstr(jv_detail.is_advance)
468 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530469
470 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530471 journal_entry.flags.ignore_validate_update_after_submit = True
472 if not do_not_save:
473 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530474
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530475def update_reference_in_payment_entry(d, payment_entry, do_not_save=False):
Nabin Hait28a05282016-06-27 17:41:39 +0530476 reference_details = {
477 "reference_doctype": d.against_voucher_type,
478 "reference_name": d.against_voucher,
479 "total_amount": d.grand_total,
480 "outstanding_amount": d.outstanding_amount,
481 "allocated_amount": d.allocated_amount,
Saqiba20999c2021-07-12 14:33:23 +0530482 "exchange_rate": d.exchange_rate if not d.exchange_gain_loss else payment_entry.get_exchange_rate(),
483 "exchange_gain_loss": d.exchange_gain_loss # only populated from invoice in case of advance allocation
Nabin Hait28a05282016-06-27 17:41:39 +0530484 }
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530485
Nabin Hait28a05282016-06-27 17:41:39 +0530486 if d.voucher_detail_no:
487 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
488 original_row = existing_row.as_dict().copy()
489 existing_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530490
Nabin Hait28a05282016-06-27 17:41:39 +0530491 if d.allocated_amount < original_row.allocated_amount:
492 new_row = payment_entry.append("references")
493 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500494 for field in list(reference_details):
Nabin Hait28a05282016-06-27 17:41:39 +0530495 new_row.set(field, original_row[field])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530496
Nabin Hait28a05282016-06-27 17:41:39 +0530497 new_row.allocated_amount = original_row.allocated_amount - d.allocated_amount
498 else:
499 new_row = payment_entry.append("references")
500 new_row.docstatus = 1
501 new_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530502
Nabin Hait28a05282016-06-27 17:41:39 +0530503 payment_entry.flags.ignore_validate_update_after_submit = True
Nabin Hait05aefbb2016-06-28 19:42:19 +0530504 payment_entry.setup_party_account_field()
Nabin Hait1991c7b2016-06-27 20:09:05 +0530505 payment_entry.set_missing_values()
Nabin Hait28a05282016-06-27 17:41:39 +0530506 payment_entry.set_amounts()
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530507
508 if d.difference_amount and d.difference_account:
Saqiba20999c2021-07-12 14:33:23 +0530509 account_details = {
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530510 'account': d.difference_account,
511 'cost_center': payment_entry.cost_center or frappe.get_cached_value('Company',
Saqiba20999c2021-07-12 14:33:23 +0530512 payment_entry.company, "cost_center")
513 }
514 if d.difference_amount:
515 account_details['amount'] = d.difference_amount
516
517 payment_entry.set_gain_or_loss(account_details=account_details)
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530518
519 if not do_not_save:
520 payment_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530521
Nabin Hait297d74a2016-11-23 15:58:51 +0530522def unlink_ref_doc_from_payment_entries(ref_doc):
523 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name)
524 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530525
Nabin Haite0cc87d2016-07-21 18:30:03 +0530526 frappe.db.sql("""update `tabGL Entry`
527 set against_voucher_type=null, against_voucher=null,
528 modified=%s, modified_by=%s
529 where against_voucher_type=%s and against_voucher=%s
530 and voucher_no != ifnull(against_voucher, '')""",
Nabin Hait297d74a2016-11-23 15:58:51 +0530531 (now(), frappe.session.user, ref_doc.doctype, ref_doc.name))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530532
Nabin Hait297d74a2016-11-23 15:58:51 +0530533 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
534 ref_doc.set("advances", [])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530535
Nabin Hait297d74a2016-11-23 15:58:51 +0530536 frappe.db.sql("""delete from `tab{0} Advance` where parent = %s"""
537 .format(ref_doc.doctype), ref_doc.name)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530538
Nabin Haite0cc87d2016-07-21 18:30:03 +0530539def remove_ref_doc_link_from_jv(ref_type, ref_no):
Nabin Haite7d15362014-12-25 16:01:55 +0530540 linked_jv = frappe.db.sql_list("""select parent from `tabJournal Entry Account`
Rushabh Mehta1828c122015-08-10 17:04:07 +0530541 where reference_type=%s and reference_name=%s and docstatus < 2""", (ref_type, ref_no))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530542
543 if linked_jv:
Rushabh Mehta1828c122015-08-10 17:04:07 +0530544 frappe.db.sql("""update `tabJournal Entry Account`
545 set reference_type=null, reference_name = null,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530546 modified=%s, modified_by=%s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530547 where reference_type=%s and reference_name=%s
548 and docstatus < 2""", (now(), frappe.session.user, ref_type, ref_no))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530549
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530550 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530551
Nabin Haite0cc87d2016-07-21 18:30:03 +0530552def remove_ref_doc_link_from_pe(ref_type, ref_no):
553 linked_pe = frappe.db.sql_list("""select parent from `tabPayment Entry Reference`
554 where reference_doctype=%s and reference_name=%s and docstatus < 2""", (ref_type, ref_no))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530555
Nabin Haite0cc87d2016-07-21 18:30:03 +0530556 if linked_pe:
557 frappe.db.sql("""update `tabPayment Entry Reference`
558 set allocated_amount=0, modified=%s, modified_by=%s
559 where reference_doctype=%s and reference_name=%s
560 and docstatus < 2""", (now(), frappe.session.user, ref_type, ref_no))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530561
Nabin Haite0cc87d2016-07-21 18:30:03 +0530562 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530563 try:
564 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530565 pe_doc.set_amounts()
Deepesh Gargb5162392021-08-10 14:52:24 +0530566 pe_doc.clear_unallocated_reference_document_rows()
567 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530568 except Exception as e:
569 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
570 msg += '<br>'
Deepesh Garg188bba82021-08-10 14:04:31 +0530571 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530572 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530573
574 frappe.db.sql("""update `tabPayment Entry` set total_allocated_amount=%s,
575 base_total_allocated_amount=%s, unallocated_amount=%s, modified=%s, modified_by=%s
576 where name=%s""", (pe_doc.total_allocated_amount, pe_doc.base_total_allocated_amount,
Nabin Haite0cc87d2016-07-21 18:30:03 +0530577 pe_doc.unallocated_amount, now(), frappe.session.user, pe))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530578
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530579 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530580
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530581@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530582def get_company_default(company, fieldname, ignore_validation=False):
Anuja Pawar3e404f12021-08-31 18:59:29 +0530583 value = frappe.get_cached_value('Company', company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530584
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530585 if not ignore_validation and not value:
Nabin Haitedba79e2017-08-01 16:43:11 +0530586 throw(_("Please set default {0} in Company {1}")
Suraj Shetty084b0b32018-05-26 09:12:59 +0530587 .format(frappe.get_meta("Company").get_label(fieldname), company))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530588
Nabin Hait0fc24542013-03-25 11:06:00 +0530589 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530590
591def fix_total_debit_credit():
Anand Doshicd71e1d2014-04-08 13:53:35 +0530592 vouchers = frappe.db.sql("""select voucher_type, voucher_no,
593 sum(debit) - sum(credit) as diff
594 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530595 group by voucher_type, voucher_no
Anand Doshi602e8252015-11-16 19:05:46 +0530596 having sum(debit) != sum(credit)""", as_dict=1)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530597
Nabin Hait8b509f52013-05-28 16:52:30 +0530598 for d in vouchers:
599 if abs(d.diff) > 0:
600 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530601
Anand Doshie9baaa62014-02-26 12:35:33 +0530602 frappe.db.sql("""update `tabGL Entry` set %s = %s + %s
Nabin Hait8b509f52013-05-28 16:52:30 +0530603 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1""" %
Anand Doshicd71e1d2014-04-08 13:53:35 +0530604 (dr_or_cr, dr_or_cr, '%s', '%s', '%s', dr_or_cr),
Nabin Haitcac622e2013-08-02 11:44:29 +0530605 (d.diff, d.voucher_type, d.voucher_no))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530606
Rushabh Mehtad50da782017-07-28 11:39:01 +0530607def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530608 precision = cint(frappe.db.get_default("currency_precision"))
609 if not precision:
610 number_format = frappe.db.get_default("number_format") or "#,###.##"
611 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530612
Nabin Hait9b20e072017-04-25 12:10:24 +0530613 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530614
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530615def get_stock_rbnb_difference(posting_date, company):
616 stock_items = frappe.db.sql_list("""select distinct item_code
Nabin Hait849b7b12014-08-07 15:13:52 +0530617 from `tabStock Ledger Entry` where company=%s""", company)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530618
619 pr_valuation_amount = frappe.db.sql("""
Anand Doshi602e8252015-11-16 19:05:46 +0530620 select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530621 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
Suraj Shetty084b0b32018-05-26 09:12:59 +0530622 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530623 and pr.posting_date <= %s and pr_item.item_code in (%s)""" %
Suraj Shetty084b0b32018-05-26 09:12:59 +0530624 ('%s', '%s', ', '.join(['%s']*len(stock_items))), tuple([company, posting_date] + stock_items))[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530625
626 pi_valuation_amount = frappe.db.sql("""
Anand Doshi602e8252015-11-16 19:05:46 +0530627 select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530628 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
Suraj Shetty084b0b32018-05-26 09:12:59 +0530629 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530630 and pi.posting_date <= %s and pi_item.item_code in (%s)""" %
Suraj Shetty084b0b32018-05-26 09:12:59 +0530631 ('%s', '%s', ', '.join(['%s']*len(stock_items))), tuple([company, posting_date] + stock_items))[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530632
633 # Balance should be
634 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
635
636 # Balance as per system
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530637 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.get_cached_value('Company', company, "abbr")
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530638 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530639
640 # Amount should be credited
641 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530642
tundec4b0d172017-09-26 00:48:30 +0100643
tundebabzyad08d4c2018-05-16 07:01:41 +0100644def get_held_invoices(party_type, party):
645 """
646 Returns a list of names Purchase Invoices for the given party that are on hold
647 """
648 held_invoices = None
649
650 if party_type == 'Supplier':
651 held_invoices = frappe.db.sql(
652 'select name from `tabPurchase Invoice` where release_date IS NOT NULL and release_date > CURDATE()',
653 as_dict=1
654 )
Ankush Menat98917802021-06-11 18:40:22 +0530655 held_invoices = set(d['name'] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +0100656
657 return held_invoices
658
659
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530660def get_outstanding_invoices(party_type, party, account, condition=None, filters=None):
Anand Doshid40d1e92015-11-12 17:05:29 +0530661 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +0530662 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +0530663
Nabin Hait9db9edc2019-11-19 18:44:32 +0530664 if account:
Saqib9291df42020-01-24 16:22:49 +0530665 root_type, account_type = frappe.get_cached_value("Account", account, ["root_type", "account_type"])
Nabin Hait9db9edc2019-11-19 18:44:32 +0530666 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +0530667 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +0530668 else:
669 party_account_type = erpnext.get_party_account_type(party_type)
670
671 if party_account_type == 'Receivable':
Anand Doshi602e8252015-11-16 19:05:46 +0530672 dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
Nabin Haitac184982019-02-04 21:13:43 +0530673 payment_dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
Anand Doshid40d1e92015-11-12 17:05:29 +0530674 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530675 dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
Nabin Haitac184982019-02-04 21:13:43 +0530676 payment_dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
Anand Doshid40d1e92015-11-12 17:05:29 +0530677
tundebabzyad08d4c2018-05-16 07:01:41 +0100678 held_invoices = get_held_invoices(party_type, party)
679
Rushabh Mehtab56f3d02018-05-16 12:03:39 +0530680 invoice_list = frappe.db.sql("""
Nabin Haite4bbb692016-07-04 16:16:24 +0530681 select
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530682 voucher_no, voucher_type, posting_date, due_date,
Deepesh Gargc7eadfc2020-07-22 17:59:37 +0530683 ifnull(sum({dr_or_cr}), 0) as invoice_amount,
684 account_currency as currency
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530685 from
Nabin Haitac184982019-02-04 21:13:43 +0530686 `tabGL Entry`
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530687 where
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530688 party_type = %(party_type)s and party = %(party)s
Nabin Haite4bbb692016-07-04 16:16:24 +0530689 and account = %(account)s and {dr_or_cr} > 0
aakvatech38ccf822020-10-03 19:41:38 +0300690 and is_cancelled=0
Anand Doshid40d1e92015-11-12 17:05:29 +0530691 {condition}
692 and ((voucher_type = 'Journal Entry'
Nabin Hait56548cb2016-07-01 15:58:39 +0530693 and (against_voucher = '' or against_voucher is null))
694 or (voucher_type not in ('Journal Entry', 'Payment Entry')))
Nabin Haita5cc84f2017-12-21 11:37:18 +0530695 group by voucher_type, voucher_no
Nabin Hait34c551d2019-07-03 10:34:31 +0530696 order by posting_date, name""".format(
tundec4b0d172017-09-26 00:48:30 +0100697 dr_or_cr=dr_or_cr,
Nabin Hait34c551d2019-07-03 10:34:31 +0530698 condition=condition or ""
Anand Doshid40d1e92015-11-12 17:05:29 +0530699 ), {
700 "party_type": party_type,
701 "party": party,
702 "account": account,
Nabin Hait56548cb2016-07-01 15:58:39 +0530703 }, as_dict=True)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530704
Nabin Haitac184982019-02-04 21:13:43 +0530705 payment_entries = frappe.db.sql("""
706 select against_voucher_type, against_voucher,
707 ifnull(sum({payment_dr_or_cr}), 0) as payment_amount
708 from `tabGL Entry`
709 where party_type = %(party_type)s and party = %(party)s
710 and account = %(account)s
711 and {payment_dr_or_cr} > 0
712 and against_voucher is not null and against_voucher != ''
aakvatech38ccf822020-10-03 19:41:38 +0300713 and is_cancelled=0
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530714 group by against_voucher_type, against_voucher
715 """.format(payment_dr_or_cr=payment_dr_or_cr), {
Nabin Haitac184982019-02-04 21:13:43 +0530716 "party_type": party_type,
717 "party": party,
Rohit Waghchaure2f3f7502019-04-28 23:30:00 +0530718 "account": account
Nabin Haitac184982019-02-04 21:13:43 +0530719 }, as_dict=True)
tundec4b0d172017-09-26 00:48:30 +0100720
Nabin Haitac184982019-02-04 21:13:43 +0530721 pe_map = frappe._dict()
722 for d in payment_entries:
723 pe_map.setdefault((d.against_voucher_type, d.against_voucher), d.payment_amount)
724
725 for d in invoice_list:
726 payment_amount = pe_map.get((d.voucher_type, d.voucher_no), 0)
727 outstanding_amount = flt(d.invoice_amount - payment_amount, precision)
728 if outstanding_amount > 0.5 / (10**precision):
crescent28b978c912019-07-22 11:13:27 +0530729 if (filters and filters.get("outstanding_amt_greater_than") and
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530730 not (outstanding_amount >= filters.get("outstanding_amt_greater_than") and
731 outstanding_amount <= filters.get("outstanding_amt_less_than"))):
732 continue
Nabin Haitac184982019-02-04 21:13:43 +0530733
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530734 if not d.voucher_type == "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +0530735 outstanding_invoices.append(
736 frappe._dict({
737 'voucher_no': d.voucher_no,
738 'voucher_type': d.voucher_type,
739 'posting_date': d.posting_date,
740 'invoice_amount': flt(d.invoice_amount),
741 'payment_amount': payment_amount,
742 'outstanding_amount': outstanding_amount,
Deepesh Gargc7eadfc2020-07-22 17:59:37 +0530743 'due_date': d.due_date,
744 'currency': d.currency
Nabin Haitac184982019-02-04 21:13:43 +0530745 })
746 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530747
Nabin Hait28a05282016-06-27 17:41:39 +0530748 outstanding_invoices = sorted(outstanding_invoices, key=lambda k: k['due_date'] or getdate(nowdate()))
Anand Doshid40d1e92015-11-12 17:05:29 +0530749 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +0530750
751
Saurabhb43df362016-03-18 15:05:50 +0530752def get_account_name(account_type=None, root_type=None, is_group=None, account_currency=None, company=None):
Saurabh3a268292016-02-22 15:18:40 +0530753 """return account based on matching conditions"""
Saurabh4a6bbf92016-02-23 20:01:04 +0530754 return frappe.db.get_value("Account", {
755 "account_type": account_type or '',
756 "root_type": root_type or '',
757 "is_group": is_group or 0,
758 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
759 "company": company or frappe.defaults.get_defaults().company
760 }, "name")
Saurabha9ba7342016-06-21 12:33:12 +0530761
762@frappe.whitelist()
763def get_companies():
764 """get a list of companies based on permission"""
765 return [d.name for d in frappe.get_list("Company", fields=["name"],
766 order_by="name")]
767
768@frappe.whitelist()
Rushabh Mehta43133262017-11-10 18:52:21 +0530769def get_children(doctype, parent, company, is_root=False):
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530770 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +0530771
Suraj Shetty084b0b32018-05-26 09:12:59 +0530772 parent_fieldname = 'parent_' + doctype.lower().replace(' ', '_')
773 fields = [
774 'name as value',
775 'is_group as expandable'
776 ]
777 filters = [['docstatus', '<', 2]]
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +0530778
Suraj Shetty084b0b32018-05-26 09:12:59 +0530779 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), '=', '' if is_root else parent])
780
Rushabh Mehta43133262017-11-10 18:52:21 +0530781 if is_root:
Rohit Waghchaure438efb42019-07-17 21:20:05 +0530782 fields += ['root_type', 'report_type', 'account_currency'] if doctype == 'Account' else []
Suraj Shetty084b0b32018-05-26 09:12:59 +0530783 filters.append(['company', '=', company])
784
Saurabha9ba7342016-06-21 12:33:12 +0530785 else:
Rohit Waghchaure438efb42019-07-17 21:20:05 +0530786 fields += ['root_type', 'account_currency'] if doctype == 'Account' else []
Suraj Shetty084b0b32018-05-26 09:12:59 +0530787 fields += [parent_fieldname + ' as parent']
788
789 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +0530790
Saurabhdc2fa862016-06-24 11:36:31 +0530791 if doctype == 'Account':
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530792 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +0530793
794 return acc
Saurabhb835fef2016-09-09 11:19:22 +0530795
Saqib90517352021-10-04 11:44:46 +0530796@frappe.whitelist()
797def get_account_balances(accounts, company):
798
799 if isinstance(accounts, string_types):
800 accounts = loads(accounts)
801
802 if not accounts:
803 return []
804
805 company_currency = frappe.get_cached_value("Company", company, "default_currency")
806
807 for account in accounts:
808 account["company_currency"] = company_currency
809 account["balance"] = flt(get_balance_on(account["value"], in_account_currency=False, company=company))
810 if account["account_currency"] and account["account_currency"] != company_currency:
811 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
812
813 return accounts
814
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +0530815def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +0530816 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +0530817
818 company = frappe.db.get_value("Global Defaults", None, "default_company")
819 if not company:
820 return
821
822 # NOTE: we translate Payment Gateway account name because that is going to be used by the end user
823 bank_account = frappe.db.get_value("Account", {"account_name": _(gateway), "company": company},
824 ["name", 'account_currency'], as_dict=1)
825
826 if not bank_account:
827 # check for untranslated one
828 bank_account = frappe.db.get_value("Account", {"account_name": gateway, "company": company},
829 ["name", 'account_currency'], as_dict=1)
830
831 if not bank_account:
832 # try creating one
833 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
834
835 if not bank_account:
836 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
837 return
838
839 # if payment gateway account exists, return
840 if frappe.db.exists("Payment Gateway Account",
841 {"payment_gateway": gateway, "currency": bank_account.account_currency}):
842 return
843
844 try:
845 frappe.get_doc({
846 "doctype": "Payment Gateway Account",
847 "is_default": 1,
848 "payment_gateway": gateway,
849 "payment_account": bank_account.name,
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +0530850 "currency": bank_account.account_currency,
851 "payment_channel": payment_channel
Saurabhb835fef2016-09-09 11:19:22 +0530852 }).insert(ignore_permissions=True)
853
854 except frappe.DuplicateEntryError:
855 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +0200856 pass
Zarrar44175902018-06-08 16:35:21 +0530857
858@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +0530859def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Zarrar44175902018-06-08 16:35:21 +0530860 '''
Zarrar44175902018-06-08 16:35:21 +0530861 Renames the document by adding the number as a prefix to the current name and updates
862 all transaction where it was present.
863 '''
Saqiba8779872020-04-30 11:28:43 +0530864 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +0530865
Saqiba8779872020-04-30 11:28:43 +0530866 if cost_center_number:
867 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
868 else:
869 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +0530870
Saqiba8779872020-04-30 11:28:43 +0530871 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +0530872
Saqiba8779872020-04-30 11:28:43 +0530873 new_name = get_autoname_with_number(cost_center_number, cost_center_name, docname, company)
874 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +0530875 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +0530876 return new_name
877
Saqiba8779872020-04-30 11:28:43 +0530878def validate_field_number(doctype_name, docname, number_value, company, field_name):
Zarrar44175902018-06-08 16:35:21 +0530879 ''' Validate if the number entered isn't already assigned to some other document. '''
Zlash651aeca1d2018-07-06 17:15:33 +0530880 if number_value:
Saqiba8779872020-04-30 11:28:43 +0530881 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +0530882 if company:
Saqiba8779872020-04-30 11:28:43 +0530883 filters["company"] = company
884
885 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
886
Zarrar44175902018-06-08 16:35:21 +0530887 if doctype_with_same_number:
Saqiba8779872020-04-30 11:28:43 +0530888 frappe.throw(_("{0} Number {1} is already used in {2} {3}")
889 .format(doctype_name, number_value, doctype_name.lower(), doctype_with_same_number))
Zarrar44175902018-06-08 16:35:21 +0530890
Zarrar17705f92018-07-06 14:44:44 +0530891def get_autoname_with_number(number_value, doc_title, name, company):
Zarrar44175902018-06-08 16:35:21 +0530892 ''' append title with prefix as number and suffix as company's abbreviation separated by '-' '''
Zarrar88a90ff2018-06-11 11:21:17 +0530893 if name:
Zarrar44175902018-06-08 16:35:21 +0530894 name_split=name.split("-")
895 parts = [doc_title.strip(), name_split[len(name_split)-1].strip()]
896 else:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530897 abbr = frappe.get_cached_value('Company', company, ["abbr"], as_dict=True)
Zarrar88a90ff2018-06-11 11:21:17 +0530898 parts = [doc_title.strip(), abbr.abbr]
Zlash651aeca1d2018-07-06 17:15:33 +0530899 if cstr(number_value).strip():
900 parts.insert(0, cstr(number_value).strip())
Zarrar44175902018-06-08 16:35:21 +0530901 return ' - '.join(parts)
Zarrar254ce642018-06-28 14:15:34 +0530902
903@frappe.whitelist()
904def get_coa(doctype, parent, is_root, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +0530905 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
906 build_tree_from_json,
907 )
Zarrar254ce642018-06-28 14:15:34 +0530908
909 # add chart to flags to retrieve when called from expand all function
910 chart = chart if chart else frappe.flags.chart
911 frappe.flags.chart = chart
912
913 parent = None if parent==_('All Accounts') else parent
914 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
915
916 # filter out to show data for the selected node only
917 accounts = [d for d in accounts if d['parent_account']==parent]
918
919 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400920
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530921def update_gl_entries_after(posting_date, posting_time, for_warehouses=None, for_items=None,
922 warehouse_account=None, company=None):
Nabin Hait9b178bc2021-02-16 14:57:00 +0530923 stock_vouchers = get_future_stock_vouchers(posting_date, posting_time, for_warehouses, for_items, company)
924 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
925
926
927def repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company=None, warehouse_account=None):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530928 def _delete_gl_entries(voucher_type, voucher_no):
929 frappe.db.sql("""delete from `tabGL Entry`
930 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
931
932 if not warehouse_account:
933 warehouse_account = get_warehouse_account_map(company)
934
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +0530935 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
936
Nabin Hait9b178bc2021-02-16 14:57:00 +0530937 gle = get_voucherwise_gl_entries(stock_vouchers, posting_date)
Nabin Hait9b178bc2021-02-16 14:57:00 +0530938 for voucher_type, voucher_no in stock_vouchers:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530939 existing_gle = gle.get((voucher_type, voucher_no), [])
Nabin Hait19f8fa52021-02-22 22:27:22 +0530940 voucher_obj = frappe.get_cached_doc(voucher_type, voucher_no)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530941 expected_gle = voucher_obj.get_gl_entries(warehouse_account)
942 if expected_gle:
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +0530943 if not existing_gle or not compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530944 _delete_gl_entries(voucher_type, voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530945 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530946 else:
947 _delete_gl_entries(voucher_type, voucher_no)
948
rohitwaghchaured60ff832021-02-16 09:12:27 +0530949def get_future_stock_vouchers(posting_date, posting_time, for_warehouses=None, for_items=None, company=None):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530950
951 values = []
952 condition = ""
953 if for_items:
954 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
955 values += for_items
956
957 if for_warehouses:
958 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
959 values += for_warehouses
960
rohitwaghchaured60ff832021-02-16 09:12:27 +0530961 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +0530962 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +0530963 values.append(company)
964
Ankush91527152021-08-11 11:17:50 +0530965 future_stock_vouchers = frappe.db.sql("""select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530966 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530967 where
968 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
969 and is_cancelled = 0
970 {condition}
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530971 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(condition=condition),
Ankush91527152021-08-11 11:17:50 +0530972 tuple([posting_date, posting_time] + values), as_dict=True)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530973
Ankush91527152021-08-11 11:17:50 +0530974 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530975
976def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush91527152021-08-11 11:17:50 +0530977 """ Get voucherwise list of GL entries.
978
979 Only fetches GLE fields required for comparing with new GLE.
980 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +0530981
982 returns:
983 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +0530984 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530985 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +0530986 if not future_stock_vouchers:
987 return gl_entries
988
989 voucher_nos = [d[1] for d in future_stock_vouchers]
990
991 gles = frappe.db.sql("""
rohitwaghchaure058d9832021-09-07 12:14:40 +0530992 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +0530993 from `tabGL Entry`
994 where
995 posting_date >= %s and voucher_no in (%s)""" %
996 ('%s', ', '.join(['%s'] * len(voucher_nos))),
997 tuple([posting_date] + voucher_nos), as_dict=1)
998
999 for d in gles:
1000 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301001
Prssanna Desai82ddef52020-06-18 18:18:41 +05301002 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301003
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301004def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301005 if len(existing_gle) != len(expected_gle):
1006 return False
1007
Nabin Haita77b8c92020-12-21 14:45:50 +05301008 matched = True
1009 for entry in expected_gle:
1010 account_existed = False
1011 for e in existing_gle:
1012 if entry.account == e.account:
1013 account_existed = True
Ankush Menat5764b492021-07-29 15:41:22 +05301014 if (entry.account == e.account
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301015 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1016 and ( flt(entry.debit, precision) != flt(e.debit, precision) or
1017 flt(entry.credit, precision) != flt(e.credit, precision))):
Nabin Haita77b8c92020-12-21 14:45:50 +05301018 matched = False
1019 break
1020 if not account_existed:
1021 matched = False
1022 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301023 return matched
1024
1025def check_if_stock_and_account_balance_synced(posting_date, company, voucher_type=None, voucher_no=None):
1026 if not cint(erpnext.is_perpetual_inventory_enabled(company)):
1027 return
1028
1029 accounts = get_stock_accounts(company, voucher_type, voucher_no)
1030 stock_adjustment_account = frappe.db.get_value("Company", company, "stock_adjustment_account")
1031
1032 for account in accounts:
1033 account_bal, stock_bal, warehouse_list = get_stock_and_account_balance(account,
1034 posting_date, company)
1035
1036 if abs(account_bal - stock_bal) > 0.1:
1037 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit"),
1038 currency=frappe.get_cached_value('Company', company, "default_currency"))
1039
1040 diff = flt(stock_bal - account_bal, precision)
1041
1042 error_reason = _("Stock Value ({0}) and Account Balance ({1}) are out of sync for account {2} and it's linked warehouses as on {3}.").format(
1043 stock_bal, account_bal, frappe.bold(account), posting_date)
1044 error_resolution = _("Please create an adjustment Journal Entry for amount {0} on {1}")\
rohitwaghchaured60ff832021-02-16 09:12:27 +05301045 .format(frappe.bold(diff), frappe.bold(posting_date))
Nabin Haitb99c77b2020-12-25 18:12:35 +05301046
1047 frappe.msgprint(
1048 msg="""{0}<br></br>{1}<br></br>""".format(error_reason, error_resolution),
1049 raise_exception=StockValueAndAccountBalanceOutOfSync,
1050 title=_('Values Out Of Sync'),
1051 primary_action={
1052 'label': _('Make Journal Entry'),
1053 'client_action': 'erpnext.route_to_adjustment_jv',
1054 'args': get_journal_entry(account, stock_adjustment_account, diff)
1055 })
1056
1057def get_stock_accounts(company, voucher_type=None, voucher_no=None):
1058 stock_accounts = [d.name for d in frappe.db.get_all("Account", {
1059 "account_type": "Stock",
1060 "company": company,
1061 "is_group": 0
1062 })]
1063 if voucher_type and voucher_no:
1064 if voucher_type == "Journal Entry":
1065 stock_accounts = [d.account for d in frappe.db.get_all("Journal Entry Account", {
1066 "parent": voucher_no,
1067 "account": ["in", stock_accounts]
1068 }, "account")]
1069
1070 else:
1071 stock_accounts = [d.account for d in frappe.db.get_all("GL Entry", {
1072 "voucher_type": voucher_type,
1073 "voucher_no": voucher_no,
1074 "account": ["in", stock_accounts]
1075 }, "account")]
1076
1077 return stock_accounts
1078
1079def get_stock_and_account_balance(account=None, posting_date=None, company=None):
1080 if not posting_date: posting_date = nowdate()
1081
1082 warehouse_account = get_warehouse_account_map(company)
1083
1084 account_balance = get_balance_on(account, posting_date, in_account_currency=False, ignore_account_permission=True)
1085
1086 related_warehouses = [wh for wh, wh_details in warehouse_account.items()
1087 if wh_details.account == account and not wh_details.is_group]
1088
1089 total_stock_value = 0.0
1090 for warehouse in related_warehouses:
1091 value = get_stock_value_on(warehouse, posting_date)
1092 total_stock_value += value
1093
1094 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1095 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1096
1097def get_journal_entry(account, stock_adjustment_account, amount):
1098 db_or_cr_warehouse_account =('credit_in_account_currency' if amount < 0 else 'debit_in_account_currency')
1099 db_or_cr_stock_adjustment_account = ('debit_in_account_currency' if amount < 0 else 'credit_in_account_currency')
1100
1101 return {
1102 'accounts':[{
1103 'account': account,
1104 db_or_cr_warehouse_account: abs(amount)
1105 }, {
1106 'account': stock_adjustment_account,
1107 db_or_cr_stock_adjustment_account : abs(amount)
1108 }]
1109 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301110
1111def check_and_delete_linked_reports(report):
1112 """ Check if reports are referenced in Desktop Icon """
1113 icons = frappe.get_all("Desktop Icon",
1114 fields = ['name'],
1115 filters = {
1116 "_report": report
1117 })
1118 if icons:
1119 for icon in icons:
1120 frappe.delete_doc("Desktop Icon", icon)