blob: 06d05cbbb6d313d7bec2b574ecf1bcbf43d10560 [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
13from frappe.query_builder.functions import 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):
Deepesh Garg0aadb682023-03-19 12:46:42 +053056 fiscal_years = get_fiscal_years(
57 date, fiscal_year, label, verbose, company, as_dict=as_dict, boolean=boolean
58 )
59 if boolean:
60 return fiscal_years
61 else:
62 return fiscal_years[0]
Nabin Hait23941aa2013-01-29 11:32:38 +053063
Ankush Menat494bd9e2022-03-28 18:52:46 +053064
65def get_fiscal_years(
Deepesh Garg0aadb682023-03-19 12:46:42 +053066 transaction_date=None,
67 fiscal_year=None,
68 label="Date",
69 verbose=1,
70 company=None,
71 as_dict=False,
72 boolean=False,
Ankush Menat494bd9e2022-03-28 18:52:46 +053073):
Nabin Hait9784d272016-12-30 16:21:35 +053074 fiscal_years = frappe.cache().hget("fiscal_years", company) or []
Rushabh Mehtad50da782017-07-28 11:39:01 +053075
76 if not fiscal_years:
Nabin Hait9784d272016-12-30 16:21:35 +053077 # 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 +053078 FY = DocType("Fiscal Year")
Nabin Haitfff3ab72015-01-14 16:27:13 +053079
Gavin D'souza0727d1d2022-06-13 12:39:28 +053080 query = (
81 frappe.qb.from_(FY)
82 .select(FY.name, FY.year_start_date, FY.year_end_date)
83 .where(FY.disabled == 0)
Ankush Menat494bd9e2022-03-28 18:52:46 +053084 )
Rushabh Mehtad50da782017-07-28 11:39:01 +053085
Gavin D'souza0727d1d2022-06-13 12:39:28 +053086 if fiscal_year:
87 query = query.where(FY.name == fiscal_year)
88
89 if company:
90 FYC = DocType("Fiscal Year Company")
91 query = query.where(
92 ExistsCriterion(frappe.qb.from_(FYC).select(FYC.name).where(FYC.parent == FY.name)).negate()
93 | ExistsCriterion(
94 frappe.qb.from_(FYC)
95 .select(FYC.company)
96 .where(FYC.parent == FY.name)
97 .where(FYC.company == company)
98 )
99 )
100
Shridhar Patil69efd2e2022-10-03 11:07:24 +0530101 query = query.orderby(FY.year_start_date, order=Order.desc)
Gavin D'souza0727d1d2022-06-13 12:39:28 +0530102 fiscal_years = query.run(as_dict=True)
103
Nabin Hait9784d272016-12-30 16:21:35 +0530104 frappe.cache().hset("fiscal_years", company, fiscal_years)
Nabin Haitfff3ab72015-01-14 16:27:13 +0530105
Prssanna Desai82ddef52020-06-18 18:18:41 +0530106 if not transaction_date and not fiscal_year:
107 return fiscal_years
108
Nabin Hait9784d272016-12-30 16:21:35 +0530109 if transaction_date:
110 transaction_date = getdate(transaction_date)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530111
Nabin Hait9784d272016-12-30 16:21:35 +0530112 for fy in fiscal_years:
113 matched = False
114 if fiscal_year and fy.name == fiscal_year:
115 matched = True
Anand Doshicd71e1d2014-04-08 13:53:35 +0530116
Ankush Menat494bd9e2022-03-28 18:52:46 +0530117 if (
118 transaction_date
119 and getdate(fy.year_start_date) <= transaction_date
120 and getdate(fy.year_end_date) >= transaction_date
121 ):
Nabin Hait9784d272016-12-30 16:21:35 +0530122 matched = True
Rushabh Mehtad50da782017-07-28 11:39:01 +0530123
Nabin Hait9784d272016-12-30 16:21:35 +0530124 if matched:
125 if as_dict:
126 return (fy,)
127 else:
128 return ((fy.name, fy.year_start_date, fy.year_end_date),)
129
Ankush Menat494bd9e2022-03-28 18:52:46 +0530130 error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(
131 label, formatdate(transaction_date)
132 )
Anuja P2e4faf92020-12-05 13:36:43 +0530133 if company:
Anuja P550cb9c2020-12-07 11:11:00 +0530134 error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company))
rohitwaghchaured60ff832021-02-16 09:12:27 +0530135
Deepesh Garg0aadb682023-03-19 12:46:42 +0530136 if boolean:
137 return False
138
Ankush Menat494bd9e2022-03-28 18:52:46 +0530139 if verbose == 1:
140 frappe.msgprint(error_msg)
Deepesh Garg0aadb682023-03-19 12:46:42 +0530141
cclauss68487082017-07-27 07:08:35 +0200142 raise FiscalYearError(error_msg)
Nabin Hait9784d272016-12-30 16:21:35 +0530143
Ankush Menat494bd9e2022-03-28 18:52:46 +0530144
Prssanna Desai82ddef52020-06-18 18:18:41 +0530145@frappe.whitelist()
146def get_fiscal_year_filter_field(company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530147 field = {"fieldtype": "Select", "options": [], "operator": "Between", "query_value": True}
Prssanna Desai82ddef52020-06-18 18:18:41 +0530148 fiscal_years = get_fiscal_years(company=company)
149 for fiscal_year in fiscal_years:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530150 field["options"].append(
151 {
152 "label": fiscal_year.name,
153 "value": fiscal_year.name,
154 "query_value": [
155 fiscal_year.year_start_date.strftime("%Y-%m-%d"),
156 fiscal_year.year_end_date.strftime("%Y-%m-%d"),
157 ],
158 }
159 )
Prssanna Desai82ddef52020-06-18 18:18:41 +0530160 return field
161
Ankush Menat494bd9e2022-03-28 18:52:46 +0530162
Nabin Hait8bf58362017-03-27 12:30:01 +0530163def validate_fiscal_year(date, fiscal_year, company, label="Date", doc=None):
164 years = [f[0] for f in get_fiscal_years(date, label=_(label), company=company)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +0530165 if fiscal_year not in years:
Rushabh Mehtad60acb92015-02-19 14:51:58 +0530166 if doc:
167 doc.fiscal_year = years[0]
168 else:
169 throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
Nabin Hait23941aa2013-01-29 11:32:38 +0530170
Ankush Menat494bd9e2022-03-28 18:52:46 +0530171
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530172@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530173def get_balance_on(
174 account=None,
175 date=None,
176 party_type=None,
177 party=None,
178 company=None,
179 in_account_currency=True,
180 cost_center=None,
181 ignore_account_permission=False,
RitvikSardanab86afb22023-08-04 22:05:30 +0530182 account_type=None,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530183):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530184 if not account and frappe.form_dict.get("account"):
185 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530186 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530187 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530188 if not party_type and frappe.form_dict.get("party_type"):
189 party_type = frappe.form_dict.get("party_type")
190 if not party and frappe.form_dict.get("party"):
191 party = frappe.form_dict.get("party")
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400192 if not cost_center and frappe.form_dict.get("cost_center"):
193 cost_center = frappe.form_dict.get("cost_center")
194
Nabin Hait98372852020-07-30 20:52:20 +0530195 cond = ["is_cancelled=0"]
Nabin Hait23941aa2013-01-29 11:32:38 +0530196 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530197 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530198 else:
199 # get balance of all entries that exist
200 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530201
Deepesh Garg8c217032019-07-16 09:41:01 +0530202 if account:
203 acc = frappe.get_doc("Account", account)
204
Nabin Hait23941aa2013-01-29 11:32:38 +0530205 try:
Deepesh Garg96d40ec2020-07-03 22:59:00 +0530206 year_start_date = get_fiscal_year(date, company=company, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530207 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +0530208 if getdate(date) > getdate(nowdate()):
209 # if fiscal year not found and the date is greater than today
210 # get fiscal year for today's date and its corresponding year start date
211 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
212 else:
213 # this indicates that it is a date older than any existing fiscal year.
214 # hence, assuming balance as 0.0
215 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530216
deepeshgarg0072ddbebf2019-07-20 14:52:59 +0530217 if account:
deepeshgarg007e097d4f2019-07-20 14:49:32 +0530218 report_type = acc.report_type
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530219 else:
220 report_type = ""
221
Ankush Menat494bd9e2022-03-28 18:52:46 +0530222 if cost_center and report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400223 cc = frappe.get_doc("Cost Center", cost_center)
224 if cc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530225 cond.append(
226 """ exists (
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400227 select 1 from `tabCost Center` cc where cc.name = gle.cost_center
228 and cc.lft >= %s and cc.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530229 )"""
230 % (cc.lft, cc.rgt)
231 )
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400232
233 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530234 cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center, percent=False),))
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400235
Nabin Hait6f17cf92014-09-17 14:11:22 +0530236 if account:
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400237
Ankush Menat494bd9e2022-03-28 18:52:46 +0530238 if not (frappe.flags.ignore_account_permission or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530239 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530240
Nabin Hait6f17cf92014-09-17 14:11:22 +0530241 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530242 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530243 cond.append(
244 """exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530245 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530246 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530247 )"""
248 % (acc.lft, acc.rgt)
249 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530250
251 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530252 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530253 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530254 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530255 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530256 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
Anand Doshic75c1d72016-03-11 14:56:19 +0530257
RitvikSardanab86afb22023-08-04 22:05:30 +0530258 if account_type:
259 accounts = frappe.db.get_all(
260 "Account",
261 filters={"company": company, "account_type": account_type, "is_group": 0},
262 pluck="name",
263 order_by="lft",
264 )
265
266 cond.append(
267 """
268 gle.account in (%s)
269 """
270 % (", ".join([frappe.db.escape(account) for account in accounts]))
271 )
272
Nabin Hait6f17cf92014-09-17 14:11:22 +0530273 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530274 cond.append(
275 """gle.party_type = %s and gle.party = %s """
276 % (frappe.db.escape(party_type), frappe.db.escape(party, percent=False))
277 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530278
Nabin Hait85648d92016-07-20 11:26:45 +0530279 if company:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530280 cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530281
RitvikSardanab86afb22023-08-04 22:05:30 +0530282 if account or (party_type and party) or account_type:
283
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530284 if in_account_currency:
Anand Doshi602e8252015-11-16 19:05:46 +0530285 select_field = "sum(debit_in_account_currency) - sum(credit_in_account_currency)"
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530286 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530287 select_field = "sum(debit) - sum(credit)"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530288 bal = frappe.db.sql(
289 """
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530290 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530291 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530292 WHERE {1}""".format(
293 select_field, " and ".join(cond)
294 )
295 )[0][0]
Nabin Haitdc768232015-08-17 11:27:00 +0530296 # if bal is None, return 0
297 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530298
Ankush Menat494bd9e2022-03-28 18:52:46 +0530299
RobertSchouten8d43b322016-09-20 13:41:39 +0800300def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530301 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800302 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530303 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800304 else:
305 # get balance of all entries that exist
306 date = nowdate()
307
308 try:
309 year_start_date = get_fiscal_year(date, verbose=0)[1]
310 except FiscalYearError:
311 if getdate(date) > getdate(nowdate()):
312 # if fiscal year not found and the date is greater than today
313 # get fiscal year for today's date and its corresponding year start date
314 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
315 else:
316 # this indicates that it is a date older than any existing fiscal year.
317 # hence, assuming balance as 0.0
318 return 0.0
319
320 if account:
321 acc = frappe.get_doc("Account", account)
322
323 if not frappe.flags.ignore_account_permission:
324 acc.check_permission("read")
325
326 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530327 if acc.report_type == "Profit and Loss":
328 cond.append(
329 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
330 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800331
332 # different filter for group and ledger - improved performance
333 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530334 cond.append(
335 """exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800336 select name from `tabAccount` ac where ac.name = gle.account
337 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530338 )"""
339 % (acc.lft, acc.rgt)
340 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800341 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530342 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
RobertSchouten8d43b322016-09-20 13:41:39 +0800343
Ankush Menat494bd9e2022-03-28 18:52:46 +0530344 entries = frappe.db.sql(
345 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800346 SELECT name, posting_date, account, party_type, party,debit,credit,
347 voucher_type, voucher_no, against_voucher_type, against_voucher
348 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530349 WHERE {0}""".format(
350 " and ".join(cond)
351 ),
352 as_dict=True,
353 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530354
RobertSchouten8d43b322016-09-20 13:41:39 +0800355 count = 0
356 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530357 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800358 count += 1
359 else:
360 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
361 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530362 select_fields = (
363 "ifnull(sum(credit-debit),0)"
364 if fieldname == "invoiced_amount"
365 else "ifnull(sum(debit-credit),0)"
366 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800367
Ankush Menat494bd9e2022-03-28 18:52:46 +0530368 if (
369 (not gle.against_voucher)
370 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
371 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
372 ):
373 payment_amount = frappe.db.sql(
374 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800375 SELECT {0}
376 FROM `tabGL Entry` gle
377 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530378 and party = %(party)s and name != %(name)s""".format(
379 select_fields
380 ),
381 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
382 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530383
RobertSchouten8d43b322016-09-20 13:41:39 +0800384 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
385 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530386 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800387 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530388
RobertSchouten8d43b322016-09-20 13:41:39 +0800389 return count
390
Ankush Menat494bd9e2022-03-28 18:52:46 +0530391
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530392@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530393def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530394 from frappe.desk.treeview import make_tree_args
395
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530396 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530397 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530398
Nabin Hait02d987e2017-02-17 15:50:26 +0530399 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530400 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530401
Anand Doshi3e41fd12014-04-22 18:54:54 +0530402 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530403
Nabin Hait665568d2016-05-13 15:56:00 +0530404 if args.get("ignore_permissions"):
405 ac.flags.ignore_permissions = True
406 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530407
Anand Doshi3e41fd12014-04-22 18:54:54 +0530408 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530409
410 if not ac.parent_account:
411 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530412
Anand Doshif78d1ae2014-03-28 13:55:00 +0530413 ac.old_parent = ""
414 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530415 if cint(ac.get("is_root")):
416 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530417 ac.flags.ignore_mandatory = True
418
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530419 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530420
Anand Doshif78d1ae2014-03-28 13:55:00 +0530421 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530422
Ankush Menat494bd9e2022-03-28 18:52:46 +0530423
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530424@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530425def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530426 from frappe.desk.treeview import make_tree_args
427
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530428 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530429 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530430
Nabin Hait02d987e2017-02-17 15:50:26 +0530431 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530432 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530433
Zarrar7ab70ca2018-06-08 14:33:15 +0530434 if args.parent_cost_center == args.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530435 args.parent_cost_center = "{0} - {1}".format(
436 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
437 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530438
Anand Doshi3e41fd12014-04-22 18:54:54 +0530439 cc = frappe.new_doc("Cost Center")
440 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530441
442 if not cc.parent_cost_center:
443 cc.parent_cost_center = args.get("parent")
444
Anand Doshif78d1ae2014-03-28 13:55:00 +0530445 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530446 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530447 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530448
Ankush Menat494bd9e2022-03-28 18:52:46 +0530449
Deepesh Garg016ed952023-06-20 13:22:32 +0530450def reconcile_against_document(args, skip_ref_details_update_for_pe=False): # nosemgrep
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530451 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530452 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530453 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530454 # To optimize making GL Entry for PE or JV with multiple references
455 reconciled_entries = {}
456 for row in args:
457 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
458 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530459
Anuja Pawar3e404f12021-08-31 18:59:29 +0530460 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
461
462 for key, entries in reconciled_entries.items():
463 voucher_type = key[0]
464 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530465
Nabin Hait28a05282016-06-27 17:41:39 +0530466 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530467 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530468 frappe.flags.ignore_party_validation = True
ruthra kumar11cf6942023-01-14 12:22:22 +0530469 _delete_pl_entries(voucher_type, voucher_no)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530470
Anuja Pawar3e404f12021-08-31 18:59:29 +0530471 for entry in entries:
472 check_if_advance_entry_modified(entry)
473 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530474
Anuja Pawar3e404f12021-08-31 18:59:29 +0530475 # update ref in advance entry
476 if voucher_type == "Journal Entry":
ruthra kumar79c6f012023-09-01 14:57:12 +0530477 referenced_row = update_reference_in_journal_entry(entry, doc, do_not_save=False)
ruthra kumar7b516f82023-06-26 17:34:28 +0530478 # advance section in sales/purchase invoice and reconciliation tool,both pass on exchange gain/loss
479 # amount and account in args
ruthra kumar79c6f012023-09-01 14:57:12 +0530480 # referenced_row is used to deduplicate gain/loss journal
481 entry.update({"referenced_row": referenced_row})
482 doc.make_exchange_gain_loss_journal([entry])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530483 else:
ruthra kumared14d1c2023-04-22 17:24:35 +0530484 update_reference_in_payment_entry(
485 entry, doc, do_not_save=True, skip_ref_details_update_for_pe=skip_ref_details_update_for_pe
486 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530487
488 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530489 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530490 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
Deepesh Garg016ed952023-06-20 13:22:32 +0530491 gl_map = doc.build_gl_map()
ruthra kumar11cf6942023-01-14 12:22:22 +0530492 create_payment_ledger_entry(gl_map, update_outstanding="No", cancel=0, adv_adj=1)
Deepesh Garg1894dc82023-06-23 21:53:34 +0530493
494 if voucher_type == "Payment Entry":
Deepesh Gargf2edc912023-06-27 18:11:47 +0530495 doc.make_advance_gl_entries()
ruthra kumar11cf6942023-01-14 12:22:22 +0530496
497 # Only update outstanding for newly linked vouchers
498 for entry in entries:
499 update_voucher_outstanding(
500 entry.against_voucher_type, entry.against_voucher, entry.account, entry.party_type, entry.party
501 )
ruthra kumar524c1752022-05-26 16:00:40 +0530502
Subin Tomb8845b92021-07-30 16:30:18 +0530503 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530504
Ankush Menat494bd9e2022-03-28 18:52:46 +0530505
Nabin Hait28a05282016-06-27 17:41:39 +0530506def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530507 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530508 check if there is already a voucher reference
509 check if amount is same
510 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530511 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530512 if not args.get("unreconciled_amount"):
513 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530514
Nabin Hait28a05282016-06-27 17:41:39 +0530515 ret = None
516 if args.voucher_type == "Journal Entry":
Gursheen Anand74619262023-06-02 17:13:51 +0530517 journal_entry = frappe.qb.DocType("Journal Entry")
518 journal_acc = frappe.qb.DocType("Journal Entry Account")
519
Gursheen Anand4ee16372023-06-08 13:15:23 +0530520 q = (
521 frappe.qb.from_(journal_entry)
Deepesh Garg3aead052023-06-22 11:41:43 +0530522 .inner_join(journal_acc)
Gursheen Anand74619262023-06-02 17:13:51 +0530523 .on(journal_entry.name == journal_acc.parent)
Deepesh Gargd81d6062023-06-22 18:28:16 +0530524 .select(journal_acc[args.get("dr_or_cr")])
525 .where(
526 (journal_acc.account == args.get("account"))
527 & ((journal_acc.party_type == args.get("party_type")))
528 & ((journal_acc.party == args.get("party")))
529 & (
530 (journal_acc.reference_type.isnull())
531 | (journal_acc.reference_type.isin(["", "Sales Order", "Purchase Order"]))
532 )
533 & ((journal_entry.name == args.get("voucher_no")))
534 & ((journal_acc.name == args.get("voucher_detail_no")))
535 & ((journal_entry.docstatus == 1))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530536 )
Gursheen Anand74619262023-06-02 17:13:51 +0530537 )
538
Nabin Hait28a05282016-06-27 17:41:39 +0530539 else:
Gursheen Anand74619262023-06-02 17:13:51 +0530540 payment_entry = frappe.qb.DocType("Payment Entry")
541 payment_ref = frappe.qb.DocType("Payment Entry Reference")
542
Gursheen Anand4ee16372023-06-08 13:15:23 +0530543 q = (
544 frappe.qb.from_(payment_entry)
Gursheen Anand74619262023-06-02 17:13:51 +0530545 .select(payment_entry.name)
546 .where(payment_entry.name == args.get("voucher_no"))
547 .where(payment_entry.docstatus == 1)
548 .where(payment_entry.party_type == args.get("party_type"))
549 .where(payment_entry.party == args.get("party"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530550 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530551
Nabin Hait28a05282016-06-27 17:41:39 +0530552 if args.voucher_detail_no:
Gursheen Anand4ee16372023-06-08 13:15:23 +0530553 q = (
554 q.inner_join(payment_ref)
Gursheen Anand74619262023-06-02 17:13:51 +0530555 .on(payment_entry.name == payment_ref.parent)
556 .where(payment_ref.name == args.get("voucher_detail_no"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530557 .where(payment_ref.reference_doctype.isin(("", "Sales Order", "Purchase Order")))
Gursheen Anand74619262023-06-02 17:13:51 +0530558 .where(payment_ref.allocated_amount == args.get("unreconciled_amount"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530559 )
Nabin Hait28a05282016-06-27 17:41:39 +0530560 else:
Gursheen Anand74619262023-06-02 17:13:51 +0530561 q = q.where(payment_entry.unallocated_amount == args.get("unreconciled_amount"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530562
Gursheen Anand74619262023-06-02 17:13:51 +0530563 ret = q.run(as_dict=True)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530564
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530565 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530566 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530567
Ankush Menat494bd9e2022-03-28 18:52:46 +0530568
Nabin Hait576f0252014-04-30 19:30:50 +0530569def validate_allocated_amount(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530570 precision = args.get("precision") or frappe.db.get_single_value(
571 "System Settings", "currency_precision"
572 )
Nabin Hait28a05282016-06-27 17:41:39 +0530573 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530574 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530575 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530576 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530577
Ankush Menat494bd9e2022-03-28 18:52:46 +0530578
Anuja Pawar3e404f12021-08-31 18:59:29 +0530579def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530580 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530581 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530582 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530583 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530584
Ankush Menat494bd9e2022-03-28 18:52:46 +0530585 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530586 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530587 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530588 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530589 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
590 jv_detail.set(
591 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
592 amount_in_company_currency,
593 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530594 else:
595 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530596
Anuja Pawar3e404f12021-08-31 18:59:29 +0530597 # new row with references
598 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530599
ruthra kumar72f577a2023-07-13 15:04:44 +0530600 # Copy field values into new row
601 [
602 new_row.set(field, jv_detail.get(field))
603 for field in frappe.get_meta("Journal Entry Account").get_fieldnames_with_value()
604 ]
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530605
Anuja Pawar3e404f12021-08-31 18:59:29 +0530606 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530607 new_row.set(
608 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
609 d["allocated_amount"] * flt(jv_detail.exchange_rate),
610 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530611
Ankush Menat494bd9e2022-03-28 18:52:46 +0530612 new_row.set(
613 "credit_in_account_currency"
614 if d["dr_or_cr"] == "debit_in_account_currency"
615 else "debit_in_account_currency",
616 0,
617 )
618 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530619
Anuja Pawar3e404f12021-08-31 18:59:29 +0530620 new_row.set("reference_type", d["against_voucher_type"])
621 new_row.set("reference_name", d["against_voucher"])
622
623 new_row.against_account = cstr(jv_detail.against_account)
624 new_row.is_advance = cstr(jv_detail.is_advance)
625 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530626
627 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530628 journal_entry.flags.ignore_validate_update_after_submit = True
629 if not do_not_save:
630 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530631
ruthra kumar79c6f012023-09-01 14:57:12 +0530632 return new_row.name
633
Ankush Menat494bd9e2022-03-28 18:52:46 +0530634
ruthra kumared14d1c2023-04-22 17:24:35 +0530635def update_reference_in_payment_entry(
636 d, payment_entry, do_not_save=False, skip_ref_details_update_for_pe=False
637):
Nabin Hait28a05282016-06-27 17:41:39 +0530638 reference_details = {
639 "reference_doctype": d.against_voucher_type,
640 "reference_name": d.against_voucher,
641 "total_amount": d.grand_total,
642 "outstanding_amount": d.outstanding_amount,
643 "allocated_amount": d.allocated_amount,
ruthra kumar81cd7872023-04-27 09:46:54 +0530644 "exchange_rate": d.exchange_rate if d.exchange_gain_loss else payment_entry.get_exchange_rate(),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530645 "exchange_gain_loss": d.exchange_gain_loss, # only populated from invoice in case of advance allocation
Gursheen Anandb65e58c2023-06-08 18:15:37 +0530646 "account": d.account,
Nabin Hait28a05282016-06-27 17:41:39 +0530647 }
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530648
Nabin Hait28a05282016-06-27 17:41:39 +0530649 if d.voucher_detail_no:
650 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
651 original_row = existing_row.as_dict().copy()
652 existing_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530653
Nabin Hait28a05282016-06-27 17:41:39 +0530654 if d.allocated_amount < original_row.allocated_amount:
655 new_row = payment_entry.append("references")
656 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500657 for field in list(reference_details):
Nabin Hait28a05282016-06-27 17:41:39 +0530658 new_row.set(field, original_row[field])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530659
Nabin Hait28a05282016-06-27 17:41:39 +0530660 new_row.allocated_amount = original_row.allocated_amount - d.allocated_amount
661 else:
662 new_row = payment_entry.append("references")
663 new_row.docstatus = 1
664 new_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530665
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500666 payment_entry.flags.ignore_validate_update_after_submit = True
667 payment_entry.setup_party_account_field()
668 payment_entry.set_missing_values()
ruthra kumared14d1c2023-04-22 17:24:35 +0530669 if not skip_ref_details_update_for_pe:
670 payment_entry.set_missing_ref_details()
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500671 payment_entry.set_amounts()
ruthra kumar81cd7872023-04-27 09:46:54 +0530672 payment_entry.make_exchange_gain_loss_journal()
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500673
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530674 if not do_not_save:
675 payment_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530676
Ankush Menat494bd9e2022-03-28 18:52:46 +0530677
ruthra kumar81cd7872023-04-27 09:46:54 +0530678def cancel_exchange_gain_loss_journal(parent_doc: dict | object) -> None:
679 """
680 Cancel Exchange Gain/Loss for Sales/Purchase Invoice, if they have any.
681 """
ruthra kumar6e18bb62023-07-11 12:21:10 +0530682 if parent_doc.doctype in ["Sales Invoice", "Purchase Invoice", "Payment Entry", "Journal Entry"]:
ruthra kumar81cd7872023-04-27 09:46:54 +0530683 journals = frappe.db.get_all(
684 "Journal Entry Account",
685 filters={
686 "reference_type": parent_doc.doctype,
687 "reference_name": parent_doc.name,
688 "docstatus": 1,
689 },
690 fields=["parent"],
691 as_list=1,
692 )
ruthra kumard9d68562023-07-27 08:02:46 +0530693
ruthra kumar81cd7872023-04-27 09:46:54 +0530694 if journals:
ruthra kumard9d68562023-07-27 08:02:46 +0530695 gain_loss_journals = frappe.db.get_all(
ruthra kumar81cd7872023-04-27 09:46:54 +0530696 "Journal Entry",
697 filters={
698 "name": ["in", [x[0] for x in journals]],
699 "voucher_type": "Exchange Gain Or Loss",
700 "docstatus": 1,
701 },
702 as_list=1,
703 )
ruthra kumard9d68562023-07-27 08:02:46 +0530704 for doc in gain_loss_journals:
ruthra kumar81cd7872023-04-27 09:46:54 +0530705 frappe.get_doc("Journal Entry", doc[0]).cancel()
706
707
Nabin Hait297d74a2016-11-23 15:58:51 +0530708def unlink_ref_doc_from_payment_entries(ref_doc):
709 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name)
710 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530711
Ankush Menat494bd9e2022-03-28 18:52:46 +0530712 frappe.db.sql(
713 """update `tabGL Entry`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530714 set against_voucher_type=null, against_voucher=null,
715 modified=%s, modified_by=%s
716 where against_voucher_type=%s and against_voucher=%s
717 and voucher_no != ifnull(against_voucher, '')""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530718 (now(), frappe.session.user, ref_doc.doctype, ref_doc.name),
719 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530720
ruthra kumar537d9532022-10-10 10:17:19 +0530721 ple = qb.DocType("Payment Ledger Entry")
722
723 qb.update(ple).set(ple.against_voucher_type, ple.voucher_type).set(
724 ple.against_voucher_no, ple.voucher_no
725 ).set(ple.modified, now()).set(ple.modified_by, frappe.session.user).where(
726 (ple.against_voucher_type == ref_doc.doctype)
727 & (ple.against_voucher_no == ref_doc.name)
728 & (ple.delinked == 0)
729 ).run()
730
Nabin Hait297d74a2016-11-23 15:58:51 +0530731 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
732 ref_doc.set("advances", [])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530733
Ankush Menat494bd9e2022-03-28 18:52:46 +0530734 frappe.db.sql(
735 """delete from `tab{0} Advance` where parent = %s""".format(ref_doc.doctype), ref_doc.name
736 )
737
Anand Doshicd71e1d2014-04-08 13:53:35 +0530738
Nabin Haite0cc87d2016-07-21 18:30:03 +0530739def remove_ref_doc_link_from_jv(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530740 linked_jv = frappe.db.sql_list(
741 """select parent from `tabJournal Entry Account`
742 where reference_type=%s and reference_name=%s and docstatus < 2""",
743 (ref_type, ref_no),
744 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530745
746 if linked_jv:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530747 frappe.db.sql(
748 """update `tabJournal Entry Account`
Rushabh Mehta1828c122015-08-10 17:04:07 +0530749 set reference_type=null, reference_name = null,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530750 modified=%s, modified_by=%s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530751 where reference_type=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530752 and docstatus < 2""",
753 (now(), frappe.session.user, ref_type, ref_no),
754 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530755
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530756 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530757
Ankush Menat494bd9e2022-03-28 18:52:46 +0530758
Nabin Haite0cc87d2016-07-21 18:30:03 +0530759def remove_ref_doc_link_from_pe(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530760 linked_pe = frappe.db.sql_list(
761 """select parent from `tabPayment Entry Reference`
762 where reference_doctype=%s and reference_name=%s and docstatus < 2""",
763 (ref_type, ref_no),
764 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530765
Nabin Haite0cc87d2016-07-21 18:30:03 +0530766 if linked_pe:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530767 frappe.db.sql(
768 """update `tabPayment Entry Reference`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530769 set allocated_amount=0, modified=%s, modified_by=%s
770 where reference_doctype=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530771 and docstatus < 2""",
772 (now(), frappe.session.user, ref_type, ref_no),
773 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530774
Nabin Haite0cc87d2016-07-21 18:30:03 +0530775 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530776 try:
Deepesh Garg1894dc82023-06-23 21:53:34 +0530777 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530778 pe_doc.set_amounts()
Deepesh Gargda6bc1a2023-06-23 20:57:51 +0530779 pe_doc.make_advance_gl_entries(against_voucher_type=ref_type, against_voucher=ref_no, cancel=1)
Deepesh Gargb5162392021-08-10 14:52:24 +0530780 pe_doc.clear_unallocated_reference_document_rows()
781 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530782 except Exception as e:
783 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530784 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530785 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530786 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530787
Ankush Menat494bd9e2022-03-28 18:52:46 +0530788 frappe.db.sql(
789 """update `tabPayment Entry` set total_allocated_amount=%s,
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530790 base_total_allocated_amount=%s, unallocated_amount=%s, modified=%s, modified_by=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530791 where name=%s""",
792 (
793 pe_doc.total_allocated_amount,
794 pe_doc.base_total_allocated_amount,
795 pe_doc.unallocated_amount,
796 now(),
797 frappe.session.user,
798 pe,
799 ),
800 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530801
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530802 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530803
Ankush Menat494bd9e2022-03-28 18:52:46 +0530804
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530805@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530806def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530807 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530808
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530809 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530810 throw(
811 _("Please set default {0} in Company {1}").format(
812 frappe.get_meta("Company").get_label(fieldname), company
813 )
814 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530815
Nabin Hait0fc24542013-03-25 11:06:00 +0530816 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530817
Ankush Menat494bd9e2022-03-28 18:52:46 +0530818
Nabin Hait8b509f52013-05-28 16:52:30 +0530819def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530820 vouchers = frappe.db.sql(
821 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530822 sum(debit) - sum(credit) as diff
823 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530824 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530825 having sum(debit) != sum(credit)""",
826 as_dict=1,
827 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530828
Nabin Hait8b509f52013-05-28 16:52:30 +0530829 for d in vouchers:
830 if abs(d.diff) > 0:
831 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530832
Ankush Menat494bd9e2022-03-28 18:52:46 +0530833 frappe.db.sql(
834 """update `tabGL Entry` set %s = %s + %s
835 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
836 % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
837 (d.diff, d.voucher_type, d.voucher_no),
838 )
839
Anand Doshicd71e1d2014-04-08 13:53:35 +0530840
Rushabh Mehtad50da782017-07-28 11:39:01 +0530841def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530842 precision = cint(frappe.db.get_default("currency_precision"))
843 if not precision:
844 number_format = frappe.db.get_default("number_format") or "#,###.##"
845 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530846
Nabin Hait9b20e072017-04-25 12:10:24 +0530847 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530848
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530849
Ankush Menat494bd9e2022-03-28 18:52:46 +0530850def get_stock_rbnb_difference(posting_date, company):
851 stock_items = frappe.db.sql_list(
852 """select distinct item_code
853 from `tabStock Ledger Entry` where company=%s""",
854 company,
855 )
856
857 pr_valuation_amount = frappe.db.sql(
858 """
Anand Doshi602e8252015-11-16 19:05:46 +0530859 select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530860 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
Suraj Shetty084b0b32018-05-26 09:12:59 +0530861 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530862 and pr.posting_date <= %s and pr_item.item_code in (%s)"""
863 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
864 tuple([company, posting_date] + stock_items),
865 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530866
Ankush Menat494bd9e2022-03-28 18:52:46 +0530867 pi_valuation_amount = frappe.db.sql(
868 """
Anand Doshi602e8252015-11-16 19:05:46 +0530869 select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530870 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
Suraj Shetty084b0b32018-05-26 09:12:59 +0530871 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530872 and pi.posting_date <= %s and pi_item.item_code in (%s)"""
873 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
874 tuple([company, posting_date] + stock_items),
875 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530876
877 # Balance should be
878 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
879
880 # Balance as per system
Ankush Menat494bd9e2022-03-28 18:52:46 +0530881 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.get_cached_value(
882 "Company", company, "abbr"
883 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530884 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530885
886 # Amount should be credited
887 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530888
tundec4b0d172017-09-26 00:48:30 +0100889
tundebabzyad08d4c2018-05-16 07:01:41 +0100890def get_held_invoices(party_type, party):
891 """
892 Returns a list of names Purchase Invoices for the given party that are on hold
893 """
894 held_invoices = None
895
Ankush Menat494bd9e2022-03-28 18:52:46 +0530896 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +0100897 held_invoices = frappe.db.sql(
mergify[bot]872a23c2023-07-10 20:34:54 +0530898 "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 +0530899 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +0100900 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530901 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +0100902
903 return held_invoices
904
905
ruthra kumar8c876742022-06-14 17:46:04 +0530906def get_outstanding_invoices(
ruthra kumar5f1562c2022-07-28 11:57:27 +0530907 party_type,
908 party,
909 account,
910 common_filter=None,
911 posting_date=None,
912 min_outstanding=None,
913 max_outstanding=None,
ruthra kumar6d9d7302022-12-14 16:05:15 +0530914 accounting_dimensions=None,
Deepesh Garg299e32b2023-08-24 18:02:06 +0530915 vouchers=None, # list of dicts [{'voucher_type': '', 'voucher_no': ''}] for filtering
916 limit=None, # passed by reconciliation tool
917 voucher_no=None, # filter passed by reconciliation tool
ruthra kumar8c876742022-06-14 17:46:04 +0530918):
919
920 ple = qb.DocType("Payment Ledger Entry")
Anand Doshid40d1e92015-11-12 17:05:29 +0530921 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +0530922 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +0530923
Nabin Hait9db9edc2019-11-19 18:44:32 +0530924 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530925 root_type, account_type = frappe.get_cached_value(
926 "Account", account, ["root_type", "account_type"]
927 )
Nabin Hait9db9edc2019-11-19 18:44:32 +0530928 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +0530929 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +0530930 else:
931 party_account_type = erpnext.get_party_account_type(party_type)
932
tundebabzyad08d4c2018-05-16 07:01:41 +0100933 held_invoices = get_held_invoices(party_type, party)
934
ruthra kumar8c876742022-06-14 17:46:04 +0530935 common_filter = common_filter or []
936 common_filter.append(ple.account_type == party_account_type)
937 common_filter.append(ple.account == account)
938 common_filter.append(ple.party_type == party_type)
939 common_filter.append(ple.party == party)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530940
ruthra kumar8c876742022-06-14 17:46:04 +0530941 ple_query = QueryPaymentLedger()
942 invoice_list = ple_query.get_voucher_outstandings(
ruthra kumardeb0d712023-08-15 05:17:01 +0530943 vouchers=vouchers,
ruthra kumar8c876742022-06-14 17:46:04 +0530944 common_filter=common_filter,
ruthra kumar5f1562c2022-07-28 11:57:27 +0530945 posting_date=posting_date,
ruthra kumar8c876742022-06-14 17:46:04 +0530946 min_outstanding=min_outstanding,
947 max_outstanding=max_outstanding,
948 get_invoices=True,
ruthra kumar6d9d7302022-12-14 16:05:15 +0530949 accounting_dimensions=accounting_dimensions or [],
ruthra kumar7a381af2023-05-03 20:45:12 +0530950 limit=limit,
951 voucher_no=voucher_no,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530952 )
tundec4b0d172017-09-26 00:48:30 +0100953
Nabin Haitac184982019-02-04 21:13:43 +0530954 for d in invoice_list:
ruthra kumar21985532022-06-30 15:14:38 +0530955 payment_amount = d.invoice_amount_in_account_currency - d.outstanding_in_account_currency
956 outstanding_amount = d.outstanding_in_account_currency
Nabin Haitac184982019-02-04 21:13:43 +0530957 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530958 if (
ruthra kumar8c876742022-06-14 17:46:04 +0530959 min_outstanding
960 and max_outstanding
961 and not (outstanding_amount >= min_outstanding and outstanding_amount <= max_outstanding)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530962 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530963 continue
Nabin Haitac184982019-02-04 21:13:43 +0530964
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530965 if not d.voucher_type == "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +0530966 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530967 frappe._dict(
968 {
969 "voucher_no": d.voucher_no,
970 "voucher_type": d.voucher_type,
971 "posting_date": d.posting_date,
ruthra kumar21985532022-06-30 15:14:38 +0530972 "invoice_amount": flt(d.invoice_amount_in_account_currency),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530973 "payment_amount": payment_amount,
974 "outstanding_amount": outstanding_amount,
975 "due_date": d.due_date,
976 "currency": d.currency,
Gursheen Anand4ee16372023-06-08 13:15:23 +0530977 "account": d.account,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530978 }
979 )
Nabin Haitac184982019-02-04 21:13:43 +0530980 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530981
Ankush Menat494bd9e2022-03-28 18:52:46 +0530982 outstanding_invoices = sorted(
983 outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
984 )
Anand Doshid40d1e92015-11-12 17:05:29 +0530985 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +0530986
987
Ankush Menat494bd9e2022-03-28 18:52:46 +0530988def get_account_name(
989 account_type=None, root_type=None, is_group=None, account_currency=None, company=None
990):
Saurabh3a268292016-02-22 15:18:40 +0530991 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530992 return frappe.db.get_value(
993 "Account",
994 {
995 "account_type": account_type or "",
996 "root_type": root_type or "",
997 "is_group": is_group or 0,
998 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
999 "company": company or frappe.defaults.get_defaults().company,
1000 },
1001 "name",
1002 )
1003
Saurabha9ba7342016-06-21 12:33:12 +05301004
1005@frappe.whitelist()
1006def get_companies():
1007 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301008 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
1009
Saurabha9ba7342016-06-21 12:33:12 +05301010
1011@frappe.whitelist()
Rushabh Mehta43133262017-11-10 18:52:21 +05301012def get_children(doctype, parent, company, is_root=False):
Nabin Haitaf98f5d2018-04-02 10:14:32 +05301013 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +05301014
Ankush Menat494bd9e2022-03-28 18:52:46 +05301015 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
1016 fields = ["name as value", "is_group as expandable"]
1017 filters = [["docstatus", "<", 2]]
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +05301018
Ankush Menat494bd9e2022-03-28 18:52:46 +05301019 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301020
Rushabh Mehta43133262017-11-10 18:52:21 +05301021 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301022 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
1023 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301024
Saurabha9ba7342016-06-21 12:33:12 +05301025 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301026 fields += ["root_type", "account_currency"] if doctype == "Account" else []
1027 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +05301028
1029 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +05301030
Ankush Menat494bd9e2022-03-28 18:52:46 +05301031 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +05301032 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +05301033
1034 return acc
Saurabhb835fef2016-09-09 11:19:22 +05301035
Ankush Menat494bd9e2022-03-28 18:52:46 +05301036
Saqib90517352021-10-04 11:44:46 +05301037@frappe.whitelist()
1038def get_account_balances(accounts, company):
1039
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301040 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +05301041 accounts = loads(accounts)
1042
1043 if not accounts:
1044 return []
1045
Ankush Menat494bd9e2022-03-28 18:52:46 +05301046 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +05301047
1048 for account in accounts:
1049 account["company_currency"] = company_currency
Ankush Menat494bd9e2022-03-28 18:52:46 +05301050 account["balance"] = flt(
1051 get_balance_on(account["value"], in_account_currency=False, company=company)
1052 )
Saqib90517352021-10-04 11:44:46 +05301053 if account["account_currency"] and account["account_currency"] != company_currency:
1054 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
1055
1056 return accounts
1057
Ankush Menat494bd9e2022-03-28 18:52:46 +05301058
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +05301059def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +05301060 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +05301061
Daizy Modifdfe5cb2022-11-17 19:14:10 +05301062 company = frappe.get_cached_value("Global Defaults", "Global Defaults", "default_company")
Saurabhb835fef2016-09-09 11:19:22 +05301063 if not company:
1064 return
1065
1066 # 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 +05301067 bank_account = frappe.db.get_value(
1068 "Account",
1069 {"account_name": _(gateway), "company": company},
1070 ["name", "account_currency"],
1071 as_dict=1,
1072 )
Saurabhb835fef2016-09-09 11:19:22 +05301073
1074 if not bank_account:
1075 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301076 bank_account = frappe.db.get_value(
1077 "Account",
1078 {"account_name": gateway, "company": company},
1079 ["name", "account_currency"],
1080 as_dict=1,
1081 )
Saurabhb835fef2016-09-09 11:19:22 +05301082
1083 if not bank_account:
1084 # try creating one
1085 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1086
1087 if not bank_account:
1088 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1089 return
1090
1091 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301092 if frappe.db.exists(
1093 "Payment Gateway Account",
1094 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1095 ):
Saurabhb835fef2016-09-09 11:19:22 +05301096 return
1097
1098 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301099 frappe.get_doc(
1100 {
1101 "doctype": "Payment Gateway Account",
1102 "is_default": 1,
1103 "payment_gateway": gateway,
1104 "payment_account": bank_account.name,
1105 "currency": bank_account.account_currency,
1106 "payment_channel": payment_channel,
1107 }
1108 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301109
1110 except frappe.DuplicateEntryError:
1111 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001112 pass
Zarrar44175902018-06-08 16:35:21 +05301113
Ankush Menat494bd9e2022-03-28 18:52:46 +05301114
Zarrar44175902018-06-08 16:35:21 +05301115@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301116def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301117 """
1118 Renames the document by adding the number as a prefix to the current name and updates
1119 all transaction where it was present.
1120 """
Saqiba8779872020-04-30 11:28:43 +05301121 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301122
Saqiba8779872020-04-30 11:28:43 +05301123 if cost_center_number:
1124 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1125 else:
1126 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301127
Saqiba8779872020-04-30 11:28:43 +05301128 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301129
Nabin Haitaf21a112022-09-15 12:09:18 +05301130 new_name = get_autoname_with_number(cost_center_number, cost_center_name, company)
Saqiba8779872020-04-30 11:28:43 +05301131 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301132 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301133 return new_name
1134
Ankush Menat494bd9e2022-03-28 18:52:46 +05301135
Saqiba8779872020-04-30 11:28:43 +05301136def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301137 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301138 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301139 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301140 if company:
Saqiba8779872020-04-30 11:28:43 +05301141 filters["company"] = company
1142
1143 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1144
Zarrar44175902018-06-08 16:35:21 +05301145 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301146 frappe.throw(
1147 _("{0} Number {1} is already used in {2} {3}").format(
1148 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1149 )
1150 )
1151
Zarrar44175902018-06-08 16:35:21 +05301152
Nabin Haitaf21a112022-09-15 12:09:18 +05301153def get_autoname_with_number(number_value, doc_title, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301154 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Nabin Haitaf21a112022-09-15 12:09:18 +05301155 company_abbr = frappe.get_cached_value("Company", company, "abbr")
1156 parts = [doc_title.strip(), company_abbr]
1157
Zlash651aeca1d2018-07-06 17:15:33 +05301158 if cstr(number_value).strip():
1159 parts.insert(0, cstr(number_value).strip())
Nabin Haitaf21a112022-09-15 12:09:18 +05301160
Ankush Menat494bd9e2022-03-28 18:52:46 +05301161 return " - ".join(parts)
1162
Zarrar254ce642018-06-28 14:15:34 +05301163
Deepesh Garg62706072023-07-16 12:58:42 +05301164def parse_naming_series_variable(doc, variable):
1165 if variable == "FY":
Deepesh Garg7a7d32d2023-07-21 16:03:17 +05301166 date = doc.get("posting_date") or doc.get("transaction_date") or getdate()
1167 return get_fiscal_year(date=date, company=doc.get("company"))[0]
Deepesh Garg62706072023-07-16 12:58:42 +05301168
1169
Zarrar254ce642018-06-28 14:15:34 +05301170@frappe.whitelist()
David Arnoldd066b5c2023-07-23 22:43:41 -05001171def get_coa(doctype, parent, is_root=None, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301172 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1173 build_tree_from_json,
1174 )
Zarrar254ce642018-06-28 14:15:34 +05301175
1176 # add chart to flags to retrieve when called from expand all function
1177 chart = chart if chart else frappe.flags.chart
1178 frappe.flags.chart = chart
1179
Ankush Menat494bd9e2022-03-28 18:52:46 +05301180 parent = None if parent == _("All Accounts") else parent
1181 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301182
1183 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301184 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301185
1186 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001187
Ankush Menat494bd9e2022-03-28 18:52:46 +05301188
1189def update_gl_entries_after(
1190 posting_date,
1191 posting_time,
1192 for_warehouses=None,
1193 for_items=None,
1194 warehouse_account=None,
1195 company=None,
1196):
1197 stock_vouchers = get_future_stock_vouchers(
1198 posting_date, posting_time, for_warehouses, for_items, company
1199 )
Nabin Hait9b178bc2021-02-16 14:57:00 +05301200 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1201
1202
Ankush Menat494bd9e2022-03-28 18:52:46 +05301203def repost_gle_for_stock_vouchers(
Ankush Menat2535d5e2022-06-14 18:20:33 +05301204 stock_vouchers: List[Tuple[str, str]],
1205 posting_date: str,
1206 company: Optional[str] = None,
1207 warehouse_account=None,
1208 repost_doc: Optional["RepostItemValuation"] = None,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301209):
Ankush Menat67c26322022-06-04 14:46:35 +05301210
1211 from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative
1212
Ankush Menat700e8642022-04-19 13:24:29 +05301213 if not stock_vouchers:
1214 return
1215
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301216 if not warehouse_account:
1217 warehouse_account = get_warehouse_account_map(company)
1218
Ankush Menat2535d5e2022-06-14 18:20:33 +05301219 stock_vouchers = sort_stock_vouchers_by_posting_date(stock_vouchers)
1220 if repost_doc and repost_doc.gl_reposting_index:
1221 # Restore progress
1222 stock_vouchers = stock_vouchers[cint(repost_doc.gl_reposting_index) :]
1223
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301224 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1225
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301226 for stock_vouchers_chunk in create_batch(stock_vouchers, GL_REPOSTING_CHUNK):
Ankush Menat2535d5e2022-06-14 18:20:33 +05301227 gle = get_voucherwise_gl_entries(stock_vouchers_chunk, posting_date)
1228
1229 for voucher_type, voucher_no in stock_vouchers_chunk:
1230 existing_gle = gle.get((voucher_type, voucher_no), [])
1231 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
1232 # Some transactions post credit as negative debit, this is handled while posting GLE
1233 # but while comparing we need to make sure it's flipped so comparisons are accurate
1234 expected_gle = toggle_debit_credit_if_negative(voucher_obj.get_gl_entries(warehouse_account))
1235 if expected_gle:
1236 if not existing_gle or not compare_existing_and_expected_gle(
1237 existing_gle, expected_gle, precision
1238 ):
ruthra kumar9209ec52022-10-21 15:18:40 +05301239 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301240 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
1241 else:
ruthra kumar9209ec52022-10-21 15:18:40 +05301242 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat86919d22022-06-15 21:19:09 +05301243
1244 if not frappe.flags.in_test:
1245 frappe.db.commit()
Ankush Menat2535d5e2022-06-14 18:20:33 +05301246
1247 if repost_doc:
1248 repost_doc.db_set(
1249 "gl_reposting_index",
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301250 cint(repost_doc.gl_reposting_index) + len(stock_vouchers_chunk),
Ankush Menat2535d5e2022-06-14 18:20:33 +05301251 )
1252
1253
ruthra kumar9209ec52022-10-21 15:18:40 +05301254def _delete_pl_entries(voucher_type, voucher_no):
ruthra kumar65992302022-10-04 16:17:56 +05301255 ple = qb.DocType("Payment Ledger Entry")
1256 qb.from_(ple).delete().where(
1257 (ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)
1258 ).run()
Ankush Menateb53a972022-06-04 18:19:44 +05301259
Ankush Menat494bd9e2022-03-28 18:52:46 +05301260
ruthra kumar9209ec52022-10-21 15:18:40 +05301261def _delete_gl_entries(voucher_type, voucher_no):
1262 gle = qb.DocType("GL Entry")
1263 qb.from_(gle).delete().where(
1264 (gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)
1265 ).run()
1266
1267
1268def _delete_accounting_ledger_entries(voucher_type, voucher_no):
1269 """
1270 Remove entries from both General and Payment Ledger for specified Voucher
1271 """
1272 _delete_gl_entries(voucher_type, voucher_no)
1273 _delete_pl_entries(voucher_type, voucher_no)
1274
1275
Ankush Menat700e8642022-04-19 13:24:29 +05301276def sort_stock_vouchers_by_posting_date(
1277 stock_vouchers: List[Tuple[str, str]]
1278) -> List[Tuple[str, str]]:
1279 sle = frappe.qb.DocType("Stock Ledger Entry")
1280 voucher_nos = [v[1] for v in stock_vouchers]
1281
1282 sles = (
1283 frappe.qb.from_(sle)
1284 .select(sle.voucher_type, sle.voucher_no, sle.posting_date, sle.posting_time, sle.creation)
1285 .where((sle.is_cancelled == 0) & (sle.voucher_no.isin(voucher_nos)))
1286 .groupby(sle.voucher_type, sle.voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301287 .orderby(sle.posting_date)
1288 .orderby(sle.posting_time)
1289 .orderby(sle.creation)
Ankush Menat700e8642022-04-19 13:24:29 +05301290 ).run(as_dict=True)
1291 sorted_vouchers = [(sle.voucher_type, sle.voucher_no) for sle in sles]
1292
1293 unknown_vouchers = set(stock_vouchers) - set(sorted_vouchers)
1294 if unknown_vouchers:
1295 sorted_vouchers.extend(unknown_vouchers)
1296
1297 return sorted_vouchers
1298
1299
Ankush Menat494bd9e2022-03-28 18:52:46 +05301300def get_future_stock_vouchers(
1301 posting_date, posting_time, for_warehouses=None, for_items=None, company=None
1302):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301303
1304 values = []
1305 condition = ""
1306 if for_items:
1307 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1308 values += for_items
1309
1310 if for_warehouses:
1311 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1312 values += for_warehouses
1313
rohitwaghchaured60ff832021-02-16 09:12:27 +05301314 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301315 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301316 values.append(company)
1317
Ankush Menat494bd9e2022-03-28 18:52:46 +05301318 future_stock_vouchers = frappe.db.sql(
1319 """select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301320 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301321 where
1322 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1323 and is_cancelled = 0
1324 {condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301325 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
1326 condition=condition
1327 ),
1328 tuple([posting_date, posting_time] + values),
1329 as_dict=True,
1330 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301331
Ankush91527152021-08-11 11:17:50 +05301332 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301333
Ankush Menat494bd9e2022-03-28 18:52:46 +05301334
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301335def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301336 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301337
1338 Only fetches GLE fields required for comparing with new GLE.
1339 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301340
1341 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301342 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301343 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301344 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301345 if not future_stock_vouchers:
1346 return gl_entries
1347
1348 voucher_nos = [d[1] for d in future_stock_vouchers]
1349
Ankush Menat494bd9e2022-03-28 18:52:46 +05301350 gles = frappe.db.sql(
1351 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301352 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301353 from `tabGL Entry`
1354 where
Ankush Menat494bd9e2022-03-28 18:52:46 +05301355 posting_date >= %s and voucher_no in (%s)"""
1356 % ("%s", ", ".join(["%s"] * len(voucher_nos))),
1357 tuple([posting_date] + voucher_nos),
1358 as_dict=1,
1359 )
Ankush91527152021-08-11 11:17:50 +05301360
1361 for d in gles:
1362 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301363
Prssanna Desai82ddef52020-06-18 18:18:41 +05301364 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301365
Ankush Menat494bd9e2022-03-28 18:52:46 +05301366
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301367def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301368 if len(existing_gle) != len(expected_gle):
1369 return False
1370
Nabin Haita77b8c92020-12-21 14:45:50 +05301371 matched = True
1372 for entry in expected_gle:
1373 account_existed = False
1374 for e in existing_gle:
1375 if entry.account == e.account:
1376 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301377 if (
1378 entry.account == e.account
1379 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1380 and (
1381 flt(entry.debit, precision) != flt(e.debit, precision)
1382 or flt(entry.credit, precision) != flt(e.credit, precision)
1383 )
1384 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301385 matched = False
1386 break
1387 if not account_existed:
1388 matched = False
1389 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301390 return matched
1391
Ankush Menat494bd9e2022-03-28 18:52:46 +05301392
Nabin Haitb99c77b2020-12-25 18:12:35 +05301393def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301394 stock_accounts = [
1395 d.name
1396 for d in frappe.db.get_all(
1397 "Account", {"account_type": "Stock", "company": company, "is_group": 0}
1398 )
1399 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301400 if voucher_type and voucher_no:
1401 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301402 stock_accounts = [
1403 d.account
1404 for d in frappe.db.get_all(
1405 "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
1406 )
1407 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301408
1409 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301410 stock_accounts = [
1411 d.account
1412 for d in frappe.db.get_all(
1413 "GL Entry",
1414 {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
1415 "account",
1416 )
1417 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301418
1419 return stock_accounts
1420
Ankush Menat494bd9e2022-03-28 18:52:46 +05301421
Nabin Haitb99c77b2020-12-25 18:12:35 +05301422def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301423 if not posting_date:
1424 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301425
1426 warehouse_account = get_warehouse_account_map(company)
1427
Ankush Menat494bd9e2022-03-28 18:52:46 +05301428 account_balance = get_balance_on(
1429 account, posting_date, in_account_currency=False, ignore_account_permission=True
1430 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301431
Ankush Menat494bd9e2022-03-28 18:52:46 +05301432 related_warehouses = [
1433 wh
1434 for wh, wh_details in warehouse_account.items()
1435 if wh_details.account == account and not wh_details.is_group
1436 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301437
s-aga-re782a052023-04-25 13:54:36 +05301438 total_stock_value = get_stock_value_on(related_warehouses, posting_date)
Nabin Haitb99c77b2020-12-25 18:12:35 +05301439
1440 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1441 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1442
Ankush Menat494bd9e2022-03-28 18:52:46 +05301443
Nabin Haitb99c77b2020-12-25 18:12:35 +05301444def get_journal_entry(account, stock_adjustment_account, amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301445 db_or_cr_warehouse_account = (
1446 "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
1447 )
1448 db_or_cr_stock_adjustment_account = (
1449 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1450 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301451
1452 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301453 "accounts": [
1454 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1455 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1456 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301457 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301458
Ankush Menat494bd9e2022-03-28 18:52:46 +05301459
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301460def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301461 """Check if reports are referenced in Desktop Icon"""
1462 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301463 if icons:
1464 for icon in icons:
1465 frappe.delete_doc("Desktop Icon", icon)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301466
1467
ruthra kumar4f51c5a2023-07-03 14:35:33 +05301468def create_err_and_its_journals(companies: list = None) -> None:
1469 if companies:
1470 for company in companies:
1471 err = frappe.new_doc("Exchange Rate Revaluation")
1472 err.company = company.name
1473 err.posting_date = nowdate()
1474 err.rounding_loss_allowance = 0.0
1475
1476 err.fetch_and_calculate_accounts_data()
1477 if err.accounts:
1478 err.save().submit()
1479 response = err.make_jv_entries()
1480
1481 if company.submit_err_jv:
1482 jv = response.get("revaluation_jv", None)
1483 jv and frappe.get_doc("Journal Entry", jv).submit()
1484 jv = response.get("zero_balance_jv", None)
1485 jv and frappe.get_doc("Journal Entry", jv).submit()
1486
1487
1488def auto_create_exchange_rate_revaluation_daily() -> None:
1489 """
1490 Executed by background job
1491 """
1492 companies = frappe.db.get_all(
1493 "Company",
1494 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Daily"},
1495 fields=["name", "submit_err_jv"],
1496 )
1497 create_err_and_its_journals(companies)
1498
1499
1500def auto_create_exchange_rate_revaluation_weekly() -> None:
1501 """
1502 Executed by background job
1503 """
1504 companies = frappe.db.get_all(
1505 "Company",
1506 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Weekly"},
1507 fields=["name", "submit_err_jv"],
1508 )
1509 create_err_and_its_journals(companies)
1510
1511
ruthra kumar9b502212022-10-13 14:13:48 +05301512def get_payment_ledger_entries(gl_entries, cancel=0):
1513 ple_map = []
ruthra kumar451cf3a2022-05-16 14:29:58 +05301514 if gl_entries:
1515 ple = None
1516
1517 # companies
1518 account = qb.DocType("Account")
1519 companies = list(set([x.company for x in gl_entries]))
1520
1521 # receivable/payable account
1522 accounts_with_types = (
1523 qb.from_(account)
1524 .select(account.name, account.account_type)
1525 .where(
1526 (account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
1527 )
1528 .run(as_dict=True)
1529 )
1530 receivable_or_payable_accounts = [y.name for y in accounts_with_types]
1531
1532 def get_account_type(account):
1533 for entry in accounts_with_types:
1534 if entry.name == account:
1535 return entry.account_type
1536
1537 dr_or_cr = 0
1538 account_type = None
1539 for gle in gl_entries:
1540 if gle.account in receivable_or_payable_accounts:
1541 account_type = get_account_type(gle.account)
1542 if account_type == "Receivable":
1543 dr_or_cr = gle.debit - gle.credit
1544 dr_or_cr_account_currency = gle.debit_in_account_currency - gle.credit_in_account_currency
1545 elif account_type == "Payable":
1546 dr_or_cr = gle.credit - gle.debit
1547 dr_or_cr_account_currency = gle.credit_in_account_currency - gle.debit_in_account_currency
1548
1549 if cancel:
1550 dr_or_cr *= -1
1551 dr_or_cr_account_currency *= -1
1552
ruthra kumar9b502212022-10-13 14:13:48 +05301553 ple = frappe._dict(
1554 doctype="Payment Ledger Entry",
1555 posting_date=gle.posting_date,
1556 company=gle.company,
1557 account_type=account_type,
1558 account=gle.account,
1559 party_type=gle.party_type,
1560 party=gle.party,
1561 cost_center=gle.cost_center,
1562 finance_book=gle.finance_book,
1563 due_date=gle.due_date,
1564 voucher_type=gle.voucher_type,
1565 voucher_no=gle.voucher_no,
Deepesh Garg1e078d02023-06-29 12:18:25 +05301566 voucher_detail_no=gle.voucher_detail_no,
ruthra kumar9b502212022-10-13 14:13:48 +05301567 against_voucher_type=gle.against_voucher_type
1568 if gle.against_voucher_type
1569 else gle.voucher_type,
1570 against_voucher_no=gle.against_voucher if gle.against_voucher else gle.voucher_no,
1571 account_currency=gle.account_currency,
1572 amount=dr_or_cr,
1573 amount_in_account_currency=dr_or_cr_account_currency,
1574 delinked=True if cancel else False,
1575 remarks=gle.remarks,
ruthra kumar451cf3a2022-05-16 14:29:58 +05301576 )
1577
1578 dimensions_and_defaults = get_dimensions()
1579 if dimensions_and_defaults:
1580 for dimension in dimensions_and_defaults[0]:
ruthra kumar9b502212022-10-13 14:13:48 +05301581 ple[dimension.fieldname] = gle.get(dimension.fieldname)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301582
ruthra kumar9b502212022-10-13 14:13:48 +05301583 ple_map.append(ple)
1584 return ple_map
1585
1586
1587def create_payment_ledger_entry(
Deepesh Garg1e078d02023-06-29 12:18:25 +05301588 gl_entries, cancel=0, adv_adj=0, update_outstanding="Yes", from_repost=0, partial_cancel=False
ruthra kumar9b502212022-10-13 14:13:48 +05301589):
1590 if gl_entries:
1591 ple_map = get_payment_ledger_entries(gl_entries, cancel=cancel)
1592
1593 for entry in ple_map:
1594
1595 ple = frappe.get_doc(entry)
1596
1597 if cancel:
Deepesh Garg1e078d02023-06-29 12:18:25 +05301598 delink_original_entry(ple, partial_cancel=partial_cancel)
ruthra kumar9b502212022-10-13 14:13:48 +05301599
1600 ple.flags.ignore_permissions = 1
1601 ple.flags.adv_adj = adv_adj
1602 ple.flags.from_repost = from_repost
1603 ple.flags.update_outstanding = update_outstanding
1604 ple.submit()
ruthra kumar451cf3a2022-05-16 14:29:58 +05301605
1606
ruthra kumar7312f222022-05-29 21:33:08 +05301607def update_voucher_outstanding(voucher_type, voucher_no, account, party_type, party):
1608 ple = frappe.qb.DocType("Payment Ledger Entry")
1609 vouchers = [frappe._dict({"voucher_type": voucher_type, "voucher_no": voucher_no})]
1610 common_filter = []
1611 if account:
1612 common_filter.append(ple.account == account)
1613
1614 if party_type:
1615 common_filter.append(ple.party_type == party_type)
1616
1617 if party:
1618 common_filter.append(ple.party == party)
1619
1620 ple_query = QueryPaymentLedger()
1621
1622 # on cancellation outstanding can be an empty list
1623 voucher_outstanding = ple_query.get_voucher_outstandings(vouchers, common_filter=common_filter)
ruthra kumar43b80682022-10-18 09:33:37 +05301624 if (
1625 voucher_type in ["Sales Invoice", "Purchase Invoice", "Fees"]
1626 and party_type
1627 and party
1628 and voucher_outstanding
1629 ):
ruthra kumar7312f222022-05-29 21:33:08 +05301630 outstanding = voucher_outstanding[0]
1631 ref_doc = frappe.get_doc(voucher_type, voucher_no)
1632
1633 # Didn't use db_set for optimisation purpose
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301634 ref_doc.outstanding_amount = outstanding["outstanding_in_account_currency"] or 0.0
ruthra kumar7312f222022-05-29 21:33:08 +05301635 frappe.db.set_value(
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301636 voucher_type,
1637 voucher_no,
1638 "outstanding_amount",
1639 outstanding["outstanding_in_account_currency"] or 0.0,
ruthra kumar7312f222022-05-29 21:33:08 +05301640 )
1641
1642 ref_doc.set_status(update=True)
1643
1644
Deepesh Garg1e078d02023-06-29 12:18:25 +05301645def delink_original_entry(pl_entry, partial_cancel=False):
ruthra kumar451cf3a2022-05-16 14:29:58 +05301646 if pl_entry:
1647 ple = qb.DocType("Payment Ledger Entry")
1648 query = (
1649 qb.update(ple)
1650 .set(ple.delinked, True)
1651 .set(ple.modified, now())
1652 .set(ple.modified_by, frappe.session.user)
1653 .where(
1654 (ple.company == pl_entry.company)
1655 & (ple.account_type == pl_entry.account_type)
1656 & (ple.account == pl_entry.account)
1657 & (ple.party_type == pl_entry.party_type)
1658 & (ple.party == pl_entry.party)
1659 & (ple.voucher_type == pl_entry.voucher_type)
1660 & (ple.voucher_no == pl_entry.voucher_no)
1661 & (ple.against_voucher_type == pl_entry.against_voucher_type)
1662 & (ple.against_voucher_no == pl_entry.against_voucher_no)
1663 )
1664 )
Deepesh Garg1e078d02023-06-29 12:18:25 +05301665
1666 if partial_cancel:
1667 query = query.where(ple.voucher_detail_no == pl_entry.voucher_detail_no)
1668
ruthra kumar451cf3a2022-05-16 14:29:58 +05301669 query.run()
ruthra kumar7b383882022-05-25 15:51:16 +05301670
1671
1672class QueryPaymentLedger(object):
1673 """
1674 Helper Class for Querying Payment Ledger Entry
1675 """
1676
1677 def __init__(self):
1678 self.ple = qb.DocType("Payment Ledger Entry")
1679
1680 # query result
1681 self.voucher_outstandings = []
1682
1683 # query filters
1684 self.vouchers = []
1685 self.common_filter = []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301686 self.voucher_posting_date = []
ruthra kumar7b383882022-05-25 15:51:16 +05301687 self.min_outstanding = None
1688 self.max_outstanding = None
ruthra kumar7a381af2023-05-03 20:45:12 +05301689 self.limit = self.voucher_no = None
ruthra kumar7b383882022-05-25 15:51:16 +05301690
1691 def reset(self):
1692 # clear filters
1693 self.vouchers.clear()
1694 self.common_filter.clear()
ruthra kumar7a381af2023-05-03 20:45:12 +05301695 self.min_outstanding = self.max_outstanding = self.limit = None
ruthra kumar7b383882022-05-25 15:51:16 +05301696
1697 # clear result
1698 self.voucher_outstandings.clear()
1699
1700 def query_for_outstanding(self):
1701 """
1702 Database query to fetch voucher amount and voucher outstanding using Common Table Expression
1703 """
1704
1705 ple = self.ple
1706
1707 filter_on_voucher_no = []
1708 filter_on_against_voucher_no = []
ruthra kumar7a381af2023-05-03 20:45:12 +05301709
ruthra kumar7b383882022-05-25 15:51:16 +05301710 if self.vouchers:
1711 voucher_types = set([x.voucher_type for x in self.vouchers])
1712 voucher_nos = set([x.voucher_no for x in self.vouchers])
1713
1714 filter_on_voucher_no.append(ple.voucher_type.isin(voucher_types))
1715 filter_on_voucher_no.append(ple.voucher_no.isin(voucher_nos))
1716
1717 filter_on_against_voucher_no.append(ple.against_voucher_type.isin(voucher_types))
1718 filter_on_against_voucher_no.append(ple.against_voucher_no.isin(voucher_nos))
1719
ruthra kumar7a381af2023-05-03 20:45:12 +05301720 if self.voucher_no:
1721 filter_on_voucher_no.append(ple.voucher_no.like(f"%{self.voucher_no}%"))
1722 filter_on_against_voucher_no.append(ple.against_voucher_no.like(f"%{self.voucher_no}%"))
1723
ruthra kumar7b383882022-05-25 15:51:16 +05301724 # build outstanding amount filter
1725 filter_on_outstanding_amount = []
1726 if self.min_outstanding:
1727 if self.min_outstanding > 0:
1728 filter_on_outstanding_amount.append(
1729 Table("outstanding").amount_in_account_currency >= self.min_outstanding
1730 )
1731 else:
1732 filter_on_outstanding_amount.append(
1733 Table("outstanding").amount_in_account_currency <= self.min_outstanding
1734 )
1735 if self.max_outstanding:
1736 if self.max_outstanding > 0:
1737 filter_on_outstanding_amount.append(
1738 Table("outstanding").amount_in_account_currency <= self.max_outstanding
1739 )
1740 else:
1741 filter_on_outstanding_amount.append(
1742 Table("outstanding").amount_in_account_currency >= self.max_outstanding
1743 )
1744
1745 # build query for voucher amount
1746 query_voucher_amount = (
1747 qb.from_(ple)
1748 .select(
1749 ple.account,
1750 ple.voucher_type,
1751 ple.voucher_no,
1752 ple.party_type,
1753 ple.party,
1754 ple.posting_date,
1755 ple.due_date,
1756 ple.account_currency.as_("currency"),
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301757 ple.cost_center.as_("cost_center"),
ruthra kumar7b383882022-05-25 15:51:16 +05301758 Sum(ple.amount).as_("amount"),
1759 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1760 )
1761 .where(ple.delinked == 0)
1762 .where(Criterion.all(filter_on_voucher_no))
1763 .where(Criterion.all(self.common_filter))
ruthra kumar6d9d7302022-12-14 16:05:15 +05301764 .where(Criterion.all(self.dimensions_filter))
ruthra kumar5f1562c2022-07-28 11:57:27 +05301765 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar7b383882022-05-25 15:51:16 +05301766 .groupby(ple.voucher_type, ple.voucher_no, ple.party_type, ple.party)
1767 )
1768
1769 # build query for voucher outstanding
1770 query_voucher_outstanding = (
1771 qb.from_(ple)
1772 .select(
1773 ple.account,
1774 ple.against_voucher_type.as_("voucher_type"),
1775 ple.against_voucher_no.as_("voucher_no"),
1776 ple.party_type,
1777 ple.party,
1778 ple.posting_date,
1779 ple.due_date,
1780 ple.account_currency.as_("currency"),
1781 Sum(ple.amount).as_("amount"),
1782 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1783 )
1784 .where(ple.delinked == 0)
1785 .where(Criterion.all(filter_on_against_voucher_no))
1786 .where(Criterion.all(self.common_filter))
1787 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1788 )
1789
1790 # build CTE for combining voucher amount and outstanding
1791 self.cte_query_voucher_amount_and_outstanding = (
1792 qb.with_(query_voucher_amount, "vouchers")
1793 .with_(query_voucher_outstanding, "outstanding")
1794 .from_(AliasedQuery("vouchers"))
1795 .left_join(AliasedQuery("outstanding"))
1796 .on(
1797 (AliasedQuery("vouchers").account == AliasedQuery("outstanding").account)
1798 & (AliasedQuery("vouchers").voucher_type == AliasedQuery("outstanding").voucher_type)
1799 & (AliasedQuery("vouchers").voucher_no == AliasedQuery("outstanding").voucher_no)
1800 & (AliasedQuery("vouchers").party_type == AliasedQuery("outstanding").party_type)
1801 & (AliasedQuery("vouchers").party == AliasedQuery("outstanding").party)
1802 )
1803 .select(
1804 Table("vouchers").account,
1805 Table("vouchers").voucher_type,
1806 Table("vouchers").voucher_no,
1807 Table("vouchers").party_type,
1808 Table("vouchers").party,
1809 Table("vouchers").posting_date,
1810 Table("vouchers").amount.as_("invoice_amount"),
1811 Table("vouchers").amount_in_account_currency.as_("invoice_amount_in_account_currency"),
1812 Table("outstanding").amount.as_("outstanding"),
1813 Table("outstanding").amount_in_account_currency.as_("outstanding_in_account_currency"),
1814 (Table("vouchers").amount - Table("outstanding").amount).as_("paid_amount"),
1815 (
1816 Table("vouchers").amount_in_account_currency - Table("outstanding").amount_in_account_currency
1817 ).as_("paid_amount_in_account_currency"),
1818 Table("vouchers").due_date,
1819 Table("vouchers").currency,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301820 Table("vouchers").cost_center.as_("cost_center"),
ruthra kumar7b383882022-05-25 15:51:16 +05301821 )
1822 .where(Criterion.all(filter_on_outstanding_amount))
1823 )
1824
1825 # build CTE filter
1826 # only fetch invoices
1827 if self.get_invoices:
1828 self.cte_query_voucher_amount_and_outstanding = (
1829 self.cte_query_voucher_amount_and_outstanding.having(
1830 qb.Field("outstanding_in_account_currency") > 0
1831 )
1832 )
1833 # only fetch payments
1834 elif self.get_payments:
1835 self.cte_query_voucher_amount_and_outstanding = (
1836 self.cte_query_voucher_amount_and_outstanding.having(
1837 qb.Field("outstanding_in_account_currency") < 0
1838 )
1839 )
1840
ruthra kumar7a381af2023-05-03 20:45:12 +05301841 if self.limit:
1842 self.cte_query_voucher_amount_and_outstanding = (
1843 self.cte_query_voucher_amount_and_outstanding.limit(self.limit)
1844 )
1845
ruthra kumar7b383882022-05-25 15:51:16 +05301846 # execute SQL
1847 self.voucher_outstandings = self.cte_query_voucher_amount_and_outstanding.run(as_dict=True)
1848
1849 def get_voucher_outstandings(
1850 self,
1851 vouchers=None,
1852 common_filter=None,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301853 posting_date=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301854 min_outstanding=None,
1855 max_outstanding=None,
1856 get_payments=False,
1857 get_invoices=False,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301858 accounting_dimensions=None,
ruthra kumar7a381af2023-05-03 20:45:12 +05301859 limit=None,
1860 voucher_no=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301861 ):
1862 """
1863 Fetch voucher amount and outstanding amount from Payment Ledger using Database CTE
1864
1865 vouchers - dict of vouchers to get
1866 common_filter - array of criterions
1867 min_outstanding - filter on minimum total outstanding amount
1868 max_outstanding - filter on maximum total outstanding amount
1869 get_invoices - only fetch vouchers(ledger entries with +ve outstanding)
1870 get_payments - only fetch payments(ledger entries with -ve outstanding)
1871 """
1872
1873 self.reset()
1874 self.vouchers = vouchers
1875 self.common_filter = common_filter or []
ruthra kumar6d9d7302022-12-14 16:05:15 +05301876 self.dimensions_filter = accounting_dimensions or []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301877 self.voucher_posting_date = posting_date or []
ruthra kumar7b383882022-05-25 15:51:16 +05301878 self.min_outstanding = min_outstanding
1879 self.max_outstanding = max_outstanding
1880 self.get_payments = get_payments
1881 self.get_invoices = get_invoices
ruthra kumar7a381af2023-05-03 20:45:12 +05301882 self.limit = limit
1883 self.voucher_no = voucher_no
ruthra kumar7b383882022-05-25 15:51:16 +05301884 self.query_for_outstanding()
1885
1886 return self.voucher_outstandings
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05301887
1888
1889def create_gain_loss_journal(
1890 company,
1891 party_type,
1892 party,
1893 party_account,
1894 gain_loss_account,
1895 exc_gain_loss,
1896 dr_or_cr,
1897 reverse_dr_or_cr,
1898 ref1_dt,
1899 ref1_dn,
1900 ref1_detail_no,
1901 ref2_dt,
1902 ref2_dn,
1903 ref2_detail_no,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301904 cost_center,
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05301905) -> str:
1906 journal_entry = frappe.new_doc("Journal Entry")
1907 journal_entry.voucher_type = "Exchange Gain Or Loss"
1908 journal_entry.company = company
1909 journal_entry.posting_date = nowdate()
1910 journal_entry.multi_currency = 1
ruthra kumar79c6f012023-09-01 14:57:12 +05301911 journal_entry.is_system_generated = True
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05301912
1913 party_account_currency = frappe.get_cached_value("Account", party_account, "account_currency")
1914
1915 if not gain_loss_account:
1916 frappe.throw(_("Please set default Exchange Gain/Loss Account in Company {}").format(company))
1917 gain_loss_account_currency = get_account_currency(gain_loss_account)
1918 company_currency = frappe.get_cached_value("Company", company, "default_currency")
1919
1920 if gain_loss_account_currency != company_currency:
1921 frappe.throw(_("Currency for {0} must be {1}").format(gain_loss_account, company_currency))
1922
1923 journal_account = frappe._dict(
1924 {
1925 "account": party_account,
1926 "party_type": party_type,
1927 "party": party,
1928 "account_currency": party_account_currency,
1929 "exchange_rate": 0,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301930 "cost_center": cost_center or erpnext.get_default_cost_center(company),
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05301931 "reference_type": ref1_dt,
1932 "reference_name": ref1_dn,
1933 "reference_detail_no": ref1_detail_no,
1934 dr_or_cr: abs(exc_gain_loss),
1935 dr_or_cr + "_in_account_currency": 0,
1936 }
1937 )
1938
1939 journal_entry.append("accounts", journal_account)
1940
1941 journal_account = frappe._dict(
1942 {
1943 "account": gain_loss_account,
1944 "account_currency": gain_loss_account_currency,
1945 "exchange_rate": 1,
ruthra kumard6a3b9a2023-09-03 07:21:09 +05301946 "cost_center": cost_center or erpnext.get_default_cost_center(company),
ruthra kumar1ea1bfe2023-07-26 16:19:38 +05301947 "reference_type": ref2_dt,
1948 "reference_name": ref2_dn,
1949 "reference_detail_no": ref2_detail_no,
1950 reverse_dr_or_cr + "_in_account_currency": 0,
1951 reverse_dr_or_cr: abs(exc_gain_loss),
1952 }
1953 )
1954
1955 journal_entry.append("accounts", journal_account)
1956
1957 journal_entry.save()
1958 journal_entry.submit()
1959 return journal_entry.name