blob: 0f21c864b0bd8ecf186ba4aff3645afbd7c7b6e5 [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:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530240 cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center, percent=False),))
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400241
Nabin Hait6f17cf92014-09-17 14:11:22 +0530242 if account:
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400243
Ankush Menat494bd9e2022-03-28 18:52:46 +0530244 if not (frappe.flags.ignore_account_permission or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530245 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530246
Nabin Hait6f17cf92014-09-17 14:11:22 +0530247 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530248 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530249 cond.append(
250 """exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530251 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530252 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530253 )"""
254 % (acc.lft, acc.rgt)
255 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530256
257 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530258 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530259 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530260 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530261 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530262 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
Anand Doshic75c1d72016-03-11 14:56:19 +0530263
RitvikSardanab86afb22023-08-04 22:05:30 +0530264 if account_type:
265 accounts = frappe.db.get_all(
266 "Account",
267 filters={"company": company, "account_type": account_type, "is_group": 0},
268 pluck="name",
269 order_by="lft",
270 )
271
272 cond.append(
273 """
274 gle.account in (%s)
275 """
276 % (", ".join([frappe.db.escape(account) for account in accounts]))
277 )
278
Nabin Hait6f17cf92014-09-17 14:11:22 +0530279 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530280 cond.append(
281 """gle.party_type = %s and gle.party = %s """
282 % (frappe.db.escape(party_type), frappe.db.escape(party, percent=False))
283 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530284
Nabin Hait85648d92016-07-20 11:26:45 +0530285 if company:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530286 cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530287
RitvikSardanab86afb22023-08-04 22:05:30 +0530288 if account or (party_type and party) or account_type:
289
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530290 if in_account_currency:
Anand Doshi602e8252015-11-16 19:05:46 +0530291 select_field = "sum(debit_in_account_currency) - sum(credit_in_account_currency)"
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530292 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530293 select_field = "sum(debit) - sum(credit)"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530294 bal = frappe.db.sql(
295 """
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530296 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530297 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530298 WHERE {1}""".format(
299 select_field, " and ".join(cond)
300 )
301 )[0][0]
Nabin Haitdc768232015-08-17 11:27:00 +0530302 # if bal is None, return 0
303 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530304
Ankush Menat494bd9e2022-03-28 18:52:46 +0530305
RobertSchouten8d43b322016-09-20 13:41:39 +0800306def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530307 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800308 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530309 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800310 else:
311 # get balance of all entries that exist
312 date = nowdate()
313
314 try:
315 year_start_date = get_fiscal_year(date, verbose=0)[1]
316 except FiscalYearError:
317 if getdate(date) > getdate(nowdate()):
318 # if fiscal year not found and the date is greater than today
319 # get fiscal year for today's date and its corresponding year start date
320 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
321 else:
322 # this indicates that it is a date older than any existing fiscal year.
323 # hence, assuming balance as 0.0
324 return 0.0
325
326 if account:
327 acc = frappe.get_doc("Account", account)
328
329 if not frappe.flags.ignore_account_permission:
330 acc.check_permission("read")
331
332 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530333 if acc.report_type == "Profit and Loss":
334 cond.append(
335 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
336 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800337
338 # different filter for group and ledger - improved performance
339 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530340 cond.append(
341 """exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800342 select name from `tabAccount` ac where ac.name = gle.account
343 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530344 )"""
345 % (acc.lft, acc.rgt)
346 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800347 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530348 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
RobertSchouten8d43b322016-09-20 13:41:39 +0800349
Ankush Menat494bd9e2022-03-28 18:52:46 +0530350 entries = frappe.db.sql(
351 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800352 SELECT name, posting_date, account, party_type, party,debit,credit,
353 voucher_type, voucher_no, against_voucher_type, against_voucher
354 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530355 WHERE {0}""".format(
356 " and ".join(cond)
357 ),
358 as_dict=True,
359 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530360
RobertSchouten8d43b322016-09-20 13:41:39 +0800361 count = 0
362 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530363 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800364 count += 1
365 else:
366 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
367 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530368 select_fields = (
369 "ifnull(sum(credit-debit),0)"
370 if fieldname == "invoiced_amount"
371 else "ifnull(sum(debit-credit),0)"
372 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800373
Ankush Menat494bd9e2022-03-28 18:52:46 +0530374 if (
375 (not gle.against_voucher)
376 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
377 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
378 ):
379 payment_amount = frappe.db.sql(
380 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800381 SELECT {0}
382 FROM `tabGL Entry` gle
383 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530384 and party = %(party)s and name != %(name)s""".format(
385 select_fields
386 ),
387 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
388 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530389
RobertSchouten8d43b322016-09-20 13:41:39 +0800390 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
391 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530392 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800393 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530394
RobertSchouten8d43b322016-09-20 13:41:39 +0800395 return count
396
Ankush Menat494bd9e2022-03-28 18:52:46 +0530397
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530398@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530399def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530400 from frappe.desk.treeview import make_tree_args
401
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530402 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530403 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530404
Nabin Hait02d987e2017-02-17 15:50:26 +0530405 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530406 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530407
Anand Doshi3e41fd12014-04-22 18:54:54 +0530408 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530409
Nabin Hait665568d2016-05-13 15:56:00 +0530410 if args.get("ignore_permissions"):
411 ac.flags.ignore_permissions = True
412 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530413
Anand Doshi3e41fd12014-04-22 18:54:54 +0530414 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530415
416 if not ac.parent_account:
417 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530418
Anand Doshif78d1ae2014-03-28 13:55:00 +0530419 ac.old_parent = ""
420 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530421 if cint(ac.get("is_root")):
422 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530423 ac.flags.ignore_mandatory = True
424
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530425 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530426
Anand Doshif78d1ae2014-03-28 13:55:00 +0530427 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530428
Ankush Menat494bd9e2022-03-28 18:52:46 +0530429
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530430@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530431def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530432 from frappe.desk.treeview import make_tree_args
433
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530434 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530435 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530436
Nabin Hait02d987e2017-02-17 15:50:26 +0530437 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530438 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530439
Zarrar7ab70ca2018-06-08 14:33:15 +0530440 if args.parent_cost_center == args.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530441 args.parent_cost_center = "{0} - {1}".format(
442 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
443 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530444
Anand Doshi3e41fd12014-04-22 18:54:54 +0530445 cc = frappe.new_doc("Cost Center")
446 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530447
448 if not cc.parent_cost_center:
449 cc.parent_cost_center = args.get("parent")
450
Anand Doshif78d1ae2014-03-28 13:55:00 +0530451 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530452 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530453 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530454
Ankush Menat494bd9e2022-03-28 18:52:46 +0530455
Deepesh Garg016ed952023-06-20 13:22:32 +0530456def reconcile_against_document(args, skip_ref_details_update_for_pe=False): # nosemgrep
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530457 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530458 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530459 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530460 # To optimize making GL Entry for PE or JV with multiple references
461 reconciled_entries = {}
462 for row in args:
463 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
464 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530465
Anuja Pawar3e404f12021-08-31 18:59:29 +0530466 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
467
468 for key, entries in reconciled_entries.items():
469 voucher_type = key[0]
470 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530471
Nabin Hait28a05282016-06-27 17:41:39 +0530472 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530473 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530474 frappe.flags.ignore_party_validation = True
ruthra kumar78ab11f2023-09-20 13:05:04 +0530475
ruthra kumarecb533c2023-11-28 17:04:07 +0530476 # For payments with `Advance` in separate account feature enabled, only new ledger entries are posted for each reference.
477 # No need to cancel/delete payment ledger entries
ruthra kumar78ab11f2023-09-20 13:05:04 +0530478 if not (voucher_type == "Payment Entry" and doc.book_advance_payments_in_separate_party_account):
479 _delete_pl_entries(voucher_type, voucher_no)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530480
Anuja Pawar3e404f12021-08-31 18:59:29 +0530481 for entry in entries:
482 check_if_advance_entry_modified(entry)
483 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530484
Anuja Pawar3e404f12021-08-31 18:59:29 +0530485 # update ref in advance entry
486 if voucher_type == "Journal Entry":
ruthra kumar79c6f012023-09-01 14:57:12 +0530487 referenced_row = update_reference_in_journal_entry(entry, doc, do_not_save=False)
ruthra kumar7b516f82023-06-26 17:34:28 +0530488 # advance section in sales/purchase invoice and reconciliation tool,both pass on exchange gain/loss
489 # amount and account in args
ruthra kumar79c6f012023-09-01 14:57:12 +0530490 # referenced_row is used to deduplicate gain/loss journal
491 entry.update({"referenced_row": referenced_row})
492 doc.make_exchange_gain_loss_journal([entry])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530493 else:
ruthra kumarecb533c2023-11-28 17:04:07 +0530494 referenced_row = update_reference_in_payment_entry(
ruthra kumared14d1c2023-04-22 17:24:35 +0530495 entry, doc, do_not_save=True, skip_ref_details_update_for_pe=skip_ref_details_update_for_pe
496 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530497
498 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530499 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530500 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
ruthra kumar78ab11f2023-09-20 13:05:04 +0530501
502 if voucher_type == "Payment Entry" and doc.book_advance_payments_in_separate_party_account:
ruthra kumarecb533c2023-11-28 17:04:07 +0530503 # both ledgers must be posted to for `Advance` in separate account feature
504 doc.make_advance_gl_entries(referenced_row, update_outstanding="No")
ruthra kumar78ab11f2023-09-20 13:05:04 +0530505 else:
506 gl_map = doc.build_gl_map()
507 create_payment_ledger_entry(gl_map, update_outstanding="No", cancel=0, adv_adj=1)
Deepesh Garg1894dc82023-06-23 21:53:34 +0530508
ruthra kumar11cf6942023-01-14 12:22:22 +0530509 # Only update outstanding for newly linked vouchers
510 for entry in entries:
511 update_voucher_outstanding(
512 entry.against_voucher_type, entry.against_voucher, entry.account, entry.party_type, entry.party
513 )
ruthra kumar524c1752022-05-26 16:00:40 +0530514
Subin Tomb8845b92021-07-30 16:30:18 +0530515 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530516
Ankush Menat494bd9e2022-03-28 18:52:46 +0530517
Nabin Hait28a05282016-06-27 17:41:39 +0530518def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530519 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530520 check if there is already a voucher reference
521 check if amount is same
522 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530523 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530524 if not args.get("unreconciled_amount"):
525 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530526
Nabin Hait28a05282016-06-27 17:41:39 +0530527 ret = None
528 if args.voucher_type == "Journal Entry":
Gursheen Anand74619262023-06-02 17:13:51 +0530529 journal_entry = frappe.qb.DocType("Journal Entry")
530 journal_acc = frappe.qb.DocType("Journal Entry Account")
531
Gursheen Anand4ee16372023-06-08 13:15:23 +0530532 q = (
533 frappe.qb.from_(journal_entry)
Deepesh Garg3aead052023-06-22 11:41:43 +0530534 .inner_join(journal_acc)
Gursheen Anand74619262023-06-02 17:13:51 +0530535 .on(journal_entry.name == journal_acc.parent)
Deepesh Gargd81d6062023-06-22 18:28:16 +0530536 .select(journal_acc[args.get("dr_or_cr")])
537 .where(
538 (journal_acc.account == args.get("account"))
539 & ((journal_acc.party_type == args.get("party_type")))
540 & ((journal_acc.party == args.get("party")))
541 & (
542 (journal_acc.reference_type.isnull())
543 | (journal_acc.reference_type.isin(["", "Sales Order", "Purchase Order"]))
544 )
545 & ((journal_entry.name == args.get("voucher_no")))
546 & ((journal_acc.name == args.get("voucher_detail_no")))
547 & ((journal_entry.docstatus == 1))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530548 )
Gursheen Anand74619262023-06-02 17:13:51 +0530549 )
550
Nabin Hait28a05282016-06-27 17:41:39 +0530551 else:
ruthra kumar60435da2023-11-03 17:58:19 +0530552 precision = frappe.get_precision("Payment Entry", "unallocated_amount")
553
Gursheen Anand74619262023-06-02 17:13:51 +0530554 payment_entry = frappe.qb.DocType("Payment Entry")
555 payment_ref = frappe.qb.DocType("Payment Entry Reference")
556
Gursheen Anand4ee16372023-06-08 13:15:23 +0530557 q = (
558 frappe.qb.from_(payment_entry)
Gursheen Anand74619262023-06-02 17:13:51 +0530559 .select(payment_entry.name)
560 .where(payment_entry.name == args.get("voucher_no"))
561 .where(payment_entry.docstatus == 1)
562 .where(payment_entry.party_type == args.get("party_type"))
563 .where(payment_entry.party == args.get("party"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530564 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530565
Nabin Hait28a05282016-06-27 17:41:39 +0530566 if args.voucher_detail_no:
Gursheen Anand4ee16372023-06-08 13:15:23 +0530567 q = (
568 q.inner_join(payment_ref)
Gursheen Anand74619262023-06-02 17:13:51 +0530569 .on(payment_entry.name == payment_ref.parent)
570 .where(payment_ref.name == args.get("voucher_detail_no"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530571 .where(payment_ref.reference_doctype.isin(("", "Sales Order", "Purchase Order")))
Gursheen Anand74619262023-06-02 17:13:51 +0530572 .where(payment_ref.allocated_amount == args.get("unreconciled_amount"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530573 )
Nabin Hait28a05282016-06-27 17:41:39 +0530574 else:
ruthra kumar60435da2023-11-03 17:58:19 +0530575 q = q.where(
576 Round(payment_entry.unallocated_amount, precision)
577 == Round(args.get("unreconciled_amount"), precision)
578 )
Gursheen Anand4ee16372023-06-08 13:15:23 +0530579
Gursheen Anand74619262023-06-02 17:13:51 +0530580 ret = q.run(as_dict=True)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530581
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530582 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530583 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530584
Ankush Menat494bd9e2022-03-28 18:52:46 +0530585
Nabin Hait576f0252014-04-30 19:30:50 +0530586def validate_allocated_amount(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530587 precision = args.get("precision") or frappe.db.get_single_value(
588 "System Settings", "currency_precision"
589 )
Nabin Hait28a05282016-06-27 17:41:39 +0530590 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530591 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530592 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530593 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530594
Ankush Menat494bd9e2022-03-28 18:52:46 +0530595
Anuja Pawar3e404f12021-08-31 18:59:29 +0530596def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530597 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530598 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530599 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530600 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530601
marination426350e2023-09-13 14:24:56 +0530602 # Update Advance Paid in SO/PO since they might be getting unlinked
603 if jv_detail.get("reference_type") in ("Sales Order", "Purchase Order"):
604 frappe.get_doc(jv_detail.reference_type, jv_detail.reference_name).set_total_advance_paid()
605
Ankush Menat494bd9e2022-03-28 18:52:46 +0530606 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530607 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530608 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530609 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530610 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
611 jv_detail.set(
612 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
613 amount_in_company_currency,
614 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530615 else:
616 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530617
Anuja Pawar3e404f12021-08-31 18:59:29 +0530618 # new row with references
619 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530620
ruthra kumar72f577a2023-07-13 15:04:44 +0530621 # Copy field values into new row
622 [
623 new_row.set(field, jv_detail.get(field))
624 for field in frappe.get_meta("Journal Entry Account").get_fieldnames_with_value()
625 ]
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530626
Anuja Pawar3e404f12021-08-31 18:59:29 +0530627 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530628 new_row.set(
629 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
630 d["allocated_amount"] * flt(jv_detail.exchange_rate),
631 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530632
Ankush Menat494bd9e2022-03-28 18:52:46 +0530633 new_row.set(
634 "credit_in_account_currency"
635 if d["dr_or_cr"] == "debit_in_account_currency"
636 else "debit_in_account_currency",
637 0,
638 )
639 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530640
Anuja Pawar3e404f12021-08-31 18:59:29 +0530641 new_row.set("reference_type", d["against_voucher_type"])
642 new_row.set("reference_name", d["against_voucher"])
643
644 new_row.against_account = cstr(jv_detail.against_account)
645 new_row.is_advance = cstr(jv_detail.is_advance)
646 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530647
648 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530649 journal_entry.flags.ignore_validate_update_after_submit = True
650 if not do_not_save:
651 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530652
ruthra kumar79c6f012023-09-01 14:57:12 +0530653 return new_row.name
654
Ankush Menat494bd9e2022-03-28 18:52:46 +0530655
ruthra kumared14d1c2023-04-22 17:24:35 +0530656def update_reference_in_payment_entry(
657 d, payment_entry, do_not_save=False, skip_ref_details_update_for_pe=False
658):
Nabin Hait28a05282016-06-27 17:41:39 +0530659 reference_details = {
660 "reference_doctype": d.against_voucher_type,
661 "reference_name": d.against_voucher,
662 "total_amount": d.grand_total,
663 "outstanding_amount": d.outstanding_amount,
664 "allocated_amount": d.allocated_amount,
ruthra kumar5eeb6502023-12-15 11:46:12 +0530665 "exchange_rate": d.exchange_rate
666 if d.difference_amount is not None
667 else payment_entry.get_exchange_rate(),
668 "exchange_gain_loss": d.difference_amount,
Gursheen Anandb65e58c2023-06-08 18:15:37 +0530669 "account": d.account,
Nabin Hait28a05282016-06-27 17:41:39 +0530670 }
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530671
Nabin Hait28a05282016-06-27 17:41:39 +0530672 if d.voucher_detail_no:
673 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
marination426350e2023-09-13 14:24:56 +0530674
675 # Update Advance Paid in SO/PO since they are getting unlinked
676 if existing_row.get("reference_doctype") in ("Sales Order", "Purchase Order"):
677 frappe.get_doc(
678 existing_row.reference_doctype, existing_row.reference_name
679 ).set_total_advance_paid()
680
ruthra kumar23df4202023-10-19 11:32:21 +0530681 if d.allocated_amount <= existing_row.allocated_amount:
682 existing_row.allocated_amount -= d.allocated_amount
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530683
Nabin Hait28a05282016-06-27 17:41:39 +0530684 new_row = payment_entry.append("references")
685 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500686 for field in list(reference_details):
ruthra kumar23df4202023-10-19 11:32:21 +0530687 new_row.set(field, reference_details[field])
ruthra kumarecb533c2023-11-28 17:04:07 +0530688 row = new_row
Nabin Hait28a05282016-06-27 17:41:39 +0530689 else:
690 new_row = payment_entry.append("references")
691 new_row.docstatus = 1
692 new_row.update(reference_details)
ruthra kumarecb533c2023-11-28 17:04:07 +0530693 row = new_row
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530694
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500695 payment_entry.flags.ignore_validate_update_after_submit = True
ruthra kumar23df4202023-10-19 11:32:21 +0530696 payment_entry.clear_unallocated_reference_document_rows()
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500697 payment_entry.setup_party_account_field()
698 payment_entry.set_missing_values()
ruthra kumared14d1c2023-04-22 17:24:35 +0530699 if not skip_ref_details_update_for_pe:
700 payment_entry.set_missing_ref_details()
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500701 payment_entry.set_amounts()
ruthra kumar7e600a62023-10-22 20:26:45 +0530702 payment_entry.make_exchange_gain_loss_journal(
703 frappe._dict({"difference_posting_date": d.difference_posting_date})
704 )
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500705
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530706 if not do_not_save:
707 payment_entry.save(ignore_permissions=True)
ruthra kumarecb533c2023-11-28 17:04:07 +0530708 return row
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530709
Ankush Menat494bd9e2022-03-28 18:52:46 +0530710
ruthra kumar5dbcf7d2023-09-05 09:52:36 +0530711def cancel_exchange_gain_loss_journal(
712 parent_doc: dict | object, referenced_dt: str = None, referenced_dn: str = None
713) -> None:
ruthra kumar81cd7872023-04-27 09:46:54 +0530714 """
715 Cancel Exchange Gain/Loss for Sales/Purchase Invoice, if they have any.
716 """
ruthra kumar6e18bb62023-07-11 12:21:10 +0530717 if parent_doc.doctype in ["Sales Invoice", "Purchase Invoice", "Payment Entry", "Journal Entry"]:
ruthra kumar81cd7872023-04-27 09:46:54 +0530718 journals = frappe.db.get_all(
719 "Journal Entry Account",
720 filters={
721 "reference_type": parent_doc.doctype,
722 "reference_name": parent_doc.name,
723 "docstatus": 1,
724 },
725 fields=["parent"],
726 as_list=1,
727 )
ruthra kumard9d68562023-07-27 08:02:46 +0530728
ruthra kumar81cd7872023-04-27 09:46:54 +0530729 if journals:
ruthra kumard9d68562023-07-27 08:02:46 +0530730 gain_loss_journals = frappe.db.get_all(
ruthra kumar81cd7872023-04-27 09:46:54 +0530731 "Journal Entry",
732 filters={
733 "name": ["in", [x[0] for x in journals]],
734 "voucher_type": "Exchange Gain Or Loss",
735 "docstatus": 1,
736 },
737 as_list=1,
738 )
ruthra kumard9d68562023-07-27 08:02:46 +0530739 for doc in gain_loss_journals:
ruthra kumar5dbcf7d2023-09-05 09:52:36 +0530740 gain_loss_je = frappe.get_doc("Journal Entry", doc[0])
741 if referenced_dt and referenced_dn:
742 references = [(x.reference_type, x.reference_name) for x in gain_loss_je.accounts]
743 if (
744 len(references) == 2
745 and (referenced_dt, referenced_dn) in references
746 and (parent_doc.doctype, parent_doc.name) in references
747 ):
748 # only cancel JE generated against parent_doc and referenced_dn
749 gain_loss_je.cancel()
750 else:
751 gain_loss_je.cancel()
ruthra kumar81cd7872023-04-27 09:46:54 +0530752
753
ruthra kumar9b6eac22023-08-30 16:44:25 +0530754def update_accounting_ledgers_after_reference_removal(
755 ref_type: str = None, ref_no: str = None, payment_name: str = None
756):
ruthra kumar0130aea2023-08-30 13:25:23 +0530757 # General Ledger
758 gle = qb.DocType("GL Entry")
ruthra kumar9b6eac22023-08-30 16:44:25 +0530759 gle_update_query = (
760 qb.update(gle)
761 .set(gle.against_voucher_type, None)
762 .set(gle.against_voucher, None)
763 .set(gle.modified, now())
764 .set(gle.modified_by, frappe.session.user)
765 .where((gle.against_voucher_type == ref_type) & (gle.against_voucher == ref_no))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530766 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530767
ruthra kumar9b6eac22023-08-30 16:44:25 +0530768 if payment_name:
769 gle_update_query = gle_update_query.where(gle.voucher_no == payment_name)
770 gle_update_query.run()
Nabin Hait297d74a2016-11-23 15:58:51 +0530771
ruthra kumar0130aea2023-08-30 13:25:23 +0530772 # Payment Ledger
ruthra kumar537d9532022-10-10 10:17:19 +0530773 ple = qb.DocType("Payment Ledger Entry")
ruthra kumar9b6eac22023-08-30 16:44:25 +0530774 ple_update_query = (
775 qb.update(ple)
776 .set(ple.against_voucher_type, ple.voucher_type)
777 .set(ple.against_voucher_no, ple.voucher_no)
778 .set(ple.modified, now())
779 .set(ple.modified_by, frappe.session.user)
780 .where(
781 (ple.against_voucher_type == ref_type)
782 & (ple.against_voucher_no == ref_no)
783 & (ple.delinked == 0)
784 )
785 )
ruthra kumar537d9532022-10-10 10:17:19 +0530786
ruthra kumar9b6eac22023-08-30 16:44:25 +0530787 if payment_name:
788 ple_update_query = ple_update_query.where(ple.voucher_no == payment_name)
789 ple_update_query.run()
ruthra kumar537d9532022-10-10 10:17:19 +0530790
ruthra kumar0130aea2023-08-30 13:25:23 +0530791
792def remove_ref_from_advance_section(ref_doc: object = None):
ruthra kumar9b6eac22023-08-30 16:44:25 +0530793 # TODO: this might need some testing
Nabin Hait297d74a2016-11-23 15:58:51 +0530794 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
795 ref_doc.set("advances", [])
ruthra kumar0130aea2023-08-30 13:25:23 +0530796 adv_type = qb.DocType(f"{ref_doc.doctype} Advance")
797 qb.from_(adv_type).delete().where(adv_type.parent == ref_doc.name).run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530798
Anand Doshicd71e1d2014-04-08 13:53:35 +0530799
ruthra kumar9b6eac22023-08-30 16:44:25 +0530800def unlink_ref_doc_from_payment_entries(ref_doc: object = None, payment_name: str = None):
801 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name, payment_name)
802 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name, payment_name)
803 update_accounting_ledgers_after_reference_removal(ref_doc.doctype, ref_doc.name, payment_name)
804 remove_ref_from_advance_section(ref_doc)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530805
Rushabh Mehta1828c122015-08-10 17:04:07 +0530806
ruthra kumar9b6eac22023-08-30 16:44:25 +0530807def remove_ref_doc_link_from_jv(
808 ref_type: str = None, ref_no: str = None, payment_name: str = None
809):
ruthra kumar0130aea2023-08-30 13:25:23 +0530810 jea = qb.DocType("Journal Entry Account")
811
812 linked_jv = (
813 qb.from_(jea)
814 .select(jea.parent)
ruthra kumar9a1588f2023-08-30 20:50:16 +0530815 .where((jea.reference_type == ref_type) & (jea.reference_name == ref_no) & (jea.docstatus.lt(2)))
ruthra kumar0130aea2023-08-30 13:25:23 +0530816 .run(as_list=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530817 )
ruthra kumar0130aea2023-08-30 13:25:23 +0530818 linked_jv = convert_to_list(linked_jv)
ruthra kumar9b6eac22023-08-30 16:44:25 +0530819 # remove reference only from specified payment
820 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 +0530821
822 if linked_jv:
ruthra kumar9b6eac22023-08-30 16:44:25 +0530823 update_query = (
824 qb.update(jea)
825 .set(jea.reference_type, None)
826 .set(jea.reference_name, None)
827 .set(jea.modified, now())
828 .set(jea.modified_by, frappe.session.user)
829 .where((jea.reference_type == ref_type) & (jea.reference_name == ref_no))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530830 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530831
ruthra kumar9b6eac22023-08-30 16:44:25 +0530832 if payment_name:
833 update_query = update_query.where(jea.parent == payment_name)
834
835 update_query.run()
Anand Doshi7da72dd2013-03-20 17:00:41 +0530836
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530837 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530838
Ankush Menat494bd9e2022-03-28 18:52:46 +0530839
ruthra kumar0130aea2023-08-30 13:25:23 +0530840def convert_to_list(result):
841 """
842 Convert tuple to list
843 """
844 return [x[0] for x in result]
845
846
ruthra kumar9b6eac22023-08-30 16:44:25 +0530847def remove_ref_doc_link_from_pe(
848 ref_type: str = None, ref_no: str = None, payment_name: str = None
849):
ruthra kumar0130aea2023-08-30 13:25:23 +0530850 per = qb.DocType("Payment Entry Reference")
851 pay = qb.DocType("Payment Entry")
852
853 linked_pe = (
854 qb.from_(per)
855 .select(per.parent)
856 .where(
857 (per.reference_doctype == ref_type) & (per.reference_name == ref_no) & (per.docstatus.lt(2))
858 )
859 .run(as_list=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530860 )
ruthra kumar0130aea2023-08-30 13:25:23 +0530861 linked_pe = convert_to_list(linked_pe)
ruthra kumar9b6eac22023-08-30 16:44:25 +0530862 # remove reference only from specified payment
863 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 +0530864
Nabin Haite0cc87d2016-07-21 18:30:03 +0530865 if linked_pe:
ruthra kumar9b6eac22023-08-30 16:44:25 +0530866 update_query = (
867 qb.update(per)
868 .set(per.allocated_amount, 0)
869 .set(per.modified, now())
870 .set(per.modified_by, frappe.session.user)
871 .where(
872 (per.docstatus.lt(2) & (per.reference_doctype == ref_type) & (per.reference_name == ref_no))
873 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530874 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530875
ruthra kumar9b6eac22023-08-30 16:44:25 +0530876 if payment_name:
877 update_query = update_query.where(per.parent == payment_name)
878
879 update_query.run()
Nabin Haite0cc87d2016-07-21 18:30:03 +0530880
881 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530882 try:
Deepesh Garg1894dc82023-06-23 21:53:34 +0530883 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530884 pe_doc.set_amounts()
ruthra kumarecb533c2023-11-28 17:04:07 +0530885
886 # Call cancel on only removed reference
887 references = [
888 x for x in pe_doc.references if x.reference_doctype == ref_type and x.reference_name == ref_no
889 ]
890 [pe_doc.make_advance_gl_entries(x, cancel=1) for x in references]
891
Deepesh Gargb5162392021-08-10 14:52:24 +0530892 pe_doc.clear_unallocated_reference_document_rows()
893 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530894 except Exception as e:
895 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530896 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530897 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530898 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530899
ruthra kumar0130aea2023-08-30 13:25:23 +0530900 qb.update(pay).set(pay.total_allocated_amount, pe_doc.total_allocated_amount).set(
901 pay.base_total_allocated_amount, pe_doc.base_total_allocated_amount
902 ).set(pay.unallocated_amount, pe_doc.unallocated_amount).set(pay.modified, now()).set(
903 pay.modified_by, frappe.session.user
904 ).where(
905 pay.name == pe
906 ).run()
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530907
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530908 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530909
Ankush Menat494bd9e2022-03-28 18:52:46 +0530910
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530911@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530912def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530913 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530914
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530915 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530916 throw(
917 _("Please set default {0} in Company {1}").format(
918 frappe.get_meta("Company").get_label(fieldname), company
919 )
920 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530921
Nabin Hait0fc24542013-03-25 11:06:00 +0530922 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530923
Ankush Menat494bd9e2022-03-28 18:52:46 +0530924
Nabin Hait8b509f52013-05-28 16:52:30 +0530925def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530926 vouchers = frappe.db.sql(
927 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530928 sum(debit) - sum(credit) as diff
929 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530930 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530931 having sum(debit) != sum(credit)""",
932 as_dict=1,
933 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530934
Nabin Hait8b509f52013-05-28 16:52:30 +0530935 for d in vouchers:
936 if abs(d.diff) > 0:
937 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530938
Ankush Menat494bd9e2022-03-28 18:52:46 +0530939 frappe.db.sql(
940 """update `tabGL Entry` set %s = %s + %s
941 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
942 % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
943 (d.diff, d.voucher_type, d.voucher_no),
944 )
945
Anand Doshicd71e1d2014-04-08 13:53:35 +0530946
Rushabh Mehtad50da782017-07-28 11:39:01 +0530947def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530948 precision = cint(frappe.db.get_default("currency_precision"))
949 if not precision:
950 number_format = frappe.db.get_default("number_format") or "#,###.##"
951 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530952
Nabin Hait9b20e072017-04-25 12:10:24 +0530953 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530954
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530955
Ankush Menat494bd9e2022-03-28 18:52:46 +0530956def get_stock_rbnb_difference(posting_date, company):
957 stock_items = frappe.db.sql_list(
958 """select distinct item_code
959 from `tabStock Ledger Entry` where company=%s""",
960 company,
961 )
962
963 pr_valuation_amount = frappe.db.sql(
964 """
Anand Doshi602e8252015-11-16 19:05:46 +0530965 select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530966 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
Suraj Shetty084b0b32018-05-26 09:12:59 +0530967 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530968 and pr.posting_date <= %s and pr_item.item_code in (%s)"""
969 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
970 tuple([company, posting_date] + stock_items),
971 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530972
Ankush Menat494bd9e2022-03-28 18:52:46 +0530973 pi_valuation_amount = frappe.db.sql(
974 """
Anand Doshi602e8252015-11-16 19:05:46 +0530975 select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530976 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
Suraj Shetty084b0b32018-05-26 09:12:59 +0530977 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530978 and pi.posting_date <= %s and pi_item.item_code in (%s)"""
979 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
980 tuple([company, posting_date] + stock_items),
981 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530982
983 # Balance should be
984 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
985
986 # Balance as per system
Ankush Menat494bd9e2022-03-28 18:52:46 +0530987 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.get_cached_value(
988 "Company", company, "abbr"
989 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530990 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530991
992 # Amount should be credited
993 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530994
tundec4b0d172017-09-26 00:48:30 +0100995
tundebabzyad08d4c2018-05-16 07:01:41 +0100996def get_held_invoices(party_type, party):
997 """
998 Returns a list of names Purchase Invoices for the given party that are on hold
999 """
1000 held_invoices = None
1001
Ankush Menat494bd9e2022-03-28 18:52:46 +05301002 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +01001003 held_invoices = frappe.db.sql(
mergify[bot]872a23c2023-07-10 20:34:54 +05301004 "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 +05301005 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +01001006 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05301007 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +01001008
1009 return held_invoices
1010
1011
ruthra kumar8c876742022-06-14 17:46:04 +05301012def get_outstanding_invoices(
ruthra kumar5f1562c2022-07-28 11:57:27 +05301013 party_type,
1014 party,
1015 account,
1016 common_filter=None,
1017 posting_date=None,
1018 min_outstanding=None,
1019 max_outstanding=None,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301020 accounting_dimensions=None,
Deepesh Garg299e32b2023-08-24 18:02:06 +05301021 vouchers=None, # list of dicts [{'voucher_type': '', 'voucher_no': ''}] for filtering
1022 limit=None, # passed by reconciliation tool
1023 voucher_no=None, # filter passed by reconciliation tool
ruthra kumar8c876742022-06-14 17:46:04 +05301024):
1025
1026 ple = qb.DocType("Payment Ledger Entry")
Anand Doshid40d1e92015-11-12 17:05:29 +05301027 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +05301028 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +05301029
Nabin Hait9db9edc2019-11-19 18:44:32 +05301030 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301031 root_type, account_type = frappe.get_cached_value(
1032 "Account", account, ["root_type", "account_type"]
1033 )
Nabin Hait9db9edc2019-11-19 18:44:32 +05301034 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +05301035 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +05301036 else:
1037 party_account_type = erpnext.get_party_account_type(party_type)
1038
tundebabzyad08d4c2018-05-16 07:01:41 +01001039 held_invoices = get_held_invoices(party_type, party)
1040
ruthra kumar8c876742022-06-14 17:46:04 +05301041 common_filter = common_filter or []
1042 common_filter.append(ple.account_type == party_account_type)
1043 common_filter.append(ple.account == account)
1044 common_filter.append(ple.party_type == party_type)
1045 common_filter.append(ple.party == party)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +05301046
ruthra kumar8c876742022-06-14 17:46:04 +05301047 ple_query = QueryPaymentLedger()
1048 invoice_list = ple_query.get_voucher_outstandings(
ruthra kumardeb0d712023-08-15 05:17:01 +05301049 vouchers=vouchers,
ruthra kumar8c876742022-06-14 17:46:04 +05301050 common_filter=common_filter,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301051 posting_date=posting_date,
ruthra kumar8c876742022-06-14 17:46:04 +05301052 min_outstanding=min_outstanding,
1053 max_outstanding=max_outstanding,
1054 get_invoices=True,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301055 accounting_dimensions=accounting_dimensions or [],
ruthra kumar7a381af2023-05-03 20:45:12 +05301056 limit=limit,
1057 voucher_no=voucher_no,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301058 )
tundec4b0d172017-09-26 00:48:30 +01001059
Nabin Haitac184982019-02-04 21:13:43 +05301060 for d in invoice_list:
ruthra kumar21985532022-06-30 15:14:38 +05301061 payment_amount = d.invoice_amount_in_account_currency - d.outstanding_in_account_currency
1062 outstanding_amount = d.outstanding_in_account_currency
Nabin Haitac184982019-02-04 21:13:43 +05301063 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301064 if (
ruthra kumar8c876742022-06-14 17:46:04 +05301065 min_outstanding
1066 and max_outstanding
barredterraeb9ee3f2023-12-05 11:22:55 +01001067 and (outstanding_amount < min_outstanding or outstanding_amount > max_outstanding)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301068 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +05301069 continue
Nabin Haitac184982019-02-04 21:13:43 +05301070
barredterraeb9ee3f2023-12-05 11:22:55 +01001071 if d.voucher_type != "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +05301072 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301073 frappe._dict(
1074 {
1075 "voucher_no": d.voucher_no,
1076 "voucher_type": d.voucher_type,
1077 "posting_date": d.posting_date,
ruthra kumar21985532022-06-30 15:14:38 +05301078 "invoice_amount": flt(d.invoice_amount_in_account_currency),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301079 "payment_amount": payment_amount,
1080 "outstanding_amount": outstanding_amount,
1081 "due_date": d.due_date,
1082 "currency": d.currency,
Gursheen Anand4ee16372023-06-08 13:15:23 +05301083 "account": d.account,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301084 }
1085 )
Nabin Haitac184982019-02-04 21:13:43 +05301086 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +05301087
Ankush Menat494bd9e2022-03-28 18:52:46 +05301088 outstanding_invoices = sorted(
1089 outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
1090 )
Anand Doshid40d1e92015-11-12 17:05:29 +05301091 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +05301092
1093
Ankush Menat494bd9e2022-03-28 18:52:46 +05301094def get_account_name(
1095 account_type=None, root_type=None, is_group=None, account_currency=None, company=None
1096):
Saurabh3a268292016-02-22 15:18:40 +05301097 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301098 return frappe.db.get_value(
1099 "Account",
1100 {
1101 "account_type": account_type or "",
1102 "root_type": root_type or "",
1103 "is_group": is_group or 0,
1104 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
1105 "company": company or frappe.defaults.get_defaults().company,
1106 },
1107 "name",
1108 )
1109
Saurabha9ba7342016-06-21 12:33:12 +05301110
1111@frappe.whitelist()
1112def get_companies():
1113 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301114 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
1115
Saurabha9ba7342016-06-21 12:33:12 +05301116
1117@frappe.whitelist()
Rushabh Mehta43133262017-11-10 18:52:21 +05301118def get_children(doctype, parent, company, is_root=False):
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]]
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +05301124
Ankush Menat494bd9e2022-03-28 18:52:46 +05301125 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301126
Rushabh Mehta43133262017-11-10 18:52:21 +05301127 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301128 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
1129 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301130
Saurabha9ba7342016-06-21 12:33:12 +05301131 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301132 fields += ["root_type", "account_currency"] if doctype == "Account" else []
1133 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +05301134
1135 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +05301136
Ankush Menat494bd9e2022-03-28 18:52:46 +05301137 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +05301138 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +05301139
1140 return acc
Saurabhb835fef2016-09-09 11:19:22 +05301141
Ankush Menat494bd9e2022-03-28 18:52:46 +05301142
Saqib90517352021-10-04 11:44:46 +05301143@frappe.whitelist()
1144def get_account_balances(accounts, company):
1145
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301146 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +05301147 accounts = loads(accounts)
1148
1149 if not accounts:
1150 return []
1151
Ankush Menat494bd9e2022-03-28 18:52:46 +05301152 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +05301153
1154 for account in accounts:
1155 account["company_currency"] = company_currency
Ankush Menat494bd9e2022-03-28 18:52:46 +05301156 account["balance"] = flt(
1157 get_balance_on(account["value"], in_account_currency=False, company=company)
1158 )
Saqib90517352021-10-04 11:44:46 +05301159 if account["account_currency"] and account["account_currency"] != company_currency:
1160 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
1161
1162 return accounts
1163
Ankush Menat494bd9e2022-03-28 18:52:46 +05301164
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +05301165def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +05301166 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +05301167
Daizy Modifdfe5cb2022-11-17 19:14:10 +05301168 company = frappe.get_cached_value("Global Defaults", "Global Defaults", "default_company")
Saurabhb835fef2016-09-09 11:19:22 +05301169 if not company:
1170 return
1171
1172 # 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 +05301173 bank_account = frappe.db.get_value(
1174 "Account",
1175 {"account_name": _(gateway), "company": company},
1176 ["name", "account_currency"],
1177 as_dict=1,
1178 )
Saurabhb835fef2016-09-09 11:19:22 +05301179
1180 if not bank_account:
1181 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301182 bank_account = frappe.db.get_value(
1183 "Account",
1184 {"account_name": gateway, "company": company},
1185 ["name", "account_currency"],
1186 as_dict=1,
1187 )
Saurabhb835fef2016-09-09 11:19:22 +05301188
1189 if not bank_account:
1190 # try creating one
1191 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1192
1193 if not bank_account:
1194 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1195 return
1196
1197 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301198 if frappe.db.exists(
1199 "Payment Gateway Account",
1200 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1201 ):
Saurabhb835fef2016-09-09 11:19:22 +05301202 return
1203
1204 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301205 frappe.get_doc(
1206 {
1207 "doctype": "Payment Gateway Account",
1208 "is_default": 1,
1209 "payment_gateway": gateway,
1210 "payment_account": bank_account.name,
1211 "currency": bank_account.account_currency,
1212 "payment_channel": payment_channel,
1213 }
1214 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301215
1216 except frappe.DuplicateEntryError:
1217 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001218 pass
Zarrar44175902018-06-08 16:35:21 +05301219
Ankush Menat494bd9e2022-03-28 18:52:46 +05301220
Zarrar44175902018-06-08 16:35:21 +05301221@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301222def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301223 """
1224 Renames the document by adding the number as a prefix to the current name and updates
1225 all transaction where it was present.
1226 """
Saqiba8779872020-04-30 11:28:43 +05301227 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301228
Saqiba8779872020-04-30 11:28:43 +05301229 if cost_center_number:
1230 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1231 else:
1232 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301233
Saqiba8779872020-04-30 11:28:43 +05301234 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301235
Nabin Haitaf21a112022-09-15 12:09:18 +05301236 new_name = get_autoname_with_number(cost_center_number, cost_center_name, company)
Saqiba8779872020-04-30 11:28:43 +05301237 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301238 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301239 return new_name
1240
Ankush Menat494bd9e2022-03-28 18:52:46 +05301241
Saqiba8779872020-04-30 11:28:43 +05301242def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301243 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301244 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301245 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301246 if company:
Saqiba8779872020-04-30 11:28:43 +05301247 filters["company"] = company
1248
1249 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1250
Zarrar44175902018-06-08 16:35:21 +05301251 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301252 frappe.throw(
1253 _("{0} Number {1} is already used in {2} {3}").format(
1254 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1255 )
1256 )
1257
Zarrar44175902018-06-08 16:35:21 +05301258
Nabin Haitaf21a112022-09-15 12:09:18 +05301259def get_autoname_with_number(number_value, doc_title, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301260 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Nabin Haitaf21a112022-09-15 12:09:18 +05301261 company_abbr = frappe.get_cached_value("Company", company, "abbr")
1262 parts = [doc_title.strip(), company_abbr]
1263
Zlash651aeca1d2018-07-06 17:15:33 +05301264 if cstr(number_value).strip():
1265 parts.insert(0, cstr(number_value).strip())
Nabin Haitaf21a112022-09-15 12:09:18 +05301266
Ankush Menat494bd9e2022-03-28 18:52:46 +05301267 return " - ".join(parts)
1268
Zarrar254ce642018-06-28 14:15:34 +05301269
Deepesh Garg62706072023-07-16 12:58:42 +05301270def parse_naming_series_variable(doc, variable):
1271 if variable == "FY":
Gughan Ravikumar89d109e2023-07-27 23:12:11 +05301272 if doc:
1273 date = doc.get("posting_date") or doc.get("transaction_date")
1274 company = doc.get("company")
1275 else:
1276 date = getdate()
1277 company = None
Gughan Ravikumarcdf100d2023-08-15 09:38:29 +05301278 return get_fiscal_year(date=date, company=company)[0]
Deepesh Garg62706072023-07-16 12:58:42 +05301279
1280
Zarrar254ce642018-06-28 14:15:34 +05301281@frappe.whitelist()
David Arnoldd066b5c2023-07-23 22:43:41 -05001282def get_coa(doctype, parent, is_root=None, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301283 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1284 build_tree_from_json,
1285 )
Zarrar254ce642018-06-28 14:15:34 +05301286
1287 # add chart to flags to retrieve when called from expand all function
1288 chart = chart if chart else frappe.flags.chart
1289 frappe.flags.chart = chart
1290
Ankush Menat494bd9e2022-03-28 18:52:46 +05301291 parent = None if parent == _("All Accounts") else parent
1292 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301293
1294 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301295 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301296
1297 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001298
Ankush Menat494bd9e2022-03-28 18:52:46 +05301299
1300def update_gl_entries_after(
1301 posting_date,
1302 posting_time,
1303 for_warehouses=None,
1304 for_items=None,
1305 warehouse_account=None,
1306 company=None,
1307):
1308 stock_vouchers = get_future_stock_vouchers(
1309 posting_date, posting_time, for_warehouses, for_items, company
1310 )
Nabin Hait9b178bc2021-02-16 14:57:00 +05301311 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1312
1313
Ankush Menat494bd9e2022-03-28 18:52:46 +05301314def repost_gle_for_stock_vouchers(
Ankush Menat2535d5e2022-06-14 18:20:33 +05301315 stock_vouchers: List[Tuple[str, str]],
1316 posting_date: str,
1317 company: Optional[str] = None,
1318 warehouse_account=None,
1319 repost_doc: Optional["RepostItemValuation"] = None,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301320):
Ankush Menat67c26322022-06-04 14:46:35 +05301321
1322 from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative
1323
Ankush Menat700e8642022-04-19 13:24:29 +05301324 if not stock_vouchers:
1325 return
1326
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301327 if not warehouse_account:
1328 warehouse_account = get_warehouse_account_map(company)
1329
Ankush Menat2535d5e2022-06-14 18:20:33 +05301330 stock_vouchers = sort_stock_vouchers_by_posting_date(stock_vouchers)
1331 if repost_doc and repost_doc.gl_reposting_index:
1332 # Restore progress
1333 stock_vouchers = stock_vouchers[cint(repost_doc.gl_reposting_index) :]
1334
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301335 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1336
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301337 for stock_vouchers_chunk in create_batch(stock_vouchers, GL_REPOSTING_CHUNK):
Ankush Menat2535d5e2022-06-14 18:20:33 +05301338 gle = get_voucherwise_gl_entries(stock_vouchers_chunk, posting_date)
1339
1340 for voucher_type, voucher_no in stock_vouchers_chunk:
1341 existing_gle = gle.get((voucher_type, voucher_no), [])
1342 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
1343 # Some transactions post credit as negative debit, this is handled while posting GLE
1344 # but while comparing we need to make sure it's flipped so comparisons are accurate
1345 expected_gle = toggle_debit_credit_if_negative(voucher_obj.get_gl_entries(warehouse_account))
1346 if expected_gle:
1347 if not existing_gle or not compare_existing_and_expected_gle(
1348 existing_gle, expected_gle, precision
1349 ):
ruthra kumar9209ec52022-10-21 15:18:40 +05301350 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301351 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
1352 else:
ruthra kumar9209ec52022-10-21 15:18:40 +05301353 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat86919d22022-06-15 21:19:09 +05301354
1355 if not frappe.flags.in_test:
1356 frappe.db.commit()
Ankush Menat2535d5e2022-06-14 18:20:33 +05301357
1358 if repost_doc:
1359 repost_doc.db_set(
1360 "gl_reposting_index",
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301361 cint(repost_doc.gl_reposting_index) + len(stock_vouchers_chunk),
Ankush Menat2535d5e2022-06-14 18:20:33 +05301362 )
1363
1364
ruthra kumar9209ec52022-10-21 15:18:40 +05301365def _delete_pl_entries(voucher_type, voucher_no):
ruthra kumar65992302022-10-04 16:17:56 +05301366 ple = qb.DocType("Payment Ledger Entry")
1367 qb.from_(ple).delete().where(
1368 (ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)
1369 ).run()
Ankush Menateb53a972022-06-04 18:19:44 +05301370
Ankush Menat494bd9e2022-03-28 18:52:46 +05301371
ruthra kumar9209ec52022-10-21 15:18:40 +05301372def _delete_gl_entries(voucher_type, voucher_no):
1373 gle = qb.DocType("GL Entry")
1374 qb.from_(gle).delete().where(
1375 (gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)
1376 ).run()
1377
1378
1379def _delete_accounting_ledger_entries(voucher_type, voucher_no):
1380 """
1381 Remove entries from both General and Payment Ledger for specified Voucher
1382 """
1383 _delete_gl_entries(voucher_type, voucher_no)
1384 _delete_pl_entries(voucher_type, voucher_no)
1385
1386
Ankush Menat700e8642022-04-19 13:24:29 +05301387def sort_stock_vouchers_by_posting_date(
1388 stock_vouchers: List[Tuple[str, str]]
1389) -> List[Tuple[str, str]]:
1390 sle = frappe.qb.DocType("Stock Ledger Entry")
1391 voucher_nos = [v[1] for v in stock_vouchers]
1392
1393 sles = (
1394 frappe.qb.from_(sle)
1395 .select(sle.voucher_type, sle.voucher_no, sle.posting_date, sle.posting_time, sle.creation)
1396 .where((sle.is_cancelled == 0) & (sle.voucher_no.isin(voucher_nos)))
1397 .groupby(sle.voucher_type, sle.voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301398 .orderby(sle.posting_date)
1399 .orderby(sle.posting_time)
1400 .orderby(sle.creation)
Ankush Menat700e8642022-04-19 13:24:29 +05301401 ).run(as_dict=True)
1402 sorted_vouchers = [(sle.voucher_type, sle.voucher_no) for sle in sles]
1403
1404 unknown_vouchers = set(stock_vouchers) - set(sorted_vouchers)
1405 if unknown_vouchers:
1406 sorted_vouchers.extend(unknown_vouchers)
1407
1408 return sorted_vouchers
1409
1410
Ankush Menat494bd9e2022-03-28 18:52:46 +05301411def get_future_stock_vouchers(
1412 posting_date, posting_time, for_warehouses=None, for_items=None, company=None
1413):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301414
1415 values = []
1416 condition = ""
1417 if for_items:
1418 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1419 values += for_items
1420
1421 if for_warehouses:
1422 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1423 values += for_warehouses
1424
rohitwaghchaured60ff832021-02-16 09:12:27 +05301425 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301426 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301427 values.append(company)
1428
Ankush Menat494bd9e2022-03-28 18:52:46 +05301429 future_stock_vouchers = frappe.db.sql(
1430 """select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301431 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301432 where
1433 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1434 and is_cancelled = 0
1435 {condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301436 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
1437 condition=condition
1438 ),
1439 tuple([posting_date, posting_time] + values),
1440 as_dict=True,
1441 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301442
Ankush91527152021-08-11 11:17:50 +05301443 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301444
Ankush Menat494bd9e2022-03-28 18:52:46 +05301445
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301446def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301447 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301448
1449 Only fetches GLE fields required for comparing with new GLE.
1450 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301451
1452 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301453 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301454 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301455 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301456 if not future_stock_vouchers:
1457 return gl_entries
1458
1459 voucher_nos = [d[1] for d in future_stock_vouchers]
1460
Ankush Menat494bd9e2022-03-28 18:52:46 +05301461 gles = frappe.db.sql(
1462 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301463 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301464 from `tabGL Entry`
1465 where
Ankush Menat494bd9e2022-03-28 18:52:46 +05301466 posting_date >= %s and voucher_no in (%s)"""
1467 % ("%s", ", ".join(["%s"] * len(voucher_nos))),
1468 tuple([posting_date] + voucher_nos),
1469 as_dict=1,
1470 )
Ankush91527152021-08-11 11:17:50 +05301471
1472 for d in gles:
1473 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301474
Prssanna Desai82ddef52020-06-18 18:18:41 +05301475 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301476
Ankush Menat494bd9e2022-03-28 18:52:46 +05301477
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301478def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301479 if len(existing_gle) != len(expected_gle):
1480 return False
1481
Nabin Haita77b8c92020-12-21 14:45:50 +05301482 matched = True
1483 for entry in expected_gle:
1484 account_existed = False
1485 for e in existing_gle:
1486 if entry.account == e.account:
1487 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301488 if (
1489 entry.account == e.account
1490 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1491 and (
1492 flt(entry.debit, precision) != flt(e.debit, precision)
1493 or flt(entry.credit, precision) != flt(e.credit, precision)
1494 )
1495 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301496 matched = False
1497 break
1498 if not account_existed:
1499 matched = False
1500 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301501 return matched
1502
Ankush Menat494bd9e2022-03-28 18:52:46 +05301503
Nabin Haitb99c77b2020-12-25 18:12:35 +05301504def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301505 stock_accounts = [
1506 d.name
1507 for d in frappe.db.get_all(
1508 "Account", {"account_type": "Stock", "company": company, "is_group": 0}
1509 )
1510 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301511 if voucher_type and voucher_no:
1512 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301513 stock_accounts = [
1514 d.account
1515 for d in frappe.db.get_all(
1516 "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
1517 )
1518 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301519
1520 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301521 stock_accounts = [
1522 d.account
1523 for d in frappe.db.get_all(
1524 "GL Entry",
1525 {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
1526 "account",
1527 )
1528 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301529
1530 return stock_accounts
1531
Ankush Menat494bd9e2022-03-28 18:52:46 +05301532
Nabin Haitb99c77b2020-12-25 18:12:35 +05301533def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301534 if not posting_date:
1535 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301536
1537 warehouse_account = get_warehouse_account_map(company)
1538
Ankush Menat494bd9e2022-03-28 18:52:46 +05301539 account_balance = get_balance_on(
1540 account, posting_date, in_account_currency=False, ignore_account_permission=True
1541 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301542
Ankush Menat494bd9e2022-03-28 18:52:46 +05301543 related_warehouses = [
1544 wh
1545 for wh, wh_details in warehouse_account.items()
1546 if wh_details.account == account and not wh_details.is_group
1547 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301548
s-aga-re782a052023-04-25 13:54:36 +05301549 total_stock_value = get_stock_value_on(related_warehouses, posting_date)
Nabin Haitb99c77b2020-12-25 18:12:35 +05301550
1551 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1552 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1553
Ankush Menat494bd9e2022-03-28 18:52:46 +05301554
Nabin Haitb99c77b2020-12-25 18:12:35 +05301555def get_journal_entry(account, stock_adjustment_account, amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301556 db_or_cr_warehouse_account = (
1557 "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
1558 )
1559 db_or_cr_stock_adjustment_account = (
1560 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1561 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301562
1563 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301564 "accounts": [
1565 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1566 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1567 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301568 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301569
Ankush Menat494bd9e2022-03-28 18:52:46 +05301570
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301571def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301572 """Check if reports are referenced in Desktop Icon"""
1573 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301574 if icons:
1575 for icon in icons:
1576 frappe.delete_doc("Desktop Icon", icon)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301577
1578
ruthra kumar4f51c5a2023-07-03 14:35:33 +05301579def create_err_and_its_journals(companies: list = None) -> None:
1580 if companies:
1581 for company in companies:
1582 err = frappe.new_doc("Exchange Rate Revaluation")
1583 err.company = company.name
1584 err.posting_date = nowdate()
1585 err.rounding_loss_allowance = 0.0
1586
1587 err.fetch_and_calculate_accounts_data()
1588 if err.accounts:
1589 err.save().submit()
1590 response = err.make_jv_entries()
1591
1592 if company.submit_err_jv:
1593 jv = response.get("revaluation_jv", None)
1594 jv and frappe.get_doc("Journal Entry", jv).submit()
1595 jv = response.get("zero_balance_jv", None)
1596 jv and frappe.get_doc("Journal Entry", jv).submit()
1597
1598
1599def auto_create_exchange_rate_revaluation_daily() -> None:
1600 """
1601 Executed by background job
1602 """
1603 companies = frappe.db.get_all(
1604 "Company",
1605 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Daily"},
1606 fields=["name", "submit_err_jv"],
1607 )
1608 create_err_and_its_journals(companies)
1609
1610
1611def auto_create_exchange_rate_revaluation_weekly() -> None:
1612 """
1613 Executed by background job
1614 """
1615 companies = frappe.db.get_all(
1616 "Company",
1617 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Weekly"},
1618 fields=["name", "submit_err_jv"],
1619 )
1620 create_err_and_its_journals(companies)
1621
1622
ruthra kumar9b502212022-10-13 14:13:48 +05301623def get_payment_ledger_entries(gl_entries, cancel=0):
1624 ple_map = []
ruthra kumar451cf3a2022-05-16 14:29:58 +05301625 if gl_entries:
1626 ple = None
1627
1628 # companies
1629 account = qb.DocType("Account")
1630 companies = list(set([x.company for x in gl_entries]))
1631
1632 # receivable/payable account
1633 accounts_with_types = (
1634 qb.from_(account)
1635 .select(account.name, account.account_type)
1636 .where(
1637 (account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
1638 )
1639 .run(as_dict=True)
1640 )
1641 receivable_or_payable_accounts = [y.name for y in accounts_with_types]
1642
1643 def get_account_type(account):
1644 for entry in accounts_with_types:
1645 if entry.name == account:
1646 return entry.account_type
1647
1648 dr_or_cr = 0
1649 account_type = None
1650 for gle in gl_entries:
1651 if gle.account in receivable_or_payable_accounts:
1652 account_type = get_account_type(gle.account)
1653 if account_type == "Receivable":
1654 dr_or_cr = gle.debit - gle.credit
1655 dr_or_cr_account_currency = gle.debit_in_account_currency - gle.credit_in_account_currency
1656 elif account_type == "Payable":
1657 dr_or_cr = gle.credit - gle.debit
1658 dr_or_cr_account_currency = gle.credit_in_account_currency - gle.debit_in_account_currency
1659
1660 if cancel:
1661 dr_or_cr *= -1
1662 dr_or_cr_account_currency *= -1
1663
ruthra kumar9b502212022-10-13 14:13:48 +05301664 ple = frappe._dict(
1665 doctype="Payment Ledger Entry",
1666 posting_date=gle.posting_date,
1667 company=gle.company,
1668 account_type=account_type,
1669 account=gle.account,
1670 party_type=gle.party_type,
1671 party=gle.party,
1672 cost_center=gle.cost_center,
1673 finance_book=gle.finance_book,
1674 due_date=gle.due_date,
1675 voucher_type=gle.voucher_type,
1676 voucher_no=gle.voucher_no,
Deepesh Garg1e078d02023-06-29 12:18:25 +05301677 voucher_detail_no=gle.voucher_detail_no,
ruthra kumar9b502212022-10-13 14:13:48 +05301678 against_voucher_type=gle.against_voucher_type
1679 if gle.against_voucher_type
1680 else gle.voucher_type,
1681 against_voucher_no=gle.against_voucher if gle.against_voucher else gle.voucher_no,
1682 account_currency=gle.account_currency,
1683 amount=dr_or_cr,
1684 amount_in_account_currency=dr_or_cr_account_currency,
1685 delinked=True if cancel else False,
1686 remarks=gle.remarks,
ruthra kumar451cf3a2022-05-16 14:29:58 +05301687 )
1688
1689 dimensions_and_defaults = get_dimensions()
1690 if dimensions_and_defaults:
1691 for dimension in dimensions_and_defaults[0]:
ruthra kumar9b502212022-10-13 14:13:48 +05301692 ple[dimension.fieldname] = gle.get(dimension.fieldname)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301693
ruthra kumar9b502212022-10-13 14:13:48 +05301694 ple_map.append(ple)
1695 return ple_map
1696
1697
1698def create_payment_ledger_entry(
Deepesh Garg1e078d02023-06-29 12:18:25 +05301699 gl_entries, cancel=0, adv_adj=0, update_outstanding="Yes", from_repost=0, partial_cancel=False
ruthra kumar9b502212022-10-13 14:13:48 +05301700):
1701 if gl_entries:
1702 ple_map = get_payment_ledger_entries(gl_entries, cancel=cancel)
1703
1704 for entry in ple_map:
1705
1706 ple = frappe.get_doc(entry)
1707
1708 if cancel:
Deepesh Garg1e078d02023-06-29 12:18:25 +05301709 delink_original_entry(ple, partial_cancel=partial_cancel)
ruthra kumar9b502212022-10-13 14:13:48 +05301710
1711 ple.flags.ignore_permissions = 1
1712 ple.flags.adv_adj = adv_adj
1713 ple.flags.from_repost = from_repost
1714 ple.flags.update_outstanding = update_outstanding
1715 ple.submit()
ruthra kumar451cf3a2022-05-16 14:29:58 +05301716
1717
ruthra kumar7312f222022-05-29 21:33:08 +05301718def update_voucher_outstanding(voucher_type, voucher_no, account, party_type, party):
1719 ple = frappe.qb.DocType("Payment Ledger Entry")
1720 vouchers = [frappe._dict({"voucher_type": voucher_type, "voucher_no": voucher_no})]
1721 common_filter = []
1722 if account:
1723 common_filter.append(ple.account == account)
1724
1725 if party_type:
1726 common_filter.append(ple.party_type == party_type)
1727
1728 if party:
1729 common_filter.append(ple.party == party)
1730
1731 ple_query = QueryPaymentLedger()
1732
1733 # on cancellation outstanding can be an empty list
1734 voucher_outstanding = ple_query.get_voucher_outstandings(vouchers, common_filter=common_filter)
ruthra kumar43b80682022-10-18 09:33:37 +05301735 if (
1736 voucher_type in ["Sales Invoice", "Purchase Invoice", "Fees"]
1737 and party_type
1738 and party
1739 and voucher_outstanding
1740 ):
ruthra kumar7312f222022-05-29 21:33:08 +05301741 outstanding = voucher_outstanding[0]
1742 ref_doc = frappe.get_doc(voucher_type, voucher_no)
1743
1744 # Didn't use db_set for optimisation purpose
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301745 ref_doc.outstanding_amount = outstanding["outstanding_in_account_currency"] or 0.0
ruthra kumar7312f222022-05-29 21:33:08 +05301746 frappe.db.set_value(
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301747 voucher_type,
1748 voucher_no,
1749 "outstanding_amount",
1750 outstanding["outstanding_in_account_currency"] or 0.0,
ruthra kumar7312f222022-05-29 21:33:08 +05301751 )
1752
1753 ref_doc.set_status(update=True)
1754
1755
Deepesh Garg1e078d02023-06-29 12:18:25 +05301756def delink_original_entry(pl_entry, partial_cancel=False):
ruthra kumar451cf3a2022-05-16 14:29:58 +05301757 if pl_entry:
1758 ple = qb.DocType("Payment Ledger Entry")
1759 query = (
1760 qb.update(ple)
1761 .set(ple.delinked, True)
1762 .set(ple.modified, now())
1763 .set(ple.modified_by, frappe.session.user)
1764 .where(
1765 (ple.company == pl_entry.company)
1766 & (ple.account_type == pl_entry.account_type)
1767 & (ple.account == pl_entry.account)
1768 & (ple.party_type == pl_entry.party_type)
1769 & (ple.party == pl_entry.party)
1770 & (ple.voucher_type == pl_entry.voucher_type)
1771 & (ple.voucher_no == pl_entry.voucher_no)
1772 & (ple.against_voucher_type == pl_entry.against_voucher_type)
1773 & (ple.against_voucher_no == pl_entry.against_voucher_no)
1774 )
1775 )
Deepesh Garg1e078d02023-06-29 12:18:25 +05301776
1777 if partial_cancel:
1778 query = query.where(ple.voucher_detail_no == pl_entry.voucher_detail_no)
1779
ruthra kumar451cf3a2022-05-16 14:29:58 +05301780 query.run()
ruthra kumar7b383882022-05-25 15:51:16 +05301781
1782
1783class QueryPaymentLedger(object):
1784 """
1785 Helper Class for Querying Payment Ledger Entry
1786 """
1787
1788 def __init__(self):
1789 self.ple = qb.DocType("Payment Ledger Entry")
1790
1791 # query result
1792 self.voucher_outstandings = []
1793
1794 # query filters
1795 self.vouchers = []
1796 self.common_filter = []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301797 self.voucher_posting_date = []
ruthra kumar7b383882022-05-25 15:51:16 +05301798 self.min_outstanding = None
1799 self.max_outstanding = None
ruthra kumar7a381af2023-05-03 20:45:12 +05301800 self.limit = self.voucher_no = None
ruthra kumar7b383882022-05-25 15:51:16 +05301801
1802 def reset(self):
1803 # clear filters
1804 self.vouchers.clear()
1805 self.common_filter.clear()
ruthra kumar7a381af2023-05-03 20:45:12 +05301806 self.min_outstanding = self.max_outstanding = self.limit = None
ruthra kumar7b383882022-05-25 15:51:16 +05301807
1808 # clear result
1809 self.voucher_outstandings.clear()
1810
1811 def query_for_outstanding(self):
1812 """
1813 Database query to fetch voucher amount and voucher outstanding using Common Table Expression
1814 """
1815
1816 ple = self.ple
1817
1818 filter_on_voucher_no = []
1819 filter_on_against_voucher_no = []
ruthra kumar7a381af2023-05-03 20:45:12 +05301820
ruthra kumar7b383882022-05-25 15:51:16 +05301821 if self.vouchers:
1822 voucher_types = set([x.voucher_type for x in self.vouchers])
1823 voucher_nos = set([x.voucher_no for x in self.vouchers])
1824
1825 filter_on_voucher_no.append(ple.voucher_type.isin(voucher_types))
1826 filter_on_voucher_no.append(ple.voucher_no.isin(voucher_nos))
1827
1828 filter_on_against_voucher_no.append(ple.against_voucher_type.isin(voucher_types))
1829 filter_on_against_voucher_no.append(ple.against_voucher_no.isin(voucher_nos))
1830
ruthra kumar7a381af2023-05-03 20:45:12 +05301831 if self.voucher_no:
1832 filter_on_voucher_no.append(ple.voucher_no.like(f"%{self.voucher_no}%"))
1833 filter_on_against_voucher_no.append(ple.against_voucher_no.like(f"%{self.voucher_no}%"))
1834
ruthra kumar7b383882022-05-25 15:51:16 +05301835 # build outstanding amount filter
1836 filter_on_outstanding_amount = []
1837 if self.min_outstanding:
1838 if self.min_outstanding > 0:
1839 filter_on_outstanding_amount.append(
1840 Table("outstanding").amount_in_account_currency >= self.min_outstanding
1841 )
1842 else:
1843 filter_on_outstanding_amount.append(
1844 Table("outstanding").amount_in_account_currency <= self.min_outstanding
1845 )
1846 if self.max_outstanding:
1847 if self.max_outstanding > 0:
1848 filter_on_outstanding_amount.append(
1849 Table("outstanding").amount_in_account_currency <= self.max_outstanding
1850 )
1851 else:
1852 filter_on_outstanding_amount.append(
1853 Table("outstanding").amount_in_account_currency >= self.max_outstanding
1854 )
1855
ruthra kumar8b04c1d2023-11-22 09:59:32 +05301856 if self.limit and self.get_invoices:
1857 outstanding_vouchers = (
1858 qb.from_(ple)
1859 .select(
1860 ple.against_voucher_no.as_("voucher_no"),
1861 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1862 )
1863 .where(ple.delinked == 0)
1864 .where(Criterion.all(filter_on_against_voucher_no))
1865 .where(Criterion.all(self.common_filter))
ruthra kumarcfd32302023-11-30 12:22:55 +05301866 .where(Criterion.all(self.dimensions_filter))
1867 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar8b04c1d2023-11-22 09:59:32 +05301868 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1869 .orderby(ple.posting_date, ple.voucher_no)
1870 .having(qb.Field("amount_in_account_currency") > 0)
1871 .limit(self.limit)
1872 .run()
1873 )
1874 if outstanding_vouchers:
1875 filter_on_voucher_no.append(ple.voucher_no.isin([x[0] for x in outstanding_vouchers]))
1876 filter_on_against_voucher_no.append(
1877 ple.against_voucher_no.isin([x[0] for x in outstanding_vouchers])
1878 )
1879
ruthra kumar7b383882022-05-25 15:51:16 +05301880 # build query for voucher amount
1881 query_voucher_amount = (
1882 qb.from_(ple)
1883 .select(
1884 ple.account,
1885 ple.voucher_type,
1886 ple.voucher_no,
1887 ple.party_type,
1888 ple.party,
1889 ple.posting_date,
1890 ple.due_date,
1891 ple.account_currency.as_("currency"),
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301892 ple.cost_center.as_("cost_center"),
ruthra kumar7b383882022-05-25 15:51:16 +05301893 Sum(ple.amount).as_("amount"),
1894 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1895 )
1896 .where(ple.delinked == 0)
1897 .where(Criterion.all(filter_on_voucher_no))
1898 .where(Criterion.all(self.common_filter))
ruthra kumar6d9d7302022-12-14 16:05:15 +05301899 .where(Criterion.all(self.dimensions_filter))
ruthra kumar5f1562c2022-07-28 11:57:27 +05301900 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar7b383882022-05-25 15:51:16 +05301901 .groupby(ple.voucher_type, ple.voucher_no, ple.party_type, ple.party)
1902 )
1903
1904 # build query for voucher outstanding
1905 query_voucher_outstanding = (
1906 qb.from_(ple)
1907 .select(
1908 ple.account,
1909 ple.against_voucher_type.as_("voucher_type"),
1910 ple.against_voucher_no.as_("voucher_no"),
1911 ple.party_type,
1912 ple.party,
1913 ple.posting_date,
1914 ple.due_date,
1915 ple.account_currency.as_("currency"),
1916 Sum(ple.amount).as_("amount"),
1917 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1918 )
1919 .where(ple.delinked == 0)
1920 .where(Criterion.all(filter_on_against_voucher_no))
1921 .where(Criterion.all(self.common_filter))
1922 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1923 )
1924
1925 # build CTE for combining voucher amount and outstanding
1926 self.cte_query_voucher_amount_and_outstanding = (
1927 qb.with_(query_voucher_amount, "vouchers")
1928 .with_(query_voucher_outstanding, "outstanding")
1929 .from_(AliasedQuery("vouchers"))
1930 .left_join(AliasedQuery("outstanding"))
1931 .on(
1932 (AliasedQuery("vouchers").account == AliasedQuery("outstanding").account)
1933 & (AliasedQuery("vouchers").voucher_type == AliasedQuery("outstanding").voucher_type)
1934 & (AliasedQuery("vouchers").voucher_no == AliasedQuery("outstanding").voucher_no)
1935 & (AliasedQuery("vouchers").party_type == AliasedQuery("outstanding").party_type)
1936 & (AliasedQuery("vouchers").party == AliasedQuery("outstanding").party)
1937 )
1938 .select(
1939 Table("vouchers").account,
1940 Table("vouchers").voucher_type,
1941 Table("vouchers").voucher_no,
1942 Table("vouchers").party_type,
1943 Table("vouchers").party,
1944 Table("vouchers").posting_date,
1945 Table("vouchers").amount.as_("invoice_amount"),
1946 Table("vouchers").amount_in_account_currency.as_("invoice_amount_in_account_currency"),
1947 Table("outstanding").amount.as_("outstanding"),
1948 Table("outstanding").amount_in_account_currency.as_("outstanding_in_account_currency"),
1949 (Table("vouchers").amount - Table("outstanding").amount).as_("paid_amount"),
1950 (
1951 Table("vouchers").amount_in_account_currency - Table("outstanding").amount_in_account_currency
1952 ).as_("paid_amount_in_account_currency"),
1953 Table("vouchers").due_date,
1954 Table("vouchers").currency,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301955 Table("vouchers").cost_center.as_("cost_center"),
ruthra kumar7b383882022-05-25 15:51:16 +05301956 )
1957 .where(Criterion.all(filter_on_outstanding_amount))
1958 )
1959
1960 # build CTE filter
1961 # only fetch invoices
1962 if self.get_invoices:
1963 self.cte_query_voucher_amount_and_outstanding = (
1964 self.cte_query_voucher_amount_and_outstanding.having(
1965 qb.Field("outstanding_in_account_currency") > 0
1966 )
1967 )
1968 # only fetch payments
1969 elif self.get_payments:
1970 self.cte_query_voucher_amount_and_outstanding = (
1971 self.cte_query_voucher_amount_and_outstanding.having(
1972 qb.Field("outstanding_in_account_currency") < 0
1973 )
1974 )
1975
ruthra kumar7a381af2023-05-03 20:45:12 +05301976 if self.limit:
1977 self.cte_query_voucher_amount_and_outstanding = (
1978 self.cte_query_voucher_amount_and_outstanding.limit(self.limit)
1979 )
1980
ruthra kumar7b383882022-05-25 15:51:16 +05301981 # execute SQL
1982 self.voucher_outstandings = self.cte_query_voucher_amount_and_outstanding.run(as_dict=True)
1983
1984 def get_voucher_outstandings(
1985 self,
1986 vouchers=None,
1987 common_filter=None,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301988 posting_date=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301989 min_outstanding=None,
1990 max_outstanding=None,
1991 get_payments=False,
1992 get_invoices=False,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301993 accounting_dimensions=None,
ruthra kumar7a381af2023-05-03 20:45:12 +05301994 limit=None,
1995 voucher_no=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301996 ):
1997 """
1998 Fetch voucher amount and outstanding amount from Payment Ledger using Database CTE
1999
2000 vouchers - dict of vouchers to get
2001 common_filter - array of criterions
2002 min_outstanding - filter on minimum total outstanding amount
2003 max_outstanding - filter on maximum total outstanding amount
2004 get_invoices - only fetch vouchers(ledger entries with +ve outstanding)
2005 get_payments - only fetch payments(ledger entries with -ve outstanding)
2006 """
2007
2008 self.reset()
2009 self.vouchers = vouchers
2010 self.common_filter = common_filter or []
ruthra kumar6d9d7302022-12-14 16:05:15 +05302011 self.dimensions_filter = accounting_dimensions or []
ruthra kumar5f1562c2022-07-28 11:57:27 +05302012 self.voucher_posting_date = posting_date or []
ruthra kumar7b383882022-05-25 15:51:16 +05302013 self.min_outstanding = min_outstanding
2014 self.max_outstanding = max_outstanding
2015 self.get_payments = get_payments
2016 self.get_invoices = get_invoices
ruthra kumar7a381af2023-05-03 20:45:12 +05302017 self.limit = limit
2018 self.voucher_no = voucher_no
ruthra kumar7b383882022-05-25 15:51:16 +05302019 self.query_for_outstanding()
2020
2021 return self.voucher_outstandings
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302022
2023
2024def create_gain_loss_journal(
2025 company,
ruthra kumarf7865da2023-09-04 20:38:10 +05302026 posting_date,
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302027 party_type,
2028 party,
2029 party_account,
2030 gain_loss_account,
2031 exc_gain_loss,
2032 dr_or_cr,
2033 reverse_dr_or_cr,
2034 ref1_dt,
2035 ref1_dn,
2036 ref1_detail_no,
2037 ref2_dt,
2038 ref2_dn,
2039 ref2_detail_no,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05302040 cost_center,
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302041) -> str:
2042 journal_entry = frappe.new_doc("Journal Entry")
2043 journal_entry.voucher_type = "Exchange Gain Or Loss"
2044 journal_entry.company = company
ruthra kumarf7865da2023-09-04 20:38:10 +05302045 journal_entry.posting_date = posting_date or nowdate()
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302046 journal_entry.multi_currency = 1
ruthra kumar79c6f012023-09-01 14:57:12 +05302047 journal_entry.is_system_generated = True
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302048
2049 party_account_currency = frappe.get_cached_value("Account", party_account, "account_currency")
2050
2051 if not gain_loss_account:
2052 frappe.throw(_("Please set default Exchange Gain/Loss Account in Company {}").format(company))
2053 gain_loss_account_currency = get_account_currency(gain_loss_account)
2054 company_currency = frappe.get_cached_value("Company", company, "default_currency")
2055
2056 if gain_loss_account_currency != company_currency:
2057 frappe.throw(_("Currency for {0} must be {1}").format(gain_loss_account, company_currency))
2058
2059 journal_account = frappe._dict(
2060 {
2061 "account": party_account,
2062 "party_type": party_type,
2063 "party": party,
2064 "account_currency": party_account_currency,
2065 "exchange_rate": 0,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05302066 "cost_center": cost_center or erpnext.get_default_cost_center(company),
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302067 "reference_type": ref1_dt,
2068 "reference_name": ref1_dn,
2069 "reference_detail_no": ref1_detail_no,
2070 dr_or_cr: abs(exc_gain_loss),
2071 dr_or_cr + "_in_account_currency": 0,
2072 }
2073 )
2074
2075 journal_entry.append("accounts", journal_account)
2076
2077 journal_account = frappe._dict(
2078 {
2079 "account": gain_loss_account,
2080 "account_currency": gain_loss_account_currency,
2081 "exchange_rate": 1,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05302082 "cost_center": cost_center or erpnext.get_default_cost_center(company),
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05302083 "reference_type": ref2_dt,
2084 "reference_name": ref2_dn,
2085 "reference_detail_no": ref2_detail_no,
2086 reverse_dr_or_cr + "_in_account_currency": 0,
2087 reverse_dr_or_cr: abs(exc_gain_loss),
2088 }
2089 )
2090
2091 journal_entry.append("accounts", journal_account)
2092
2093 journal_entry.save()
2094 journal_entry.submit()
2095 return journal_entry.name
Gursheen Anand40157232023-11-03 11:58:25 +05302096
2097
2098def get_party_types_from_account_type(account_type):
Gursheen Anand2984a862023-11-08 12:30:24 +05302099 return frappe.db.get_all("Party Type", {"account_type": account_type}, pluck="name")