blob: 02012ad09e44249d075181a94304dfb3c6cd96f2 [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
Ankush Menat2535d5e2022-06-14 18:20:33 +05306from typing import TYPE_CHECKING, List, Optional, Tuple
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 (
16 cint,
17 create_batch,
18 cstr,
19 flt,
20 formatdate,
21 get_number_format_info,
22 getdate,
23 now,
24 nowdate,
25)
Gavin D'souza0727d1d2022-06-13 12:39:28 +053026from pypika import Order
27from pypika.terms import ExistsCriterion
Anand Doshicd0989e2015-09-28 13:31:17 +053028
Chillar Anand915b3432021-09-02 16:44:59 +053029import erpnext
30
31# imported to enable erpnext.accounts.utils.get_account_currency
32from erpnext.accounts.doctype.account.account import get_account_currency # noqa
ruthra kumar451cf3a2022-05-16 14:29:58 +053033from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_dimensions
Anurag Mishraa11e7382019-10-31 15:55:03 +053034from erpnext.stock import get_warehouse_account_map
Chillar Anand915b3432021-09-02 16:44:59 +053035from erpnext.stock.utils import get_stock_value_on
36
Ankush Menat2535d5e2022-06-14 18:20:33 +053037if TYPE_CHECKING:
38 from erpnext.stock.doctype.repost_item_valuation.repost_item_valuation import RepostItemValuation
39
Anurag Mishraa11e7382019-10-31 15:55:03 +053040
Ankush Menat494bd9e2022-03-28 18:52:46 +053041class FiscalYearError(frappe.ValidationError):
42 pass
43
44
45class PaymentEntryUnlinkError(frappe.ValidationError):
46 pass
47
Nabin Hait2b06aaa2013-08-22 18:25:43 +053048
Ankush Menat2535d5e2022-06-14 18:20:33 +053049GL_REPOSTING_CHUNK = 100
50
51
Neil Trini Lasrado78fa6952014-10-03 17:43:02 +053052@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +053053def get_fiscal_year(
Deepesh Garg0aadb682023-03-19 12:46:42 +053054 date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False, boolean=False
Ankush Menat494bd9e2022-03-28 18:52:46 +053055):
ruthra kumarc31ee8e2023-11-14 06:44:49 +053056 if isinstance(boolean, str):
57 boolean = frappe.json.loads(boolean)
58
Deepesh Garg0aadb682023-03-19 12:46:42 +053059 fiscal_years = get_fiscal_years(
60 date, fiscal_year, label, verbose, company, as_dict=as_dict, boolean=boolean
61 )
62 if boolean:
63 return fiscal_years
64 else:
65 return fiscal_years[0]
Nabin Hait23941aa2013-01-29 11:32:38 +053066
Ankush Menat494bd9e2022-03-28 18:52:46 +053067
68def get_fiscal_years(
Deepesh Garg0aadb682023-03-19 12:46:42 +053069 transaction_date=None,
70 fiscal_year=None,
71 label="Date",
72 verbose=1,
73 company=None,
74 as_dict=False,
75 boolean=False,
Ankush Menat494bd9e2022-03-28 18:52:46 +053076):
Nabin Hait9784d272016-12-30 16:21:35 +053077 fiscal_years = frappe.cache().hget("fiscal_years", company) or []
Rushabh Mehtad50da782017-07-28 11:39:01 +053078
79 if not fiscal_years:
Nabin Hait9784d272016-12-30 16:21:35 +053080 # 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 +053081 FY = DocType("Fiscal Year")
Nabin Haitfff3ab72015-01-14 16:27:13 +053082
Gavin D'souza0727d1d2022-06-13 12:39:28 +053083 query = (
84 frappe.qb.from_(FY)
85 .select(FY.name, FY.year_start_date, FY.year_end_date)
86 .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
Ankush Menat494bd9e2022-03-28 18:52:46 +0530133 error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(
134 label, formatdate(transaction_date)
135 )
Anuja P2e4faf92020-12-05 13:36:43 +0530136 if company:
Anuja P550cb9c2020-12-07 11:11:00 +0530137 error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company))
rohitwaghchaured60ff832021-02-16 09:12:27 +0530138
Deepesh Garg0aadb682023-03-19 12:46:42 +0530139 if boolean:
140 return False
141
Ankush Menat494bd9e2022-03-28 18:52:46 +0530142 if verbose == 1:
143 frappe.msgprint(error_msg)
Deepesh Garg0aadb682023-03-19 12:46:42 +0530144
cclauss68487082017-07-27 07:08:35 +0200145 raise FiscalYearError(error_msg)
Nabin Hait9784d272016-12-30 16:21:35 +0530146
Ankush Menat494bd9e2022-03-28 18:52:46 +0530147
Prssanna Desai82ddef52020-06-18 18:18:41 +0530148@frappe.whitelist()
149def get_fiscal_year_filter_field(company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530150 field = {"fieldtype": "Select", "options": [], "operator": "Between", "query_value": True}
Prssanna Desai82ddef52020-06-18 18:18:41 +0530151 fiscal_years = get_fiscal_years(company=company)
152 for fiscal_year in fiscal_years:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530153 field["options"].append(
154 {
155 "label": fiscal_year.name,
156 "value": fiscal_year.name,
157 "query_value": [
158 fiscal_year.year_start_date.strftime("%Y-%m-%d"),
159 fiscal_year.year_end_date.strftime("%Y-%m-%d"),
160 ],
161 }
162 )
Prssanna Desai82ddef52020-06-18 18:18:41 +0530163 return field
164
Ankush Menat494bd9e2022-03-28 18:52:46 +0530165
Nabin Hait8bf58362017-03-27 12:30:01 +0530166def validate_fiscal_year(date, fiscal_year, company, label="Date", doc=None):
167 years = [f[0] for f in get_fiscal_years(date, label=_(label), company=company)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +0530168 if fiscal_year not in years:
Rushabh Mehtad60acb92015-02-19 14:51:58 +0530169 if doc:
170 doc.fiscal_year = years[0]
171 else:
172 throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
Nabin Hait23941aa2013-01-29 11:32:38 +0530173
Ankush Menat494bd9e2022-03-28 18:52:46 +0530174
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530175@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530176def get_balance_on(
177 account=None,
178 date=None,
179 party_type=None,
180 party=None,
181 company=None,
182 in_account_currency=True,
183 cost_center=None,
184 ignore_account_permission=False,
RitvikSardanab86afb22023-08-04 22:05:30 +0530185 account_type=None,
Gursheen Anand52305e32023-11-22 18:38:33 +0530186 start_date=None,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530187):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530188 if not account and frappe.form_dict.get("account"):
189 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530190 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530191 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530192 if not party_type and frappe.form_dict.get("party_type"):
193 party_type = frappe.form_dict.get("party_type")
194 if not party and frappe.form_dict.get("party"):
195 party = frappe.form_dict.get("party")
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400196 if not cost_center and frappe.form_dict.get("cost_center"):
197 cost_center = frappe.form_dict.get("cost_center")
198
Nabin Hait98372852020-07-30 20:52:20 +0530199 cond = ["is_cancelled=0"]
Gursheen Anand52305e32023-11-22 18:38:33 +0530200 if start_date:
201 cond.append("posting_date >= %s" % frappe.db.escape(cstr(start_date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530202 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530203 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530204 else:
205 # get balance of all entries that exist
206 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530207
Deepesh Garg8c217032019-07-16 09:41:01 +0530208 if account:
209 acc = frappe.get_doc("Account", account)
210
Nabin Hait23941aa2013-01-29 11:32:38 +0530211 try:
Deepesh Garg96d40ec2020-07-03 22:59:00 +0530212 year_start_date = get_fiscal_year(date, company=company, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530213 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +0530214 if getdate(date) > getdate(nowdate()):
215 # if fiscal year not found and the date is greater than today
216 # get fiscal year for today's date and its corresponding year start date
217 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
218 else:
219 # this indicates that it is a date older than any existing fiscal year.
220 # hence, assuming balance as 0.0
221 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530222
deepeshgarg0072ddbebf2019-07-20 14:52:59 +0530223 if account:
deepeshgarg007e097d4f2019-07-20 14:49:32 +0530224 report_type = acc.report_type
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530225 else:
226 report_type = ""
227
Ankush Menat494bd9e2022-03-28 18:52:46 +0530228 if cost_center and report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400229 cc = frappe.get_doc("Cost Center", cost_center)
230 if cc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530231 cond.append(
232 """ exists (
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400233 select 1 from `tabCost Center` cc where cc.name = gle.cost_center
234 and cc.lft >= %s and cc.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530235 )"""
236 % (cc.lft, cc.rgt)
237 )
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400238
239 else:
Deepesh Garg6d87cfe2024-02-02 18:08:33 +0530240 cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center),))
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400241
Nabin Hait6f17cf92014-09-17 14:11:22 +0530242 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530243 if not (frappe.flags.ignore_account_permission or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530244 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530245
Nabin Hait6f17cf92014-09-17 14:11:22 +0530246 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530247 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530248 cond.append(
249 """exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530250 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530251 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530252 )"""
253 % (acc.lft, acc.rgt)
254 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530255
256 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530257 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530258 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530259 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530260 else:
Deepesh Garg6d87cfe2024-02-02 18:08:33 +0530261 cond.append("""gle.account = %s """ % (frappe.db.escape(account),))
Anand Doshic75c1d72016-03-11 14:56:19 +0530262
RitvikSardanab86afb22023-08-04 22:05:30 +0530263 if account_type:
264 accounts = frappe.db.get_all(
265 "Account",
266 filters={"company": company, "account_type": account_type, "is_group": 0},
267 pluck="name",
268 order_by="lft",
269 )
270
271 cond.append(
272 """
273 gle.account in (%s)
274 """
275 % (", ".join([frappe.db.escape(account) for account in accounts]))
276 )
277
Nabin Hait6f17cf92014-09-17 14:11:22 +0530278 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530279 cond.append(
280 """gle.party_type = %s and gle.party = %s """
Deepesh Garg6d87cfe2024-02-02 18:08:33 +0530281 % (frappe.db.escape(party_type), frappe.db.escape(party))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530282 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530283
Nabin Hait85648d92016-07-20 11:26:45 +0530284 if company:
Deepesh Garg6d87cfe2024-02-02 18:08:33 +0530285 cond.append("""gle.company = %s """ % (frappe.db.escape(company)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530286
RitvikSardanab86afb22023-08-04 22:05:30 +0530287 if account or (party_type and party) or account_type:
Dany Roberta8949172023-12-09 09:30:17 +0530288 precision = get_currency_precision()
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530289 if in_account_currency:
Dany Robert383a4b12023-11-21 12:46:56 +0000290 select_field = (
291 "sum(round(debit_in_account_currency, %s)) - sum(round(credit_in_account_currency, %s))"
292 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530293 else:
Dany Robert383a4b12023-11-21 12:46:56 +0000294 select_field = "sum(round(debit, %s)) - sum(round(credit, %s))"
295
Ankush Menat494bd9e2022-03-28 18:52:46 +0530296 bal = frappe.db.sql(
297 """
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530298 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530299 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530300 WHERE {1}""".format(
301 select_field, " and ".join(cond)
Dany Robert383a4b12023-11-21 12:46:56 +0000302 ),
303 (precision, precision),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530304 )[0][0]
Nabin Haitdc768232015-08-17 11:27:00 +0530305 # if bal is None, return 0
306 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530307
Ankush Menat494bd9e2022-03-28 18:52:46 +0530308
RobertSchouten8d43b322016-09-20 13:41:39 +0800309def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530310 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800311 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530312 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800313 else:
314 # get balance of all entries that exist
315 date = nowdate()
316
317 try:
318 year_start_date = get_fiscal_year(date, verbose=0)[1]
319 except FiscalYearError:
320 if getdate(date) > getdate(nowdate()):
321 # if fiscal year not found and the date is greater than today
322 # get fiscal year for today's date and its corresponding year start date
323 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
324 else:
325 # this indicates that it is a date older than any existing fiscal year.
326 # hence, assuming balance as 0.0
327 return 0.0
328
329 if account:
330 acc = frappe.get_doc("Account", account)
331
332 if not frappe.flags.ignore_account_permission:
333 acc.check_permission("read")
334
335 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530336 if acc.report_type == "Profit and Loss":
337 cond.append(
338 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
339 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800340
341 # different filter for group and ledger - improved performance
342 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530343 cond.append(
344 """exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800345 select name from `tabAccount` ac where ac.name = gle.account
346 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530347 )"""
348 % (acc.lft, acc.rgt)
349 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800350 else:
Deepesh Garg6d87cfe2024-02-02 18:08:33 +0530351 cond.append("""gle.account = %s """ % (frappe.db.escape(account),))
RobertSchouten8d43b322016-09-20 13:41:39 +0800352
Ankush Menat494bd9e2022-03-28 18:52:46 +0530353 entries = frappe.db.sql(
354 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800355 SELECT name, posting_date, account, party_type, party,debit,credit,
356 voucher_type, voucher_no, against_voucher_type, against_voucher
357 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530358 WHERE {0}""".format(
359 " and ".join(cond)
360 ),
361 as_dict=True,
362 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530363
RobertSchouten8d43b322016-09-20 13:41:39 +0800364 count = 0
365 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530366 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800367 count += 1
368 else:
369 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
370 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530371 select_fields = (
372 "ifnull(sum(credit-debit),0)"
373 if fieldname == "invoiced_amount"
374 else "ifnull(sum(debit-credit),0)"
375 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800376
Ankush Menat494bd9e2022-03-28 18:52:46 +0530377 if (
378 (not gle.against_voucher)
379 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
380 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
381 ):
382 payment_amount = frappe.db.sql(
383 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800384 SELECT {0}
385 FROM `tabGL Entry` gle
386 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530387 and party = %(party)s and name != %(name)s""".format(
388 select_fields
389 ),
390 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
391 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530392
RobertSchouten8d43b322016-09-20 13:41:39 +0800393 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
394 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530395 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800396 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530397
RobertSchouten8d43b322016-09-20 13:41:39 +0800398 return count
399
Ankush Menat494bd9e2022-03-28 18:52:46 +0530400
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530401@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530402def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530403 from frappe.desk.treeview import make_tree_args
404
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530405 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530406 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530407
Nabin Hait02d987e2017-02-17 15:50:26 +0530408 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530409 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530410
Anand Doshi3e41fd12014-04-22 18:54:54 +0530411 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530412
Nabin Hait665568d2016-05-13 15:56:00 +0530413 if args.get("ignore_permissions"):
414 ac.flags.ignore_permissions = True
415 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530416
Anand Doshi3e41fd12014-04-22 18:54:54 +0530417 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530418
419 if not ac.parent_account:
420 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530421
Anand Doshif78d1ae2014-03-28 13:55:00 +0530422 ac.old_parent = ""
423 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530424 if cint(ac.get("is_root")):
425 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530426 ac.flags.ignore_mandatory = True
427
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530428 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530429
Anand Doshif78d1ae2014-03-28 13:55:00 +0530430 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530431
Ankush Menat494bd9e2022-03-28 18:52:46 +0530432
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530433@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530434def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530435 from frappe.desk.treeview import make_tree_args
436
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530437 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530438 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530439
Nabin Hait02d987e2017-02-17 15:50:26 +0530440 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530441 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530442
Zarrar7ab70ca2018-06-08 14:33:15 +0530443 if args.parent_cost_center == args.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530444 args.parent_cost_center = "{0} - {1}".format(
445 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
446 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530447
Anand Doshi3e41fd12014-04-22 18:54:54 +0530448 cc = frappe.new_doc("Cost Center")
449 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530450
451 if not cc.parent_cost_center:
452 cc.parent_cost_center = args.get("parent")
453
Anand Doshif78d1ae2014-03-28 13:55:00 +0530454 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530455 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530456 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530457
Ankush Menat494bd9e2022-03-28 18:52:46 +0530458
ruthra kumarc44eb432024-01-18 14:35:06 +0530459def _build_dimensions_dict_for_exc_gain_loss(
460 entry: dict | object = None, active_dimensions: list = None
461):
462 dimensions_dict = frappe._dict()
463 if entry and active_dimensions:
464 for dim in active_dimensions:
465 dimensions_dict[dim.fieldname] = entry.get(dim.fieldname)
466 return dimensions_dict
467
468
469def reconcile_against_document(
470 args, skip_ref_details_update_for_pe=False, active_dimensions=None
471): # nosemgrep
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530472 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530473 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530474 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530475 # To optimize making GL Entry for PE or JV with multiple references
476 reconciled_entries = {}
477 for row in args:
478 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
479 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530480
Anuja Pawar3e404f12021-08-31 18:59:29 +0530481 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
482
483 for key, entries in reconciled_entries.items():
484 voucher_type = key[0]
485 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530486
Nabin Hait28a05282016-06-27 17:41:39 +0530487 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530488 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530489 frappe.flags.ignore_party_validation = True
ruthra kumar78ab11f2023-09-20 13:05:04 +0530490
ruthra kumarecb533c2023-11-28 17:04:07 +0530491 # For payments with `Advance` in separate account feature enabled, only new ledger entries are posted for each reference.
492 # No need to cancel/delete payment ledger entries
ruthra kumard9a04942024-03-04 10:28:43 +0530493 if voucher_type == "Payment Entry" and doc.book_advance_payments_in_separate_party_account:
494 doc.make_advance_gl_entries(cancel=1)
495 else:
ruthra kumar78ab11f2023-09-20 13:05:04 +0530496 _delete_pl_entries(voucher_type, voucher_no)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530497
Anuja Pawar3e404f12021-08-31 18:59:29 +0530498 for entry in entries:
499 check_if_advance_entry_modified(entry)
500 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530501
ruthra kumarc44eb432024-01-18 14:35:06 +0530502 dimensions_dict = _build_dimensions_dict_for_exc_gain_loss(entry, active_dimensions)
503
Anuja Pawar3e404f12021-08-31 18:59:29 +0530504 # update ref in advance entry
505 if voucher_type == "Journal Entry":
ruthra kumard9a04942024-03-04 10:28:43 +0530506 referenced_row, update_advance_paid = update_reference_in_journal_entry(
507 entry, doc, do_not_save=False
508 )
ruthra kumar7b516f82023-06-26 17:34:28 +0530509 # advance section in sales/purchase invoice and reconciliation tool,both pass on exchange gain/loss
510 # amount and account in args
ruthra kumar79c6f012023-09-01 14:57:12 +0530511 # referenced_row is used to deduplicate gain/loss journal
512 entry.update({"referenced_row": referenced_row})
ruthra kumarc44eb432024-01-18 14:35:06 +0530513 doc.make_exchange_gain_loss_journal([entry], dimensions_dict)
Anuja Pawar3e404f12021-08-31 18:59:29 +0530514 else:
ruthra kumard9a04942024-03-04 10:28:43 +0530515 referenced_row, update_advance_paid = update_reference_in_payment_entry(
ruthra kumarc44eb432024-01-18 14:35:06 +0530516 entry,
517 doc,
518 do_not_save=True,
519 skip_ref_details_update_for_pe=skip_ref_details_update_for_pe,
520 dimensions_dict=dimensions_dict,
ruthra kumared14d1c2023-04-22 17:24:35 +0530521 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530522
523 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530524 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530525 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
ruthra kumar78ab11f2023-09-20 13:05:04 +0530526
527 if voucher_type == "Payment Entry" and doc.book_advance_payments_in_separate_party_account:
ruthra kumarecb533c2023-11-28 17:04:07 +0530528 # both ledgers must be posted to for `Advance` in separate account feature
ruthra kumard9a04942024-03-04 10:28:43 +0530529 # TODO: find a more efficient way post only for the new linked vouchers
ruthra kumar9d9b8332024-01-31 20:40:26 +0530530 doc.make_advance_gl_entries()
ruthra kumar78ab11f2023-09-20 13:05:04 +0530531 else:
532 gl_map = doc.build_gl_map()
533 create_payment_ledger_entry(gl_map, update_outstanding="No", cancel=0, adv_adj=1)
Deepesh Garg1894dc82023-06-23 21:53:34 +0530534
ruthra kumar11cf6942023-01-14 12:22:22 +0530535 # Only update outstanding for newly linked vouchers
536 for entry in entries:
537 update_voucher_outstanding(
538 entry.against_voucher_type, entry.against_voucher, entry.account, entry.party_type, entry.party
539 )
ruthra kumard9a04942024-03-04 10:28:43 +0530540 # update advance paid in Advance Receivable/Payable doctypes
541 if update_advance_paid:
542 for t, n in update_advance_paid:
543 frappe.get_doc(t, n).set_total_advance_paid()
ruthra kumar524c1752022-05-26 16:00:40 +0530544
Subin Tomb8845b92021-07-30 16:30:18 +0530545 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530546
Ankush Menat494bd9e2022-03-28 18:52:46 +0530547
Nabin Hait28a05282016-06-27 17:41:39 +0530548def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530549 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530550 check if there is already a voucher reference
551 check if amount is same
552 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530553 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530554 if not args.get("unreconciled_amount"):
555 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530556
Nabin Hait28a05282016-06-27 17:41:39 +0530557 ret = None
558 if args.voucher_type == "Journal Entry":
Gursheen Anand74619262023-06-02 17:13:51 +0530559 journal_entry = frappe.qb.DocType("Journal Entry")
560 journal_acc = frappe.qb.DocType("Journal Entry Account")
561
Gursheen Anand4ee16372023-06-08 13:15:23 +0530562 q = (
563 frappe.qb.from_(journal_entry)
Deepesh Garg3aead052023-06-22 11:41:43 +0530564 .inner_join(journal_acc)
Gursheen Anand74619262023-06-02 17:13:51 +0530565 .on(journal_entry.name == journal_acc.parent)
Deepesh Gargd81d6062023-06-22 18:28:16 +0530566 .select(journal_acc[args.get("dr_or_cr")])
567 .where(
568 (journal_acc.account == args.get("account"))
569 & ((journal_acc.party_type == args.get("party_type")))
570 & ((journal_acc.party == args.get("party")))
571 & (
572 (journal_acc.reference_type.isnull())
573 | (journal_acc.reference_type.isin(["", "Sales Order", "Purchase Order"]))
574 )
575 & ((journal_entry.name == args.get("voucher_no")))
576 & ((journal_acc.name == args.get("voucher_detail_no")))
577 & ((journal_entry.docstatus == 1))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530578 )
Gursheen Anand74619262023-06-02 17:13:51 +0530579 )
580
Nabin Hait28a05282016-06-27 17:41:39 +0530581 else:
ruthra kumar60435da2023-11-03 17:58:19 +0530582 precision = frappe.get_precision("Payment Entry", "unallocated_amount")
583
Gursheen Anand74619262023-06-02 17:13:51 +0530584 payment_entry = frappe.qb.DocType("Payment Entry")
585 payment_ref = frappe.qb.DocType("Payment Entry Reference")
586
Gursheen Anand4ee16372023-06-08 13:15:23 +0530587 q = (
588 frappe.qb.from_(payment_entry)
Gursheen Anand74619262023-06-02 17:13:51 +0530589 .select(payment_entry.name)
590 .where(payment_entry.name == args.get("voucher_no"))
591 .where(payment_entry.docstatus == 1)
592 .where(payment_entry.party_type == args.get("party_type"))
593 .where(payment_entry.party == args.get("party"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530594 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530595
Nabin Hait28a05282016-06-27 17:41:39 +0530596 if args.voucher_detail_no:
Gursheen Anand4ee16372023-06-08 13:15:23 +0530597 q = (
598 q.inner_join(payment_ref)
Gursheen Anand74619262023-06-02 17:13:51 +0530599 .on(payment_entry.name == payment_ref.parent)
600 .where(payment_ref.name == args.get("voucher_detail_no"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530601 .where(payment_ref.reference_doctype.isin(("", "Sales Order", "Purchase Order")))
Gursheen Anand74619262023-06-02 17:13:51 +0530602 .where(payment_ref.allocated_amount == args.get("unreconciled_amount"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530603 )
Nabin Hait28a05282016-06-27 17:41:39 +0530604 else:
ruthra kumar60435da2023-11-03 17:58:19 +0530605 q = q.where(
606 Round(payment_entry.unallocated_amount, precision)
607 == Round(args.get("unreconciled_amount"), precision)
608 )
Gursheen Anand4ee16372023-06-08 13:15:23 +0530609
Gursheen Anand74619262023-06-02 17:13:51 +0530610 ret = q.run(as_dict=True)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530611
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530612 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530613 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530614
Ankush Menat494bd9e2022-03-28 18:52:46 +0530615
Nabin Hait576f0252014-04-30 19:30:50 +0530616def validate_allocated_amount(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530617 precision = args.get("precision") or frappe.db.get_single_value(
618 "System Settings", "currency_precision"
619 )
Nabin Hait28a05282016-06-27 17:41:39 +0530620 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530621 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530622 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530623 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530624
Ankush Menat494bd9e2022-03-28 18:52:46 +0530625
Anuja Pawar3e404f12021-08-31 18:59:29 +0530626def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530627 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530628 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530629 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530630 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530631
marination426350e2023-09-13 14:24:56 +0530632 # Update Advance Paid in SO/PO since they might be getting unlinked
ruthra kumard9a04942024-03-04 10:28:43 +0530633 update_advance_paid = []
David Arnoldc88ce552024-01-22 22:04:30 +0100634 advance_payment_doctypes = frappe.get_hooks(
ruthra kumar9fcd89d2024-01-24 13:27:31 +0530635 "advance_payment_receivable_doctypes"
636 ) + frappe.get_hooks("advance_payment_payable_doctypes")
David Arnoldc88ce552024-01-22 22:04:30 +0100637 if jv_detail.get("reference_type") in advance_payment_doctypes:
ruthra kumard9a04942024-03-04 10:28:43 +0530638 update_advance_paid.append((jv_detail.reference_type, jv_detail.reference_name))
marination426350e2023-09-13 14:24:56 +0530639
Ankush Menat494bd9e2022-03-28 18:52:46 +0530640 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530641 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530642 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530643 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530644 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
645 jv_detail.set(
646 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
647 amount_in_company_currency,
648 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530649 else:
650 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530651
Anuja Pawar3e404f12021-08-31 18:59:29 +0530652 # new row with references
653 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530654
ruthra kumar72f577a2023-07-13 15:04:44 +0530655 # Copy field values into new row
656 [
657 new_row.set(field, jv_detail.get(field))
658 for field in frappe.get_meta("Journal Entry Account").get_fieldnames_with_value()
659 ]
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530660
Anuja Pawar3e404f12021-08-31 18:59:29 +0530661 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530662 new_row.set(
663 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
664 d["allocated_amount"] * flt(jv_detail.exchange_rate),
665 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530666
Ankush Menat494bd9e2022-03-28 18:52:46 +0530667 new_row.set(
668 "credit_in_account_currency"
669 if d["dr_or_cr"] == "debit_in_account_currency"
670 else "debit_in_account_currency",
671 0,
672 )
673 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530674
Anuja Pawar3e404f12021-08-31 18:59:29 +0530675 new_row.set("reference_type", d["against_voucher_type"])
676 new_row.set("reference_name", d["against_voucher"])
677
678 new_row.against_account = cstr(jv_detail.against_account)
679 new_row.is_advance = cstr(jv_detail.is_advance)
680 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530681
682 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530683 journal_entry.flags.ignore_validate_update_after_submit = True
684 if not do_not_save:
685 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530686
ruthra kumard9a04942024-03-04 10:28:43 +0530687 return new_row.name, update_advance_paid
ruthra kumar79c6f012023-09-01 14:57:12 +0530688
Ankush Menat494bd9e2022-03-28 18:52:46 +0530689
ruthra kumared14d1c2023-04-22 17:24:35 +0530690def update_reference_in_payment_entry(
ruthra kumarc44eb432024-01-18 14:35:06 +0530691 d, payment_entry, do_not_save=False, skip_ref_details_update_for_pe=False, dimensions_dict=None
ruthra kumared14d1c2023-04-22 17:24:35 +0530692):
Nabin Hait28a05282016-06-27 17:41:39 +0530693 reference_details = {
694 "reference_doctype": d.against_voucher_type,
695 "reference_name": d.against_voucher,
696 "total_amount": d.grand_total,
697 "outstanding_amount": d.outstanding_amount,
698 "allocated_amount": d.allocated_amount,
ruthra kumar5eeb6502023-12-15 11:46:12 +0530699 "exchange_rate": d.exchange_rate
700 if d.difference_amount is not None
701 else payment_entry.get_exchange_rate(),
702 "exchange_gain_loss": d.difference_amount,
Gursheen Anandb65e58c2023-06-08 18:15:37 +0530703 "account": d.account,
ruthra kumar5dc22e12023-12-20 17:19:27 +0530704 "dimensions": d.dimensions,
Nabin Hait28a05282016-06-27 17:41:39 +0530705 }
ruthra kumard9a04942024-03-04 10:28:43 +0530706 update_advance_paid = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530707
Nabin Hait28a05282016-06-27 17:41:39 +0530708 if d.voucher_detail_no:
709 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
marination426350e2023-09-13 14:24:56 +0530710
711 # Update Advance Paid in SO/PO since they are getting unlinked
David Arnoldc88ce552024-01-22 22:04:30 +0100712 advance_payment_doctypes = frappe.get_hooks(
ruthra kumar9fcd89d2024-01-24 13:27:31 +0530713 "advance_payment_receivable_doctypes"
714 ) + frappe.get_hooks("advance_payment_payable_doctypes")
David Arnoldc88ce552024-01-22 22:04:30 +0100715 if existing_row.get("reference_doctype") in advance_payment_doctypes:
ruthra kumard9a04942024-03-04 10:28:43 +0530716 update_advance_paid.append((existing_row.reference_doctype, existing_row.reference_name))
marination426350e2023-09-13 14:24:56 +0530717
ruthra kumar23df4202023-10-19 11:32:21 +0530718 if d.allocated_amount <= existing_row.allocated_amount:
719 existing_row.allocated_amount -= d.allocated_amount
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530720
Nabin Hait28a05282016-06-27 17:41:39 +0530721 new_row = payment_entry.append("references")
722 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500723 for field in list(reference_details):
ruthra kumar23df4202023-10-19 11:32:21 +0530724 new_row.set(field, reference_details[field])
ruthra kumarecb533c2023-11-28 17:04:07 +0530725 row = new_row
Nabin Hait28a05282016-06-27 17:41:39 +0530726 else:
727 new_row = payment_entry.append("references")
728 new_row.docstatus = 1
729 new_row.update(reference_details)
ruthra kumarecb533c2023-11-28 17:04:07 +0530730 row = new_row
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530731
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500732 payment_entry.flags.ignore_validate_update_after_submit = True
ruthra kumar23df4202023-10-19 11:32:21 +0530733 payment_entry.clear_unallocated_reference_document_rows()
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500734 payment_entry.setup_party_account_field()
735 payment_entry.set_missing_values()
ruthra kumared14d1c2023-04-22 17:24:35 +0530736 if not skip_ref_details_update_for_pe:
ruthra kumareaac0262024-02-28 17:07:37 +0530737 payment_entry.set_missing_ref_details(ref_exchange_rate=d.exchange_rate or None)
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(
750 parent_doc: dict | object, referenced_dt: str = None, referenced_dn: str = None
751) -> 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(
793 ref_type: str = None, ref_no: str = None, payment_name: str = None
794):
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(
819 (ple.against_voucher_type == ref_type)
820 & (ple.against_voucher_no == ref_no)
821 & (ple.delinked == 0)
822 )
823 )
ruthra kumar537d9532022-10-10 10:17:19 +0530824
ruthra kumar9b6eac22023-08-30 16:44:25 +0530825 if payment_name:
826 ple_update_query = ple_update_query.where(ple.voucher_no == payment_name)
827 ple_update_query.run()
ruthra kumar537d9532022-10-10 10:17:19 +0530828
ruthra kumar0130aea2023-08-30 13:25:23 +0530829
830def remove_ref_from_advance_section(ref_doc: object = None):
ruthra kumar9b6eac22023-08-30 16:44:25 +0530831 # TODO: this might need some testing
Nabin Hait297d74a2016-11-23 15:58:51 +0530832 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
833 ref_doc.set("advances", [])
ruthra kumar0130aea2023-08-30 13:25:23 +0530834 adv_type = qb.DocType(f"{ref_doc.doctype} Advance")
835 qb.from_(adv_type).delete().where(adv_type.parent == ref_doc.name).run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530836
Anand Doshicd71e1d2014-04-08 13:53:35 +0530837
ruthra kumar9b6eac22023-08-30 16:44:25 +0530838def unlink_ref_doc_from_payment_entries(ref_doc: object = None, payment_name: str = None):
839 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name, payment_name)
840 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name, payment_name)
841 update_accounting_ledgers_after_reference_removal(ref_doc.doctype, ref_doc.name, payment_name)
842 remove_ref_from_advance_section(ref_doc)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530843
Rushabh Mehta1828c122015-08-10 17:04:07 +0530844
ruthra kumar9b6eac22023-08-30 16:44:25 +0530845def remove_ref_doc_link_from_jv(
846 ref_type: str = None, ref_no: str = None, payment_name: str = None
847):
ruthra kumar0130aea2023-08-30 13:25:23 +0530848 jea = qb.DocType("Journal Entry Account")
849
850 linked_jv = (
851 qb.from_(jea)
852 .select(jea.parent)
ruthra kumar9a1588f2023-08-30 20:50:16 +0530853 .where((jea.reference_type == ref_type) & (jea.reference_name == ref_no) & (jea.docstatus.lt(2)))
ruthra kumar0130aea2023-08-30 13:25:23 +0530854 .run(as_list=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530855 )
ruthra kumar0130aea2023-08-30 13:25:23 +0530856 linked_jv = convert_to_list(linked_jv)
ruthra kumar9b6eac22023-08-30 16:44:25 +0530857 # remove reference only from specified payment
858 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 +0530859
860 if linked_jv:
ruthra kumar9b6eac22023-08-30 16:44:25 +0530861 update_query = (
862 qb.update(jea)
863 .set(jea.reference_type, None)
864 .set(jea.reference_name, None)
865 .set(jea.modified, now())
866 .set(jea.modified_by, frappe.session.user)
867 .where((jea.reference_type == ref_type) & (jea.reference_name == ref_no))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530868 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530869
ruthra kumar9b6eac22023-08-30 16:44:25 +0530870 if payment_name:
871 update_query = update_query.where(jea.parent == payment_name)
872
873 update_query.run()
Anand Doshi7da72dd2013-03-20 17:00:41 +0530874
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530875 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530876
Ankush Menat494bd9e2022-03-28 18:52:46 +0530877
ruthra kumar0130aea2023-08-30 13:25:23 +0530878def convert_to_list(result):
879 """
880 Convert tuple to list
881 """
882 return [x[0] for x in result]
883
884
ruthra kumar9b6eac22023-08-30 16:44:25 +0530885def remove_ref_doc_link_from_pe(
886 ref_type: str = None, ref_no: str = None, payment_name: str = None
887):
ruthra kumar0130aea2023-08-30 13:25:23 +0530888 per = qb.DocType("Payment Entry Reference")
889 pay = qb.DocType("Payment Entry")
890
891 linked_pe = (
892 qb.from_(per)
893 .select(per.parent)
894 .where(
895 (per.reference_doctype == ref_type) & (per.reference_name == ref_no) & (per.docstatus.lt(2))
896 )
897 .run(as_list=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530898 )
ruthra kumar0130aea2023-08-30 13:25:23 +0530899 linked_pe = convert_to_list(linked_pe)
ruthra kumar9b6eac22023-08-30 16:44:25 +0530900 # remove reference only from specified payment
901 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 +0530902
Nabin Haite0cc87d2016-07-21 18:30:03 +0530903 if linked_pe:
ruthra kumar9b6eac22023-08-30 16:44:25 +0530904 update_query = (
905 qb.update(per)
906 .set(per.allocated_amount, 0)
907 .set(per.modified, now())
908 .set(per.modified_by, frappe.session.user)
909 .where(
910 (per.docstatus.lt(2) & (per.reference_doctype == ref_type) & (per.reference_name == ref_no))
911 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530912 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530913
ruthra kumar9b6eac22023-08-30 16:44:25 +0530914 if payment_name:
915 update_query = update_query.where(per.parent == payment_name)
916
917 update_query.run()
Nabin Haite0cc87d2016-07-21 18:30:03 +0530918
919 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530920 try:
Deepesh Garg1894dc82023-06-23 21:53:34 +0530921 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530922 pe_doc.set_amounts()
ruthra kumarecb533c2023-11-28 17:04:07 +0530923
924 # Call cancel on only removed reference
925 references = [
926 x for x in pe_doc.references if x.reference_doctype == ref_type and x.reference_name == ref_no
927 ]
928 [pe_doc.make_advance_gl_entries(x, cancel=1) for x in references]
929
Deepesh Gargb5162392021-08-10 14:52:24 +0530930 pe_doc.clear_unallocated_reference_document_rows()
931 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530932 except Exception as e:
933 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530934 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530935 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530936 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530937
ruthra kumar0130aea2023-08-30 13:25:23 +0530938 qb.update(pay).set(pay.total_allocated_amount, pe_doc.total_allocated_amount).set(
939 pay.base_total_allocated_amount, pe_doc.base_total_allocated_amount
940 ).set(pay.unallocated_amount, pe_doc.unallocated_amount).set(pay.modified, now()).set(
941 pay.modified_by, frappe.session.user
942 ).where(
943 pay.name == pe
944 ).run()
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530945
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530946 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530947
Ankush Menat494bd9e2022-03-28 18:52:46 +0530948
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530949@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530950def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530951 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530952
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530953 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530954 throw(
955 _("Please set default {0} in Company {1}").format(
956 frappe.get_meta("Company").get_label(fieldname), company
957 )
958 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530959
Nabin Hait0fc24542013-03-25 11:06:00 +0530960 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530961
Ankush Menat494bd9e2022-03-28 18:52:46 +0530962
Nabin Hait8b509f52013-05-28 16:52:30 +0530963def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530964 vouchers = frappe.db.sql(
965 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530966 sum(debit) - sum(credit) as diff
967 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530968 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530969 having sum(debit) != sum(credit)""",
970 as_dict=1,
971 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530972
Nabin Hait8b509f52013-05-28 16:52:30 +0530973 for d in vouchers:
974 if abs(d.diff) > 0:
975 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530976
Ankush Menat494bd9e2022-03-28 18:52:46 +0530977 frappe.db.sql(
978 """update `tabGL Entry` set %s = %s + %s
979 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
980 % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
981 (d.diff, d.voucher_type, d.voucher_no),
982 )
983
Anand Doshicd71e1d2014-04-08 13:53:35 +0530984
Rushabh Mehtad50da782017-07-28 11:39:01 +0530985def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530986 precision = cint(frappe.db.get_default("currency_precision"))
987 if not precision:
988 number_format = frappe.db.get_default("number_format") or "#,###.##"
989 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530990
Nabin Hait9b20e072017-04-25 12:10:24 +0530991 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530992
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530993
tundebabzyad08d4c2018-05-16 07:01:41 +0100994def get_held_invoices(party_type, party):
995 """
996 Returns a list of names Purchase Invoices for the given party that are on hold
997 """
998 held_invoices = None
999
Ankush Menat494bd9e2022-03-28 18:52:46 +05301000 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +01001001 held_invoices = frappe.db.sql(
mergify[bot]872a23c2023-07-10 20:34:54 +05301002 "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 +05301003 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +01001004 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05301005 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +01001006
1007 return held_invoices
1008
1009
ruthra kumar8c876742022-06-14 17:46:04 +05301010def get_outstanding_invoices(
ruthra kumar5f1562c2022-07-28 11:57:27 +05301011 party_type,
1012 party,
1013 account,
1014 common_filter=None,
1015 posting_date=None,
1016 min_outstanding=None,
1017 max_outstanding=None,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301018 accounting_dimensions=None,
Deepesh Garg299e32b2023-08-24 18:02:06 +05301019 vouchers=None, # list of dicts [{'voucher_type': '', 'voucher_no': ''}] for filtering
1020 limit=None, # passed by reconciliation tool
1021 voucher_no=None, # filter passed by reconciliation tool
ruthra kumar8c876742022-06-14 17:46:04 +05301022):
1023
1024 ple = qb.DocType("Payment Ledger Entry")
Anand Doshid40d1e92015-11-12 17:05:29 +05301025 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +05301026 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +05301027
Nabin Hait9db9edc2019-11-19 18:44:32 +05301028 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301029 root_type, account_type = frappe.get_cached_value(
ruthra kumar5f152972024-03-02 19:29:58 +05301030 "Account", account[0], ["root_type", "account_type"]
Ankush Menat494bd9e2022-03-28 18:52:46 +05301031 )
Nabin Hait9db9edc2019-11-19 18:44:32 +05301032 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +05301033 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +05301034 else:
1035 party_account_type = erpnext.get_party_account_type(party_type)
1036
tundebabzyad08d4c2018-05-16 07:01:41 +01001037 held_invoices = get_held_invoices(party_type, party)
1038
ruthra kumar8c876742022-06-14 17:46:04 +05301039 common_filter = common_filter or []
1040 common_filter.append(ple.account_type == party_account_type)
ruthra kumar5f152972024-03-02 19:29:58 +05301041 common_filter.append(ple.account.isin(account))
ruthra kumar8c876742022-06-14 17:46:04 +05301042 common_filter.append(ple.party_type == party_type)
1043 common_filter.append(ple.party == party)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301044
ruthra kumar8c876742022-06-14 17:46:04 +05301045 ple_query = QueryPaymentLedger()
1046 invoice_list = ple_query.get_voucher_outstandings(
ruthra kumardeb0d712023-08-15 05:17:01 +05301047 vouchers=vouchers,
ruthra kumar8c876742022-06-14 17:46:04 +05301048 common_filter=common_filter,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301049 posting_date=posting_date,
ruthra kumar8c876742022-06-14 17:46:04 +05301050 min_outstanding=min_outstanding,
1051 max_outstanding=max_outstanding,
1052 get_invoices=True,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301053 accounting_dimensions=accounting_dimensions or [],
ruthra kumar7a381af2023-05-03 20:45:12 +05301054 limit=limit,
1055 voucher_no=voucher_no,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301056 )
tundec4b0d172017-09-26 00:48:30 +01001057
Nabin Haitac184982019-02-04 21:13:43 +05301058 for d in invoice_list:
ruthra kumar21985532022-06-30 15:14:38 +05301059 payment_amount = d.invoice_amount_in_account_currency - d.outstanding_in_account_currency
1060 outstanding_amount = d.outstanding_in_account_currency
Nabin Haitac184982019-02-04 21:13:43 +05301061 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301062 if (
ruthra kumar8c876742022-06-14 17:46:04 +05301063 min_outstanding
1064 and max_outstanding
barredterraeb9ee3f2023-12-05 11:22:55 +01001065 and (outstanding_amount < min_outstanding or outstanding_amount > max_outstanding)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301066 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +05301067 continue
Nabin Haitac184982019-02-04 21:13:43 +05301068
barredterraeb9ee3f2023-12-05 11:22:55 +01001069 if d.voucher_type != "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +05301070 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301071 frappe._dict(
1072 {
1073 "voucher_no": d.voucher_no,
1074 "voucher_type": d.voucher_type,
1075 "posting_date": d.posting_date,
ruthra kumar21985532022-06-30 15:14:38 +05301076 "invoice_amount": flt(d.invoice_amount_in_account_currency),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301077 "payment_amount": payment_amount,
1078 "outstanding_amount": outstanding_amount,
1079 "due_date": d.due_date,
1080 "currency": d.currency,
Gursheen Anand4ee16372023-06-08 13:15:23 +05301081 "account": d.account,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301082 }
1083 )
Nabin Haitac184982019-02-04 21:13:43 +05301084 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +05301085
Ankush Menat494bd9e2022-03-28 18:52:46 +05301086 outstanding_invoices = sorted(
1087 outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
1088 )
Anand Doshid40d1e92015-11-12 17:05:29 +05301089 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +05301090
1091
Ankush Menat494bd9e2022-03-28 18:52:46 +05301092def get_account_name(
1093 account_type=None, root_type=None, is_group=None, account_currency=None, company=None
1094):
Saurabh3a268292016-02-22 15:18:40 +05301095 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301096 return frappe.db.get_value(
1097 "Account",
1098 {
1099 "account_type": account_type or "",
1100 "root_type": root_type or "",
1101 "is_group": is_group or 0,
1102 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
1103 "company": company or frappe.defaults.get_defaults().company,
1104 },
1105 "name",
1106 )
1107
Saurabha9ba7342016-06-21 12:33:12 +05301108
1109@frappe.whitelist()
1110def get_companies():
1111 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301112 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
1113
Saurabha9ba7342016-06-21 12:33:12 +05301114
1115@frappe.whitelist()
Gursheen Kaur Anandb7f283b2023-12-29 12:55:37 +05301116def get_children(doctype, parent, company, is_root=False, include_disabled=False):
1117 if isinstance(include_disabled, str):
1118 include_disabled = frappe.json.loads(include_disabled)
Nabin Haitaf98f5d2018-04-02 10:14:32 +05301119 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +05301120
Ankush Menat494bd9e2022-03-28 18:52:46 +05301121 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
1122 fields = ["name as value", "is_group as expandable"]
1123 filters = [["docstatus", "<", 2]]
Gursheen Kaur Anandb7f283b2023-12-29 12:55:37 +05301124 if frappe.db.has_column(doctype, "disabled") and not include_disabled:
1125 filters.append(["disabled", "=", False])
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +05301126
Ankush Menat494bd9e2022-03-28 18:52:46 +05301127 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301128
Rushabh Mehta43133262017-11-10 18:52:21 +05301129 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301130 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
1131 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301132
Saurabha9ba7342016-06-21 12:33:12 +05301133 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301134 fields += ["root_type", "account_currency"] if doctype == "Account" else []
1135 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +05301136
1137 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +05301138
Ankush Menat494bd9e2022-03-28 18:52:46 +05301139 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +05301140 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +05301141
1142 return acc
Saurabhb835fef2016-09-09 11:19:22 +05301143
Ankush Menat494bd9e2022-03-28 18:52:46 +05301144
Saqib90517352021-10-04 11:44:46 +05301145@frappe.whitelist()
1146def get_account_balances(accounts, company):
1147
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301148 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +05301149 accounts = loads(accounts)
1150
1151 if not accounts:
1152 return []
1153
Ankush Menat494bd9e2022-03-28 18:52:46 +05301154 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +05301155
1156 for account in accounts:
1157 account["company_currency"] = company_currency
Ankush Menat494bd9e2022-03-28 18:52:46 +05301158 account["balance"] = flt(
1159 get_balance_on(account["value"], in_account_currency=False, company=company)
1160 )
Saqib90517352021-10-04 11:44:46 +05301161 if account["account_currency"] and account["account_currency"] != company_currency:
1162 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
1163
1164 return accounts
1165
Ankush Menat494bd9e2022-03-28 18:52:46 +05301166
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +05301167def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +05301168 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +05301169
Daizy Modifdfe5cb2022-11-17 19:14:10 +05301170 company = frappe.get_cached_value("Global Defaults", "Global Defaults", "default_company")
Saurabhb835fef2016-09-09 11:19:22 +05301171 if not company:
1172 return
1173
1174 # 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 +05301175 bank_account = frappe.db.get_value(
1176 "Account",
1177 {"account_name": _(gateway), "company": company},
1178 ["name", "account_currency"],
1179 as_dict=1,
1180 )
Saurabhb835fef2016-09-09 11:19:22 +05301181
1182 if not bank_account:
1183 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301184 bank_account = frappe.db.get_value(
1185 "Account",
1186 {"account_name": gateway, "company": company},
1187 ["name", "account_currency"],
1188 as_dict=1,
1189 )
Saurabhb835fef2016-09-09 11:19:22 +05301190
1191 if not bank_account:
1192 # try creating one
1193 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1194
1195 if not bank_account:
1196 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1197 return
1198
1199 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301200 if frappe.db.exists(
1201 "Payment Gateway Account",
1202 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1203 ):
Saurabhb835fef2016-09-09 11:19:22 +05301204 return
1205
1206 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301207 frappe.get_doc(
1208 {
1209 "doctype": "Payment Gateway Account",
1210 "is_default": 1,
1211 "payment_gateway": gateway,
1212 "payment_account": bank_account.name,
1213 "currency": bank_account.account_currency,
1214 "payment_channel": payment_channel,
1215 }
1216 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301217
1218 except frappe.DuplicateEntryError:
1219 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001220 pass
Zarrar44175902018-06-08 16:35:21 +05301221
Ankush Menat494bd9e2022-03-28 18:52:46 +05301222
Zarrar44175902018-06-08 16:35:21 +05301223@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301224def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301225 """
1226 Renames the document by adding the number as a prefix to the current name and updates
1227 all transaction where it was present.
1228 """
Saqiba8779872020-04-30 11:28:43 +05301229 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301230
Saqiba8779872020-04-30 11:28:43 +05301231 if cost_center_number:
1232 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1233 else:
1234 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301235
Saqiba8779872020-04-30 11:28:43 +05301236 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301237
Nabin Haitaf21a112022-09-15 12:09:18 +05301238 new_name = get_autoname_with_number(cost_center_number, cost_center_name, company)
Saqiba8779872020-04-30 11:28:43 +05301239 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301240 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301241 return new_name
1242
Ankush Menat494bd9e2022-03-28 18:52:46 +05301243
Saqiba8779872020-04-30 11:28:43 +05301244def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301245 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301246 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301247 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301248 if company:
Saqiba8779872020-04-30 11:28:43 +05301249 filters["company"] = company
1250
1251 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1252
Zarrar44175902018-06-08 16:35:21 +05301253 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301254 frappe.throw(
1255 _("{0} Number {1} is already used in {2} {3}").format(
1256 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1257 )
1258 )
1259
Zarrar44175902018-06-08 16:35:21 +05301260
Nabin Haitaf21a112022-09-15 12:09:18 +05301261def get_autoname_with_number(number_value, doc_title, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301262 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Nabin Haitaf21a112022-09-15 12:09:18 +05301263 company_abbr = frappe.get_cached_value("Company", company, "abbr")
1264 parts = [doc_title.strip(), company_abbr]
1265
Zlash651aeca1d2018-07-06 17:15:33 +05301266 if cstr(number_value).strip():
1267 parts.insert(0, cstr(number_value).strip())
Nabin Haitaf21a112022-09-15 12:09:18 +05301268
Ankush Menat494bd9e2022-03-28 18:52:46 +05301269 return " - ".join(parts)
1270
Zarrar254ce642018-06-28 14:15:34 +05301271
Deepesh Garg62706072023-07-16 12:58:42 +05301272def parse_naming_series_variable(doc, variable):
1273 if variable == "FY":
Gughan Ravikumar89d109e2023-07-27 23:12:11 +05301274 if doc:
Gursheen Anandd96a7772024-01-10 22:05:02 +05301275 date = doc.get("posting_date") or doc.get("transaction_date") or getdate()
Gughan Ravikumar89d109e2023-07-27 23:12:11 +05301276 company = doc.get("company")
1277 else:
1278 date = getdate()
1279 company = None
Gughan Ravikumarcdf100d2023-08-15 09:38:29 +05301280 return get_fiscal_year(date=date, company=company)[0]
Deepesh Garg62706072023-07-16 12:58:42 +05301281
1282
Zarrar254ce642018-06-28 14:15:34 +05301283@frappe.whitelist()
David Arnoldd066b5c2023-07-23 22:43:41 -05001284def get_coa(doctype, parent, is_root=None, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301285 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1286 build_tree_from_json,
1287 )
Zarrar254ce642018-06-28 14:15:34 +05301288
1289 # add chart to flags to retrieve when called from expand all function
1290 chart = chart if chart else frappe.flags.chart
1291 frappe.flags.chart = chart
1292
Ankush Menat494bd9e2022-03-28 18:52:46 +05301293 parent = None if parent == _("All Accounts") else parent
1294 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301295
1296 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301297 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301298
1299 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001300
Ankush Menat494bd9e2022-03-28 18:52:46 +05301301
1302def update_gl_entries_after(
1303 posting_date,
1304 posting_time,
1305 for_warehouses=None,
1306 for_items=None,
1307 warehouse_account=None,
1308 company=None,
1309):
1310 stock_vouchers = get_future_stock_vouchers(
1311 posting_date, posting_time, for_warehouses, for_items, company
1312 )
Nabin Hait9b178bc2021-02-16 14:57:00 +05301313 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1314
1315
Ankush Menat494bd9e2022-03-28 18:52:46 +05301316def repost_gle_for_stock_vouchers(
Ankush Menat2535d5e2022-06-14 18:20:33 +05301317 stock_vouchers: List[Tuple[str, str]],
1318 posting_date: str,
1319 company: Optional[str] = None,
1320 warehouse_account=None,
1321 repost_doc: Optional["RepostItemValuation"] = None,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301322):
Ankush Menat67c26322022-06-04 14:46:35 +05301323
1324 from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative
1325
Ankush Menat700e8642022-04-19 13:24:29 +05301326 if not stock_vouchers:
1327 return
1328
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301329 if not warehouse_account:
1330 warehouse_account = get_warehouse_account_map(company)
1331
Ankush Menat2535d5e2022-06-14 18:20:33 +05301332 stock_vouchers = sort_stock_vouchers_by_posting_date(stock_vouchers)
1333 if repost_doc and repost_doc.gl_reposting_index:
1334 # Restore progress
1335 stock_vouchers = stock_vouchers[cint(repost_doc.gl_reposting_index) :]
1336
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301337 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1338
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301339 for stock_vouchers_chunk in create_batch(stock_vouchers, GL_REPOSTING_CHUNK):
Ankush Menat2535d5e2022-06-14 18:20:33 +05301340 gle = get_voucherwise_gl_entries(stock_vouchers_chunk, posting_date)
1341
1342 for voucher_type, voucher_no in stock_vouchers_chunk:
1343 existing_gle = gle.get((voucher_type, voucher_no), [])
1344 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
1345 # Some transactions post credit as negative debit, this is handled while posting GLE
1346 # but while comparing we need to make sure it's flipped so comparisons are accurate
1347 expected_gle = toggle_debit_credit_if_negative(voucher_obj.get_gl_entries(warehouse_account))
1348 if expected_gle:
1349 if not existing_gle or not compare_existing_and_expected_gle(
1350 existing_gle, expected_gle, precision
1351 ):
ruthra kumar9209ec52022-10-21 15:18:40 +05301352 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301353 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
1354 else:
ruthra kumar9209ec52022-10-21 15:18:40 +05301355 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat86919d22022-06-15 21:19:09 +05301356
1357 if not frappe.flags.in_test:
1358 frappe.db.commit()
Ankush Menat2535d5e2022-06-14 18:20:33 +05301359
1360 if repost_doc:
1361 repost_doc.db_set(
1362 "gl_reposting_index",
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301363 cint(repost_doc.gl_reposting_index) + len(stock_vouchers_chunk),
Ankush Menat2535d5e2022-06-14 18:20:33 +05301364 )
1365
1366
ruthra kumar9209ec52022-10-21 15:18:40 +05301367def _delete_pl_entries(voucher_type, voucher_no):
ruthra kumar65992302022-10-04 16:17:56 +05301368 ple = qb.DocType("Payment Ledger Entry")
1369 qb.from_(ple).delete().where(
1370 (ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)
1371 ).run()
Ankush Menateb53a972022-06-04 18:19:44 +05301372
Ankush Menat494bd9e2022-03-28 18:52:46 +05301373
ruthra kumar9209ec52022-10-21 15:18:40 +05301374def _delete_gl_entries(voucher_type, voucher_no):
1375 gle = qb.DocType("GL Entry")
1376 qb.from_(gle).delete().where(
1377 (gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)
1378 ).run()
1379
1380
1381def _delete_accounting_ledger_entries(voucher_type, voucher_no):
1382 """
1383 Remove entries from both General and Payment Ledger for specified Voucher
1384 """
1385 _delete_gl_entries(voucher_type, voucher_no)
1386 _delete_pl_entries(voucher_type, voucher_no)
1387
1388
Ankush Menat700e8642022-04-19 13:24:29 +05301389def sort_stock_vouchers_by_posting_date(
1390 stock_vouchers: List[Tuple[str, str]]
1391) -> List[Tuple[str, str]]:
1392 sle = frappe.qb.DocType("Stock Ledger Entry")
1393 voucher_nos = [v[1] for v in stock_vouchers]
1394
1395 sles = (
1396 frappe.qb.from_(sle)
1397 .select(sle.voucher_type, sle.voucher_no, sle.posting_date, sle.posting_time, sle.creation)
1398 .where((sle.is_cancelled == 0) & (sle.voucher_no.isin(voucher_nos)))
1399 .groupby(sle.voucher_type, sle.voucher_no)
Rohit Waghchaured80ca522024-02-07 21:56:21 +05301400 .orderby(sle.posting_datetime)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301401 .orderby(sle.creation)
Ankush Menat700e8642022-04-19 13:24:29 +05301402 ).run(as_dict=True)
1403 sorted_vouchers = [(sle.voucher_type, sle.voucher_no) for sle in sles]
1404
1405 unknown_vouchers = set(stock_vouchers) - set(sorted_vouchers)
1406 if unknown_vouchers:
1407 sorted_vouchers.extend(unknown_vouchers)
1408
1409 return sorted_vouchers
1410
1411
Ankush Menat494bd9e2022-03-28 18:52:46 +05301412def get_future_stock_vouchers(
1413 posting_date, posting_time, for_warehouses=None, for_items=None, company=None
1414):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301415
1416 values = []
1417 condition = ""
1418 if for_items:
1419 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1420 values += for_items
1421
1422 if for_warehouses:
1423 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1424 values += for_warehouses
1425
rohitwaghchaured60ff832021-02-16 09:12:27 +05301426 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301427 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301428 values.append(company)
1429
Ankush Menat494bd9e2022-03-28 18:52:46 +05301430 future_stock_vouchers = frappe.db.sql(
1431 """select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301432 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301433 where
1434 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1435 and is_cancelled = 0
1436 {condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301437 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
1438 condition=condition
1439 ),
1440 tuple([posting_date, posting_time] + values),
1441 as_dict=True,
1442 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301443
Ankush91527152021-08-11 11:17:50 +05301444 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301445
Ankush Menat494bd9e2022-03-28 18:52:46 +05301446
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301447def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301448 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301449
1450 Only fetches GLE fields required for comparing with new GLE.
1451 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301452
1453 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301454 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301455 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301456 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301457 if not future_stock_vouchers:
1458 return gl_entries
1459
1460 voucher_nos = [d[1] for d in future_stock_vouchers]
1461
Ankush Menat494bd9e2022-03-28 18:52:46 +05301462 gles = frappe.db.sql(
1463 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301464 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301465 from `tabGL Entry`
1466 where
Ankush Menat494bd9e2022-03-28 18:52:46 +05301467 posting_date >= %s and voucher_no in (%s)"""
1468 % ("%s", ", ".join(["%s"] * len(voucher_nos))),
1469 tuple([posting_date] + voucher_nos),
1470 as_dict=1,
1471 )
Ankush91527152021-08-11 11:17:50 +05301472
1473 for d in gles:
1474 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301475
Prssanna Desai82ddef52020-06-18 18:18:41 +05301476 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301477
Ankush Menat494bd9e2022-03-28 18:52:46 +05301478
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301479def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301480 if len(existing_gle) != len(expected_gle):
1481 return False
1482
Nabin Haita77b8c92020-12-21 14:45:50 +05301483 matched = True
1484 for entry in expected_gle:
1485 account_existed = False
1486 for e in existing_gle:
1487 if entry.account == e.account:
1488 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301489 if (
1490 entry.account == e.account
1491 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1492 and (
1493 flt(entry.debit, precision) != flt(e.debit, precision)
1494 or flt(entry.credit, precision) != flt(e.credit, precision)
1495 )
1496 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301497 matched = False
1498 break
1499 if not account_existed:
1500 matched = False
1501 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301502 return matched
1503
Ankush Menat494bd9e2022-03-28 18:52:46 +05301504
Nabin Haitb99c77b2020-12-25 18:12:35 +05301505def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301506 stock_accounts = [
1507 d.name
1508 for d in frappe.db.get_all(
1509 "Account", {"account_type": "Stock", "company": company, "is_group": 0}
1510 )
1511 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301512 if voucher_type and voucher_no:
1513 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301514 stock_accounts = [
1515 d.account
1516 for d in frappe.db.get_all(
1517 "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
1518 )
1519 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301520
1521 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301522 stock_accounts = [
1523 d.account
1524 for d in frappe.db.get_all(
1525 "GL Entry",
1526 {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
1527 "account",
1528 )
1529 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301530
1531 return stock_accounts
1532
Ankush Menat494bd9e2022-03-28 18:52:46 +05301533
Nabin Haitb99c77b2020-12-25 18:12:35 +05301534def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301535 if not posting_date:
1536 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301537
1538 warehouse_account = get_warehouse_account_map(company)
1539
Ankush Menat494bd9e2022-03-28 18:52:46 +05301540 account_balance = get_balance_on(
1541 account, posting_date, in_account_currency=False, ignore_account_permission=True
1542 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301543
Ankush Menat494bd9e2022-03-28 18:52:46 +05301544 related_warehouses = [
1545 wh
1546 for wh, wh_details in warehouse_account.items()
1547 if wh_details.account == account and not wh_details.is_group
1548 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301549
s-aga-re782a052023-04-25 13:54:36 +05301550 total_stock_value = get_stock_value_on(related_warehouses, posting_date)
Nabin Haitb99c77b2020-12-25 18:12:35 +05301551
1552 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1553 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1554
Ankush Menat494bd9e2022-03-28 18:52:46 +05301555
Nabin Haitb99c77b2020-12-25 18:12:35 +05301556def get_journal_entry(account, stock_adjustment_account, amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301557 db_or_cr_warehouse_account = (
1558 "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
1559 )
1560 db_or_cr_stock_adjustment_account = (
1561 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1562 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301563
1564 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301565 "accounts": [
1566 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1567 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1568 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301569 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301570
Ankush Menat494bd9e2022-03-28 18:52:46 +05301571
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301572def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301573 """Check if reports are referenced in Desktop Icon"""
1574 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301575 if icons:
1576 for icon in icons:
1577 frappe.delete_doc("Desktop Icon", icon)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301578
1579
ruthra kumar4f51c5a2023-07-03 14:35:33 +05301580def create_err_and_its_journals(companies: list = None) -> None:
1581 if companies:
1582 for company in companies:
1583 err = frappe.new_doc("Exchange Rate Revaluation")
1584 err.company = company.name
1585 err.posting_date = nowdate()
1586 err.rounding_loss_allowance = 0.0
1587
1588 err.fetch_and_calculate_accounts_data()
1589 if err.accounts:
1590 err.save().submit()
1591 response = err.make_jv_entries()
1592
1593 if company.submit_err_jv:
1594 jv = response.get("revaluation_jv", None)
1595 jv and frappe.get_doc("Journal Entry", jv).submit()
1596 jv = response.get("zero_balance_jv", None)
1597 jv and frappe.get_doc("Journal Entry", jv).submit()
1598
1599
1600def auto_create_exchange_rate_revaluation_daily() -> None:
1601 """
1602 Executed by background job
1603 """
1604 companies = frappe.db.get_all(
1605 "Company",
1606 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Daily"},
1607 fields=["name", "submit_err_jv"],
1608 )
1609 create_err_and_its_journals(companies)
1610
1611
1612def auto_create_exchange_rate_revaluation_weekly() -> None:
1613 """
1614 Executed by background job
1615 """
1616 companies = frappe.db.get_all(
1617 "Company",
1618 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Weekly"},
1619 fields=["name", "submit_err_jv"],
1620 )
1621 create_err_and_its_journals(companies)
1622
1623
ruthra kumar9b502212022-10-13 14:13:48 +05301624def get_payment_ledger_entries(gl_entries, cancel=0):
1625 ple_map = []
ruthra kumar451cf3a2022-05-16 14:29:58 +05301626 if gl_entries:
1627 ple = None
1628
1629 # companies
1630 account = qb.DocType("Account")
1631 companies = list(set([x.company for x in gl_entries]))
1632
1633 # receivable/payable account
1634 accounts_with_types = (
1635 qb.from_(account)
1636 .select(account.name, account.account_type)
1637 .where(
1638 (account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
1639 )
1640 .run(as_dict=True)
1641 )
1642 receivable_or_payable_accounts = [y.name for y in accounts_with_types]
1643
1644 def get_account_type(account):
1645 for entry in accounts_with_types:
1646 if entry.name == account:
1647 return entry.account_type
1648
1649 dr_or_cr = 0
1650 account_type = None
1651 for gle in gl_entries:
1652 if gle.account in receivable_or_payable_accounts:
1653 account_type = get_account_type(gle.account)
1654 if account_type == "Receivable":
1655 dr_or_cr = gle.debit - gle.credit
1656 dr_or_cr_account_currency = gle.debit_in_account_currency - gle.credit_in_account_currency
1657 elif account_type == "Payable":
1658 dr_or_cr = gle.credit - gle.debit
1659 dr_or_cr_account_currency = gle.credit_in_account_currency - gle.debit_in_account_currency
1660
1661 if cancel:
1662 dr_or_cr *= -1
1663 dr_or_cr_account_currency *= -1
1664
ruthra kumar9b502212022-10-13 14:13:48 +05301665 ple = frappe._dict(
1666 doctype="Payment Ledger Entry",
1667 posting_date=gle.posting_date,
1668 company=gle.company,
1669 account_type=account_type,
1670 account=gle.account,
1671 party_type=gle.party_type,
1672 party=gle.party,
1673 cost_center=gle.cost_center,
1674 finance_book=gle.finance_book,
1675 due_date=gle.due_date,
1676 voucher_type=gle.voucher_type,
1677 voucher_no=gle.voucher_no,
Deepesh Garg1e078d02023-06-29 12:18:25 +05301678 voucher_detail_no=gle.voucher_detail_no,
ruthra kumar9b502212022-10-13 14:13:48 +05301679 against_voucher_type=gle.against_voucher_type
1680 if gle.against_voucher_type
1681 else gle.voucher_type,
1682 against_voucher_no=gle.against_voucher if gle.against_voucher else gle.voucher_no,
1683 account_currency=gle.account_currency,
1684 amount=dr_or_cr,
1685 amount_in_account_currency=dr_or_cr_account_currency,
1686 delinked=True if cancel else False,
1687 remarks=gle.remarks,
ruthra kumar451cf3a2022-05-16 14:29:58 +05301688 )
1689
1690 dimensions_and_defaults = get_dimensions()
1691 if dimensions_and_defaults:
1692 for dimension in dimensions_and_defaults[0]:
ruthra kumar9b502212022-10-13 14:13:48 +05301693 ple[dimension.fieldname] = gle.get(dimension.fieldname)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301694
ruthra kumar9b502212022-10-13 14:13:48 +05301695 ple_map.append(ple)
1696 return ple_map
1697
1698
1699def create_payment_ledger_entry(
Deepesh Garg1e078d02023-06-29 12:18:25 +05301700 gl_entries, cancel=0, adv_adj=0, update_outstanding="Yes", from_repost=0, partial_cancel=False
ruthra kumar9b502212022-10-13 14:13:48 +05301701):
1702 if gl_entries:
1703 ple_map = get_payment_ledger_entries(gl_entries, cancel=cancel)
1704
1705 for entry in ple_map:
1706
1707 ple = frappe.get_doc(entry)
1708
1709 if cancel:
Deepesh Garg1e078d02023-06-29 12:18:25 +05301710 delink_original_entry(ple, partial_cancel=partial_cancel)
ruthra kumar9b502212022-10-13 14:13:48 +05301711
1712 ple.flags.ignore_permissions = 1
1713 ple.flags.adv_adj = adv_adj
1714 ple.flags.from_repost = from_repost
1715 ple.flags.update_outstanding = update_outstanding
1716 ple.submit()
ruthra kumar451cf3a2022-05-16 14:29:58 +05301717
1718
ruthra kumar7312f222022-05-29 21:33:08 +05301719def update_voucher_outstanding(voucher_type, voucher_no, account, party_type, party):
1720 ple = frappe.qb.DocType("Payment Ledger Entry")
1721 vouchers = [frappe._dict({"voucher_type": voucher_type, "voucher_no": voucher_no})]
1722 common_filter = []
1723 if account:
1724 common_filter.append(ple.account == account)
1725
1726 if party_type:
1727 common_filter.append(ple.party_type == party_type)
1728
1729 if party:
1730 common_filter.append(ple.party == party)
1731
1732 ple_query = QueryPaymentLedger()
1733
1734 # on cancellation outstanding can be an empty list
1735 voucher_outstanding = ple_query.get_voucher_outstandings(vouchers, common_filter=common_filter)
ruthra kumar43b80682022-10-18 09:33:37 +05301736 if (
1737 voucher_type in ["Sales Invoice", "Purchase Invoice", "Fees"]
1738 and party_type
1739 and party
1740 and voucher_outstanding
1741 ):
ruthra kumar7312f222022-05-29 21:33:08 +05301742 outstanding = voucher_outstanding[0]
1743 ref_doc = frappe.get_doc(voucher_type, voucher_no)
1744
1745 # Didn't use db_set for optimisation purpose
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301746 ref_doc.outstanding_amount = outstanding["outstanding_in_account_currency"] or 0.0
ruthra kumar7312f222022-05-29 21:33:08 +05301747 frappe.db.set_value(
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301748 voucher_type,
1749 voucher_no,
1750 "outstanding_amount",
1751 outstanding["outstanding_in_account_currency"] or 0.0,
ruthra kumar7312f222022-05-29 21:33:08 +05301752 )
1753
1754 ref_doc.set_status(update=True)
1755
1756
Deepesh Garg1e078d02023-06-29 12:18:25 +05301757def delink_original_entry(pl_entry, partial_cancel=False):
ruthra kumar451cf3a2022-05-16 14:29:58 +05301758 if pl_entry:
1759 ple = qb.DocType("Payment Ledger Entry")
1760 query = (
1761 qb.update(ple)
1762 .set(ple.delinked, True)
1763 .set(ple.modified, now())
1764 .set(ple.modified_by, frappe.session.user)
1765 .where(
1766 (ple.company == pl_entry.company)
1767 & (ple.account_type == pl_entry.account_type)
1768 & (ple.account == pl_entry.account)
1769 & (ple.party_type == pl_entry.party_type)
1770 & (ple.party == pl_entry.party)
1771 & (ple.voucher_type == pl_entry.voucher_type)
1772 & (ple.voucher_no == pl_entry.voucher_no)
1773 & (ple.against_voucher_type == pl_entry.against_voucher_type)
1774 & (ple.against_voucher_no == pl_entry.against_voucher_no)
1775 )
1776 )
Deepesh Garg1e078d02023-06-29 12:18:25 +05301777
1778 if partial_cancel:
1779 query = query.where(ple.voucher_detail_no == pl_entry.voucher_detail_no)
1780
ruthra kumar451cf3a2022-05-16 14:29:58 +05301781 query.run()
ruthra kumar7b383882022-05-25 15:51:16 +05301782
1783
1784class QueryPaymentLedger(object):
1785 """
1786 Helper Class for Querying Payment Ledger Entry
1787 """
1788
1789 def __init__(self):
1790 self.ple = qb.DocType("Payment Ledger Entry")
1791
1792 # query result
1793 self.voucher_outstandings = []
1794
1795 # query filters
1796 self.vouchers = []
1797 self.common_filter = []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301798 self.voucher_posting_date = []
ruthra kumar7b383882022-05-25 15:51:16 +05301799 self.min_outstanding = None
1800 self.max_outstanding = None
ruthra kumar7a381af2023-05-03 20:45:12 +05301801 self.limit = self.voucher_no = None
ruthra kumar7b383882022-05-25 15:51:16 +05301802
1803 def reset(self):
1804 # clear filters
1805 self.vouchers.clear()
1806 self.common_filter.clear()
ruthra kumar7a381af2023-05-03 20:45:12 +05301807 self.min_outstanding = self.max_outstanding = self.limit = None
ruthra kumar7b383882022-05-25 15:51:16 +05301808
1809 # clear result
1810 self.voucher_outstandings.clear()
1811
1812 def query_for_outstanding(self):
1813 """
1814 Database query to fetch voucher amount and voucher outstanding using Common Table Expression
1815 """
1816
1817 ple = self.ple
1818
1819 filter_on_voucher_no = []
1820 filter_on_against_voucher_no = []
ruthra kumar7a381af2023-05-03 20:45:12 +05301821
ruthra kumar7b383882022-05-25 15:51:16 +05301822 if self.vouchers:
1823 voucher_types = set([x.voucher_type for x in self.vouchers])
1824 voucher_nos = set([x.voucher_no for x in self.vouchers])
1825
1826 filter_on_voucher_no.append(ple.voucher_type.isin(voucher_types))
1827 filter_on_voucher_no.append(ple.voucher_no.isin(voucher_nos))
1828
1829 filter_on_against_voucher_no.append(ple.against_voucher_type.isin(voucher_types))
1830 filter_on_against_voucher_no.append(ple.against_voucher_no.isin(voucher_nos))
1831
ruthra kumar7a381af2023-05-03 20:45:12 +05301832 if self.voucher_no:
1833 filter_on_voucher_no.append(ple.voucher_no.like(f"%{self.voucher_no}%"))
1834 filter_on_against_voucher_no.append(ple.against_voucher_no.like(f"%{self.voucher_no}%"))
1835
ruthra kumar7b383882022-05-25 15:51:16 +05301836 # build outstanding amount filter
1837 filter_on_outstanding_amount = []
1838 if self.min_outstanding:
1839 if self.min_outstanding > 0:
1840 filter_on_outstanding_amount.append(
1841 Table("outstanding").amount_in_account_currency >= self.min_outstanding
1842 )
1843 else:
1844 filter_on_outstanding_amount.append(
1845 Table("outstanding").amount_in_account_currency <= self.min_outstanding
1846 )
1847 if self.max_outstanding:
1848 if self.max_outstanding > 0:
1849 filter_on_outstanding_amount.append(
1850 Table("outstanding").amount_in_account_currency <= self.max_outstanding
1851 )
1852 else:
1853 filter_on_outstanding_amount.append(
1854 Table("outstanding").amount_in_account_currency >= self.max_outstanding
1855 )
1856
ruthra kumar8b04c1d2023-11-22 09:59:32 +05301857 if self.limit and self.get_invoices:
1858 outstanding_vouchers = (
1859 qb.from_(ple)
1860 .select(
1861 ple.against_voucher_no.as_("voucher_no"),
1862 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1863 )
1864 .where(ple.delinked == 0)
1865 .where(Criterion.all(filter_on_against_voucher_no))
1866 .where(Criterion.all(self.common_filter))
ruthra kumarcfd32302023-11-30 12:22:55 +05301867 .where(Criterion.all(self.dimensions_filter))
1868 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar8b04c1d2023-11-22 09:59:32 +05301869 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1870 .orderby(ple.posting_date, ple.voucher_no)
1871 .having(qb.Field("amount_in_account_currency") > 0)
1872 .limit(self.limit)
1873 .run()
1874 )
1875 if outstanding_vouchers:
1876 filter_on_voucher_no.append(ple.voucher_no.isin([x[0] for x in outstanding_vouchers]))
1877 filter_on_against_voucher_no.append(
1878 ple.against_voucher_no.isin([x[0] for x in outstanding_vouchers])
1879 )
1880
ruthra kumar7b383882022-05-25 15:51:16 +05301881 # build query for voucher amount
1882 query_voucher_amount = (
1883 qb.from_(ple)
1884 .select(
1885 ple.account,
1886 ple.voucher_type,
1887 ple.voucher_no,
1888 ple.party_type,
1889 ple.party,
1890 ple.posting_date,
1891 ple.due_date,
1892 ple.account_currency.as_("currency"),
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301893 ple.cost_center.as_("cost_center"),
ruthra kumar7b383882022-05-25 15:51:16 +05301894 Sum(ple.amount).as_("amount"),
1895 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1896 )
1897 .where(ple.delinked == 0)
1898 .where(Criterion.all(filter_on_voucher_no))
1899 .where(Criterion.all(self.common_filter))
ruthra kumar6d9d7302022-12-14 16:05:15 +05301900 .where(Criterion.all(self.dimensions_filter))
ruthra kumar5f1562c2022-07-28 11:57:27 +05301901 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar7b383882022-05-25 15:51:16 +05301902 .groupby(ple.voucher_type, ple.voucher_no, ple.party_type, ple.party)
1903 )
1904
1905 # build query for voucher outstanding
1906 query_voucher_outstanding = (
1907 qb.from_(ple)
1908 .select(
1909 ple.account,
1910 ple.against_voucher_type.as_("voucher_type"),
1911 ple.against_voucher_no.as_("voucher_no"),
1912 ple.party_type,
1913 ple.party,
1914 ple.posting_date,
1915 ple.due_date,
1916 ple.account_currency.as_("currency"),
1917 Sum(ple.amount).as_("amount"),
1918 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1919 )
1920 .where(ple.delinked == 0)
1921 .where(Criterion.all(filter_on_against_voucher_no))
1922 .where(Criterion.all(self.common_filter))
1923 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1924 )
1925
1926 # build CTE for combining voucher amount and outstanding
1927 self.cte_query_voucher_amount_and_outstanding = (
1928 qb.with_(query_voucher_amount, "vouchers")
1929 .with_(query_voucher_outstanding, "outstanding")
1930 .from_(AliasedQuery("vouchers"))
1931 .left_join(AliasedQuery("outstanding"))
1932 .on(
1933 (AliasedQuery("vouchers").account == AliasedQuery("outstanding").account)
1934 & (AliasedQuery("vouchers").voucher_type == AliasedQuery("outstanding").voucher_type)
1935 & (AliasedQuery("vouchers").voucher_no == AliasedQuery("outstanding").voucher_no)
1936 & (AliasedQuery("vouchers").party_type == AliasedQuery("outstanding").party_type)
1937 & (AliasedQuery("vouchers").party == AliasedQuery("outstanding").party)
1938 )
1939 .select(
1940 Table("vouchers").account,
1941 Table("vouchers").voucher_type,
1942 Table("vouchers").voucher_no,
1943 Table("vouchers").party_type,
1944 Table("vouchers").party,
1945 Table("vouchers").posting_date,
1946 Table("vouchers").amount.as_("invoice_amount"),
1947 Table("vouchers").amount_in_account_currency.as_("invoice_amount_in_account_currency"),
1948 Table("outstanding").amount.as_("outstanding"),
1949 Table("outstanding").amount_in_account_currency.as_("outstanding_in_account_currency"),
1950 (Table("vouchers").amount - Table("outstanding").amount).as_("paid_amount"),
1951 (
1952 Table("vouchers").amount_in_account_currency - Table("outstanding").amount_in_account_currency
1953 ).as_("paid_amount_in_account_currency"),
1954 Table("vouchers").due_date,
1955 Table("vouchers").currency,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301956 Table("vouchers").cost_center.as_("cost_center"),
ruthra kumar7b383882022-05-25 15:51:16 +05301957 )
1958 .where(Criterion.all(filter_on_outstanding_amount))
1959 )
1960
1961 # build CTE filter
1962 # only fetch invoices
1963 if self.get_invoices:
1964 self.cte_query_voucher_amount_and_outstanding = (
1965 self.cte_query_voucher_amount_and_outstanding.having(
1966 qb.Field("outstanding_in_account_currency") > 0
1967 )
1968 )
1969 # only fetch payments
1970 elif self.get_payments:
1971 self.cte_query_voucher_amount_and_outstanding = (
1972 self.cte_query_voucher_amount_and_outstanding.having(
1973 qb.Field("outstanding_in_account_currency") < 0
1974 )
1975 )
1976
ruthra kumar7a381af2023-05-03 20:45:12 +05301977 if self.limit:
1978 self.cte_query_voucher_amount_and_outstanding = (
1979 self.cte_query_voucher_amount_and_outstanding.limit(self.limit)
1980 )
1981
ruthra kumar7b383882022-05-25 15:51:16 +05301982 # execute SQL
1983 self.voucher_outstandings = self.cte_query_voucher_amount_and_outstanding.run(as_dict=True)
1984
1985 def get_voucher_outstandings(
1986 self,
1987 vouchers=None,
1988 common_filter=None,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301989 posting_date=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301990 min_outstanding=None,
1991 max_outstanding=None,
1992 get_payments=False,
1993 get_invoices=False,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301994 accounting_dimensions=None,
ruthra kumar7a381af2023-05-03 20:45:12 +05301995 limit=None,
1996 voucher_no=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301997 ):
1998 """
1999 Fetch voucher amount and outstanding amount from Payment Ledger using Database CTE
2000
2001 vouchers - dict of vouchers to get
2002 common_filter - array of criterions
2003 min_outstanding - filter on minimum total outstanding amount
2004 max_outstanding - filter on maximum total outstanding amount
2005 get_invoices - only fetch vouchers(ledger entries with +ve outstanding)
2006 get_payments - only fetch payments(ledger entries with -ve outstanding)
2007 """
2008
2009 self.reset()
2010 self.vouchers = vouchers
2011 self.common_filter = common_filter or []
ruthra kumar6d9d7302022-12-14 16:05:15 +05302012 self.dimensions_filter = accounting_dimensions or []
ruthra kumar5f1562c2022-07-28 11:57:27 +05302013 self.voucher_posting_date = posting_date or []
ruthra kumar7b383882022-05-25 15:51:16 +05302014 self.min_outstanding = min_outstanding
2015 self.max_outstanding = max_outstanding
2016 self.get_payments = get_payments
2017 self.get_invoices = get_invoices
ruthra kumar7a381af2023-05-03 20:45:12 +05302018 self.limit = limit
2019 self.voucher_no = voucher_no
ruthra kumar7b383882022-05-25 15:51:16 +05302020 self.query_for_outstanding()
2021
2022 return self.voucher_outstandings
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302023
2024
2025def create_gain_loss_journal(
2026 company,
ruthra kumarf7865da2023-09-04 20:38:10 +05302027 posting_date,
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302028 party_type,
2029 party,
2030 party_account,
2031 gain_loss_account,
2032 exc_gain_loss,
2033 dr_or_cr,
2034 reverse_dr_or_cr,
2035 ref1_dt,
2036 ref1_dn,
2037 ref1_detail_no,
2038 ref2_dt,
2039 ref2_dn,
2040 ref2_detail_no,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05302041 cost_center,
ruthra kumar5dc22e12023-12-20 17:19:27 +05302042 dimensions,
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302043) -> str:
2044 journal_entry = frappe.new_doc("Journal Entry")
2045 journal_entry.voucher_type = "Exchange Gain Or Loss"
2046 journal_entry.company = company
ruthra kumarf7865da2023-09-04 20:38:10 +05302047 journal_entry.posting_date = posting_date or nowdate()
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302048 journal_entry.multi_currency = 1
ruthra kumar79c6f012023-09-01 14:57:12 +05302049 journal_entry.is_system_generated = True
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302050
2051 party_account_currency = frappe.get_cached_value("Account", party_account, "account_currency")
2052
2053 if not gain_loss_account:
2054 frappe.throw(_("Please set default Exchange Gain/Loss Account in Company {}").format(company))
2055 gain_loss_account_currency = get_account_currency(gain_loss_account)
2056 company_currency = frappe.get_cached_value("Company", company, "default_currency")
2057
2058 if gain_loss_account_currency != company_currency:
2059 frappe.throw(_("Currency for {0} must be {1}").format(gain_loss_account, company_currency))
2060
2061 journal_account = frappe._dict(
2062 {
2063 "account": party_account,
2064 "party_type": party_type,
2065 "party": party,
2066 "account_currency": party_account_currency,
2067 "exchange_rate": 0,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05302068 "cost_center": cost_center or erpnext.get_default_cost_center(company),
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302069 "reference_type": ref1_dt,
2070 "reference_name": ref1_dn,
2071 "reference_detail_no": ref1_detail_no,
2072 dr_or_cr: abs(exc_gain_loss),
2073 dr_or_cr + "_in_account_currency": 0,
2074 }
2075 )
ruthra kumarec0f17c2024-01-22 11:59:20 +05302076 if dimensions:
2077 journal_account.update(dimensions)
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302078 journal_entry.append("accounts", journal_account)
2079
2080 journal_account = frappe._dict(
2081 {
2082 "account": gain_loss_account,
2083 "account_currency": gain_loss_account_currency,
2084 "exchange_rate": 1,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05302085 "cost_center": cost_center or erpnext.get_default_cost_center(company),
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302086 "reference_type": ref2_dt,
2087 "reference_name": ref2_dn,
2088 "reference_detail_no": ref2_detail_no,
2089 reverse_dr_or_cr + "_in_account_currency": 0,
2090 reverse_dr_or_cr: abs(exc_gain_loss),
2091 }
2092 )
ruthra kumarec0f17c2024-01-22 11:59:20 +05302093 if dimensions:
2094 journal_account.update(dimensions)
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302095 journal_entry.append("accounts", journal_account)
2096
2097 journal_entry.save()
2098 journal_entry.submit()
2099 return journal_entry.name
Gursheen Anand40157232023-11-03 11:58:25 +05302100
2101
2102def get_party_types_from_account_type(account_type):
Gursheen Anand2984a862023-11-08 12:30:24 +05302103 return frappe.db.get_all("Party Type", {"account_type": account_type}, pluck="name")