blob: cfd0133700da0fe25c3414faf1311ecc00e94d9f [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,
182):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530183 if not account and frappe.form_dict.get("account"):
184 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530185 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530186 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530187 if not party_type and frappe.form_dict.get("party_type"):
188 party_type = frappe.form_dict.get("party_type")
189 if not party and frappe.form_dict.get("party"):
190 party = frappe.form_dict.get("party")
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400191 if not cost_center and frappe.form_dict.get("cost_center"):
192 cost_center = frappe.form_dict.get("cost_center")
193
Nabin Hait98372852020-07-30 20:52:20 +0530194 cond = ["is_cancelled=0"]
Nabin Hait23941aa2013-01-29 11:32:38 +0530195 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530196 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530197 else:
198 # get balance of all entries that exist
199 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530200
Deepesh Garg8c217032019-07-16 09:41:01 +0530201 if account:
202 acc = frappe.get_doc("Account", account)
203
Nabin Hait23941aa2013-01-29 11:32:38 +0530204 try:
Deepesh Garg96d40ec2020-07-03 22:59:00 +0530205 year_start_date = get_fiscal_year(date, company=company, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530206 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +0530207 if getdate(date) > getdate(nowdate()):
208 # if fiscal year not found and the date is greater than today
209 # get fiscal year for today's date and its corresponding year start date
210 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
211 else:
212 # this indicates that it is a date older than any existing fiscal year.
213 # hence, assuming balance as 0.0
214 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530215
deepeshgarg0072ddbebf2019-07-20 14:52:59 +0530216 if account:
deepeshgarg007e097d4f2019-07-20 14:49:32 +0530217 report_type = acc.report_type
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530218 else:
219 report_type = ""
220
Ankush Menat494bd9e2022-03-28 18:52:46 +0530221 if cost_center and report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400222 cc = frappe.get_doc("Cost Center", cost_center)
223 if cc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530224 cond.append(
225 """ exists (
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400226 select 1 from `tabCost Center` cc where cc.name = gle.cost_center
227 and cc.lft >= %s and cc.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530228 )"""
229 % (cc.lft, cc.rgt)
230 )
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400231
232 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center, percent=False),))
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400234
Nabin Hait6f17cf92014-09-17 14:11:22 +0530235 if account:
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400236
Ankush Menat494bd9e2022-03-28 18:52:46 +0530237 if not (frappe.flags.ignore_account_permission or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530238 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530239
Nabin Hait6f17cf92014-09-17 14:11:22 +0530240 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530241 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530242 cond.append(
243 """exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530244 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530245 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530246 )"""
247 % (acc.lft, acc.rgt)
248 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530249
250 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530251 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530252 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530253 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530254 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530255 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
Anand Doshic75c1d72016-03-11 14:56:19 +0530256
Nabin Hait6f17cf92014-09-17 14:11:22 +0530257 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530258 cond.append(
259 """gle.party_type = %s and gle.party = %s """
260 % (frappe.db.escape(party_type), frappe.db.escape(party, percent=False))
261 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530262
Nabin Hait85648d92016-07-20 11:26:45 +0530263 if company:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530264 cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530265
Nabin Haitdc768232015-08-17 11:27:00 +0530266 if account or (party_type and party):
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530267 if in_account_currency:
Anand Doshi602e8252015-11-16 19:05:46 +0530268 select_field = "sum(debit_in_account_currency) - sum(credit_in_account_currency)"
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530269 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530270 select_field = "sum(debit) - sum(credit)"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530271 bal = frappe.db.sql(
272 """
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530273 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530274 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530275 WHERE {1}""".format(
276 select_field, " and ".join(cond)
277 )
278 )[0][0]
Anand Doshicd71e1d2014-04-08 13:53:35 +0530279
Nabin Haitdc768232015-08-17 11:27:00 +0530280 # if bal is None, return 0
281 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530282
Ankush Menat494bd9e2022-03-28 18:52:46 +0530283
RobertSchouten8d43b322016-09-20 13:41:39 +0800284def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530285 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800286 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530287 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800288 else:
289 # get balance of all entries that exist
290 date = nowdate()
291
292 try:
293 year_start_date = get_fiscal_year(date, verbose=0)[1]
294 except FiscalYearError:
295 if getdate(date) > getdate(nowdate()):
296 # if fiscal year not found and the date is greater than today
297 # get fiscal year for today's date and its corresponding year start date
298 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
299 else:
300 # this indicates that it is a date older than any existing fiscal year.
301 # hence, assuming balance as 0.0
302 return 0.0
303
304 if account:
305 acc = frappe.get_doc("Account", account)
306
307 if not frappe.flags.ignore_account_permission:
308 acc.check_permission("read")
309
310 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530311 if acc.report_type == "Profit and Loss":
312 cond.append(
313 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
314 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800315
316 # different filter for group and ledger - improved performance
317 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530318 cond.append(
319 """exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800320 select name from `tabAccount` ac where ac.name = gle.account
321 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530322 )"""
323 % (acc.lft, acc.rgt)
324 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800325 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530326 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
RobertSchouten8d43b322016-09-20 13:41:39 +0800327
Ankush Menat494bd9e2022-03-28 18:52:46 +0530328 entries = frappe.db.sql(
329 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800330 SELECT name, posting_date, account, party_type, party,debit,credit,
331 voucher_type, voucher_no, against_voucher_type, against_voucher
332 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530333 WHERE {0}""".format(
334 " and ".join(cond)
335 ),
336 as_dict=True,
337 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530338
RobertSchouten8d43b322016-09-20 13:41:39 +0800339 count = 0
340 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530341 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800342 count += 1
343 else:
344 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
345 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530346 select_fields = (
347 "ifnull(sum(credit-debit),0)"
348 if fieldname == "invoiced_amount"
349 else "ifnull(sum(debit-credit),0)"
350 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800351
Ankush Menat494bd9e2022-03-28 18:52:46 +0530352 if (
353 (not gle.against_voucher)
354 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
355 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
356 ):
357 payment_amount = frappe.db.sql(
358 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800359 SELECT {0}
360 FROM `tabGL Entry` gle
361 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530362 and party = %(party)s and name != %(name)s""".format(
363 select_fields
364 ),
365 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
366 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530367
RobertSchouten8d43b322016-09-20 13:41:39 +0800368 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
369 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530370 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800371 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530372
RobertSchouten8d43b322016-09-20 13:41:39 +0800373 return count
374
Ankush Menat494bd9e2022-03-28 18:52:46 +0530375
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530376@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530377def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530378 from frappe.desk.treeview import make_tree_args
379
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530380 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530381 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530382
Nabin Hait02d987e2017-02-17 15:50:26 +0530383 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530384 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530385
Anand Doshi3e41fd12014-04-22 18:54:54 +0530386 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530387
Nabin Hait665568d2016-05-13 15:56:00 +0530388 if args.get("ignore_permissions"):
389 ac.flags.ignore_permissions = True
390 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530391
Anand Doshi3e41fd12014-04-22 18:54:54 +0530392 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530393
394 if not ac.parent_account:
395 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530396
Anand Doshif78d1ae2014-03-28 13:55:00 +0530397 ac.old_parent = ""
398 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530399 if cint(ac.get("is_root")):
400 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530401 ac.flags.ignore_mandatory = True
402
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530403 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530404
Anand Doshif78d1ae2014-03-28 13:55:00 +0530405 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530406
Ankush Menat494bd9e2022-03-28 18:52:46 +0530407
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530408@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530409def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530410 from frappe.desk.treeview import make_tree_args
411
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530412 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530413 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530414
Nabin Hait02d987e2017-02-17 15:50:26 +0530415 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530416 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530417
Zarrar7ab70ca2018-06-08 14:33:15 +0530418 if args.parent_cost_center == args.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530419 args.parent_cost_center = "{0} - {1}".format(
420 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
421 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530422
Anand Doshi3e41fd12014-04-22 18:54:54 +0530423 cc = frappe.new_doc("Cost Center")
424 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530425
426 if not cc.parent_cost_center:
427 cc.parent_cost_center = args.get("parent")
428
Anand Doshif78d1ae2014-03-28 13:55:00 +0530429 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530430 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530431 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530432
Ankush Menat494bd9e2022-03-28 18:52:46 +0530433
Deepesh Garg016ed952023-06-20 13:22:32 +0530434def reconcile_against_document(args, skip_ref_details_update_for_pe=False): # nosemgrep
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530435 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530436 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530437 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530438 # To optimize making GL Entry for PE or JV with multiple references
439 reconciled_entries = {}
440 for row in args:
441 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
442 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530443
Anuja Pawar3e404f12021-08-31 18:59:29 +0530444 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
445
446 for key, entries in reconciled_entries.items():
447 voucher_type = key[0]
448 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530449
Nabin Hait28a05282016-06-27 17:41:39 +0530450 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530451 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530452 frappe.flags.ignore_party_validation = True
ruthra kumar11cf6942023-01-14 12:22:22 +0530453 _delete_pl_entries(voucher_type, voucher_no)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530454
Anuja Pawar3e404f12021-08-31 18:59:29 +0530455 for entry in entries:
456 check_if_advance_entry_modified(entry)
457 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530458
Anuja Pawar3e404f12021-08-31 18:59:29 +0530459 # update ref in advance entry
460 if voucher_type == "Journal Entry":
461 update_reference_in_journal_entry(entry, doc, do_not_save=True)
ruthra kumar7b516f82023-06-26 17:34:28 +0530462 # advance section in sales/purchase invoice and reconciliation tool,both pass on exchange gain/loss
463 # amount and account in args
464 doc.make_exchange_gain_loss_journal(args)
Anuja Pawar3e404f12021-08-31 18:59:29 +0530465 else:
ruthra kumared14d1c2023-04-22 17:24:35 +0530466 update_reference_in_payment_entry(
467 entry, doc, do_not_save=True, skip_ref_details_update_for_pe=skip_ref_details_update_for_pe
468 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530469
470 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530471 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530472 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
Deepesh Garg016ed952023-06-20 13:22:32 +0530473 gl_map = doc.build_gl_map()
ruthra kumar11cf6942023-01-14 12:22:22 +0530474 create_payment_ledger_entry(gl_map, update_outstanding="No", cancel=0, adv_adj=1)
Deepesh Garg1894dc82023-06-23 21:53:34 +0530475
476 if voucher_type == "Payment Entry":
Deepesh Gargf2edc912023-06-27 18:11:47 +0530477 doc.make_advance_gl_entries()
ruthra kumar11cf6942023-01-14 12:22:22 +0530478
479 # Only update outstanding for newly linked vouchers
480 for entry in entries:
481 update_voucher_outstanding(
482 entry.against_voucher_type, entry.against_voucher, entry.account, entry.party_type, entry.party
483 )
ruthra kumar524c1752022-05-26 16:00:40 +0530484
Subin Tomb8845b92021-07-30 16:30:18 +0530485 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530486
Ankush Menat494bd9e2022-03-28 18:52:46 +0530487
Nabin Hait28a05282016-06-27 17:41:39 +0530488def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530489 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530490 check if there is already a voucher reference
491 check if amount is same
492 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530493 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530494 if not args.get("unreconciled_amount"):
495 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530496
Nabin Hait28a05282016-06-27 17:41:39 +0530497 ret = None
498 if args.voucher_type == "Journal Entry":
Gursheen Anand74619262023-06-02 17:13:51 +0530499 journal_entry = frappe.qb.DocType("Journal Entry")
500 journal_acc = frappe.qb.DocType("Journal Entry Account")
501
Gursheen Anand4ee16372023-06-08 13:15:23 +0530502 q = (
503 frappe.qb.from_(journal_entry)
Deepesh Garg3aead052023-06-22 11:41:43 +0530504 .inner_join(journal_acc)
Gursheen Anand74619262023-06-02 17:13:51 +0530505 .on(journal_entry.name == journal_acc.parent)
Deepesh Gargd81d6062023-06-22 18:28:16 +0530506 .select(journal_acc[args.get("dr_or_cr")])
507 .where(
508 (journal_acc.account == args.get("account"))
509 & ((journal_acc.party_type == args.get("party_type")))
510 & ((journal_acc.party == args.get("party")))
511 & (
512 (journal_acc.reference_type.isnull())
513 | (journal_acc.reference_type.isin(["", "Sales Order", "Purchase Order"]))
514 )
515 & ((journal_entry.name == args.get("voucher_no")))
516 & ((journal_acc.name == args.get("voucher_detail_no")))
517 & ((journal_entry.docstatus == 1))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530518 )
Gursheen Anand74619262023-06-02 17:13:51 +0530519 )
520
Nabin Hait28a05282016-06-27 17:41:39 +0530521 else:
Gursheen Anand74619262023-06-02 17:13:51 +0530522 payment_entry = frappe.qb.DocType("Payment Entry")
523 payment_ref = frappe.qb.DocType("Payment Entry Reference")
524
Gursheen Anand4ee16372023-06-08 13:15:23 +0530525 q = (
526 frappe.qb.from_(payment_entry)
Gursheen Anand74619262023-06-02 17:13:51 +0530527 .select(payment_entry.name)
528 .where(payment_entry.name == args.get("voucher_no"))
529 .where(payment_entry.docstatus == 1)
530 .where(payment_entry.party_type == args.get("party_type"))
531 .where(payment_entry.party == args.get("party"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530532 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530533
Nabin Hait28a05282016-06-27 17:41:39 +0530534 if args.voucher_detail_no:
Gursheen Anand4ee16372023-06-08 13:15:23 +0530535 q = (
536 q.inner_join(payment_ref)
Gursheen Anand74619262023-06-02 17:13:51 +0530537 .on(payment_entry.name == payment_ref.parent)
538 .where(payment_ref.name == args.get("voucher_detail_no"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530539 .where(payment_ref.reference_doctype.isin(("", "Sales Order", "Purchase Order")))
Gursheen Anand74619262023-06-02 17:13:51 +0530540 .where(payment_ref.allocated_amount == args.get("unreconciled_amount"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530541 )
Nabin Hait28a05282016-06-27 17:41:39 +0530542 else:
Gursheen Anand74619262023-06-02 17:13:51 +0530543 q = q.where(payment_entry.unallocated_amount == args.get("unreconciled_amount"))
Gursheen Anand4ee16372023-06-08 13:15:23 +0530544
Gursheen Anand74619262023-06-02 17:13:51 +0530545 ret = q.run(as_dict=True)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530546
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530547 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530548 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530549
Ankush Menat494bd9e2022-03-28 18:52:46 +0530550
Nabin Hait576f0252014-04-30 19:30:50 +0530551def validate_allocated_amount(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530552 precision = args.get("precision") or frappe.db.get_single_value(
553 "System Settings", "currency_precision"
554 )
Nabin Hait28a05282016-06-27 17:41:39 +0530555 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530556 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530557 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530558 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530559
Ankush Menat494bd9e2022-03-28 18:52:46 +0530560
Anuja Pawar3e404f12021-08-31 18:59:29 +0530561def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530562 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530563 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530564 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530565 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530566
Ankush Menat494bd9e2022-03-28 18:52:46 +0530567 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530568 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530569 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530570 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530571 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
572 jv_detail.set(
573 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
574 amount_in_company_currency,
575 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530576 else:
577 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530578
Anuja Pawar3e404f12021-08-31 18:59:29 +0530579 # new row with references
580 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530581
582 new_row.update((frappe.copy_doc(jv_detail)).as_dict())
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530583
Anuja Pawar3e404f12021-08-31 18:59:29 +0530584 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530585 new_row.set(
586 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
587 d["allocated_amount"] * flt(jv_detail.exchange_rate),
588 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530589
Ankush Menat494bd9e2022-03-28 18:52:46 +0530590 new_row.set(
591 "credit_in_account_currency"
592 if d["dr_or_cr"] == "debit_in_account_currency"
593 else "debit_in_account_currency",
594 0,
595 )
596 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530597
Anuja Pawar3e404f12021-08-31 18:59:29 +0530598 new_row.set("reference_type", d["against_voucher_type"])
599 new_row.set("reference_name", d["against_voucher"])
600
601 new_row.against_account = cstr(jv_detail.against_account)
602 new_row.is_advance = cstr(jv_detail.is_advance)
603 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530604
605 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530606 journal_entry.flags.ignore_validate_update_after_submit = True
607 if not do_not_save:
608 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530609
Ankush Menat494bd9e2022-03-28 18:52:46 +0530610
ruthra kumared14d1c2023-04-22 17:24:35 +0530611def update_reference_in_payment_entry(
612 d, payment_entry, do_not_save=False, skip_ref_details_update_for_pe=False
613):
Nabin Hait28a05282016-06-27 17:41:39 +0530614 reference_details = {
615 "reference_doctype": d.against_voucher_type,
616 "reference_name": d.against_voucher,
617 "total_amount": d.grand_total,
618 "outstanding_amount": d.outstanding_amount,
619 "allocated_amount": d.allocated_amount,
ruthra kumar81cd7872023-04-27 09:46:54 +0530620 "exchange_rate": d.exchange_rate if d.exchange_gain_loss else payment_entry.get_exchange_rate(),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530621 "exchange_gain_loss": d.exchange_gain_loss, # only populated from invoice in case of advance allocation
Gursheen Anandb65e58c2023-06-08 18:15:37 +0530622 "account": d.account,
Nabin Hait28a05282016-06-27 17:41:39 +0530623 }
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530624
Nabin Hait28a05282016-06-27 17:41:39 +0530625 if d.voucher_detail_no:
626 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
627 original_row = existing_row.as_dict().copy()
628 existing_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530629
Nabin Hait28a05282016-06-27 17:41:39 +0530630 if d.allocated_amount < original_row.allocated_amount:
631 new_row = payment_entry.append("references")
632 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500633 for field in list(reference_details):
Nabin Hait28a05282016-06-27 17:41:39 +0530634 new_row.set(field, original_row[field])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530635
Nabin Hait28a05282016-06-27 17:41:39 +0530636 new_row.allocated_amount = original_row.allocated_amount - d.allocated_amount
637 else:
638 new_row = payment_entry.append("references")
639 new_row.docstatus = 1
640 new_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530641
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530642 if d.difference_amount and d.difference_account:
Saqiba20999c2021-07-12 14:33:23 +0530643 account_details = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530644 "account": d.difference_account,
645 "cost_center": payment_entry.cost_center
646 or frappe.get_cached_value("Company", payment_entry.company, "cost_center"),
Saqiba20999c2021-07-12 14:33:23 +0530647 }
648 if d.difference_amount:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 account_details["amount"] = d.difference_amount
Saqiba20999c2021-07-12 14:33:23 +0530650
651 payment_entry.set_gain_or_loss(account_details=account_details)
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530652
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500653 payment_entry.flags.ignore_validate_update_after_submit = True
654 payment_entry.setup_party_account_field()
655 payment_entry.set_missing_values()
ruthra kumared14d1c2023-04-22 17:24:35 +0530656 if not skip_ref_details_update_for_pe:
657 payment_entry.set_missing_ref_details()
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500658 payment_entry.set_amounts()
ruthra kumar81cd7872023-04-27 09:46:54 +0530659 payment_entry.make_exchange_gain_loss_journal()
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500660
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530661 if not do_not_save:
662 payment_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530663
Ankush Menat494bd9e2022-03-28 18:52:46 +0530664
ruthra kumar81cd7872023-04-27 09:46:54 +0530665def cancel_exchange_gain_loss_journal(parent_doc: dict | object) -> None:
666 """
667 Cancel Exchange Gain/Loss for Sales/Purchase Invoice, if they have any.
668 """
669 if parent_doc.doctype in ["Sales Invoice", "Purchase Invoice", "Payment Entry"]:
670 journals = frappe.db.get_all(
671 "Journal Entry Account",
672 filters={
673 "reference_type": parent_doc.doctype,
674 "reference_name": parent_doc.name,
675 "docstatus": 1,
676 },
677 fields=["parent"],
678 as_list=1,
679 )
680 if journals:
681 exchange_journals = frappe.db.get_all(
682 "Journal Entry",
683 filters={
684 "name": ["in", [x[0] for x in journals]],
685 "voucher_type": "Exchange Gain Or Loss",
686 "docstatus": 1,
687 },
688 as_list=1,
689 )
690 for doc in exchange_journals:
691 frappe.get_doc("Journal Entry", doc[0]).cancel()
692
693
Nabin Hait297d74a2016-11-23 15:58:51 +0530694def unlink_ref_doc_from_payment_entries(ref_doc):
695 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name)
696 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530697
Ankush Menat494bd9e2022-03-28 18:52:46 +0530698 frappe.db.sql(
699 """update `tabGL Entry`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530700 set against_voucher_type=null, against_voucher=null,
701 modified=%s, modified_by=%s
702 where against_voucher_type=%s and against_voucher=%s
703 and voucher_no != ifnull(against_voucher, '')""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530704 (now(), frappe.session.user, ref_doc.doctype, ref_doc.name),
705 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530706
ruthra kumar537d9532022-10-10 10:17:19 +0530707 ple = qb.DocType("Payment Ledger Entry")
708
709 qb.update(ple).set(ple.against_voucher_type, ple.voucher_type).set(
710 ple.against_voucher_no, ple.voucher_no
711 ).set(ple.modified, now()).set(ple.modified_by, frappe.session.user).where(
712 (ple.against_voucher_type == ref_doc.doctype)
713 & (ple.against_voucher_no == ref_doc.name)
714 & (ple.delinked == 0)
715 ).run()
716
Nabin Hait297d74a2016-11-23 15:58:51 +0530717 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
718 ref_doc.set("advances", [])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530719
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 frappe.db.sql(
721 """delete from `tab{0} Advance` where parent = %s""".format(ref_doc.doctype), ref_doc.name
722 )
723
Anand Doshicd71e1d2014-04-08 13:53:35 +0530724
Nabin Haite0cc87d2016-07-21 18:30:03 +0530725def remove_ref_doc_link_from_jv(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530726 linked_jv = frappe.db.sql_list(
727 """select parent from `tabJournal Entry Account`
728 where reference_type=%s and reference_name=%s and docstatus < 2""",
729 (ref_type, ref_no),
730 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530731
732 if linked_jv:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530733 frappe.db.sql(
734 """update `tabJournal Entry Account`
Rushabh Mehta1828c122015-08-10 17:04:07 +0530735 set reference_type=null, reference_name = null,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530736 modified=%s, modified_by=%s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530737 where reference_type=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530738 and docstatus < 2""",
739 (now(), frappe.session.user, ref_type, ref_no),
740 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530741
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530742 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530743
Ankush Menat494bd9e2022-03-28 18:52:46 +0530744
Nabin Haite0cc87d2016-07-21 18:30:03 +0530745def remove_ref_doc_link_from_pe(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530746 linked_pe = frappe.db.sql_list(
747 """select parent from `tabPayment Entry Reference`
748 where reference_doctype=%s and reference_name=%s and docstatus < 2""",
749 (ref_type, ref_no),
750 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530751
Nabin Haite0cc87d2016-07-21 18:30:03 +0530752 if linked_pe:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530753 frappe.db.sql(
754 """update `tabPayment Entry Reference`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530755 set allocated_amount=0, modified=%s, modified_by=%s
756 where reference_doctype=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530757 and docstatus < 2""",
758 (now(), frappe.session.user, ref_type, ref_no),
759 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530760
Nabin Haite0cc87d2016-07-21 18:30:03 +0530761 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530762 try:
Deepesh Garg1894dc82023-06-23 21:53:34 +0530763 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530764 pe_doc.set_amounts()
Deepesh Gargda6bc1a2023-06-23 20:57:51 +0530765 pe_doc.make_advance_gl_entries(against_voucher_type=ref_type, against_voucher=ref_no, cancel=1)
Deepesh Gargb5162392021-08-10 14:52:24 +0530766 pe_doc.clear_unallocated_reference_document_rows()
767 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530768 except Exception as e:
769 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530770 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530771 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530772 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530773
Ankush Menat494bd9e2022-03-28 18:52:46 +0530774 frappe.db.sql(
775 """update `tabPayment Entry` set total_allocated_amount=%s,
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530776 base_total_allocated_amount=%s, unallocated_amount=%s, modified=%s, modified_by=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530777 where name=%s""",
778 (
779 pe_doc.total_allocated_amount,
780 pe_doc.base_total_allocated_amount,
781 pe_doc.unallocated_amount,
782 now(),
783 frappe.session.user,
784 pe,
785 ),
786 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530787
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530788 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530789
Ankush Menat494bd9e2022-03-28 18:52:46 +0530790
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530791@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530792def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530793 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530794
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530795 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530796 throw(
797 _("Please set default {0} in Company {1}").format(
798 frappe.get_meta("Company").get_label(fieldname), company
799 )
800 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530801
Nabin Hait0fc24542013-03-25 11:06:00 +0530802 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530803
Ankush Menat494bd9e2022-03-28 18:52:46 +0530804
Nabin Hait8b509f52013-05-28 16:52:30 +0530805def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530806 vouchers = frappe.db.sql(
807 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530808 sum(debit) - sum(credit) as diff
809 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530810 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530811 having sum(debit) != sum(credit)""",
812 as_dict=1,
813 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530814
Nabin Hait8b509f52013-05-28 16:52:30 +0530815 for d in vouchers:
816 if abs(d.diff) > 0:
817 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530818
Ankush Menat494bd9e2022-03-28 18:52:46 +0530819 frappe.db.sql(
820 """update `tabGL Entry` set %s = %s + %s
821 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
822 % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
823 (d.diff, d.voucher_type, d.voucher_no),
824 )
825
Anand Doshicd71e1d2014-04-08 13:53:35 +0530826
Rushabh Mehtad50da782017-07-28 11:39:01 +0530827def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530828 precision = cint(frappe.db.get_default("currency_precision"))
829 if not precision:
830 number_format = frappe.db.get_default("number_format") or "#,###.##"
831 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530832
Nabin Hait9b20e072017-04-25 12:10:24 +0530833 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530834
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530835
Ankush Menat494bd9e2022-03-28 18:52:46 +0530836def get_stock_rbnb_difference(posting_date, company):
837 stock_items = frappe.db.sql_list(
838 """select distinct item_code
839 from `tabStock Ledger Entry` where company=%s""",
840 company,
841 )
842
843 pr_valuation_amount = frappe.db.sql(
844 """
Anand Doshi602e8252015-11-16 19:05:46 +0530845 select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530846 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
Suraj Shetty084b0b32018-05-26 09:12:59 +0530847 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530848 and pr.posting_date <= %s and pr_item.item_code in (%s)"""
849 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
850 tuple([company, posting_date] + stock_items),
851 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530852
Ankush Menat494bd9e2022-03-28 18:52:46 +0530853 pi_valuation_amount = frappe.db.sql(
854 """
Anand Doshi602e8252015-11-16 19:05:46 +0530855 select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530856 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
Suraj Shetty084b0b32018-05-26 09:12:59 +0530857 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530858 and pi.posting_date <= %s and pi_item.item_code in (%s)"""
859 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
860 tuple([company, posting_date] + stock_items),
861 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530862
863 # Balance should be
864 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
865
866 # Balance as per system
Ankush Menat494bd9e2022-03-28 18:52:46 +0530867 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.get_cached_value(
868 "Company", company, "abbr"
869 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530870 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530871
872 # Amount should be credited
873 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530874
tundec4b0d172017-09-26 00:48:30 +0100875
tundebabzyad08d4c2018-05-16 07:01:41 +0100876def get_held_invoices(party_type, party):
877 """
878 Returns a list of names Purchase Invoices for the given party that are on hold
879 """
880 held_invoices = None
881
Ankush Menat494bd9e2022-03-28 18:52:46 +0530882 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +0100883 held_invoices = frappe.db.sql(
mergify[bot]872a23c2023-07-10 20:34:54 +0530884 "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 +0530885 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +0100886 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530887 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +0100888
889 return held_invoices
890
891
ruthra kumar8c876742022-06-14 17:46:04 +0530892def get_outstanding_invoices(
ruthra kumar5f1562c2022-07-28 11:57:27 +0530893 party_type,
894 party,
895 account,
896 common_filter=None,
897 posting_date=None,
898 min_outstanding=None,
899 max_outstanding=None,
ruthra kumar6d9d7302022-12-14 16:05:15 +0530900 accounting_dimensions=None,
ruthra kumar8c876742022-06-14 17:46:04 +0530901):
902
903 ple = qb.DocType("Payment Ledger Entry")
Anand Doshid40d1e92015-11-12 17:05:29 +0530904 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +0530905 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +0530906
Nabin Hait9db9edc2019-11-19 18:44:32 +0530907 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530908 root_type, account_type = frappe.get_cached_value(
909 "Account", account, ["root_type", "account_type"]
910 )
Nabin Hait9db9edc2019-11-19 18:44:32 +0530911 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +0530912 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +0530913 else:
914 party_account_type = erpnext.get_party_account_type(party_type)
915
tundebabzyad08d4c2018-05-16 07:01:41 +0100916 held_invoices = get_held_invoices(party_type, party)
917
ruthra kumar8c876742022-06-14 17:46:04 +0530918 common_filter = common_filter or []
919 common_filter.append(ple.account_type == party_account_type)
920 common_filter.append(ple.account == account)
921 common_filter.append(ple.party_type == party_type)
922 common_filter.append(ple.party == party)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530923
ruthra kumar8c876742022-06-14 17:46:04 +0530924 ple_query = QueryPaymentLedger()
925 invoice_list = ple_query.get_voucher_outstandings(
926 common_filter=common_filter,
ruthra kumar5f1562c2022-07-28 11:57:27 +0530927 posting_date=posting_date,
ruthra kumar8c876742022-06-14 17:46:04 +0530928 min_outstanding=min_outstanding,
929 max_outstanding=max_outstanding,
930 get_invoices=True,
ruthra kumar6d9d7302022-12-14 16:05:15 +0530931 accounting_dimensions=accounting_dimensions or [],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530932 )
tundec4b0d172017-09-26 00:48:30 +0100933
Nabin Haitac184982019-02-04 21:13:43 +0530934 for d in invoice_list:
ruthra kumar21985532022-06-30 15:14:38 +0530935 payment_amount = d.invoice_amount_in_account_currency - d.outstanding_in_account_currency
936 outstanding_amount = d.outstanding_in_account_currency
Nabin Haitac184982019-02-04 21:13:43 +0530937 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530938 if (
ruthra kumar8c876742022-06-14 17:46:04 +0530939 min_outstanding
940 and max_outstanding
941 and not (outstanding_amount >= min_outstanding and outstanding_amount <= max_outstanding)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530942 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530943 continue
Nabin Haitac184982019-02-04 21:13:43 +0530944
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530945 if not d.voucher_type == "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +0530946 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530947 frappe._dict(
948 {
949 "voucher_no": d.voucher_no,
950 "voucher_type": d.voucher_type,
951 "posting_date": d.posting_date,
ruthra kumar21985532022-06-30 15:14:38 +0530952 "invoice_amount": flt(d.invoice_amount_in_account_currency),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530953 "payment_amount": payment_amount,
954 "outstanding_amount": outstanding_amount,
955 "due_date": d.due_date,
956 "currency": d.currency,
Gursheen Anand4ee16372023-06-08 13:15:23 +0530957 "account": d.account,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530958 }
959 )
Nabin Haitac184982019-02-04 21:13:43 +0530960 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530961
Ankush Menat494bd9e2022-03-28 18:52:46 +0530962 outstanding_invoices = sorted(
963 outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
964 )
Anand Doshid40d1e92015-11-12 17:05:29 +0530965 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +0530966
967
Ankush Menat494bd9e2022-03-28 18:52:46 +0530968def get_account_name(
969 account_type=None, root_type=None, is_group=None, account_currency=None, company=None
970):
Saurabh3a268292016-02-22 15:18:40 +0530971 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530972 return frappe.db.get_value(
973 "Account",
974 {
975 "account_type": account_type or "",
976 "root_type": root_type or "",
977 "is_group": is_group or 0,
978 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
979 "company": company or frappe.defaults.get_defaults().company,
980 },
981 "name",
982 )
983
Saurabha9ba7342016-06-21 12:33:12 +0530984
985@frappe.whitelist()
986def get_companies():
987 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530988 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
989
Saurabha9ba7342016-06-21 12:33:12 +0530990
991@frappe.whitelist()
Rushabh Mehta43133262017-11-10 18:52:21 +0530992def get_children(doctype, parent, company, is_root=False):
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530993 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +0530994
Ankush Menat494bd9e2022-03-28 18:52:46 +0530995 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
996 fields = ["name as value", "is_group as expandable"]
997 filters = [["docstatus", "<", 2]]
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +0530998
Ankush Menat494bd9e2022-03-28 18:52:46 +0530999 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301000
Rushabh Mehta43133262017-11-10 18:52:21 +05301001 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301002 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
1003 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +05301004
Saurabha9ba7342016-06-21 12:33:12 +05301005 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301006 fields += ["root_type", "account_currency"] if doctype == "Account" else []
1007 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +05301008
1009 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +05301010
Ankush Menat494bd9e2022-03-28 18:52:46 +05301011 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +05301012 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +05301013
1014 return acc
Saurabhb835fef2016-09-09 11:19:22 +05301015
Ankush Menat494bd9e2022-03-28 18:52:46 +05301016
Saqib90517352021-10-04 11:44:46 +05301017@frappe.whitelist()
1018def get_account_balances(accounts, company):
1019
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301020 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +05301021 accounts = loads(accounts)
1022
1023 if not accounts:
1024 return []
1025
Ankush Menat494bd9e2022-03-28 18:52:46 +05301026 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +05301027
1028 for account in accounts:
1029 account["company_currency"] = company_currency
Ankush Menat494bd9e2022-03-28 18:52:46 +05301030 account["balance"] = flt(
1031 get_balance_on(account["value"], in_account_currency=False, company=company)
1032 )
Saqib90517352021-10-04 11:44:46 +05301033 if account["account_currency"] and account["account_currency"] != company_currency:
1034 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
1035
1036 return accounts
1037
Ankush Menat494bd9e2022-03-28 18:52:46 +05301038
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +05301039def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +05301040 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +05301041
Daizy Modifdfe5cb2022-11-17 19:14:10 +05301042 company = frappe.get_cached_value("Global Defaults", "Global Defaults", "default_company")
Saurabhb835fef2016-09-09 11:19:22 +05301043 if not company:
1044 return
1045
1046 # 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 +05301047 bank_account = frappe.db.get_value(
1048 "Account",
1049 {"account_name": _(gateway), "company": company},
1050 ["name", "account_currency"],
1051 as_dict=1,
1052 )
Saurabhb835fef2016-09-09 11:19:22 +05301053
1054 if not bank_account:
1055 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301056 bank_account = frappe.db.get_value(
1057 "Account",
1058 {"account_name": gateway, "company": company},
1059 ["name", "account_currency"],
1060 as_dict=1,
1061 )
Saurabhb835fef2016-09-09 11:19:22 +05301062
1063 if not bank_account:
1064 # try creating one
1065 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1066
1067 if not bank_account:
1068 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1069 return
1070
1071 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301072 if frappe.db.exists(
1073 "Payment Gateway Account",
1074 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1075 ):
Saurabhb835fef2016-09-09 11:19:22 +05301076 return
1077
1078 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301079 frappe.get_doc(
1080 {
1081 "doctype": "Payment Gateway Account",
1082 "is_default": 1,
1083 "payment_gateway": gateway,
1084 "payment_account": bank_account.name,
1085 "currency": bank_account.account_currency,
1086 "payment_channel": payment_channel,
1087 }
1088 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301089
1090 except frappe.DuplicateEntryError:
1091 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001092 pass
Zarrar44175902018-06-08 16:35:21 +05301093
Ankush Menat494bd9e2022-03-28 18:52:46 +05301094
Zarrar44175902018-06-08 16:35:21 +05301095@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301096def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301097 """
1098 Renames the document by adding the number as a prefix to the current name and updates
1099 all transaction where it was present.
1100 """
Saqiba8779872020-04-30 11:28:43 +05301101 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301102
Saqiba8779872020-04-30 11:28:43 +05301103 if cost_center_number:
1104 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1105 else:
1106 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301107
Saqiba8779872020-04-30 11:28:43 +05301108 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301109
Nabin Haitaf21a112022-09-15 12:09:18 +05301110 new_name = get_autoname_with_number(cost_center_number, cost_center_name, company)
Saqiba8779872020-04-30 11:28:43 +05301111 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301112 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301113 return new_name
1114
Ankush Menat494bd9e2022-03-28 18:52:46 +05301115
Saqiba8779872020-04-30 11:28:43 +05301116def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301117 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301118 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301119 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301120 if company:
Saqiba8779872020-04-30 11:28:43 +05301121 filters["company"] = company
1122
1123 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1124
Zarrar44175902018-06-08 16:35:21 +05301125 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301126 frappe.throw(
1127 _("{0} Number {1} is already used in {2} {3}").format(
1128 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1129 )
1130 )
1131
Zarrar44175902018-06-08 16:35:21 +05301132
Nabin Haitaf21a112022-09-15 12:09:18 +05301133def get_autoname_with_number(number_value, doc_title, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301134 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Nabin Haitaf21a112022-09-15 12:09:18 +05301135 company_abbr = frappe.get_cached_value("Company", company, "abbr")
1136 parts = [doc_title.strip(), company_abbr]
1137
Zlash651aeca1d2018-07-06 17:15:33 +05301138 if cstr(number_value).strip():
1139 parts.insert(0, cstr(number_value).strip())
Nabin Haitaf21a112022-09-15 12:09:18 +05301140
Ankush Menat494bd9e2022-03-28 18:52:46 +05301141 return " - ".join(parts)
1142
Zarrar254ce642018-06-28 14:15:34 +05301143
Deepesh Garg62706072023-07-16 12:58:42 +05301144def parse_naming_series_variable(doc, variable):
1145 if variable == "FY":
Deepesh Garg7a7d32d2023-07-21 16:03:17 +05301146 date = doc.get("posting_date") or doc.get("transaction_date") or getdate()
1147 return get_fiscal_year(date=date, company=doc.get("company"))[0]
Deepesh Garg62706072023-07-16 12:58:42 +05301148
1149
Zarrar254ce642018-06-28 14:15:34 +05301150@frappe.whitelist()
1151def get_coa(doctype, parent, is_root, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301152 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1153 build_tree_from_json,
1154 )
Zarrar254ce642018-06-28 14:15:34 +05301155
1156 # add chart to flags to retrieve when called from expand all function
1157 chart = chart if chart else frappe.flags.chart
1158 frappe.flags.chart = chart
1159
Ankush Menat494bd9e2022-03-28 18:52:46 +05301160 parent = None if parent == _("All Accounts") else parent
1161 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301162
1163 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301164 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301165
1166 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001167
Ankush Menat494bd9e2022-03-28 18:52:46 +05301168
1169def update_gl_entries_after(
1170 posting_date,
1171 posting_time,
1172 for_warehouses=None,
1173 for_items=None,
1174 warehouse_account=None,
1175 company=None,
1176):
1177 stock_vouchers = get_future_stock_vouchers(
1178 posting_date, posting_time, for_warehouses, for_items, company
1179 )
Nabin Hait9b178bc2021-02-16 14:57:00 +05301180 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1181
1182
Ankush Menat494bd9e2022-03-28 18:52:46 +05301183def repost_gle_for_stock_vouchers(
Ankush Menat2535d5e2022-06-14 18:20:33 +05301184 stock_vouchers: List[Tuple[str, str]],
1185 posting_date: str,
1186 company: Optional[str] = None,
1187 warehouse_account=None,
1188 repost_doc: Optional["RepostItemValuation"] = None,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301189):
Ankush Menat67c26322022-06-04 14:46:35 +05301190
1191 from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative
1192
Ankush Menat700e8642022-04-19 13:24:29 +05301193 if not stock_vouchers:
1194 return
1195
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301196 if not warehouse_account:
1197 warehouse_account = get_warehouse_account_map(company)
1198
Ankush Menat2535d5e2022-06-14 18:20:33 +05301199 stock_vouchers = sort_stock_vouchers_by_posting_date(stock_vouchers)
1200 if repost_doc and repost_doc.gl_reposting_index:
1201 # Restore progress
1202 stock_vouchers = stock_vouchers[cint(repost_doc.gl_reposting_index) :]
1203
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301204 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1205
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301206 for stock_vouchers_chunk in create_batch(stock_vouchers, GL_REPOSTING_CHUNK):
Ankush Menat2535d5e2022-06-14 18:20:33 +05301207 gle = get_voucherwise_gl_entries(stock_vouchers_chunk, posting_date)
1208
1209 for voucher_type, voucher_no in stock_vouchers_chunk:
1210 existing_gle = gle.get((voucher_type, voucher_no), [])
1211 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
1212 # Some transactions post credit as negative debit, this is handled while posting GLE
1213 # but while comparing we need to make sure it's flipped so comparisons are accurate
1214 expected_gle = toggle_debit_credit_if_negative(voucher_obj.get_gl_entries(warehouse_account))
1215 if expected_gle:
1216 if not existing_gle or not compare_existing_and_expected_gle(
1217 existing_gle, expected_gle, precision
1218 ):
ruthra kumar9209ec52022-10-21 15:18:40 +05301219 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301220 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
1221 else:
ruthra kumar9209ec52022-10-21 15:18:40 +05301222 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat86919d22022-06-15 21:19:09 +05301223
1224 if not frappe.flags.in_test:
1225 frappe.db.commit()
Ankush Menat2535d5e2022-06-14 18:20:33 +05301226
1227 if repost_doc:
1228 repost_doc.db_set(
1229 "gl_reposting_index",
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301230 cint(repost_doc.gl_reposting_index) + len(stock_vouchers_chunk),
Ankush Menat2535d5e2022-06-14 18:20:33 +05301231 )
1232
1233
ruthra kumar9209ec52022-10-21 15:18:40 +05301234def _delete_pl_entries(voucher_type, voucher_no):
ruthra kumar65992302022-10-04 16:17:56 +05301235 ple = qb.DocType("Payment Ledger Entry")
1236 qb.from_(ple).delete().where(
1237 (ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)
1238 ).run()
Ankush Menateb53a972022-06-04 18:19:44 +05301239
Ankush Menat494bd9e2022-03-28 18:52:46 +05301240
ruthra kumar9209ec52022-10-21 15:18:40 +05301241def _delete_gl_entries(voucher_type, voucher_no):
1242 gle = qb.DocType("GL Entry")
1243 qb.from_(gle).delete().where(
1244 (gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)
1245 ).run()
1246
1247
1248def _delete_accounting_ledger_entries(voucher_type, voucher_no):
1249 """
1250 Remove entries from both General and Payment Ledger for specified Voucher
1251 """
1252 _delete_gl_entries(voucher_type, voucher_no)
1253 _delete_pl_entries(voucher_type, voucher_no)
1254
1255
Ankush Menat700e8642022-04-19 13:24:29 +05301256def sort_stock_vouchers_by_posting_date(
1257 stock_vouchers: List[Tuple[str, str]]
1258) -> List[Tuple[str, str]]:
1259 sle = frappe.qb.DocType("Stock Ledger Entry")
1260 voucher_nos = [v[1] for v in stock_vouchers]
1261
1262 sles = (
1263 frappe.qb.from_(sle)
1264 .select(sle.voucher_type, sle.voucher_no, sle.posting_date, sle.posting_time, sle.creation)
1265 .where((sle.is_cancelled == 0) & (sle.voucher_no.isin(voucher_nos)))
1266 .groupby(sle.voucher_type, sle.voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301267 .orderby(sle.posting_date)
1268 .orderby(sle.posting_time)
1269 .orderby(sle.creation)
Ankush Menat700e8642022-04-19 13:24:29 +05301270 ).run(as_dict=True)
1271 sorted_vouchers = [(sle.voucher_type, sle.voucher_no) for sle in sles]
1272
1273 unknown_vouchers = set(stock_vouchers) - set(sorted_vouchers)
1274 if unknown_vouchers:
1275 sorted_vouchers.extend(unknown_vouchers)
1276
1277 return sorted_vouchers
1278
1279
Ankush Menat494bd9e2022-03-28 18:52:46 +05301280def get_future_stock_vouchers(
1281 posting_date, posting_time, for_warehouses=None, for_items=None, company=None
1282):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301283
1284 values = []
1285 condition = ""
1286 if for_items:
1287 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1288 values += for_items
1289
1290 if for_warehouses:
1291 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1292 values += for_warehouses
1293
rohitwaghchaured60ff832021-02-16 09:12:27 +05301294 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301295 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301296 values.append(company)
1297
Ankush Menat494bd9e2022-03-28 18:52:46 +05301298 future_stock_vouchers = frappe.db.sql(
1299 """select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301300 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301301 where
1302 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1303 and is_cancelled = 0
1304 {condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301305 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
1306 condition=condition
1307 ),
1308 tuple([posting_date, posting_time] + values),
1309 as_dict=True,
1310 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301311
Ankush91527152021-08-11 11:17:50 +05301312 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301313
Ankush Menat494bd9e2022-03-28 18:52:46 +05301314
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301315def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301316 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301317
1318 Only fetches GLE fields required for comparing with new GLE.
1319 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301320
1321 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301322 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301323 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301324 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301325 if not future_stock_vouchers:
1326 return gl_entries
1327
1328 voucher_nos = [d[1] for d in future_stock_vouchers]
1329
Ankush Menat494bd9e2022-03-28 18:52:46 +05301330 gles = frappe.db.sql(
1331 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301332 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301333 from `tabGL Entry`
1334 where
Ankush Menat494bd9e2022-03-28 18:52:46 +05301335 posting_date >= %s and voucher_no in (%s)"""
1336 % ("%s", ", ".join(["%s"] * len(voucher_nos))),
1337 tuple([posting_date] + voucher_nos),
1338 as_dict=1,
1339 )
Ankush91527152021-08-11 11:17:50 +05301340
1341 for d in gles:
1342 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301343
Prssanna Desai82ddef52020-06-18 18:18:41 +05301344 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301345
Ankush Menat494bd9e2022-03-28 18:52:46 +05301346
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301347def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301348 if len(existing_gle) != len(expected_gle):
1349 return False
1350
Nabin Haita77b8c92020-12-21 14:45:50 +05301351 matched = True
1352 for entry in expected_gle:
1353 account_existed = False
1354 for e in existing_gle:
1355 if entry.account == e.account:
1356 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301357 if (
1358 entry.account == e.account
1359 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1360 and (
1361 flt(entry.debit, precision) != flt(e.debit, precision)
1362 or flt(entry.credit, precision) != flt(e.credit, precision)
1363 )
1364 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301365 matched = False
1366 break
1367 if not account_existed:
1368 matched = False
1369 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301370 return matched
1371
Ankush Menat494bd9e2022-03-28 18:52:46 +05301372
Nabin Haitb99c77b2020-12-25 18:12:35 +05301373def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301374 stock_accounts = [
1375 d.name
1376 for d in frappe.db.get_all(
1377 "Account", {"account_type": "Stock", "company": company, "is_group": 0}
1378 )
1379 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301380 if voucher_type and voucher_no:
1381 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301382 stock_accounts = [
1383 d.account
1384 for d in frappe.db.get_all(
1385 "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
1386 )
1387 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301388
1389 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301390 stock_accounts = [
1391 d.account
1392 for d in frappe.db.get_all(
1393 "GL Entry",
1394 {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
1395 "account",
1396 )
1397 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301398
1399 return stock_accounts
1400
Ankush Menat494bd9e2022-03-28 18:52:46 +05301401
Nabin Haitb99c77b2020-12-25 18:12:35 +05301402def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301403 if not posting_date:
1404 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301405
1406 warehouse_account = get_warehouse_account_map(company)
1407
Ankush Menat494bd9e2022-03-28 18:52:46 +05301408 account_balance = get_balance_on(
1409 account, posting_date, in_account_currency=False, ignore_account_permission=True
1410 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301411
Ankush Menat494bd9e2022-03-28 18:52:46 +05301412 related_warehouses = [
1413 wh
1414 for wh, wh_details in warehouse_account.items()
1415 if wh_details.account == account and not wh_details.is_group
1416 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301417
s-aga-re782a052023-04-25 13:54:36 +05301418 total_stock_value = get_stock_value_on(related_warehouses, posting_date)
Nabin Haitb99c77b2020-12-25 18:12:35 +05301419
1420 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1421 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1422
Ankush Menat494bd9e2022-03-28 18:52:46 +05301423
Nabin Haitb99c77b2020-12-25 18:12:35 +05301424def get_journal_entry(account, stock_adjustment_account, amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301425 db_or_cr_warehouse_account = (
1426 "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
1427 )
1428 db_or_cr_stock_adjustment_account = (
1429 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1430 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301431
1432 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301433 "accounts": [
1434 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1435 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1436 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301437 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301438
Ankush Menat494bd9e2022-03-28 18:52:46 +05301439
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301440def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301441 """Check if reports are referenced in Desktop Icon"""
1442 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301443 if icons:
1444 for icon in icons:
1445 frappe.delete_doc("Desktop Icon", icon)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301446
1447
ruthra kumar4f51c5a2023-07-03 14:35:33 +05301448def create_err_and_its_journals(companies: list = None) -> None:
1449 if companies:
1450 for company in companies:
1451 err = frappe.new_doc("Exchange Rate Revaluation")
1452 err.company = company.name
1453 err.posting_date = nowdate()
1454 err.rounding_loss_allowance = 0.0
1455
1456 err.fetch_and_calculate_accounts_data()
1457 if err.accounts:
1458 err.save().submit()
1459 response = err.make_jv_entries()
1460
1461 if company.submit_err_jv:
1462 jv = response.get("revaluation_jv", None)
1463 jv and frappe.get_doc("Journal Entry", jv).submit()
1464 jv = response.get("zero_balance_jv", None)
1465 jv and frappe.get_doc("Journal Entry", jv).submit()
1466
1467
1468def auto_create_exchange_rate_revaluation_daily() -> None:
1469 """
1470 Executed by background job
1471 """
1472 companies = frappe.db.get_all(
1473 "Company",
1474 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Daily"},
1475 fields=["name", "submit_err_jv"],
1476 )
1477 create_err_and_its_journals(companies)
1478
1479
1480def auto_create_exchange_rate_revaluation_weekly() -> None:
1481 """
1482 Executed by background job
1483 """
1484 companies = frappe.db.get_all(
1485 "Company",
1486 filters={"auto_exchange_rate_revaluation": 1, "auto_err_frequency": "Weekly"},
1487 fields=["name", "submit_err_jv"],
1488 )
1489 create_err_and_its_journals(companies)
1490
1491
ruthra kumar9b502212022-10-13 14:13:48 +05301492def get_payment_ledger_entries(gl_entries, cancel=0):
1493 ple_map = []
ruthra kumar451cf3a2022-05-16 14:29:58 +05301494 if gl_entries:
1495 ple = None
1496
1497 # companies
1498 account = qb.DocType("Account")
1499 companies = list(set([x.company for x in gl_entries]))
1500
1501 # receivable/payable account
1502 accounts_with_types = (
1503 qb.from_(account)
1504 .select(account.name, account.account_type)
1505 .where(
1506 (account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
1507 )
1508 .run(as_dict=True)
1509 )
1510 receivable_or_payable_accounts = [y.name for y in accounts_with_types]
1511
1512 def get_account_type(account):
1513 for entry in accounts_with_types:
1514 if entry.name == account:
1515 return entry.account_type
1516
1517 dr_or_cr = 0
1518 account_type = None
1519 for gle in gl_entries:
1520 if gle.account in receivable_or_payable_accounts:
1521 account_type = get_account_type(gle.account)
1522 if account_type == "Receivable":
1523 dr_or_cr = gle.debit - gle.credit
1524 dr_or_cr_account_currency = gle.debit_in_account_currency - gle.credit_in_account_currency
1525 elif account_type == "Payable":
1526 dr_or_cr = gle.credit - gle.debit
1527 dr_or_cr_account_currency = gle.credit_in_account_currency - gle.debit_in_account_currency
1528
1529 if cancel:
1530 dr_or_cr *= -1
1531 dr_or_cr_account_currency *= -1
1532
ruthra kumar9b502212022-10-13 14:13:48 +05301533 ple = frappe._dict(
1534 doctype="Payment Ledger Entry",
1535 posting_date=gle.posting_date,
1536 company=gle.company,
1537 account_type=account_type,
1538 account=gle.account,
1539 party_type=gle.party_type,
1540 party=gle.party,
1541 cost_center=gle.cost_center,
1542 finance_book=gle.finance_book,
1543 due_date=gle.due_date,
1544 voucher_type=gle.voucher_type,
1545 voucher_no=gle.voucher_no,
Deepesh Garg1e078d02023-06-29 12:18:25 +05301546 voucher_detail_no=gle.voucher_detail_no,
ruthra kumar9b502212022-10-13 14:13:48 +05301547 against_voucher_type=gle.against_voucher_type
1548 if gle.against_voucher_type
1549 else gle.voucher_type,
1550 against_voucher_no=gle.against_voucher if gle.against_voucher else gle.voucher_no,
1551 account_currency=gle.account_currency,
1552 amount=dr_or_cr,
1553 amount_in_account_currency=dr_or_cr_account_currency,
1554 delinked=True if cancel else False,
1555 remarks=gle.remarks,
ruthra kumar451cf3a2022-05-16 14:29:58 +05301556 )
1557
1558 dimensions_and_defaults = get_dimensions()
1559 if dimensions_and_defaults:
1560 for dimension in dimensions_and_defaults[0]:
ruthra kumar9b502212022-10-13 14:13:48 +05301561 ple[dimension.fieldname] = gle.get(dimension.fieldname)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301562
ruthra kumar9b502212022-10-13 14:13:48 +05301563 ple_map.append(ple)
1564 return ple_map
1565
1566
1567def create_payment_ledger_entry(
Deepesh Garg1e078d02023-06-29 12:18:25 +05301568 gl_entries, cancel=0, adv_adj=0, update_outstanding="Yes", from_repost=0, partial_cancel=False
ruthra kumar9b502212022-10-13 14:13:48 +05301569):
1570 if gl_entries:
1571 ple_map = get_payment_ledger_entries(gl_entries, cancel=cancel)
1572
1573 for entry in ple_map:
1574
1575 ple = frappe.get_doc(entry)
1576
1577 if cancel:
Deepesh Garg1e078d02023-06-29 12:18:25 +05301578 delink_original_entry(ple, partial_cancel=partial_cancel)
ruthra kumar9b502212022-10-13 14:13:48 +05301579
1580 ple.flags.ignore_permissions = 1
1581 ple.flags.adv_adj = adv_adj
1582 ple.flags.from_repost = from_repost
1583 ple.flags.update_outstanding = update_outstanding
1584 ple.submit()
ruthra kumar451cf3a2022-05-16 14:29:58 +05301585
1586
ruthra kumar7312f222022-05-29 21:33:08 +05301587def update_voucher_outstanding(voucher_type, voucher_no, account, party_type, party):
1588 ple = frappe.qb.DocType("Payment Ledger Entry")
1589 vouchers = [frappe._dict({"voucher_type": voucher_type, "voucher_no": voucher_no})]
1590 common_filter = []
1591 if account:
1592 common_filter.append(ple.account == account)
1593
1594 if party_type:
1595 common_filter.append(ple.party_type == party_type)
1596
1597 if party:
1598 common_filter.append(ple.party == party)
1599
1600 ple_query = QueryPaymentLedger()
1601
1602 # on cancellation outstanding can be an empty list
1603 voucher_outstanding = ple_query.get_voucher_outstandings(vouchers, common_filter=common_filter)
ruthra kumar43b80682022-10-18 09:33:37 +05301604 if (
1605 voucher_type in ["Sales Invoice", "Purchase Invoice", "Fees"]
1606 and party_type
1607 and party
1608 and voucher_outstanding
1609 ):
ruthra kumar7312f222022-05-29 21:33:08 +05301610 outstanding = voucher_outstanding[0]
1611 ref_doc = frappe.get_doc(voucher_type, voucher_no)
1612
1613 # Didn't use db_set for optimisation purpose
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301614 ref_doc.outstanding_amount = outstanding["outstanding_in_account_currency"] or 0.0
ruthra kumar7312f222022-05-29 21:33:08 +05301615 frappe.db.set_value(
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301616 voucher_type,
1617 voucher_no,
1618 "outstanding_amount",
1619 outstanding["outstanding_in_account_currency"] or 0.0,
ruthra kumar7312f222022-05-29 21:33:08 +05301620 )
1621
1622 ref_doc.set_status(update=True)
1623
1624
Deepesh Garg1e078d02023-06-29 12:18:25 +05301625def delink_original_entry(pl_entry, partial_cancel=False):
ruthra kumar451cf3a2022-05-16 14:29:58 +05301626 if pl_entry:
1627 ple = qb.DocType("Payment Ledger Entry")
1628 query = (
1629 qb.update(ple)
1630 .set(ple.delinked, True)
1631 .set(ple.modified, now())
1632 .set(ple.modified_by, frappe.session.user)
1633 .where(
1634 (ple.company == pl_entry.company)
1635 & (ple.account_type == pl_entry.account_type)
1636 & (ple.account == pl_entry.account)
1637 & (ple.party_type == pl_entry.party_type)
1638 & (ple.party == pl_entry.party)
1639 & (ple.voucher_type == pl_entry.voucher_type)
1640 & (ple.voucher_no == pl_entry.voucher_no)
1641 & (ple.against_voucher_type == pl_entry.against_voucher_type)
1642 & (ple.against_voucher_no == pl_entry.against_voucher_no)
1643 )
1644 )
Deepesh Garg1e078d02023-06-29 12:18:25 +05301645
1646 if partial_cancel:
1647 query = query.where(ple.voucher_detail_no == pl_entry.voucher_detail_no)
1648
ruthra kumar451cf3a2022-05-16 14:29:58 +05301649 query.run()
ruthra kumar7b383882022-05-25 15:51:16 +05301650
1651
1652class QueryPaymentLedger(object):
1653 """
1654 Helper Class for Querying Payment Ledger Entry
1655 """
1656
1657 def __init__(self):
1658 self.ple = qb.DocType("Payment Ledger Entry")
1659
1660 # query result
1661 self.voucher_outstandings = []
1662
1663 # query filters
1664 self.vouchers = []
1665 self.common_filter = []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301666 self.voucher_posting_date = []
ruthra kumar7b383882022-05-25 15:51:16 +05301667 self.min_outstanding = None
1668 self.max_outstanding = None
1669
1670 def reset(self):
1671 # clear filters
1672 self.vouchers.clear()
1673 self.common_filter.clear()
1674 self.min_outstanding = self.max_outstanding = None
1675
1676 # clear result
1677 self.voucher_outstandings.clear()
1678
1679 def query_for_outstanding(self):
1680 """
1681 Database query to fetch voucher amount and voucher outstanding using Common Table Expression
1682 """
1683
1684 ple = self.ple
1685
1686 filter_on_voucher_no = []
1687 filter_on_against_voucher_no = []
1688 if self.vouchers:
1689 voucher_types = set([x.voucher_type for x in self.vouchers])
1690 voucher_nos = set([x.voucher_no for x in self.vouchers])
1691
1692 filter_on_voucher_no.append(ple.voucher_type.isin(voucher_types))
1693 filter_on_voucher_no.append(ple.voucher_no.isin(voucher_nos))
1694
1695 filter_on_against_voucher_no.append(ple.against_voucher_type.isin(voucher_types))
1696 filter_on_against_voucher_no.append(ple.against_voucher_no.isin(voucher_nos))
1697
1698 # build outstanding amount filter
1699 filter_on_outstanding_amount = []
1700 if self.min_outstanding:
1701 if self.min_outstanding > 0:
1702 filter_on_outstanding_amount.append(
1703 Table("outstanding").amount_in_account_currency >= self.min_outstanding
1704 )
1705 else:
1706 filter_on_outstanding_amount.append(
1707 Table("outstanding").amount_in_account_currency <= self.min_outstanding
1708 )
1709 if self.max_outstanding:
1710 if self.max_outstanding > 0:
1711 filter_on_outstanding_amount.append(
1712 Table("outstanding").amount_in_account_currency <= self.max_outstanding
1713 )
1714 else:
1715 filter_on_outstanding_amount.append(
1716 Table("outstanding").amount_in_account_currency >= self.max_outstanding
1717 )
1718
1719 # build query for voucher amount
1720 query_voucher_amount = (
1721 qb.from_(ple)
1722 .select(
1723 ple.account,
1724 ple.voucher_type,
1725 ple.voucher_no,
1726 ple.party_type,
1727 ple.party,
1728 ple.posting_date,
1729 ple.due_date,
1730 ple.account_currency.as_("currency"),
1731 Sum(ple.amount).as_("amount"),
1732 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1733 )
1734 .where(ple.delinked == 0)
1735 .where(Criterion.all(filter_on_voucher_no))
1736 .where(Criterion.all(self.common_filter))
ruthra kumar6d9d7302022-12-14 16:05:15 +05301737 .where(Criterion.all(self.dimensions_filter))
ruthra kumar5f1562c2022-07-28 11:57:27 +05301738 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar7b383882022-05-25 15:51:16 +05301739 .groupby(ple.voucher_type, ple.voucher_no, ple.party_type, ple.party)
1740 )
1741
1742 # build query for voucher outstanding
1743 query_voucher_outstanding = (
1744 qb.from_(ple)
1745 .select(
1746 ple.account,
1747 ple.against_voucher_type.as_("voucher_type"),
1748 ple.against_voucher_no.as_("voucher_no"),
1749 ple.party_type,
1750 ple.party,
1751 ple.posting_date,
1752 ple.due_date,
1753 ple.account_currency.as_("currency"),
1754 Sum(ple.amount).as_("amount"),
1755 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1756 )
1757 .where(ple.delinked == 0)
1758 .where(Criterion.all(filter_on_against_voucher_no))
1759 .where(Criterion.all(self.common_filter))
1760 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1761 )
1762
1763 # build CTE for combining voucher amount and outstanding
1764 self.cte_query_voucher_amount_and_outstanding = (
1765 qb.with_(query_voucher_amount, "vouchers")
1766 .with_(query_voucher_outstanding, "outstanding")
1767 .from_(AliasedQuery("vouchers"))
1768 .left_join(AliasedQuery("outstanding"))
1769 .on(
1770 (AliasedQuery("vouchers").account == AliasedQuery("outstanding").account)
1771 & (AliasedQuery("vouchers").voucher_type == AliasedQuery("outstanding").voucher_type)
1772 & (AliasedQuery("vouchers").voucher_no == AliasedQuery("outstanding").voucher_no)
1773 & (AliasedQuery("vouchers").party_type == AliasedQuery("outstanding").party_type)
1774 & (AliasedQuery("vouchers").party == AliasedQuery("outstanding").party)
1775 )
1776 .select(
1777 Table("vouchers").account,
1778 Table("vouchers").voucher_type,
1779 Table("vouchers").voucher_no,
1780 Table("vouchers").party_type,
1781 Table("vouchers").party,
1782 Table("vouchers").posting_date,
1783 Table("vouchers").amount.as_("invoice_amount"),
1784 Table("vouchers").amount_in_account_currency.as_("invoice_amount_in_account_currency"),
1785 Table("outstanding").amount.as_("outstanding"),
1786 Table("outstanding").amount_in_account_currency.as_("outstanding_in_account_currency"),
1787 (Table("vouchers").amount - Table("outstanding").amount).as_("paid_amount"),
1788 (
1789 Table("vouchers").amount_in_account_currency - Table("outstanding").amount_in_account_currency
1790 ).as_("paid_amount_in_account_currency"),
1791 Table("vouchers").due_date,
1792 Table("vouchers").currency,
1793 )
1794 .where(Criterion.all(filter_on_outstanding_amount))
1795 )
1796
1797 # build CTE filter
1798 # only fetch invoices
1799 if self.get_invoices:
1800 self.cte_query_voucher_amount_and_outstanding = (
1801 self.cte_query_voucher_amount_and_outstanding.having(
1802 qb.Field("outstanding_in_account_currency") > 0
1803 )
1804 )
1805 # only fetch payments
1806 elif self.get_payments:
1807 self.cte_query_voucher_amount_and_outstanding = (
1808 self.cte_query_voucher_amount_and_outstanding.having(
1809 qb.Field("outstanding_in_account_currency") < 0
1810 )
1811 )
1812
1813 # execute SQL
1814 self.voucher_outstandings = self.cte_query_voucher_amount_and_outstanding.run(as_dict=True)
1815
1816 def get_voucher_outstandings(
1817 self,
1818 vouchers=None,
1819 common_filter=None,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301820 posting_date=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301821 min_outstanding=None,
1822 max_outstanding=None,
1823 get_payments=False,
1824 get_invoices=False,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301825 accounting_dimensions=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301826 ):
1827 """
1828 Fetch voucher amount and outstanding amount from Payment Ledger using Database CTE
1829
1830 vouchers - dict of vouchers to get
1831 common_filter - array of criterions
1832 min_outstanding - filter on minimum total outstanding amount
1833 max_outstanding - filter on maximum total outstanding amount
1834 get_invoices - only fetch vouchers(ledger entries with +ve outstanding)
1835 get_payments - only fetch payments(ledger entries with -ve outstanding)
1836 """
1837
1838 self.reset()
1839 self.vouchers = vouchers
1840 self.common_filter = common_filter or []
ruthra kumar6d9d7302022-12-14 16:05:15 +05301841 self.dimensions_filter = accounting_dimensions or []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301842 self.voucher_posting_date = posting_date or []
ruthra kumar7b383882022-05-25 15:51:16 +05301843 self.min_outstanding = min_outstanding
1844 self.max_outstanding = max_outstanding
1845 self.get_payments = get_payments
1846 self.get_invoices = get_invoices
1847 self.query_for_outstanding()
1848
1849 return self.voucher_outstandings