blob: 65ba9afef4874d8d61df8dd37221a296b80aeab2 [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 Hait23941aa2013-01-29 11:32:38 +05303
Nabin Hait23941aa2013-01-29 11:32:38 +05304
Saqib90517352021-10-04 11:44:46 +05305from json import loads
Akhil Narang3effaf22024-03-27 11:37:26 +05306from typing import TYPE_CHECKING, Optional
Saqib90517352021-10-04 11:44:46 +05307
Chillar Anand915b3432021-09-02 16:44:59 +05308import frappe
Nabin Hait9b20e072017-04-25 12:10:24 +05309import frappe.defaults
ruthra kumar451cf3a2022-05-16 14:29:58 +053010from frappe import _, qb, throw
Nabin Haitb99c77b2020-12-25 18:12:35 +053011from frappe.model.meta import get_field_precision
ruthra kumar8c876742022-06-14 17:46:04 +053012from frappe.query_builder import AliasedQuery, Criterion, Table
ruthra kumar60435da2023-11-03 17:58:19 +053013from frappe.query_builder.functions import Round, Sum
Gavin D'souza0727d1d2022-06-13 12:39:28 +053014from frappe.query_builder.utils import DocType
Ankush Menat5c6f22f2022-06-15 19:30:26 +053015from frappe.utils import (
ruthra kumar8c8d9be2024-03-26 17:57:43 +053016 add_days,
Ankush Menat5c6f22f2022-06-15 19:30:26 +053017 cint,
18 create_batch,
19 cstr,
20 flt,
21 formatdate,
ruthra kumar8c8d9be2024-03-26 17:57:43 +053022 get_datetime,
Ankush Menat5c6f22f2022-06-15 19:30:26 +053023 get_number_format_info,
24 getdate,
25 now,
26 nowdate,
27)
Gavin D'souza0727d1d2022-06-13 12:39:28 +053028from pypika import Order
29from pypika.terms import ExistsCriterion
Anand Doshicd0989e2015-09-28 13:31:17 +053030
Chillar Anand915b3432021-09-02 16:44:59 +053031import erpnext
32
33# imported to enable erpnext.accounts.utils.get_account_currency
Akhil Narang3effaf22024-03-27 11:37:26 +053034from erpnext.accounts.doctype.account.account import get_account_currency
ruthra kumar451cf3a2022-05-16 14:29:58 +053035from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_dimensions
Anurag Mishraa11e7382019-10-31 15:55:03 +053036from erpnext.stock import get_warehouse_account_map
Chillar Anand915b3432021-09-02 16:44:59 +053037from erpnext.stock.utils import get_stock_value_on
38
Ankush Menat2535d5e2022-06-14 18:20:33 +053039if TYPE_CHECKING:
40 from erpnext.stock.doctype.repost_item_valuation.repost_item_valuation import RepostItemValuation
41
Anurag Mishraa11e7382019-10-31 15:55:03 +053042
Ankush Menat494bd9e2022-03-28 18:52:46 +053043class FiscalYearError(frappe.ValidationError):
44 pass
45
46
47class PaymentEntryUnlinkError(frappe.ValidationError):
48 pass
49
Nabin Hait2b06aaa2013-08-22 18:25:43 +053050
Ankush Menat2535d5e2022-06-14 18:20:33 +053051GL_REPOSTING_CHUNK = 100
52
53
Neil Trini Lasrado78fa6952014-10-03 17:43:02 +053054@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +053055def get_fiscal_year(
Deepesh Garg0aadb682023-03-19 12:46:42 +053056 date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False, boolean=False
Ankush Menat494bd9e2022-03-28 18:52:46 +053057):
ruthra kumarc31ee8e2023-11-14 06:44:49 +053058 if isinstance(boolean, str):
59 boolean = frappe.json.loads(boolean)
60
Deepesh Garg0aadb682023-03-19 12:46:42 +053061 fiscal_years = get_fiscal_years(
62 date, fiscal_year, label, verbose, company, as_dict=as_dict, boolean=boolean
63 )
64 if boolean:
65 return fiscal_years
66 else:
67 return fiscal_years[0]
Nabin Hait23941aa2013-01-29 11:32:38 +053068
Ankush Menat494bd9e2022-03-28 18:52:46 +053069
70def get_fiscal_years(
Deepesh Garg0aadb682023-03-19 12:46:42 +053071 transaction_date=None,
72 fiscal_year=None,
73 label="Date",
74 verbose=1,
75 company=None,
76 as_dict=False,
77 boolean=False,
Ankush Menat494bd9e2022-03-28 18:52:46 +053078):
Nabin Hait9784d272016-12-30 16:21:35 +053079 fiscal_years = frappe.cache().hget("fiscal_years", company) or []
Rushabh Mehtad50da782017-07-28 11:39:01 +053080
81 if not fiscal_years:
Nabin Hait9784d272016-12-30 16:21:35 +053082 # if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
Gavin D'souza0727d1d2022-06-13 12:39:28 +053083 FY = DocType("Fiscal Year")
Nabin Haitfff3ab72015-01-14 16:27:13 +053084
Gavin D'souza0727d1d2022-06-13 12:39:28 +053085 query = (
Akhil Narang3effaf22024-03-27 11:37:26 +053086 frappe.qb.from_(FY).select(FY.name, FY.year_start_date, FY.year_end_date).where(FY.disabled == 0)
Ankush Menat494bd9e2022-03-28 18:52:46 +053087 )
Rushabh Mehtad50da782017-07-28 11:39:01 +053088
Gavin D'souza0727d1d2022-06-13 12:39:28 +053089 if fiscal_year:
90 query = query.where(FY.name == fiscal_year)
91
92 if company:
93 FYC = DocType("Fiscal Year Company")
94 query = query.where(
95 ExistsCriterion(frappe.qb.from_(FYC).select(FYC.name).where(FYC.parent == FY.name)).negate()
96 | ExistsCriterion(
97 frappe.qb.from_(FYC)
98 .select(FYC.company)
99 .where(FYC.parent == FY.name)
100 .where(FYC.company == company)
101 )
102 )
103
Shridhar Patil69efd2e2022-10-03 11:07:24 +0530104 query = query.orderby(FY.year_start_date, order=Order.desc)
Gavin D'souza0727d1d2022-06-13 12:39:28 +0530105 fiscal_years = query.run(as_dict=True)
106
Nabin Hait9784d272016-12-30 16:21:35 +0530107 frappe.cache().hset("fiscal_years", company, fiscal_years)
Nabin Haitfff3ab72015-01-14 16:27:13 +0530108
Prssanna Desai82ddef52020-06-18 18:18:41 +0530109 if not transaction_date and not fiscal_year:
110 return fiscal_years
111
Nabin Hait9784d272016-12-30 16:21:35 +0530112 if transaction_date:
113 transaction_date = getdate(transaction_date)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530114
Nabin Hait9784d272016-12-30 16:21:35 +0530115 for fy in fiscal_years:
116 matched = False
117 if fiscal_year and fy.name == fiscal_year:
118 matched = True
Anand Doshicd71e1d2014-04-08 13:53:35 +0530119
Ankush Menat494bd9e2022-03-28 18:52:46 +0530120 if (
121 transaction_date
122 and getdate(fy.year_start_date) <= transaction_date
123 and getdate(fy.year_end_date) >= transaction_date
124 ):
Nabin Hait9784d272016-12-30 16:21:35 +0530125 matched = True
Rushabh Mehtad50da782017-07-28 11:39:01 +0530126
Nabin Hait9784d272016-12-30 16:21:35 +0530127 if matched:
128 if as_dict:
129 return (fy,)
130 else:
131 return ((fy.name, fy.year_start_date, fy.year_end_date),)
132
Akhil Narang3effaf22024-03-27 11:37:26 +0530133 error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(label, formatdate(transaction_date))
Anuja P2e4faf92020-12-05 13:36:43 +0530134 if company:
Anuja P550cb9c2020-12-07 11:11:00 +0530135 error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company))
rohitwaghchaured60ff832021-02-16 09:12:27 +0530136
Deepesh Garg0aadb682023-03-19 12:46:42 +0530137 if boolean:
138 return False
139
Ankush Menat494bd9e2022-03-28 18:52:46 +0530140 if verbose == 1:
141 frappe.msgprint(error_msg)
Deepesh Garg0aadb682023-03-19 12:46:42 +0530142
cclauss68487082017-07-27 07:08:35 +0200143 raise FiscalYearError(error_msg)
Nabin Hait9784d272016-12-30 16:21:35 +0530144
Ankush Menat494bd9e2022-03-28 18:52:46 +0530145
Prssanna Desai82ddef52020-06-18 18:18:41 +0530146@frappe.whitelist()
147def get_fiscal_year_filter_field(company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530148 field = {"fieldtype": "Select", "options": [], "operator": "Between", "query_value": True}
Prssanna Desai82ddef52020-06-18 18:18:41 +0530149 fiscal_years = get_fiscal_years(company=company)
150 for fiscal_year in fiscal_years:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530151 field["options"].append(
152 {
153 "label": fiscal_year.name,
154 "value": fiscal_year.name,
155 "query_value": [
156 fiscal_year.year_start_date.strftime("%Y-%m-%d"),
157 fiscal_year.year_end_date.strftime("%Y-%m-%d"),
158 ],
159 }
160 )
Prssanna Desai82ddef52020-06-18 18:18:41 +0530161 return field
162
Ankush Menat494bd9e2022-03-28 18:52:46 +0530163
Nabin Hait8bf58362017-03-27 12:30:01 +0530164def validate_fiscal_year(date, fiscal_year, company, label="Date", doc=None):
165 years = [f[0] for f in get_fiscal_years(date, label=_(label), company=company)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +0530166 if fiscal_year not in years:
Rushabh Mehtad60acb92015-02-19 14:51:58 +0530167 if doc:
168 doc.fiscal_year = years[0]
169 else:
170 throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
Nabin Hait23941aa2013-01-29 11:32:38 +0530171
Ankush Menat494bd9e2022-03-28 18:52:46 +0530172
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530173@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530174def get_balance_on(
175 account=None,
176 date=None,
177 party_type=None,
178 party=None,
179 company=None,
180 in_account_currency=True,
181 cost_center=None,
182 ignore_account_permission=False,
RitvikSardanab86afb22023-08-04 22:05:30 +0530183 account_type=None,
Gursheen Anand52305e32023-11-22 18:38:33 +0530184 start_date=None,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530185):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530186 if not account and frappe.form_dict.get("account"):
187 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530188 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530189 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530190 if not party_type and frappe.form_dict.get("party_type"):
191 party_type = frappe.form_dict.get("party_type")
192 if not party and frappe.form_dict.get("party"):
193 party = frappe.form_dict.get("party")
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400194 if not cost_center and frappe.form_dict.get("cost_center"):
195 cost_center = frappe.form_dict.get("cost_center")
196
Nabin Hait98372852020-07-30 20:52:20 +0530197 cond = ["is_cancelled=0"]
Gursheen Anand52305e32023-11-22 18:38:33 +0530198 if start_date:
199 cond.append("posting_date >= %s" % frappe.db.escape(cstr(start_date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530200 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530201 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530202 else:
203 # get balance of all entries that exist
204 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530205
Deepesh Garg8c217032019-07-16 09:41:01 +0530206 if account:
207 acc = frappe.get_doc("Account", account)
208
Nabin Hait23941aa2013-01-29 11:32:38 +0530209 try:
Akhil Narang3effaf22024-03-27 11:37:26 +0530210 get_fiscal_year(date, company=company, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530211 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +0530212 if getdate(date) > getdate(nowdate()):
213 # if fiscal year not found and the date is greater than today
214 # get fiscal year for today's date and its corresponding year start date
Akhil Narang3effaf22024-03-27 11:37:26 +0530215 get_fiscal_year(nowdate(), verbose=1)[1]
Nabin Hait23941aa2013-01-29 11:32:38 +0530216 else:
217 # this indicates that it is a date older than any existing fiscal year.
218 # hence, assuming balance as 0.0
219 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530220
deepeshgarg0072ddbebf2019-07-20 14:52:59 +0530221 if account:
deepeshgarg007e097d4f2019-07-20 14:49:32 +0530222 report_type = acc.report_type
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530223 else:
224 report_type = ""
225
Ankush Menat494bd9e2022-03-28 18:52:46 +0530226 if cost_center and report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400227 cc = frappe.get_doc("Cost Center", cost_center)
228 if cc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530229 cond.append(
Akhil Narang3effaf22024-03-27 11:37:26 +0530230 f""" exists (
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400231 select 1 from `tabCost Center` cc where cc.name = gle.cost_center
Akhil Narang3effaf22024-03-27 11:37:26 +0530232 and cc.lft >= {cc.lft} and cc.rgt <= {cc.rgt}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 )"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530234 )
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400235
236 else:
Akhil Narang3effaf22024-03-27 11:37:26 +0530237 cond.append(f"""gle.cost_center = {frappe.db.escape(cost_center)} """)
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400238
Nabin Hait6f17cf92014-09-17 14:11:22 +0530239 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530240 if not (frappe.flags.ignore_account_permission or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530241 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530242
Nabin Hait6f17cf92014-09-17 14:11:22 +0530243 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530244 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530245 cond.append(
Akhil Narang3effaf22024-03-27 11:37:26 +0530246 f"""exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530247 select name from `tabAccount` ac where ac.name = gle.account
Akhil Narang3effaf22024-03-27 11:37:26 +0530248 and ac.lft >= {acc.lft} and ac.rgt <= {acc.rgt}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530249 )"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530250 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530251
252 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530253 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530254 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530255 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530256 else:
Akhil Narang3effaf22024-03-27 11:37:26 +0530257 cond.append(f"""gle.account = {frappe.db.escape(account)} """)
Anand Doshic75c1d72016-03-11 14:56:19 +0530258
RitvikSardanab86afb22023-08-04 22:05:30 +0530259 if account_type:
260 accounts = frappe.db.get_all(
261 "Account",
262 filters={"company": company, "account_type": account_type, "is_group": 0},
263 pluck="name",
264 order_by="lft",
265 )
266
267 cond.append(
268 """
269 gle.account in (%s)
270 """
271 % (", ".join([frappe.db.escape(account) for account in accounts]))
272 )
273
Nabin Hait6f17cf92014-09-17 14:11:22 +0530274 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530275 cond.append(
Akhil Narang3effaf22024-03-27 11:37:26 +0530276 f"""gle.party_type = {frappe.db.escape(party_type)} and gle.party = {frappe.db.escape(party)} """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530277 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530278
Nabin Hait85648d92016-07-20 11:26:45 +0530279 if company:
Deepesh Garg6d87cfe2024-02-02 18:08:33 +0530280 cond.append("""gle.company = %s """ % (frappe.db.escape(company)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530281
RitvikSardanab86afb22023-08-04 22:05:30 +0530282 if account or (party_type and party) or account_type:
Dany Roberta8949172023-12-09 09:30:17 +0530283 precision = get_currency_precision()
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530284 if in_account_currency:
Dany Robert383a4b12023-11-21 12:46:56 +0000285 select_field = (
286 "sum(round(debit_in_account_currency, %s)) - sum(round(credit_in_account_currency, %s))"
287 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530288 else:
Dany Robert383a4b12023-11-21 12:46:56 +0000289 select_field = "sum(round(debit, %s)) - sum(round(credit, %s))"
290
Ankush Menat494bd9e2022-03-28 18:52:46 +0530291 bal = frappe.db.sql(
292 """
Akhil Narang3effaf22024-03-27 11:37:26 +0530293 SELECT {}
Nabin Haitdc768232015-08-17 11:27:00 +0530294 FROM `tabGL Entry` gle
Akhil Narang3effaf22024-03-27 11:37:26 +0530295 WHERE {}""".format(select_field, " and ".join(cond)),
Dany Robert383a4b12023-11-21 12:46:56 +0000296 (precision, precision),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530297 )[0][0]
Nabin Haitdc768232015-08-17 11:27:00 +0530298 # if bal is None, return 0
299 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530300
Ankush Menat494bd9e2022-03-28 18:52:46 +0530301
RobertSchouten8d43b322016-09-20 13:41:39 +0800302def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530303 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800304 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530305 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800306 else:
307 # get balance of all entries that exist
308 date = nowdate()
309
310 try:
311 year_start_date = get_fiscal_year(date, verbose=0)[1]
312 except FiscalYearError:
313 if getdate(date) > getdate(nowdate()):
314 # if fiscal year not found and the date is greater than today
315 # get fiscal year for today's date and its corresponding year start date
316 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
317 else:
318 # this indicates that it is a date older than any existing fiscal year.
319 # hence, assuming balance as 0.0
320 return 0.0
321
322 if account:
323 acc = frappe.get_doc("Account", account)
324
325 if not frappe.flags.ignore_account_permission:
326 acc.check_permission("read")
327
328 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530329 if acc.report_type == "Profit and Loss":
Akhil Narang3effaf22024-03-27 11:37:26 +0530330 cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date)
RobertSchouten8d43b322016-09-20 13:41:39 +0800331
332 # different filter for group and ledger - improved performance
333 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530334 cond.append(
Akhil Narang3effaf22024-03-27 11:37:26 +0530335 f"""exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800336 select name from `tabAccount` ac where ac.name = gle.account
Akhil Narang3effaf22024-03-27 11:37:26 +0530337 and ac.lft >= {acc.lft} and ac.rgt <= {acc.rgt}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530338 )"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530339 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800340 else:
Akhil Narang3effaf22024-03-27 11:37:26 +0530341 cond.append(f"""gle.account = {frappe.db.escape(account)} """)
RobertSchouten8d43b322016-09-20 13:41:39 +0800342
Ankush Menat494bd9e2022-03-28 18:52:46 +0530343 entries = frappe.db.sql(
344 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800345 SELECT name, posting_date, account, party_type, party,debit,credit,
346 voucher_type, voucher_no, against_voucher_type, against_voucher
347 FROM `tabGL Entry` gle
Akhil Narang3effaf22024-03-27 11:37:26 +0530348 WHERE {}""".format(" and ".join(cond)),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530349 as_dict=True,
350 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530351
RobertSchouten8d43b322016-09-20 13:41:39 +0800352 count = 0
353 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530354 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800355 count += 1
356 else:
357 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
358 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530359 select_fields = (
360 "ifnull(sum(credit-debit),0)"
361 if fieldname == "invoiced_amount"
362 else "ifnull(sum(debit-credit),0)"
363 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800364
Ankush Menat494bd9e2022-03-28 18:52:46 +0530365 if (
366 (not gle.against_voucher)
367 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
368 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
369 ):
370 payment_amount = frappe.db.sql(
Akhil Narang3effaf22024-03-27 11:37:26 +0530371 f"""
372 SELECT {select_fields}
RobertSchouten8d43b322016-09-20 13:41:39 +0800373 FROM `tabGL Entry` gle
374 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Akhil Narang3effaf22024-03-27 11:37:26 +0530375 and party = %(party)s and name != %(name)s""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530376 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
377 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530378
RobertSchouten8d43b322016-09-20 13:41:39 +0800379 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
380 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530381 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800382 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530383
RobertSchouten8d43b322016-09-20 13:41:39 +0800384 return count
385
Ankush Menat494bd9e2022-03-28 18:52:46 +0530386
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530387@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530388def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530389 from frappe.desk.treeview import make_tree_args
390
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530391 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530392 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530393
Nabin Hait02d987e2017-02-17 15:50:26 +0530394 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530395 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530396
Anand Doshi3e41fd12014-04-22 18:54:54 +0530397 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530398
Nabin Hait665568d2016-05-13 15:56:00 +0530399 if args.get("ignore_permissions"):
400 ac.flags.ignore_permissions = True
401 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530402
Anand Doshi3e41fd12014-04-22 18:54:54 +0530403 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530404
405 if not ac.parent_account:
406 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530407
Anand Doshif78d1ae2014-03-28 13:55:00 +0530408 ac.old_parent = ""
409 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530410 if cint(ac.get("is_root")):
411 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530412 ac.flags.ignore_mandatory = True
413
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530414 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530415
Anand Doshif78d1ae2014-03-28 13:55:00 +0530416 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530417
Ankush Menat494bd9e2022-03-28 18:52:46 +0530418
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530419@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530420def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530421 from frappe.desk.treeview import make_tree_args
422
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530423 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530424 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530425
Nabin Hait02d987e2017-02-17 15:50:26 +0530426 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530427 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530428
Zarrar7ab70ca2018-06-08 14:33:15 +0530429 if args.parent_cost_center == args.company:
Akhil Narang3effaf22024-03-27 11:37:26 +0530430 args.parent_cost_center = "{} - {}".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530431 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
432 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530433
Anand Doshi3e41fd12014-04-22 18:54:54 +0530434 cc = frappe.new_doc("Cost Center")
435 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530436
437 if not cc.parent_cost_center:
438 cc.parent_cost_center = args.get("parent")
439
Anand Doshif78d1ae2014-03-28 13:55:00 +0530440 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530441 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530442 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530443
Ankush Menat494bd9e2022-03-28 18:52:46 +0530444
ruthra kumarc44eb432024-01-18 14:35:06 +0530445def _build_dimensions_dict_for_exc_gain_loss(
Akhil Narang3effaf22024-03-27 11:37:26 +0530446 entry: dict | object = None, active_dimensions: list | None = None
ruthra kumarc44eb432024-01-18 14:35:06 +0530447):
448 dimensions_dict = frappe._dict()
449 if entry and active_dimensions:
450 for dim in active_dimensions:
451 dimensions_dict[dim.fieldname] = entry.get(dim.fieldname)
452 return dimensions_dict
453
454
455def reconcile_against_document(
456 args, skip_ref_details_update_for_pe=False, active_dimensions=None
457): # nosemgrep
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530458 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530459 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530460 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530461 # To optimize making GL Entry for PE or JV with multiple references
462 reconciled_entries = {}
463 for row in args:
464 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
465 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530466
Anuja Pawar3e404f12021-08-31 18:59:29 +0530467 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
468
469 for key, entries in reconciled_entries.items():
470 voucher_type = key[0]
471 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530472
Nabin Hait28a05282016-06-27 17:41:39 +0530473 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530474 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530475 frappe.flags.ignore_party_validation = True
ruthra kumar78ab11f2023-09-20 13:05:04 +0530476
ruthra kumarecb533c2023-11-28 17:04:07 +0530477 # For payments with `Advance` in separate account feature enabled, only new ledger entries are posted for each reference.
478 # No need to cancel/delete payment ledger entries
ruthra kumard9a04942024-03-04 10:28:43 +0530479 if voucher_type == "Payment Entry" and doc.book_advance_payments_in_separate_party_account:
480 doc.make_advance_gl_entries(cancel=1)
481 else:
ruthra kumar78ab11f2023-09-20 13:05:04 +0530482 _delete_pl_entries(voucher_type, voucher_no)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530483
Anuja Pawar3e404f12021-08-31 18:59:29 +0530484 for entry in entries:
485 check_if_advance_entry_modified(entry)
486 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530487
ruthra kumarc44eb432024-01-18 14:35:06 +0530488 dimensions_dict = _build_dimensions_dict_for_exc_gain_loss(entry, active_dimensions)
489
Anuja Pawar3e404f12021-08-31 18:59:29 +0530490 # update ref in advance entry
491 if voucher_type == "Journal Entry":
ruthra kumard9a04942024-03-04 10:28:43 +0530492 referenced_row, update_advance_paid = update_reference_in_journal_entry(
493 entry, doc, do_not_save=False
494 )
ruthra kumar7b516f82023-06-26 17:34:28 +0530495 # advance section in sales/purchase invoice and reconciliation tool,both pass on exchange gain/loss
496 # amount and account in args
ruthra kumar79c6f012023-09-01 14:57:12 +0530497 # referenced_row is used to deduplicate gain/loss journal
498 entry.update({"referenced_row": referenced_row})
ruthra kumarc44eb432024-01-18 14:35:06 +0530499 doc.make_exchange_gain_loss_journal([entry], dimensions_dict)
Anuja Pawar3e404f12021-08-31 18:59:29 +0530500 else:
ruthra kumard9a04942024-03-04 10:28:43 +0530501 referenced_row, update_advance_paid = update_reference_in_payment_entry(
ruthra kumarc44eb432024-01-18 14:35:06 +0530502 entry,
503 doc,
504 do_not_save=True,
505 skip_ref_details_update_for_pe=skip_ref_details_update_for_pe,
506 dimensions_dict=dimensions_dict,
ruthra kumared14d1c2023-04-22 17:24:35 +0530507 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530508
509 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530510 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530511 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
ruthra kumar78ab11f2023-09-20 13:05:04 +0530512
513 if voucher_type == "Payment Entry" and doc.book_advance_payments_in_separate_party_account:
ruthra kumarecb533c2023-11-28 17:04:07 +0530514 # both ledgers must be posted to for `Advance` in separate account feature
ruthra kumard9a04942024-03-04 10:28:43 +0530515 # TODO: find a more efficient way post only for the new linked vouchers
ruthra kumar9d9b8332024-01-31 20:40:26 +0530516 doc.make_advance_gl_entries()
ruthra kumar78ab11f2023-09-20 13:05:04 +0530517 else:
518 gl_map = doc.build_gl_map()
519 create_payment_ledger_entry(gl_map, update_outstanding="No", cancel=0, adv_adj=1)
Deepesh Garg1894dc82023-06-23 21:53:34 +0530520
ruthra kumar11cf6942023-01-14 12:22:22 +0530521 # Only update outstanding for newly linked vouchers
522 for entry in entries:
523 update_voucher_outstanding(
Akhil Narang3effaf22024-03-27 11:37:26 +0530524 entry.against_voucher_type,
525 entry.against_voucher,
526 entry.account,
527 entry.party_type,
528 entry.party,
ruthra kumar11cf6942023-01-14 12:22:22 +0530529 )
ruthra kumard9a04942024-03-04 10:28:43 +0530530 # update advance paid in Advance Receivable/Payable doctypes
531 if update_advance_paid:
532 for t, n in update_advance_paid:
533 frappe.get_doc(t, n).set_total_advance_paid()
ruthra kumar524c1752022-05-26 16:00:40 +0530534
Subin Tomb8845b92021-07-30 16:30:18 +0530535 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530536
Ankush Menat494bd9e2022-03-28 18:52:46 +0530537
Nabin Hait28a05282016-06-27 17:41:39 +0530538def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530539 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 check if there is already a voucher reference
541 check if amount is same
542 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530543 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530544 if not args.get("unreconciled_amount"):
545 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530546
Nabin Hait28a05282016-06-27 17:41:39 +0530547 ret = None
548 if args.voucher_type == "Journal Entry":
Gursheen Anand74619262023-06-02 17:13:51 +0530549 journal_entry = frappe.qb.DocType("Journal Entry")
550 journal_acc = frappe.qb.DocType("Journal Entry Account")
551
Gursheen Anand4ee16372023-06-08 13:15:23 +0530552 q = (
553 frappe.qb.from_(journal_entry)
Deepesh Garg3aead052023-06-22 11:41:43 +0530554 .inner_join(journal_acc)
Gursheen Anand74619262023-06-02 17:13:51 +0530555 .on(journal_entry.name == journal_acc.parent)
Deepesh Gargd81d6062023-06-22 18:28:16 +0530556 .select(journal_acc[args.get("dr_or_cr")])
557 .where(
558 (journal_acc.account == args.get("account"))
Akhil Narang3effaf22024-03-27 11:37:26 +0530559 & (journal_acc.party_type == args.get("party_type"))
560 & (journal_acc.party == args.get("party"))
Deepesh Gargd81d6062023-06-22 18:28:16 +0530561 & (
562 (journal_acc.reference_type.isnull())
563 | (journal_acc.reference_type.isin(["", "Sales Order", "Purchase Order"]))
564 )
Akhil Narang3effaf22024-03-27 11:37:26 +0530565 & (journal_entry.name == args.get("voucher_no"))
566 & (journal_acc.name == args.get("voucher_detail_no"))
567 & (journal_entry.docstatus == 1)
Gursheen Anand4ee16372023-06-08 13:15:23 +0530568 )
Gursheen Anand74619262023-06-02 17:13:51 +0530569 )
570
Nabin Hait28a05282016-06-27 17:41:39 +0530571 else:
ruthra kumar60435da2023-11-03 17:58:19 +0530572 precision = frappe.get_precision("Payment Entry", "unallocated_amount")
573
Gursheen Anand74619262023-06-02 17:13:51 +0530574 payment_entry = frappe.qb.DocType("Payment Entry")
575 payment_ref = frappe.qb.DocType("Payment Entry Reference")
576
Gursheen Anand4ee16372023-06-08 13:15:23 +0530577 q = (
578 frappe.qb.from_(payment_entry)
Gursheen Anand74619262023-06-02 17:13:51 +0530579 .select(payment_entry.name)
580 .where(payment_entry.name == args.get("voucher_no"))
581 .where(payment_entry.docstatus == 1)
582 .where(payment_entry.party_type == args.get("party_type"))
583 .where(payment_entry.party == args.get("party"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530584 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530585
Nabin Hait28a05282016-06-27 17:41:39 +0530586 if args.voucher_detail_no:
Gursheen Anand4ee16372023-06-08 13:15:23 +0530587 q = (
588 q.inner_join(payment_ref)
Gursheen Anand74619262023-06-02 17:13:51 +0530589 .on(payment_entry.name == payment_ref.parent)
590 .where(payment_ref.name == args.get("voucher_detail_no"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530591 .where(payment_ref.reference_doctype.isin(("", "Sales Order", "Purchase Order")))
Gursheen Anand74619262023-06-02 17:13:51 +0530592 .where(payment_ref.allocated_amount == args.get("unreconciled_amount"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530593 )
Nabin Hait28a05282016-06-27 17:41:39 +0530594 else:
ruthra kumar60435da2023-11-03 17:58:19 +0530595 q = q.where(
596 Round(payment_entry.unallocated_amount, precision)
597 == Round(args.get("unreconciled_amount"), precision)
598 )
Gursheen Anand4ee16372023-06-08 13:15:23 +0530599
Gursheen Anand74619262023-06-02 17:13:51 +0530600 ret = q.run(as_dict=True)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530601
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530602 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530603 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530604
Ankush Menat494bd9e2022-03-28 18:52:46 +0530605
Nabin Hait576f0252014-04-30 19:30:50 +0530606def validate_allocated_amount(args):
Akhil Narang3effaf22024-03-27 11:37:26 +0530607 precision = args.get("precision") or frappe.db.get_single_value("System Settings", "currency_precision")
Nabin Hait28a05282016-06-27 17:41:39 +0530608 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530609 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530610 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530611 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530612
Ankush Menat494bd9e2022-03-28 18:52:46 +0530613
Anuja Pawar3e404f12021-08-31 18:59:29 +0530614def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530615 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530616 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530617 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530618 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530619
marination426350e2023-09-13 14:24:56 +0530620 # Update Advance Paid in SO/PO since they might be getting unlinked
ruthra kumard9a04942024-03-04 10:28:43 +0530621 update_advance_paid = []
Akhil Narang3effaf22024-03-27 11:37:26 +0530622 advance_payment_doctypes = frappe.get_hooks("advance_payment_receivable_doctypes") + frappe.get_hooks(
623 "advance_payment_payable_doctypes"
624 )
David Arnoldc88ce552024-01-22 22:04:30 +0100625 if jv_detail.get("reference_type") in advance_payment_doctypes:
ruthra kumard9a04942024-03-04 10:28:43 +0530626 update_advance_paid.append((jv_detail.reference_type, jv_detail.reference_name))
marination426350e2023-09-13 14:24:56 +0530627
Ankush Menat494bd9e2022-03-28 18:52:46 +0530628 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530629 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530630 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530631 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530632 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
633 jv_detail.set(
634 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
635 amount_in_company_currency,
636 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530637 else:
638 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530639
Anuja Pawar3e404f12021-08-31 18:59:29 +0530640 # new row with references
641 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530642
ruthra kumar72f577a2023-07-13 15:04:44 +0530643 # Copy field values into new row
644 [
645 new_row.set(field, jv_detail.get(field))
646 for field in frappe.get_meta("Journal Entry Account").get_fieldnames_with_value()
647 ]
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530648
Anuja Pawar3e404f12021-08-31 18:59:29 +0530649 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530650 new_row.set(
651 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
652 d["allocated_amount"] * flt(jv_detail.exchange_rate),
653 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530654
Ankush Menat494bd9e2022-03-28 18:52:46 +0530655 new_row.set(
656 "credit_in_account_currency"
657 if d["dr_or_cr"] == "debit_in_account_currency"
658 else "debit_in_account_currency",
659 0,
660 )
661 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530662
Anuja Pawar3e404f12021-08-31 18:59:29 +0530663 new_row.set("reference_type", d["against_voucher_type"])
664 new_row.set("reference_name", d["against_voucher"])
665
666 new_row.against_account = cstr(jv_detail.against_account)
667 new_row.is_advance = cstr(jv_detail.is_advance)
668 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530669
670 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530671 journal_entry.flags.ignore_validate_update_after_submit = True
672 if not do_not_save:
673 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530674
ruthra kumard9a04942024-03-04 10:28:43 +0530675 return new_row.name, update_advance_paid
ruthra kumar79c6f012023-09-01 14:57:12 +0530676
Ankush Menat494bd9e2022-03-28 18:52:46 +0530677
ruthra kumared14d1c2023-04-22 17:24:35 +0530678def update_reference_in_payment_entry(
ruthra kumarc44eb432024-01-18 14:35:06 +0530679 d, payment_entry, do_not_save=False, skip_ref_details_update_for_pe=False, dimensions_dict=None
ruthra kumared14d1c2023-04-22 17:24:35 +0530680):
Nabin Hait28a05282016-06-27 17:41:39 +0530681 reference_details = {
682 "reference_doctype": d.against_voucher_type,
683 "reference_name": d.against_voucher,
684 "total_amount": d.grand_total,
685 "outstanding_amount": d.outstanding_amount,
686 "allocated_amount": d.allocated_amount,
ruthra kumar5eeb6502023-12-15 11:46:12 +0530687 "exchange_rate": d.exchange_rate
688 if d.difference_amount is not None
689 else payment_entry.get_exchange_rate(),
690 "exchange_gain_loss": d.difference_amount,
Gursheen Anandb65e58c2023-06-08 18:15:37 +0530691 "account": d.account,
ruthra kumar5dc22e12023-12-20 17:19:27 +0530692 "dimensions": d.dimensions,
Nabin Hait28a05282016-06-27 17:41:39 +0530693 }
ruthra kumard9a04942024-03-04 10:28:43 +0530694 update_advance_paid = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530695
Nabin Hait28a05282016-06-27 17:41:39 +0530696 if d.voucher_detail_no:
697 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
marination426350e2023-09-13 14:24:56 +0530698
699 # Update Advance Paid in SO/PO since they are getting unlinked
Akhil Narang3effaf22024-03-27 11:37:26 +0530700 advance_payment_doctypes = frappe.get_hooks("advance_payment_receivable_doctypes") + frappe.get_hooks(
701 "advance_payment_payable_doctypes"
702 )
David Arnoldc88ce552024-01-22 22:04:30 +0100703 if existing_row.get("reference_doctype") in advance_payment_doctypes:
ruthra kumard9a04942024-03-04 10:28:43 +0530704 update_advance_paid.append((existing_row.reference_doctype, existing_row.reference_name))
marination426350e2023-09-13 14:24:56 +0530705
ruthra kumar23df4202023-10-19 11:32:21 +0530706 if d.allocated_amount <= existing_row.allocated_amount:
707 existing_row.allocated_amount -= d.allocated_amount
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530708
Nabin Hait28a05282016-06-27 17:41:39 +0530709 new_row = payment_entry.append("references")
710 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500711 for field in list(reference_details):
ruthra kumar23df4202023-10-19 11:32:21 +0530712 new_row.set(field, reference_details[field])
ruthra kumarecb533c2023-11-28 17:04:07 +0530713 row = new_row
Nabin Hait28a05282016-06-27 17:41:39 +0530714 else:
715 new_row = payment_entry.append("references")
716 new_row.docstatus = 1
717 new_row.update(reference_details)
ruthra kumarecb533c2023-11-28 17:04:07 +0530718 row = new_row
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530719
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500720 payment_entry.flags.ignore_validate_update_after_submit = True
ruthra kumar23df4202023-10-19 11:32:21 +0530721 payment_entry.clear_unallocated_reference_document_rows()
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500722 payment_entry.setup_party_account_field()
723 payment_entry.set_missing_values()
ruthra kumared14d1c2023-04-22 17:24:35 +0530724 if not skip_ref_details_update_for_pe:
ruthra kumarc15690e2024-04-04 11:58:05 +0530725 reference_exchange_details = frappe._dict()
726 if d.against_voucher_type == "Journal Entry" and d.exchange_rate:
727 reference_exchange_details.update(
728 {
729 "reference_doctype": d.against_voucher_type,
730 "reference_name": d.against_voucher,
731 "exchange_rate": d.exchange_rate,
732 }
733 )
734 payment_entry.set_missing_ref_details(
735 update_ref_details_only_for=[(d.against_voucher_type, d.against_voucher)],
736 reference_exchange_details=reference_exchange_details,
737 )
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500738 payment_entry.set_amounts()
ruthra kumarc44eb432024-01-18 14:35:06 +0530739
ruthra kumar7e600a62023-10-22 20:26:45 +0530740 payment_entry.make_exchange_gain_loss_journal(
ruthra kumarc44eb432024-01-18 14:35:06 +0530741 frappe._dict({"difference_posting_date": d.difference_posting_date}), dimensions_dict
ruthra kumar7e600a62023-10-22 20:26:45 +0530742 )
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500743
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530744 if not do_not_save:
745 payment_entry.save(ignore_permissions=True)
ruthra kumard9a04942024-03-04 10:28:43 +0530746 return row, update_advance_paid
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530747
Ankush Menat494bd9e2022-03-28 18:52:46 +0530748
ruthra kumar5dbcf7d2023-09-05 09:52:36 +0530749def cancel_exchange_gain_loss_journal(
Akhil Narang3effaf22024-03-27 11:37:26 +0530750 parent_doc: dict | object, referenced_dt: str | None = None, referenced_dn: str | None = None
ruthra kumar5dbcf7d2023-09-05 09:52:36 +0530751) -> None:
ruthra kumar81cd7872023-04-27 09:46:54 +0530752 """
753 Cancel Exchange Gain/Loss for Sales/Purchase Invoice, if they have any.
754 """
ruthra kumar6e18bb62023-07-11 12:21:10 +0530755 if parent_doc.doctype in ["Sales Invoice", "Purchase Invoice", "Payment Entry", "Journal Entry"]:
ruthra kumar81cd7872023-04-27 09:46:54 +0530756 journals = frappe.db.get_all(
757 "Journal Entry Account",
758 filters={
759 "reference_type": parent_doc.doctype,
760 "reference_name": parent_doc.name,
761 "docstatus": 1,
762 },
763 fields=["parent"],
764 as_list=1,
765 )
ruthra kumard9d68562023-07-27 08:02:46 +0530766
ruthra kumar81cd7872023-04-27 09:46:54 +0530767 if journals:
ruthra kumard9d68562023-07-27 08:02:46 +0530768 gain_loss_journals = frappe.db.get_all(
ruthra kumar81cd7872023-04-27 09:46:54 +0530769 "Journal Entry",
770 filters={
771 "name": ["in", [x[0] for x in journals]],
772 "voucher_type": "Exchange Gain Or Loss",
773 "docstatus": 1,
774 },
775 as_list=1,
776 )
ruthra kumard9d68562023-07-27 08:02:46 +0530777 for doc in gain_loss_journals:
ruthra kumar5dbcf7d2023-09-05 09:52:36 +0530778 gain_loss_je = frappe.get_doc("Journal Entry", doc[0])
779 if referenced_dt and referenced_dn:
780 references = [(x.reference_type, x.reference_name) for x in gain_loss_je.accounts]
781 if (
782 len(references) == 2
783 and (referenced_dt, referenced_dn) in references
784 and (parent_doc.doctype, parent_doc.name) in references
785 ):
786 # only cancel JE generated against parent_doc and referenced_dn
787 gain_loss_je.cancel()
788 else:
789 gain_loss_je.cancel()
ruthra kumar81cd7872023-04-27 09:46:54 +0530790
791
ruthra kumar9b6eac22023-08-30 16:44:25 +0530792def update_accounting_ledgers_after_reference_removal(
Akhil Narang3effaf22024-03-27 11:37:26 +0530793 ref_type: str | None = None, ref_no: str | None = None, payment_name: str | None = None
ruthra kumar9b6eac22023-08-30 16:44:25 +0530794):
ruthra kumar0130aea2023-08-30 13:25:23 +0530795 # General Ledger
796 gle = qb.DocType("GL Entry")
ruthra kumar9b6eac22023-08-30 16:44:25 +0530797 gle_update_query = (
798 qb.update(gle)
799 .set(gle.against_voucher_type, None)
800 .set(gle.against_voucher, None)
801 .set(gle.modified, now())
802 .set(gle.modified_by, frappe.session.user)
803 .where((gle.against_voucher_type == ref_type) & (gle.against_voucher == ref_no))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530804 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530805
ruthra kumar9b6eac22023-08-30 16:44:25 +0530806 if payment_name:
807 gle_update_query = gle_update_query.where(gle.voucher_no == payment_name)
808 gle_update_query.run()
Nabin Hait297d74a2016-11-23 15:58:51 +0530809
ruthra kumar0130aea2023-08-30 13:25:23 +0530810 # Payment Ledger
ruthra kumar537d9532022-10-10 10:17:19 +0530811 ple = qb.DocType("Payment Ledger Entry")
ruthra kumar9b6eac22023-08-30 16:44:25 +0530812 ple_update_query = (
813 qb.update(ple)
814 .set(ple.against_voucher_type, ple.voucher_type)
815 .set(ple.against_voucher_no, ple.voucher_no)
816 .set(ple.modified, now())
817 .set(ple.modified_by, frappe.session.user)
818 .where(
Akhil Narang3effaf22024-03-27 11:37:26 +0530819 (ple.against_voucher_type == ref_type) & (ple.against_voucher_no == ref_no) & (ple.delinked == 0)
ruthra kumar9b6eac22023-08-30 16:44:25 +0530820 )
821 )
ruthra kumar537d9532022-10-10 10:17:19 +0530822
ruthra kumar9b6eac22023-08-30 16:44:25 +0530823 if payment_name:
824 ple_update_query = ple_update_query.where(ple.voucher_no == payment_name)
825 ple_update_query.run()
ruthra kumar537d9532022-10-10 10:17:19 +0530826
ruthra kumar0130aea2023-08-30 13:25:23 +0530827
828def remove_ref_from_advance_section(ref_doc: object = None):
ruthra kumar9b6eac22023-08-30 16:44:25 +0530829 # TODO: this might need some testing
Nabin Hait297d74a2016-11-23 15:58:51 +0530830 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
831 ref_doc.set("advances", [])
ruthra kumar0130aea2023-08-30 13:25:23 +0530832 adv_type = qb.DocType(f"{ref_doc.doctype} Advance")
833 qb.from_(adv_type).delete().where(adv_type.parent == ref_doc.name).run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530834
Anand Doshicd71e1d2014-04-08 13:53:35 +0530835
Akhil Narang3effaf22024-03-27 11:37:26 +0530836def unlink_ref_doc_from_payment_entries(ref_doc: object = None, payment_name: str | None = None):
ruthra kumar9b6eac22023-08-30 16:44:25 +0530837 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name, payment_name)
838 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name, payment_name)
839 update_accounting_ledgers_after_reference_removal(ref_doc.doctype, ref_doc.name, payment_name)
840 remove_ref_from_advance_section(ref_doc)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530841
Rushabh Mehta1828c122015-08-10 17:04:07 +0530842
ruthra kumar9b6eac22023-08-30 16:44:25 +0530843def remove_ref_doc_link_from_jv(
Akhil Narang3effaf22024-03-27 11:37:26 +0530844 ref_type: str | None = None, ref_no: str | None = None, payment_name: str | None = None
ruthra kumar9b6eac22023-08-30 16:44:25 +0530845):
ruthra kumar0130aea2023-08-30 13:25:23 +0530846 jea = qb.DocType("Journal Entry Account")
847
848 linked_jv = (
849 qb.from_(jea)
850 .select(jea.parent)
ruthra kumar9a1588f2023-08-30 20:50:16 +0530851 .where((jea.reference_type == ref_type) & (jea.reference_name == ref_no) & (jea.docstatus.lt(2)))
ruthra kumar0130aea2023-08-30 13:25:23 +0530852 .run(as_list=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530853 )
ruthra kumar0130aea2023-08-30 13:25:23 +0530854 linked_jv = convert_to_list(linked_jv)
ruthra kumar9b6eac22023-08-30 16:44:25 +0530855 # remove reference only from specified payment
856 linked_jv = [x for x in linked_jv if x == payment_name] if payment_name else linked_jv
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530857
858 if linked_jv:
ruthra kumar9b6eac22023-08-30 16:44:25 +0530859 update_query = (
860 qb.update(jea)
861 .set(jea.reference_type, None)
862 .set(jea.reference_name, None)
863 .set(jea.modified, now())
864 .set(jea.modified_by, frappe.session.user)
865 .where((jea.reference_type == ref_type) & (jea.reference_name == ref_no))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530866 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530867
ruthra kumar9b6eac22023-08-30 16:44:25 +0530868 if payment_name:
869 update_query = update_query.where(jea.parent == payment_name)
870
871 update_query.run()
Anand Doshi7da72dd2013-03-20 17:00:41 +0530872
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530873 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530874
Ankush Menat494bd9e2022-03-28 18:52:46 +0530875
ruthra kumar0130aea2023-08-30 13:25:23 +0530876def convert_to_list(result):
877 """
878 Convert tuple to list
879 """
880 return [x[0] for x in result]
881
882
ruthra kumar9b6eac22023-08-30 16:44:25 +0530883def remove_ref_doc_link_from_pe(
Akhil Narang3effaf22024-03-27 11:37:26 +0530884 ref_type: str | None = None, ref_no: str | None = None, payment_name: str | None = None
ruthra kumar9b6eac22023-08-30 16:44:25 +0530885):
ruthra kumar0130aea2023-08-30 13:25:23 +0530886 per = qb.DocType("Payment Entry Reference")
887 pay = qb.DocType("Payment Entry")
888
889 linked_pe = (
890 qb.from_(per)
891 .select(per.parent)
Akhil Narang3effaf22024-03-27 11:37:26 +0530892 .where((per.reference_doctype == ref_type) & (per.reference_name == ref_no) & (per.docstatus.lt(2)))
ruthra kumar0130aea2023-08-30 13:25:23 +0530893 .run(as_list=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530894 )
ruthra kumar0130aea2023-08-30 13:25:23 +0530895 linked_pe = convert_to_list(linked_pe)
ruthra kumar9b6eac22023-08-30 16:44:25 +0530896 # remove reference only from specified payment
897 linked_pe = [x for x in linked_pe if x == payment_name] if payment_name else linked_pe
Anand Doshicd71e1d2014-04-08 13:53:35 +0530898
Nabin Haite0cc87d2016-07-21 18:30:03 +0530899 if linked_pe:
ruthra kumar9b6eac22023-08-30 16:44:25 +0530900 update_query = (
901 qb.update(per)
902 .set(per.allocated_amount, 0)
903 .set(per.modified, now())
904 .set(per.modified_by, frappe.session.user)
Akhil Narang3effaf22024-03-27 11:37:26 +0530905 .where(per.docstatus.lt(2) & (per.reference_doctype == ref_type) & (per.reference_name == ref_no))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530906 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530907
ruthra kumar9b6eac22023-08-30 16:44:25 +0530908 if payment_name:
909 update_query = update_query.where(per.parent == payment_name)
910
911 update_query.run()
Nabin Haite0cc87d2016-07-21 18:30:03 +0530912
913 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530914 try:
Deepesh Garg1894dc82023-06-23 21:53:34 +0530915 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530916 pe_doc.set_amounts()
ruthra kumarecb533c2023-11-28 17:04:07 +0530917
918 # Call cancel on only removed reference
919 references = [
Akhil Narang3effaf22024-03-27 11:37:26 +0530920 x
921 for x in pe_doc.references
922 if x.reference_doctype == ref_type and x.reference_name == ref_no
ruthra kumarecb533c2023-11-28 17:04:07 +0530923 ]
924 [pe_doc.make_advance_gl_entries(x, cancel=1) for x in references]
925
Deepesh Gargb5162392021-08-10 14:52:24 +0530926 pe_doc.clear_unallocated_reference_document_rows()
927 pe_doc.validate_payment_type_with_outstanding()
Akhil Narang3effaf22024-03-27 11:37:26 +0530928 except Exception:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530929 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530930 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530931 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530932 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530933
ruthra kumar0130aea2023-08-30 13:25:23 +0530934 qb.update(pay).set(pay.total_allocated_amount, pe_doc.total_allocated_amount).set(
935 pay.base_total_allocated_amount, pe_doc.base_total_allocated_amount
936 ).set(pay.unallocated_amount, pe_doc.unallocated_amount).set(pay.modified, now()).set(
937 pay.modified_by, frappe.session.user
Akhil Narang3effaf22024-03-27 11:37:26 +0530938 ).where(pay.name == pe).run()
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530939
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530940 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530941
Ankush Menat494bd9e2022-03-28 18:52:46 +0530942
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530943@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530944def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530945 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530946
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530947 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530948 throw(
949 _("Please set default {0} in Company {1}").format(
950 frappe.get_meta("Company").get_label(fieldname), company
951 )
952 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530953
Nabin Hait0fc24542013-03-25 11:06:00 +0530954 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530955
Ankush Menat494bd9e2022-03-28 18:52:46 +0530956
Nabin Hait8b509f52013-05-28 16:52:30 +0530957def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530958 vouchers = frappe.db.sql(
959 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530960 sum(debit) - sum(credit) as diff
961 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530962 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530963 having sum(debit) != sum(credit)""",
964 as_dict=1,
965 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530966
Nabin Hait8b509f52013-05-28 16:52:30 +0530967 for d in vouchers:
968 if abs(d.diff) > 0:
969 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530970
Ankush Menat494bd9e2022-03-28 18:52:46 +0530971 frappe.db.sql(
Akhil Narang3effaf22024-03-27 11:37:26 +0530972 """update `tabGL Entry` set {} = {} + {}
973 where voucher_type = {} and voucher_no = {} and {} > 0 limit 1""".format(
974 dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr
975 ),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530976 (d.diff, d.voucher_type, d.voucher_no),
977 )
978
Anand Doshicd71e1d2014-04-08 13:53:35 +0530979
Rushabh Mehtad50da782017-07-28 11:39:01 +0530980def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530981 precision = cint(frappe.db.get_default("currency_precision"))
982 if not precision:
983 number_format = frappe.db.get_default("number_format") or "#,###.##"
984 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530985
Nabin Hait9b20e072017-04-25 12:10:24 +0530986 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530987
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530988
tundebabzyad08d4c2018-05-16 07:01:41 +0100989def get_held_invoices(party_type, party):
990 """
991 Returns a list of names Purchase Invoices for the given party that are on hold
992 """
993 held_invoices = None
994
Ankush Menat494bd9e2022-03-28 18:52:46 +0530995 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +0100996 held_invoices = frappe.db.sql(
mergify[bot]872a23c2023-07-10 20:34:54 +0530997 "select name from `tabPurchase Invoice` where on_hold = 1 and release_date IS NOT NULL and release_date > CURDATE()",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530998 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +0100999 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05301000 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +01001001
1002 return held_invoices
1003
1004
ruthra kumar8c876742022-06-14 17:46:04 +05301005def get_outstanding_invoices(
ruthra kumar5f1562c2022-07-28 11:57:27 +05301006 party_type,
1007 party,
1008 account,
1009 common_filter=None,
1010 posting_date=None,
1011 min_outstanding=None,
1012 max_outstanding=None,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301013 accounting_dimensions=None,
Deepesh Garg299e32b2023-08-24 18:02:06 +05301014 vouchers=None, # list of dicts [{'voucher_type': '', 'voucher_no': ''}] for filtering
1015 limit=None, # passed by reconciliation tool
1016 voucher_no=None, # filter passed by reconciliation tool
ruthra kumar8c876742022-06-14 17:46:04 +05301017):
ruthra kumar8c876742022-06-14 17:46:04 +05301018 ple = qb.DocType("Payment Ledger Entry")
Anand Doshid40d1e92015-11-12 17:05:29 +05301019 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +05301020 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +05301021
Nabin Hait9db9edc2019-11-19 18:44:32 +05301022 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301023 root_type, account_type = frappe.get_cached_value(
ruthra kumar5f152972024-03-02 19:29:58 +05301024 "Account", account[0], ["root_type", "account_type"]
Ankush Menat494bd9e2022-03-28 18:52:46 +05301025 )
Nabin Hait9db9edc2019-11-19 18:44:32 +05301026 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +05301027 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +05301028 else:
1029 party_account_type = erpnext.get_party_account_type(party_type)
1030
tundebabzyad08d4c2018-05-16 07:01:41 +01001031 held_invoices = get_held_invoices(party_type, party)
1032
ruthra kumar8c876742022-06-14 17:46:04 +05301033 common_filter = common_filter or []
1034 common_filter.append(ple.account_type == party_account_type)
ruthra kumar5f152972024-03-02 19:29:58 +05301035 common_filter.append(ple.account.isin(account))
ruthra kumar8c876742022-06-14 17:46:04 +05301036 common_filter.append(ple.party_type == party_type)
1037 common_filter.append(ple.party == party)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301038
ruthra kumar8c876742022-06-14 17:46:04 +05301039 ple_query = QueryPaymentLedger()
1040 invoice_list = ple_query.get_voucher_outstandings(
ruthra kumardeb0d712023-08-15 05:17:01 +05301041 vouchers=vouchers,
ruthra kumar8c876742022-06-14 17:46:04 +05301042 common_filter=common_filter,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301043 posting_date=posting_date,
ruthra kumar8c876742022-06-14 17:46:04 +05301044 min_outstanding=min_outstanding,
1045 max_outstanding=max_outstanding,
1046 get_invoices=True,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301047 accounting_dimensions=accounting_dimensions or [],
ruthra kumar7a381af2023-05-03 20:45:12 +05301048 limit=limit,
1049 voucher_no=voucher_no,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301050 )
tundec4b0d172017-09-26 00:48:30 +01001051
Nabin Haitac184982019-02-04 21:13:43 +05301052 for d in invoice_list:
ruthra kumar21985532022-06-30 15:14:38 +05301053 payment_amount = d.invoice_amount_in_account_currency - d.outstanding_in_account_currency
1054 outstanding_amount = d.outstanding_in_account_currency
Nabin Haitac184982019-02-04 21:13:43 +05301055 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301056 if (
ruthra kumar8c876742022-06-14 17:46:04 +05301057 min_outstanding
1058 and max_outstanding
barredterraeb9ee3f2023-12-05 11:22:55 +01001059 and (outstanding_amount < min_outstanding or outstanding_amount > max_outstanding)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301060 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +05301061 continue
Nabin Haitac184982019-02-04 21:13:43 +05301062
barredterraeb9ee3f2023-12-05 11:22:55 +01001063 if d.voucher_type != "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +05301064 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301065 frappe._dict(
1066 {
1067 "voucher_no": d.voucher_no,
1068 "voucher_type": d.voucher_type,
1069 "posting_date": d.posting_date,
ruthra kumar21985532022-06-30 15:14:38 +05301070 "invoice_amount": flt(d.invoice_amount_in_account_currency),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301071 "payment_amount": payment_amount,
1072 "outstanding_amount": outstanding_amount,
1073 "due_date": d.due_date,
1074 "currency": d.currency,
Gursheen Anand4ee16372023-06-08 13:15:23 +05301075 "account": d.account,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301076 }
1077 )
Nabin Haitac184982019-02-04 21:13:43 +05301078 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +05301079
Akhil Narang3effaf22024-03-27 11:37:26 +05301080 outstanding_invoices = sorted(outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate()))
Anand Doshid40d1e92015-11-12 17:05:29 +05301081 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +05301082
1083
Akhil Narang3effaf22024-03-27 11:37:26 +05301084def get_account_name(account_type=None, root_type=None, is_group=None, account_currency=None, company=None):
Saurabh3a268292016-02-22 15:18:40 +05301085 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301086 return frappe.db.get_value(
1087 "Account",
1088 {
1089 "account_type": account_type or "",
1090 "root_type": root_type or "",
1091 "is_group": is_group or 0,
1092 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
1093 "company": company or frappe.defaults.get_defaults().company,
1094 },
1095 "name",
1096 )
1097
Saurabha9ba7342016-06-21 12:33:12 +05301098
1099@frappe.whitelist()
1100def get_companies():
1101 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301102 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
1103
Saurabha9ba7342016-06-21 12:33:12 +05301104
1105@frappe.whitelist()
Gursheen Kaur Anandb7f283b2023-12-29 12:55:37 +05301106def get_children(doctype, parent, company, is_root=False, include_disabled=False):
1107 if isinstance(include_disabled, str):
1108 include_disabled = frappe.json.loads(include_disabled)
Nabin Haitaf98f5d2018-04-02 10:14:32 +05301109 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +05301110
Ankush Menat494bd9e2022-03-28 18:52:46 +05301111 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
1112 fields = ["name as value", "is_group as expandable"]
1113 filters = [["docstatus", "<", 2]]
Gursheen Kaur Anandb7f283b2023-12-29 12:55:37 +05301114 if frappe.db.has_column(doctype, "disabled") and not include_disabled:
1115 filters.append(["disabled", "=", False])
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +05301116
Akhil Narang3effaf22024-03-27 11:37:26 +05301117 filters.append([f'ifnull(`{parent_fieldname}`,"")', "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301118
Rushabh Mehta43133262017-11-10 18:52:21 +05301119 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301120 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
1121 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301122
Saurabha9ba7342016-06-21 12:33:12 +05301123 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301124 fields += ["root_type", "account_currency"] if doctype == "Account" else []
1125 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +05301126
1127 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +05301128
Ankush Menat494bd9e2022-03-28 18:52:46 +05301129 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +05301130 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +05301131
1132 return acc
Saurabhb835fef2016-09-09 11:19:22 +05301133
Ankush Menat494bd9e2022-03-28 18:52:46 +05301134
Saqib90517352021-10-04 11:44:46 +05301135@frappe.whitelist()
1136def get_account_balances(accounts, company):
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301137 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +05301138 accounts = loads(accounts)
1139
1140 if not accounts:
1141 return []
1142
Ankush Menat494bd9e2022-03-28 18:52:46 +05301143 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +05301144
1145 for account in accounts:
1146 account["company_currency"] = company_currency
Akhil Narang3effaf22024-03-27 11:37:26 +05301147 account["balance"] = flt(get_balance_on(account["value"], in_account_currency=False, company=company))
Saqib90517352021-10-04 11:44:46 +05301148 if account["account_currency"] and account["account_currency"] != company_currency:
1149 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
1150
1151 return accounts
1152
Ankush Menat494bd9e2022-03-28 18:52:46 +05301153
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +05301154def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +05301155 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +05301156
Daizy Modifdfe5cb2022-11-17 19:14:10 +05301157 company = frappe.get_cached_value("Global Defaults", "Global Defaults", "default_company")
Saurabhb835fef2016-09-09 11:19:22 +05301158 if not company:
1159 return
1160
1161 # NOTE: we translate Payment Gateway account name because that is going to be used by the end user
Ankush Menat494bd9e2022-03-28 18:52:46 +05301162 bank_account = frappe.db.get_value(
1163 "Account",
1164 {"account_name": _(gateway), "company": company},
1165 ["name", "account_currency"],
1166 as_dict=1,
1167 )
Saurabhb835fef2016-09-09 11:19:22 +05301168
1169 if not bank_account:
1170 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301171 bank_account = frappe.db.get_value(
1172 "Account",
1173 {"account_name": gateway, "company": company},
1174 ["name", "account_currency"],
1175 as_dict=1,
1176 )
Saurabhb835fef2016-09-09 11:19:22 +05301177
1178 if not bank_account:
1179 # try creating one
1180 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1181
1182 if not bank_account:
1183 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1184 return
1185
1186 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301187 if frappe.db.exists(
1188 "Payment Gateway Account",
1189 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1190 ):
Saurabhb835fef2016-09-09 11:19:22 +05301191 return
1192
1193 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301194 frappe.get_doc(
1195 {
1196 "doctype": "Payment Gateway Account",
1197 "is_default": 1,
1198 "payment_gateway": gateway,
1199 "payment_account": bank_account.name,
1200 "currency": bank_account.account_currency,
1201 "payment_channel": payment_channel,
1202 }
1203 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301204
1205 except frappe.DuplicateEntryError:
1206 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001207 pass
Zarrar44175902018-06-08 16:35:21 +05301208
Ankush Menat494bd9e2022-03-28 18:52:46 +05301209
Zarrar44175902018-06-08 16:35:21 +05301210@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301211def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301212 """
1213 Renames the document by adding the number as a prefix to the current name and updates
1214 all transaction where it was present.
1215 """
Saqiba8779872020-04-30 11:28:43 +05301216 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301217
Saqiba8779872020-04-30 11:28:43 +05301218 if cost_center_number:
1219 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1220 else:
1221 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301222
Saqiba8779872020-04-30 11:28:43 +05301223 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301224
Nabin Haitaf21a112022-09-15 12:09:18 +05301225 new_name = get_autoname_with_number(cost_center_number, cost_center_name, company)
Saqiba8779872020-04-30 11:28:43 +05301226 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301227 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301228 return new_name
1229
Ankush Menat494bd9e2022-03-28 18:52:46 +05301230
Saqiba8779872020-04-30 11:28:43 +05301231def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301232 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301233 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301234 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301235 if company:
Saqiba8779872020-04-30 11:28:43 +05301236 filters["company"] = company
1237
1238 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1239
Zarrar44175902018-06-08 16:35:21 +05301240 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301241 frappe.throw(
1242 _("{0} Number {1} is already used in {2} {3}").format(
1243 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1244 )
1245 )
1246
Zarrar44175902018-06-08 16:35:21 +05301247
Nabin Haitaf21a112022-09-15 12:09:18 +05301248def get_autoname_with_number(number_value, doc_title, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301249 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Nabin Haitaf21a112022-09-15 12:09:18 +05301250 company_abbr = frappe.get_cached_value("Company", company, "abbr")
1251 parts = [doc_title.strip(), company_abbr]
1252
Zlash651aeca1d2018-07-06 17:15:33 +05301253 if cstr(number_value).strip():
1254 parts.insert(0, cstr(number_value).strip())
Nabin Haitaf21a112022-09-15 12:09:18 +05301255
Ankush Menat494bd9e2022-03-28 18:52:46 +05301256 return " - ".join(parts)
1257
Zarrar254ce642018-06-28 14:15:34 +05301258
Deepesh Garg62706072023-07-16 12:58:42 +05301259def parse_naming_series_variable(doc, variable):
1260 if variable == "FY":
Gughan Ravikumar89d109e2023-07-27 23:12:11 +05301261 if doc:
Gursheen Anandd96a7772024-01-10 22:05:02 +05301262 date = doc.get("posting_date") or doc.get("transaction_date") or getdate()
Gughan Ravikumar89d109e2023-07-27 23:12:11 +05301263 company = doc.get("company")
1264 else:
1265 date = getdate()
1266 company = None
Gughan Ravikumarcdf100d2023-08-15 09:38:29 +05301267 return get_fiscal_year(date=date, company=company)[0]
Deepesh Garg62706072023-07-16 12:58:42 +05301268
1269
Zarrar254ce642018-06-28 14:15:34 +05301270@frappe.whitelist()
David Arnoldd066b5c2023-07-23 22:43:41 -05001271def get_coa(doctype, parent, is_root=None, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301272 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1273 build_tree_from_json,
1274 )
Zarrar254ce642018-06-28 14:15:34 +05301275
1276 # add chart to flags to retrieve when called from expand all function
1277 chart = chart if chart else frappe.flags.chart
1278 frappe.flags.chart = chart
1279
Ankush Menat494bd9e2022-03-28 18:52:46 +05301280 parent = None if parent == _("All Accounts") else parent
1281 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301282
1283 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301284 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301285
1286 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001287
Ankush Menat494bd9e2022-03-28 18:52:46 +05301288
1289def update_gl_entries_after(
1290 posting_date,
1291 posting_time,
1292 for_warehouses=None,
1293 for_items=None,
1294 warehouse_account=None,
1295 company=None,
1296):
Akhil Narang3effaf22024-03-27 11:37:26 +05301297 stock_vouchers = get_future_stock_vouchers(posting_date, posting_time, for_warehouses, for_items, company)
Nabin Hait9b178bc2021-02-16 14:57:00 +05301298 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1299
1300
Ankush Menat494bd9e2022-03-28 18:52:46 +05301301def repost_gle_for_stock_vouchers(
Akhil Narang3effaf22024-03-27 11:37:26 +05301302 stock_vouchers: list[tuple[str, str]],
Ankush Menat2535d5e2022-06-14 18:20:33 +05301303 posting_date: str,
Akhil Narang3effaf22024-03-27 11:37:26 +05301304 company: str | None = None,
Ankush Menat2535d5e2022-06-14 18:20:33 +05301305 warehouse_account=None,
1306 repost_doc: Optional["RepostItemValuation"] = None,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301307):
Ankush Menat67c26322022-06-04 14:46:35 +05301308 from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative
1309
Ankush Menat700e8642022-04-19 13:24:29 +05301310 if not stock_vouchers:
1311 return
1312
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301313 if not warehouse_account:
1314 warehouse_account = get_warehouse_account_map(company)
1315
Ankush Menat2535d5e2022-06-14 18:20:33 +05301316 stock_vouchers = sort_stock_vouchers_by_posting_date(stock_vouchers)
1317 if repost_doc and repost_doc.gl_reposting_index:
1318 # Restore progress
1319 stock_vouchers = stock_vouchers[cint(repost_doc.gl_reposting_index) :]
1320
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301321 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1322
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301323 for stock_vouchers_chunk in create_batch(stock_vouchers, GL_REPOSTING_CHUNK):
Ankush Menat2535d5e2022-06-14 18:20:33 +05301324 gle = get_voucherwise_gl_entries(stock_vouchers_chunk, posting_date)
1325
1326 for voucher_type, voucher_no in stock_vouchers_chunk:
1327 existing_gle = gle.get((voucher_type, voucher_no), [])
1328 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
1329 # Some transactions post credit as negative debit, this is handled while posting GLE
1330 # but while comparing we need to make sure it's flipped so comparisons are accurate
1331 expected_gle = toggle_debit_credit_if_negative(voucher_obj.get_gl_entries(warehouse_account))
1332 if expected_gle:
1333 if not existing_gle or not compare_existing_and_expected_gle(
1334 existing_gle, expected_gle, precision
1335 ):
ruthra kumar9209ec52022-10-21 15:18:40 +05301336 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301337 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
1338 else:
ruthra kumar9209ec52022-10-21 15:18:40 +05301339 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat86919d22022-06-15 21:19:09 +05301340
1341 if not frappe.flags.in_test:
1342 frappe.db.commit()
Ankush Menat2535d5e2022-06-14 18:20:33 +05301343
1344 if repost_doc:
1345 repost_doc.db_set(
1346 "gl_reposting_index",
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301347 cint(repost_doc.gl_reposting_index) + len(stock_vouchers_chunk),
Ankush Menat2535d5e2022-06-14 18:20:33 +05301348 )
1349
1350
ruthra kumar9209ec52022-10-21 15:18:40 +05301351def _delete_pl_entries(voucher_type, voucher_no):
ruthra kumar65992302022-10-04 16:17:56 +05301352 ple = qb.DocType("Payment Ledger Entry")
Akhil Narang3effaf22024-03-27 11:37:26 +05301353 qb.from_(ple).delete().where((ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)).run()
Ankush Menateb53a972022-06-04 18:19:44 +05301354
Ankush Menat494bd9e2022-03-28 18:52:46 +05301355
ruthra kumar9209ec52022-10-21 15:18:40 +05301356def _delete_gl_entries(voucher_type, voucher_no):
1357 gle = qb.DocType("GL Entry")
Akhil Narang3effaf22024-03-27 11:37:26 +05301358 qb.from_(gle).delete().where((gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)).run()
ruthra kumar9209ec52022-10-21 15:18:40 +05301359
1360
1361def _delete_accounting_ledger_entries(voucher_type, voucher_no):
1362 """
1363 Remove entries from both General and Payment Ledger for specified Voucher
1364 """
1365 _delete_gl_entries(voucher_type, voucher_no)
1366 _delete_pl_entries(voucher_type, voucher_no)
1367
1368
Akhil Narang3effaf22024-03-27 11:37:26 +05301369def sort_stock_vouchers_by_posting_date(stock_vouchers: list[tuple[str, str]]) -> list[tuple[str, str]]:
Ankush Menat700e8642022-04-19 13:24:29 +05301370 sle = frappe.qb.DocType("Stock Ledger Entry")
1371 voucher_nos = [v[1] for v in stock_vouchers]
1372
1373 sles = (
1374 frappe.qb.from_(sle)
1375 .select(sle.voucher_type, sle.voucher_no, sle.posting_date, sle.posting_time, sle.creation)
1376 .where((sle.is_cancelled == 0) & (sle.voucher_no.isin(voucher_nos)))
1377 .groupby(sle.voucher_type, sle.voucher_no)
Rohit Waghchaured80ca522024-02-07 21:56:21 +05301378 .orderby(sle.posting_datetime)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301379 .orderby(sle.creation)
Ankush Menat700e8642022-04-19 13:24:29 +05301380 ).run(as_dict=True)
1381 sorted_vouchers = [(sle.voucher_type, sle.voucher_no) for sle in sles]
1382
1383 unknown_vouchers = set(stock_vouchers) - set(sorted_vouchers)
1384 if unknown_vouchers:
1385 sorted_vouchers.extend(unknown_vouchers)
1386
1387 return sorted_vouchers
1388
1389
Akhil Narang3effaf22024-03-27 11:37:26 +05301390def get_future_stock_vouchers(posting_date, posting_time, for_warehouses=None, for_items=None, company=None):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301391 values = []
1392 condition = ""
1393 if for_items:
1394 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1395 values += for_items
1396
1397 if for_warehouses:
1398 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1399 values += for_warehouses
1400
rohitwaghchaured60ff832021-02-16 09:12:27 +05301401 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301402 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301403 values.append(company)
1404
Ankush Menat494bd9e2022-03-28 18:52:46 +05301405 future_stock_vouchers = frappe.db.sql(
Akhil Narang3effaf22024-03-27 11:37:26 +05301406 f"""select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301407 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301408 where
1409 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1410 and is_cancelled = 0
1411 {condition}
Akhil Narang3effaf22024-03-27 11:37:26 +05301412 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""",
1413 tuple([posting_date, posting_time, *values]),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301414 as_dict=True,
1415 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301416
Ankush91527152021-08-11 11:17:50 +05301417 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301418
Ankush Menat494bd9e2022-03-28 18:52:46 +05301419
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301420def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301421 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301422
1423 Only fetches GLE fields required for comparing with new GLE.
1424 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301425
1426 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301427 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301428 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301429 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301430 if not future_stock_vouchers:
1431 return gl_entries
1432
1433 voucher_nos = [d[1] for d in future_stock_vouchers]
1434
Ankush Menat494bd9e2022-03-28 18:52:46 +05301435 gles = frappe.db.sql(
1436 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301437 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301438 from `tabGL Entry`
1439 where
Akhil Narang3effaf22024-03-27 11:37:26 +05301440 posting_date >= {} and voucher_no in ({})""".format("%s", ", ".join(["%s"] * len(voucher_nos))),
1441 tuple([posting_date, *voucher_nos]),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301442 as_dict=1,
1443 )
Ankush91527152021-08-11 11:17:50 +05301444
1445 for d in gles:
1446 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301447
Prssanna Desai82ddef52020-06-18 18:18:41 +05301448 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301449
Ankush Menat494bd9e2022-03-28 18:52:46 +05301450
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301451def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301452 if len(existing_gle) != len(expected_gle):
1453 return False
1454
Nabin Haita77b8c92020-12-21 14:45:50 +05301455 matched = True
1456 for entry in expected_gle:
1457 account_existed = False
1458 for e in existing_gle:
1459 if entry.account == e.account:
1460 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301461 if (
1462 entry.account == e.account
1463 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1464 and (
1465 flt(entry.debit, precision) != flt(e.debit, precision)
1466 or flt(entry.credit, precision) != flt(e.credit, precision)
1467 )
1468 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301469 matched = False
1470 break
1471 if not account_existed:
1472 matched = False
1473 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301474 return matched
1475
Ankush Menat494bd9e2022-03-28 18:52:46 +05301476
Nabin Haitb99c77b2020-12-25 18:12:35 +05301477def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301478 stock_accounts = [
1479 d.name
Akhil Narang3effaf22024-03-27 11:37:26 +05301480 for d in frappe.db.get_all("Account", {"account_type": "Stock", "company": company, "is_group": 0})
Ankush Menat494bd9e2022-03-28 18:52:46 +05301481 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301482 if voucher_type and voucher_no:
1483 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301484 stock_accounts = [
1485 d.account
1486 for d in frappe.db.get_all(
Akhil Narang3effaf22024-03-27 11:37:26 +05301487 "Journal Entry Account",
1488 {"parent": voucher_no, "account": ["in", stock_accounts]},
1489 "account",
Ankush Menat494bd9e2022-03-28 18:52:46 +05301490 )
1491 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301492
1493 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301494 stock_accounts = [
1495 d.account
1496 for d in frappe.db.get_all(
1497 "GL Entry",
Akhil Narang3effaf22024-03-27 11:37:26 +05301498 {
1499 "voucher_type": voucher_type,
1500 "voucher_no": voucher_no,
1501 "account": ["in", stock_accounts],
1502 },
Ankush Menat494bd9e2022-03-28 18:52:46 +05301503 "account",
1504 )
1505 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301506
1507 return stock_accounts
1508
Ankush Menat494bd9e2022-03-28 18:52:46 +05301509
Nabin Haitb99c77b2020-12-25 18:12:35 +05301510def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301511 if not posting_date:
1512 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301513
1514 warehouse_account = get_warehouse_account_map(company)
1515
Ankush Menat494bd9e2022-03-28 18:52:46 +05301516 account_balance = get_balance_on(
1517 account, posting_date, in_account_currency=False, ignore_account_permission=True
1518 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301519
Ankush Menat494bd9e2022-03-28 18:52:46 +05301520 related_warehouses = [
1521 wh
1522 for wh, wh_details in warehouse_account.items()
1523 if wh_details.account == account and not wh_details.is_group
1524 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301525
s-aga-re782a052023-04-25 13:54:36 +05301526 total_stock_value = get_stock_value_on(related_warehouses, posting_date)
Nabin Haitb99c77b2020-12-25 18:12:35 +05301527
1528 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1529 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1530
Ankush Menat494bd9e2022-03-28 18:52:46 +05301531
Nabin Haitb99c77b2020-12-25 18:12:35 +05301532def get_journal_entry(account, stock_adjustment_account, amount):
Akhil Narang3effaf22024-03-27 11:37:26 +05301533 db_or_cr_warehouse_account = "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
Ankush Menat494bd9e2022-03-28 18:52:46 +05301534 db_or_cr_stock_adjustment_account = (
1535 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1536 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301537
1538 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301539 "accounts": [
1540 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1541 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1542 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301543 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301544
Ankush Menat494bd9e2022-03-28 18:52:46 +05301545
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301546def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301547 """Check if reports are referenced in Desktop Icon"""
1548 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301549 if icons:
1550 for icon in icons:
1551 frappe.delete_doc("Desktop Icon", icon)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301552
1553
Akhil Narang3effaf22024-03-27 11:37:26 +05301554def create_err_and_its_journals(companies: list | None = None) -> None:
ruthra kumar4f51c5a2023-07-03 14:35:33 +05301555 if companies:
1556 for company in companies:
1557 err = frappe.new_doc("Exchange Rate Revaluation")
1558 err.company = company.name
1559 err.posting_date = nowdate()
1560 err.rounding_loss_allowance = 0.0
1561
1562 err.fetch_and_calculate_accounts_data()
1563 if err.accounts:
1564 err.save().submit()
1565 response = err.make_jv_entries()
1566
1567 if company.submit_err_jv:
1568 jv = response.get("revaluation_jv", None)
1569 jv and frappe.get_doc("Journal Entry", jv).submit()
1570 jv = response.get("zero_balance_jv", None)
1571 jv and frappe.get_doc("Journal Entry", jv).submit()
1572
1573
1574def auto_create_exchange_rate_revaluation_daily() -> None:
1575 """
1576 Executed by background job
1577 """
1578 companies = frappe.db.get_all(
1579 "Company",
1580 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Daily"},
1581 fields=["name", "submit_err_jv"],
1582 )
1583 create_err_and_its_journals(companies)
1584
1585
1586def auto_create_exchange_rate_revaluation_weekly() -> None:
1587 """
1588 Executed by background job
1589 """
1590 companies = frappe.db.get_all(
1591 "Company",
1592 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Weekly"},
1593 fields=["name", "submit_err_jv"],
1594 )
1595 create_err_and_its_journals(companies)
1596
1597
ruthra kumar9b502212022-10-13 14:13:48 +05301598def get_payment_ledger_entries(gl_entries, cancel=0):
1599 ple_map = []
ruthra kumar451cf3a2022-05-16 14:29:58 +05301600 if gl_entries:
1601 ple = None
1602
1603 # companies
1604 account = qb.DocType("Account")
1605 companies = list(set([x.company for x in gl_entries]))
1606
1607 # receivable/payable account
1608 accounts_with_types = (
1609 qb.from_(account)
1610 .select(account.name, account.account_type)
Akhil Narang3effaf22024-03-27 11:37:26 +05301611 .where(account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
ruthra kumar451cf3a2022-05-16 14:29:58 +05301612 .run(as_dict=True)
1613 )
1614 receivable_or_payable_accounts = [y.name for y in accounts_with_types]
1615
1616 def get_account_type(account):
1617 for entry in accounts_with_types:
1618 if entry.name == account:
1619 return entry.account_type
1620
1621 dr_or_cr = 0
1622 account_type = None
1623 for gle in gl_entries:
1624 if gle.account in receivable_or_payable_accounts:
1625 account_type = get_account_type(gle.account)
1626 if account_type == "Receivable":
1627 dr_or_cr = gle.debit - gle.credit
1628 dr_or_cr_account_currency = gle.debit_in_account_currency - gle.credit_in_account_currency
1629 elif account_type == "Payable":
1630 dr_or_cr = gle.credit - gle.debit
1631 dr_or_cr_account_currency = gle.credit_in_account_currency - gle.debit_in_account_currency
1632
1633 if cancel:
1634 dr_or_cr *= -1
1635 dr_or_cr_account_currency *= -1
1636
ruthra kumar9b502212022-10-13 14:13:48 +05301637 ple = frappe._dict(
1638 doctype="Payment Ledger Entry",
1639 posting_date=gle.posting_date,
1640 company=gle.company,
1641 account_type=account_type,
1642 account=gle.account,
1643 party_type=gle.party_type,
1644 party=gle.party,
1645 cost_center=gle.cost_center,
1646 finance_book=gle.finance_book,
1647 due_date=gle.due_date,
1648 voucher_type=gle.voucher_type,
1649 voucher_no=gle.voucher_no,
Deepesh Garg1e078d02023-06-29 12:18:25 +05301650 voucher_detail_no=gle.voucher_detail_no,
ruthra kumar9b502212022-10-13 14:13:48 +05301651 against_voucher_type=gle.against_voucher_type
1652 if gle.against_voucher_type
1653 else gle.voucher_type,
1654 against_voucher_no=gle.against_voucher if gle.against_voucher else gle.voucher_no,
1655 account_currency=gle.account_currency,
1656 amount=dr_or_cr,
1657 amount_in_account_currency=dr_or_cr_account_currency,
1658 delinked=True if cancel else False,
1659 remarks=gle.remarks,
ruthra kumar451cf3a2022-05-16 14:29:58 +05301660 )
1661
1662 dimensions_and_defaults = get_dimensions()
1663 if dimensions_and_defaults:
1664 for dimension in dimensions_and_defaults[0]:
ruthra kumar9b502212022-10-13 14:13:48 +05301665 ple[dimension.fieldname] = gle.get(dimension.fieldname)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301666
ruthra kumar9b502212022-10-13 14:13:48 +05301667 ple_map.append(ple)
1668 return ple_map
1669
1670
1671def create_payment_ledger_entry(
Deepesh Garg1e078d02023-06-29 12:18:25 +05301672 gl_entries, cancel=0, adv_adj=0, update_outstanding="Yes", from_repost=0, partial_cancel=False
ruthra kumar9b502212022-10-13 14:13:48 +05301673):
1674 if gl_entries:
1675 ple_map = get_payment_ledger_entries(gl_entries, cancel=cancel)
1676
1677 for entry in ple_map:
ruthra kumar9b502212022-10-13 14:13:48 +05301678 ple = frappe.get_doc(entry)
1679
1680 if cancel:
Deepesh Garg1e078d02023-06-29 12:18:25 +05301681 delink_original_entry(ple, partial_cancel=partial_cancel)
ruthra kumar9b502212022-10-13 14:13:48 +05301682
1683 ple.flags.ignore_permissions = 1
1684 ple.flags.adv_adj = adv_adj
1685 ple.flags.from_repost = from_repost
1686 ple.flags.update_outstanding = update_outstanding
1687 ple.submit()
ruthra kumar451cf3a2022-05-16 14:29:58 +05301688
1689
ruthra kumar7312f222022-05-29 21:33:08 +05301690def update_voucher_outstanding(voucher_type, voucher_no, account, party_type, party):
1691 ple = frappe.qb.DocType("Payment Ledger Entry")
1692 vouchers = [frappe._dict({"voucher_type": voucher_type, "voucher_no": voucher_no})]
1693 common_filter = []
1694 if account:
1695 common_filter.append(ple.account == account)
1696
1697 if party_type:
1698 common_filter.append(ple.party_type == party_type)
1699
1700 if party:
1701 common_filter.append(ple.party == party)
1702
1703 ple_query = QueryPaymentLedger()
1704
1705 # on cancellation outstanding can be an empty list
1706 voucher_outstanding = ple_query.get_voucher_outstandings(vouchers, common_filter=common_filter)
ruthra kumar43b80682022-10-18 09:33:37 +05301707 if (
1708 voucher_type in ["Sales Invoice", "Purchase Invoice", "Fees"]
1709 and party_type
1710 and party
1711 and voucher_outstanding
1712 ):
ruthra kumar7312f222022-05-29 21:33:08 +05301713 outstanding = voucher_outstanding[0]
1714 ref_doc = frappe.get_doc(voucher_type, voucher_no)
1715
1716 # Didn't use db_set for optimisation purpose
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301717 ref_doc.outstanding_amount = outstanding["outstanding_in_account_currency"] or 0.0
ruthra kumar7312f222022-05-29 21:33:08 +05301718 frappe.db.set_value(
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301719 voucher_type,
1720 voucher_no,
1721 "outstanding_amount",
1722 outstanding["outstanding_in_account_currency"] or 0.0,
ruthra kumar7312f222022-05-29 21:33:08 +05301723 )
1724
1725 ref_doc.set_status(update=True)
HarryPaulof67f1632024-04-02 18:42:30 -03001726 ref_doc.notify_update()
ruthra kumar7312f222022-05-29 21:33:08 +05301727
1728
Deepesh Garg1e078d02023-06-29 12:18:25 +05301729def delink_original_entry(pl_entry, partial_cancel=False):
ruthra kumar451cf3a2022-05-16 14:29:58 +05301730 if pl_entry:
1731 ple = qb.DocType("Payment Ledger Entry")
1732 query = (
1733 qb.update(ple)
1734 .set(ple.delinked, True)
1735 .set(ple.modified, now())
1736 .set(ple.modified_by, frappe.session.user)
1737 .where(
1738 (ple.company == pl_entry.company)
1739 & (ple.account_type == pl_entry.account_type)
1740 & (ple.account == pl_entry.account)
1741 & (ple.party_type == pl_entry.party_type)
1742 & (ple.party == pl_entry.party)
1743 & (ple.voucher_type == pl_entry.voucher_type)
1744 & (ple.voucher_no == pl_entry.voucher_no)
1745 & (ple.against_voucher_type == pl_entry.against_voucher_type)
1746 & (ple.against_voucher_no == pl_entry.against_voucher_no)
1747 )
1748 )
Deepesh Garg1e078d02023-06-29 12:18:25 +05301749
1750 if partial_cancel:
1751 query = query.where(ple.voucher_detail_no == pl_entry.voucher_detail_no)
1752
ruthra kumar451cf3a2022-05-16 14:29:58 +05301753 query.run()
ruthra kumar7b383882022-05-25 15:51:16 +05301754
1755
Akhil Narang3effaf22024-03-27 11:37:26 +05301756class QueryPaymentLedger:
ruthra kumar7b383882022-05-25 15:51:16 +05301757 """
1758 Helper Class for Querying Payment Ledger Entry
1759 """
1760
1761 def __init__(self):
1762 self.ple = qb.DocType("Payment Ledger Entry")
1763
1764 # query result
1765 self.voucher_outstandings = []
1766
1767 # query filters
1768 self.vouchers = []
1769 self.common_filter = []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301770 self.voucher_posting_date = []
ruthra kumar7b383882022-05-25 15:51:16 +05301771 self.min_outstanding = None
1772 self.max_outstanding = None
ruthra kumar7a381af2023-05-03 20:45:12 +05301773 self.limit = self.voucher_no = None
ruthra kumar7b383882022-05-25 15:51:16 +05301774
1775 def reset(self):
1776 # clear filters
1777 self.vouchers.clear()
1778 self.common_filter.clear()
ruthra kumar7a381af2023-05-03 20:45:12 +05301779 self.min_outstanding = self.max_outstanding = self.limit = None
ruthra kumar7b383882022-05-25 15:51:16 +05301780
1781 # clear result
1782 self.voucher_outstandings.clear()
1783
1784 def query_for_outstanding(self):
1785 """
1786 Database query to fetch voucher amount and voucher outstanding using Common Table Expression
1787 """
1788
1789 ple = self.ple
1790
1791 filter_on_voucher_no = []
1792 filter_on_against_voucher_no = []
ruthra kumar7a381af2023-05-03 20:45:12 +05301793
ruthra kumar7b383882022-05-25 15:51:16 +05301794 if self.vouchers:
1795 voucher_types = set([x.voucher_type for x in self.vouchers])
1796 voucher_nos = set([x.voucher_no for x in self.vouchers])
1797
1798 filter_on_voucher_no.append(ple.voucher_type.isin(voucher_types))
1799 filter_on_voucher_no.append(ple.voucher_no.isin(voucher_nos))
1800
1801 filter_on_against_voucher_no.append(ple.against_voucher_type.isin(voucher_types))
1802 filter_on_against_voucher_no.append(ple.against_voucher_no.isin(voucher_nos))
1803
ruthra kumar7a381af2023-05-03 20:45:12 +05301804 if self.voucher_no:
1805 filter_on_voucher_no.append(ple.voucher_no.like(f"%{self.voucher_no}%"))
1806 filter_on_against_voucher_no.append(ple.against_voucher_no.like(f"%{self.voucher_no}%"))
1807
ruthra kumar7b383882022-05-25 15:51:16 +05301808 # build outstanding amount filter
1809 filter_on_outstanding_amount = []
1810 if self.min_outstanding:
1811 if self.min_outstanding > 0:
1812 filter_on_outstanding_amount.append(
1813 Table("outstanding").amount_in_account_currency >= self.min_outstanding
1814 )
1815 else:
1816 filter_on_outstanding_amount.append(
1817 Table("outstanding").amount_in_account_currency <= self.min_outstanding
1818 )
1819 if self.max_outstanding:
1820 if self.max_outstanding > 0:
1821 filter_on_outstanding_amount.append(
1822 Table("outstanding").amount_in_account_currency <= self.max_outstanding
1823 )
1824 else:
1825 filter_on_outstanding_amount.append(
1826 Table("outstanding").amount_in_account_currency >= self.max_outstanding
1827 )
1828
ruthra kumar8b04c1d2023-11-22 09:59:32 +05301829 if self.limit and self.get_invoices:
1830 outstanding_vouchers = (
1831 qb.from_(ple)
1832 .select(
1833 ple.against_voucher_no.as_("voucher_no"),
1834 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1835 )
1836 .where(ple.delinked == 0)
1837 .where(Criterion.all(filter_on_against_voucher_no))
1838 .where(Criterion.all(self.common_filter))
ruthra kumarcfd32302023-11-30 12:22:55 +05301839 .where(Criterion.all(self.dimensions_filter))
1840 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar8b04c1d2023-11-22 09:59:32 +05301841 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1842 .orderby(ple.posting_date, ple.voucher_no)
1843 .having(qb.Field("amount_in_account_currency") > 0)
1844 .limit(self.limit)
1845 .run()
1846 )
1847 if outstanding_vouchers:
1848 filter_on_voucher_no.append(ple.voucher_no.isin([x[0] for x in outstanding_vouchers]))
1849 filter_on_against_voucher_no.append(
1850 ple.against_voucher_no.isin([x[0] for x in outstanding_vouchers])
1851 )
1852
ruthra kumar7b383882022-05-25 15:51:16 +05301853 # build query for voucher amount
1854 query_voucher_amount = (
1855 qb.from_(ple)
1856 .select(
1857 ple.account,
1858 ple.voucher_type,
1859 ple.voucher_no,
1860 ple.party_type,
1861 ple.party,
1862 ple.posting_date,
1863 ple.due_date,
1864 ple.account_currency.as_("currency"),
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301865 ple.cost_center.as_("cost_center"),
ruthra kumar7b383882022-05-25 15:51:16 +05301866 Sum(ple.amount).as_("amount"),
1867 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1868 )
1869 .where(ple.delinked == 0)
1870 .where(Criterion.all(filter_on_voucher_no))
1871 .where(Criterion.all(self.common_filter))
ruthra kumar6d9d7302022-12-14 16:05:15 +05301872 .where(Criterion.all(self.dimensions_filter))
ruthra kumar5f1562c2022-07-28 11:57:27 +05301873 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar7b383882022-05-25 15:51:16 +05301874 .groupby(ple.voucher_type, ple.voucher_no, ple.party_type, ple.party)
1875 )
1876
1877 # build query for voucher outstanding
1878 query_voucher_outstanding = (
1879 qb.from_(ple)
1880 .select(
1881 ple.account,
1882 ple.against_voucher_type.as_("voucher_type"),
1883 ple.against_voucher_no.as_("voucher_no"),
1884 ple.party_type,
1885 ple.party,
1886 ple.posting_date,
1887 ple.due_date,
1888 ple.account_currency.as_("currency"),
1889 Sum(ple.amount).as_("amount"),
1890 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1891 )
1892 .where(ple.delinked == 0)
1893 .where(Criterion.all(filter_on_against_voucher_no))
1894 .where(Criterion.all(self.common_filter))
1895 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1896 )
1897
1898 # build CTE for combining voucher amount and outstanding
1899 self.cte_query_voucher_amount_and_outstanding = (
1900 qb.with_(query_voucher_amount, "vouchers")
1901 .with_(query_voucher_outstanding, "outstanding")
1902 .from_(AliasedQuery("vouchers"))
1903 .left_join(AliasedQuery("outstanding"))
1904 .on(
1905 (AliasedQuery("vouchers").account == AliasedQuery("outstanding").account)
1906 & (AliasedQuery("vouchers").voucher_type == AliasedQuery("outstanding").voucher_type)
1907 & (AliasedQuery("vouchers").voucher_no == AliasedQuery("outstanding").voucher_no)
1908 & (AliasedQuery("vouchers").party_type == AliasedQuery("outstanding").party_type)
1909 & (AliasedQuery("vouchers").party == AliasedQuery("outstanding").party)
1910 )
1911 .select(
1912 Table("vouchers").account,
1913 Table("vouchers").voucher_type,
1914 Table("vouchers").voucher_no,
1915 Table("vouchers").party_type,
1916 Table("vouchers").party,
1917 Table("vouchers").posting_date,
1918 Table("vouchers").amount.as_("invoice_amount"),
1919 Table("vouchers").amount_in_account_currency.as_("invoice_amount_in_account_currency"),
1920 Table("outstanding").amount.as_("outstanding"),
1921 Table("outstanding").amount_in_account_currency.as_("outstanding_in_account_currency"),
1922 (Table("vouchers").amount - Table("outstanding").amount).as_("paid_amount"),
1923 (
Akhil Narang3effaf22024-03-27 11:37:26 +05301924 Table("vouchers").amount_in_account_currency
1925 - Table("outstanding").amount_in_account_currency
ruthra kumar7b383882022-05-25 15:51:16 +05301926 ).as_("paid_amount_in_account_currency"),
1927 Table("vouchers").due_date,
1928 Table("vouchers").currency,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301929 Table("vouchers").cost_center.as_("cost_center"),
ruthra kumar7b383882022-05-25 15:51:16 +05301930 )
1931 .where(Criterion.all(filter_on_outstanding_amount))
1932 )
1933
1934 # build CTE filter
1935 # only fetch invoices
1936 if self.get_invoices:
1937 self.cte_query_voucher_amount_and_outstanding = (
1938 self.cte_query_voucher_amount_and_outstanding.having(
1939 qb.Field("outstanding_in_account_currency") > 0
1940 )
1941 )
1942 # only fetch payments
1943 elif self.get_payments:
1944 self.cte_query_voucher_amount_and_outstanding = (
1945 self.cte_query_voucher_amount_and_outstanding.having(
1946 qb.Field("outstanding_in_account_currency") < 0
1947 )
1948 )
1949
ruthra kumar7a381af2023-05-03 20:45:12 +05301950 if self.limit:
1951 self.cte_query_voucher_amount_and_outstanding = (
1952 self.cte_query_voucher_amount_and_outstanding.limit(self.limit)
1953 )
1954
ruthra kumar7b383882022-05-25 15:51:16 +05301955 # execute SQL
1956 self.voucher_outstandings = self.cte_query_voucher_amount_and_outstanding.run(as_dict=True)
1957
1958 def get_voucher_outstandings(
1959 self,
1960 vouchers=None,
1961 common_filter=None,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301962 posting_date=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301963 min_outstanding=None,
1964 max_outstanding=None,
1965 get_payments=False,
1966 get_invoices=False,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301967 accounting_dimensions=None,
ruthra kumar7a381af2023-05-03 20:45:12 +05301968 limit=None,
1969 voucher_no=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301970 ):
1971 """
1972 Fetch voucher amount and outstanding amount from Payment Ledger using Database CTE
1973
1974 vouchers - dict of vouchers to get
1975 common_filter - array of criterions
1976 min_outstanding - filter on minimum total outstanding amount
1977 max_outstanding - filter on maximum total outstanding amount
1978 get_invoices - only fetch vouchers(ledger entries with +ve outstanding)
1979 get_payments - only fetch payments(ledger entries with -ve outstanding)
1980 """
1981
1982 self.reset()
1983 self.vouchers = vouchers
1984 self.common_filter = common_filter or []
ruthra kumar6d9d7302022-12-14 16:05:15 +05301985 self.dimensions_filter = accounting_dimensions or []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301986 self.voucher_posting_date = posting_date or []
ruthra kumar7b383882022-05-25 15:51:16 +05301987 self.min_outstanding = min_outstanding
1988 self.max_outstanding = max_outstanding
1989 self.get_payments = get_payments
1990 self.get_invoices = get_invoices
ruthra kumar7a381af2023-05-03 20:45:12 +05301991 self.limit = limit
1992 self.voucher_no = voucher_no
ruthra kumar7b383882022-05-25 15:51:16 +05301993 self.query_for_outstanding()
1994
1995 return self.voucher_outstandings
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05301996
1997
1998def create_gain_loss_journal(
1999 company,
ruthra kumarf7865da2023-09-04 20:38:10 +05302000 posting_date,
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302001 party_type,
2002 party,
2003 party_account,
2004 gain_loss_account,
2005 exc_gain_loss,
2006 dr_or_cr,
2007 reverse_dr_or_cr,
2008 ref1_dt,
2009 ref1_dn,
2010 ref1_detail_no,
2011 ref2_dt,
2012 ref2_dn,
2013 ref2_detail_no,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05302014 cost_center,
ruthra kumar5dc22e12023-12-20 17:19:27 +05302015 dimensions,
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302016) -> str:
2017 journal_entry = frappe.new_doc("Journal Entry")
2018 journal_entry.voucher_type = "Exchange Gain Or Loss"
2019 journal_entry.company = company
ruthra kumarf7865da2023-09-04 20:38:10 +05302020 journal_entry.posting_date = posting_date or nowdate()
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302021 journal_entry.multi_currency = 1
ruthra kumar79c6f012023-09-01 14:57:12 +05302022 journal_entry.is_system_generated = True
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302023
2024 party_account_currency = frappe.get_cached_value("Account", party_account, "account_currency")
2025
2026 if not gain_loss_account:
2027 frappe.throw(_("Please set default Exchange Gain/Loss Account in Company {}").format(company))
2028 gain_loss_account_currency = get_account_currency(gain_loss_account)
2029 company_currency = frappe.get_cached_value("Company", company, "default_currency")
2030
2031 if gain_loss_account_currency != company_currency:
2032 frappe.throw(_("Currency for {0} must be {1}").format(gain_loss_account, company_currency))
2033
2034 journal_account = frappe._dict(
2035 {
2036 "account": party_account,
2037 "party_type": party_type,
2038 "party": party,
2039 "account_currency": party_account_currency,
2040 "exchange_rate": 0,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05302041 "cost_center": cost_center or erpnext.get_default_cost_center(company),
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302042 "reference_type": ref1_dt,
2043 "reference_name": ref1_dn,
2044 "reference_detail_no": ref1_detail_no,
2045 dr_or_cr: abs(exc_gain_loss),
2046 dr_or_cr + "_in_account_currency": 0,
2047 }
2048 )
ruthra kumarec0f17c2024-01-22 11:59:20 +05302049 if dimensions:
2050 journal_account.update(dimensions)
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302051 journal_entry.append("accounts", journal_account)
2052
2053 journal_account = frappe._dict(
2054 {
2055 "account": gain_loss_account,
2056 "account_currency": gain_loss_account_currency,
2057 "exchange_rate": 1,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05302058 "cost_center": cost_center or erpnext.get_default_cost_center(company),
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302059 "reference_type": ref2_dt,
2060 "reference_name": ref2_dn,
2061 "reference_detail_no": ref2_detail_no,
2062 reverse_dr_or_cr + "_in_account_currency": 0,
2063 reverse_dr_or_cr: abs(exc_gain_loss),
2064 }
2065 )
ruthra kumarec0f17c2024-01-22 11:59:20 +05302066 if dimensions:
2067 journal_account.update(dimensions)
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302068 journal_entry.append("accounts", journal_account)
2069
2070 journal_entry.save()
2071 journal_entry.submit()
2072 return journal_entry.name
Gursheen Anand40157232023-11-03 11:58:25 +05302073
2074
2075def get_party_types_from_account_type(account_type):
Gursheen Anand2984a862023-11-08 12:30:24 +05302076 return frappe.db.get_all("Party Type", {"account_type": account_type}, pluck="name")
ruthra kumar8c8d9be2024-03-26 17:57:43 +05302077
2078
2079def run_ledger_health_checks():
ruthra kumara42482c2024-03-27 10:01:03 +05302080 health_monitor_settings = frappe.get_doc("Ledger Health Monitor")
2081 if health_monitor_settings.enable_health_monitor:
2082 period_end = getdate()
2083 period_start = add_days(period_end, -abs(health_monitor_settings.monitor_for_last_x_days))
ruthra kumar8c8d9be2024-03-26 17:57:43 +05302084
ruthra kumara42482c2024-03-27 10:01:03 +05302085 run_date = get_datetime()
ruthra kumar8c8d9be2024-03-26 17:57:43 +05302086
ruthra kumara42482c2024-03-27 10:01:03 +05302087 # Debit-Credit mismatch report
2088 if health_monitor_settings.debit_credit_mismatch:
ruthra kumar00eeacd2024-03-27 10:10:55 +05302089 for x in health_monitor_settings.companies:
2090 filters = {"company": x.company, "from_date": period_start, "to_date": period_end}
2091 voucher_wise = frappe.get_doc("Report", "Voucher-wise Balance")
2092 res = voucher_wise.execute_script_report(filters=filters)
2093 for x in res[1]:
2094 doc = frappe.new_doc("Ledger Health")
2095 doc.voucher_type = x.voucher_type
2096 doc.voucher_no = x.voucher_no
2097 doc.debit_credit_mismatch = True
2098 doc.checked_on = run_date
2099 doc.save()
ruthra kumar8c8d9be2024-03-26 17:57:43 +05302100
ruthra kumara42482c2024-03-27 10:01:03 +05302101 # General Ledger and Payment Ledger discrepancy
2102 if health_monitor_settings.general_and_payment_ledger_mismatch:
ruthra kumar00eeacd2024-03-27 10:10:55 +05302103 for x in health_monitor_settings.companies:
2104 filters = {
2105 "company": x.company,
2106 "period_start_date": period_start,
2107 "period_end_date": period_end,
2108 }
2109 gl_pl_comparison = frappe.get_doc("Report", "General and Payment Ledger Comparison")
2110 res = gl_pl_comparison.execute_script_report(filters=filters)
2111 for x in res[1]:
2112 doc = frappe.new_doc("Ledger Health")
2113 doc.voucher_type = x.voucher_type
2114 doc.voucher_no = x.voucher_no
2115 doc.general_and_payment_ledger_mismatch = True
2116 doc.checked_on = run_date
2117 doc.save()