blob: 5abc64315ccd1484b1e341926b459332ed70b3d8 [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
Ankush Menat494bd9e2022-03-28 18:52:46 +0530240 if report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400241 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530242 cond.append(
243 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
244 )
Nabin Hait6f17cf92014-09-17 14:11:22 +0530245 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530246 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530247 cond.append(
248 """exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530249 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530250 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530251 )"""
252 % (acc.lft, acc.rgt)
253 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530254
255 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530256 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530257 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530258 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530259 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530260 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
Anand Doshic75c1d72016-03-11 14:56:19 +0530261
Nabin Hait6f17cf92014-09-17 14:11:22 +0530262 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530263 cond.append(
264 """gle.party_type = %s and gle.party = %s """
265 % (frappe.db.escape(party_type), frappe.db.escape(party, percent=False))
266 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530267
Nabin Hait85648d92016-07-20 11:26:45 +0530268 if company:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530269 cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530270
Nabin Haitdc768232015-08-17 11:27:00 +0530271 if account or (party_type and party):
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530272 if in_account_currency:
Anand Doshi602e8252015-11-16 19:05:46 +0530273 select_field = "sum(debit_in_account_currency) - sum(credit_in_account_currency)"
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530274 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530275 select_field = "sum(debit) - sum(credit)"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530276 bal = frappe.db.sql(
277 """
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530278 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530279 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530280 WHERE {1}""".format(
281 select_field, " and ".join(cond)
282 )
283 )[0][0]
Anand Doshicd71e1d2014-04-08 13:53:35 +0530284
Nabin Haitdc768232015-08-17 11:27:00 +0530285 # if bal is None, return 0
286 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530287
Ankush Menat494bd9e2022-03-28 18:52:46 +0530288
RobertSchouten8d43b322016-09-20 13:41:39 +0800289def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530290 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800291 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530292 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800293 else:
294 # get balance of all entries that exist
295 date = nowdate()
296
297 try:
298 year_start_date = get_fiscal_year(date, verbose=0)[1]
299 except FiscalYearError:
300 if getdate(date) > getdate(nowdate()):
301 # if fiscal year not found and the date is greater than today
302 # get fiscal year for today's date and its corresponding year start date
303 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
304 else:
305 # this indicates that it is a date older than any existing fiscal year.
306 # hence, assuming balance as 0.0
307 return 0.0
308
309 if account:
310 acc = frappe.get_doc("Account", account)
311
312 if not frappe.flags.ignore_account_permission:
313 acc.check_permission("read")
314
315 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530316 if acc.report_type == "Profit and Loss":
317 cond.append(
318 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
319 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800320
321 # different filter for group and ledger - improved performance
322 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530323 cond.append(
324 """exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800325 select name from `tabAccount` ac where ac.name = gle.account
326 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530327 )"""
328 % (acc.lft, acc.rgt)
329 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800330 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530331 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
RobertSchouten8d43b322016-09-20 13:41:39 +0800332
Ankush Menat494bd9e2022-03-28 18:52:46 +0530333 entries = frappe.db.sql(
334 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800335 SELECT name, posting_date, account, party_type, party,debit,credit,
336 voucher_type, voucher_no, against_voucher_type, against_voucher
337 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530338 WHERE {0}""".format(
339 " and ".join(cond)
340 ),
341 as_dict=True,
342 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530343
RobertSchouten8d43b322016-09-20 13:41:39 +0800344 count = 0
345 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530346 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800347 count += 1
348 else:
349 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
350 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530351 select_fields = (
352 "ifnull(sum(credit-debit),0)"
353 if fieldname == "invoiced_amount"
354 else "ifnull(sum(debit-credit),0)"
355 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800356
Ankush Menat494bd9e2022-03-28 18:52:46 +0530357 if (
358 (not gle.against_voucher)
359 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
360 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
361 ):
362 payment_amount = frappe.db.sql(
363 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800364 SELECT {0}
365 FROM `tabGL Entry` gle
366 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530367 and party = %(party)s and name != %(name)s""".format(
368 select_fields
369 ),
370 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
371 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530372
RobertSchouten8d43b322016-09-20 13:41:39 +0800373 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
374 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530375 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800376 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530377
RobertSchouten8d43b322016-09-20 13:41:39 +0800378 return count
379
Ankush Menat494bd9e2022-03-28 18:52:46 +0530380
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530381@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530382def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530383 from frappe.desk.treeview import make_tree_args
384
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530385 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530386 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530387
Nabin Hait02d987e2017-02-17 15:50:26 +0530388 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530389 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530390
Anand Doshi3e41fd12014-04-22 18:54:54 +0530391 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530392
Nabin Hait665568d2016-05-13 15:56:00 +0530393 if args.get("ignore_permissions"):
394 ac.flags.ignore_permissions = True
395 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530396
Anand Doshi3e41fd12014-04-22 18:54:54 +0530397 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530398
399 if not ac.parent_account:
400 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530401
Anand Doshif78d1ae2014-03-28 13:55:00 +0530402 ac.old_parent = ""
403 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530404 if cint(ac.get("is_root")):
405 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530406 ac.flags.ignore_mandatory = True
407
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530408 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530409
Anand Doshif78d1ae2014-03-28 13:55:00 +0530410 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530411
Ankush Menat494bd9e2022-03-28 18:52:46 +0530412
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530413@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530414def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530415 from frappe.desk.treeview import make_tree_args
416
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530417 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530418 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530419
Nabin Hait02d987e2017-02-17 15:50:26 +0530420 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530421 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530422
Zarrar7ab70ca2018-06-08 14:33:15 +0530423 if args.parent_cost_center == args.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530424 args.parent_cost_center = "{0} - {1}".format(
425 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
426 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530427
Anand Doshi3e41fd12014-04-22 18:54:54 +0530428 cc = frappe.new_doc("Cost Center")
429 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530430
431 if not cc.parent_cost_center:
432 cc.parent_cost_center = args.get("parent")
433
Anand Doshif78d1ae2014-03-28 13:55:00 +0530434 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530435 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530436 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530437
Ankush Menat494bd9e2022-03-28 18:52:46 +0530438
ruthra kumared14d1c2023-04-22 17:24:35 +0530439def reconcile_against_document(args, skip_ref_details_update_for_pe=False): # nosemgrep
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530440 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530441 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530442 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530443 # To optimize making GL Entry for PE or JV with multiple references
444 reconciled_entries = {}
445 for row in args:
446 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
447 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530448
Anuja Pawar3e404f12021-08-31 18:59:29 +0530449 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
450
451 for key, entries in reconciled_entries.items():
452 voucher_type = key[0]
453 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530454
Nabin Hait28a05282016-06-27 17:41:39 +0530455 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530456 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530457 frappe.flags.ignore_party_validation = True
ruthra kumar11cf6942023-01-14 12:22:22 +0530458 _delete_pl_entries(voucher_type, voucher_no)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530459
Anuja Pawar3e404f12021-08-31 18:59:29 +0530460 for entry in entries:
461 check_if_advance_entry_modified(entry)
462 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530463
Anuja Pawar3e404f12021-08-31 18:59:29 +0530464 # update ref in advance entry
465 if voucher_type == "Journal Entry":
466 update_reference_in_journal_entry(entry, doc, do_not_save=True)
467 else:
ruthra kumared14d1c2023-04-22 17:24:35 +0530468 update_reference_in_payment_entry(
469 entry, doc, do_not_save=True, skip_ref_details_update_for_pe=skip_ref_details_update_for_pe
470 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530471
472 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530473 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530474 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
ruthra kumar524c1752022-05-26 16:00:40 +0530475 gl_map = doc.build_gl_map()
ruthra kumar11cf6942023-01-14 12:22:22 +0530476 create_payment_ledger_entry(gl_map, update_outstanding="No", cancel=0, adv_adj=1)
477
478 # Only update outstanding for newly linked vouchers
479 for entry in entries:
480 update_voucher_outstanding(
481 entry.against_voucher_type, entry.against_voucher, entry.account, entry.party_type, entry.party
482 )
ruthra kumar524c1752022-05-26 16:00:40 +0530483
Subin Tomb8845b92021-07-30 16:30:18 +0530484 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530485
Ankush Menat494bd9e2022-03-28 18:52:46 +0530486
Nabin Hait28a05282016-06-27 17:41:39 +0530487def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530488 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530489 check if there is already a voucher reference
490 check if amount is same
491 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530492 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530493 if not args.get("unreconciled_amount"):
494 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530495
Nabin Hait28a05282016-06-27 17:41:39 +0530496 ret = None
497 if args.voucher_type == "Journal Entry":
Gursheen Anand74619262023-06-02 17:13:51 +0530498 journal_entry = frappe.qb.DocType("Journal Entry")
499 journal_acc = frappe.qb.DocType("Journal Entry Account")
500
501 q = (frappe.qb.from_(journal_entry)
502 .innerjoin(journal_acc)
503 .on(journal_entry.name == journal_acc.parent)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530504 )
Gursheen Anand74619262023-06-02 17:13:51 +0530505
506 if args.get("dr_or_cr") == 'debit_in_account_currency':
507 q = q.select(journal_acc.debit_in_account_currency)
508 else:
509 q = q.select(journal_acc.credit_in_account_currency)
510
511 q = q.where((journal_acc.account == args.get("account"))
512 &((journal_acc.party_type == args.get("party_type")))
513 &((journal_acc.party == args.get("party")))
514 &((journal_acc.reference_type == None) | (journal_acc.reference_type.isin(['', 'Sales Order', 'Purchase Order'])))
515 &((journal_entry.name == args.get("voucher_no")))
516 &((journal_acc.name == args.get("voucher_detail_no")))
517 &((journal_entry.docstatus == 1))
518 )
519
Nabin Hait28a05282016-06-27 17:41:39 +0530520 else:
Gursheen Anand74619262023-06-02 17:13:51 +0530521 payment_entry = frappe.qb.DocType("Payment Entry")
522 payment_ref = frappe.qb.DocType("Payment Entry Reference")
523
524 q = (frappe.qb.from_(payment_entry)
525 .select(payment_entry.name)
526 .where(payment_entry.name == args.get("voucher_no"))
527 .where(payment_entry.docstatus == 1)
528 .where(payment_entry.party_type == args.get("party_type"))
529 .where(payment_entry.party == args.get("party"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530530 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530531
Nabin Hait28a05282016-06-27 17:41:39 +0530532 if args.voucher_detail_no:
Gursheen Anand74619262023-06-02 17:13:51 +0530533 q = ( q.inner_join(payment_ref)
534 .on(payment_entry.name == payment_ref.parent)
535 .where(payment_ref.name == args.get("voucher_detail_no"))
536 .where(payment_ref.reference_doctype.isin(('', 'Sales Order', 'Purchase Order')))
537 .where(payment_ref.allocated_amount == args.get("unreconciled_amount"))
538 )
Nabin Hait28a05282016-06-27 17:41:39 +0530539 else:
Gursheen Anand74619262023-06-02 17:13:51 +0530540 q = q.where(payment_entry.unallocated_amount == args.get("unreconciled_amount"))
541
542 ret = q.run(as_dict=True)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530543
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530544 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530545 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530546
Ankush Menat494bd9e2022-03-28 18:52:46 +0530547
Nabin Hait576f0252014-04-30 19:30:50 +0530548def validate_allocated_amount(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530549 precision = args.get("precision") or frappe.db.get_single_value(
550 "System Settings", "currency_precision"
551 )
Nabin Hait28a05282016-06-27 17:41:39 +0530552 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530553 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530554 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530555 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530556
Ankush Menat494bd9e2022-03-28 18:52:46 +0530557
Anuja Pawar3e404f12021-08-31 18:59:29 +0530558def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530559 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530560 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530561 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530562 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530563
Ankush Menat494bd9e2022-03-28 18:52:46 +0530564 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530565 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530566 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530567 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530568 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
569 jv_detail.set(
570 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
571 amount_in_company_currency,
572 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530573 else:
574 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530575
Anuja Pawar3e404f12021-08-31 18:59:29 +0530576 # new row with references
577 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530578
579 new_row.update((frappe.copy_doc(jv_detail)).as_dict())
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530580
Anuja Pawar3e404f12021-08-31 18:59:29 +0530581 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530582 new_row.set(
583 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
584 d["allocated_amount"] * flt(jv_detail.exchange_rate),
585 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530586
Ankush Menat494bd9e2022-03-28 18:52:46 +0530587 new_row.set(
588 "credit_in_account_currency"
589 if d["dr_or_cr"] == "debit_in_account_currency"
590 else "debit_in_account_currency",
591 0,
592 )
593 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530594
Anuja Pawar3e404f12021-08-31 18:59:29 +0530595 new_row.set("reference_type", d["against_voucher_type"])
596 new_row.set("reference_name", d["against_voucher"])
597
598 new_row.against_account = cstr(jv_detail.against_account)
599 new_row.is_advance = cstr(jv_detail.is_advance)
600 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530601
602 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530603 journal_entry.flags.ignore_validate_update_after_submit = True
604 if not do_not_save:
605 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530606
Ankush Menat494bd9e2022-03-28 18:52:46 +0530607
ruthra kumared14d1c2023-04-22 17:24:35 +0530608def update_reference_in_payment_entry(
609 d, payment_entry, do_not_save=False, skip_ref_details_update_for_pe=False
610):
Nabin Hait28a05282016-06-27 17:41:39 +0530611 reference_details = {
612 "reference_doctype": d.against_voucher_type,
613 "reference_name": d.against_voucher,
614 "total_amount": d.grand_total,
615 "outstanding_amount": d.outstanding_amount,
616 "allocated_amount": d.allocated_amount,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530617 "exchange_rate": d.exchange_rate
618 if not d.exchange_gain_loss
619 else payment_entry.get_exchange_rate(),
620 "exchange_gain_loss": d.exchange_gain_loss, # only populated from invoice in case of advance allocation
Nabin Hait28a05282016-06-27 17:41:39 +0530621 }
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530622
Nabin Hait28a05282016-06-27 17:41:39 +0530623 if d.voucher_detail_no:
624 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
625 original_row = existing_row.as_dict().copy()
626 existing_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530627
Nabin Hait28a05282016-06-27 17:41:39 +0530628 if d.allocated_amount < original_row.allocated_amount:
629 new_row = payment_entry.append("references")
630 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500631 for field in list(reference_details):
Nabin Hait28a05282016-06-27 17:41:39 +0530632 new_row.set(field, original_row[field])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530633
Nabin Hait28a05282016-06-27 17:41:39 +0530634 new_row.allocated_amount = original_row.allocated_amount - d.allocated_amount
635 else:
636 new_row = payment_entry.append("references")
637 new_row.docstatus = 1
638 new_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530639
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530640 if d.difference_amount and d.difference_account:
Saqiba20999c2021-07-12 14:33:23 +0530641 account_details = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530642 "account": d.difference_account,
643 "cost_center": payment_entry.cost_center
644 or frappe.get_cached_value("Company", payment_entry.company, "cost_center"),
Saqiba20999c2021-07-12 14:33:23 +0530645 }
646 if d.difference_amount:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530647 account_details["amount"] = d.difference_amount
Saqiba20999c2021-07-12 14:33:23 +0530648
649 payment_entry.set_gain_or_loss(account_details=account_details)
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530650
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500651 payment_entry.flags.ignore_validate_update_after_submit = True
652 payment_entry.setup_party_account_field()
653 payment_entry.set_missing_values()
ruthra kumared14d1c2023-04-22 17:24:35 +0530654 if not skip_ref_details_update_for_pe:
655 payment_entry.set_missing_ref_details()
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500656 payment_entry.set_amounts()
657
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530658 if not do_not_save:
659 payment_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530660
Ankush Menat494bd9e2022-03-28 18:52:46 +0530661
Nabin Hait297d74a2016-11-23 15:58:51 +0530662def unlink_ref_doc_from_payment_entries(ref_doc):
663 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name)
664 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530665
Ankush Menat494bd9e2022-03-28 18:52:46 +0530666 frappe.db.sql(
667 """update `tabGL Entry`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530668 set against_voucher_type=null, against_voucher=null,
669 modified=%s, modified_by=%s
670 where against_voucher_type=%s and against_voucher=%s
671 and voucher_no != ifnull(against_voucher, '')""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672 (now(), frappe.session.user, ref_doc.doctype, ref_doc.name),
673 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530674
ruthra kumar537d9532022-10-10 10:17:19 +0530675 ple = qb.DocType("Payment Ledger Entry")
676
677 qb.update(ple).set(ple.against_voucher_type, ple.voucher_type).set(
678 ple.against_voucher_no, ple.voucher_no
679 ).set(ple.modified, now()).set(ple.modified_by, frappe.session.user).where(
680 (ple.against_voucher_type == ref_doc.doctype)
681 & (ple.against_voucher_no == ref_doc.name)
682 & (ple.delinked == 0)
683 ).run()
684
Nabin Hait297d74a2016-11-23 15:58:51 +0530685 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
686 ref_doc.set("advances", [])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530687
Ankush Menat494bd9e2022-03-28 18:52:46 +0530688 frappe.db.sql(
689 """delete from `tab{0} Advance` where parent = %s""".format(ref_doc.doctype), ref_doc.name
690 )
691
Anand Doshicd71e1d2014-04-08 13:53:35 +0530692
Nabin Haite0cc87d2016-07-21 18:30:03 +0530693def remove_ref_doc_link_from_jv(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530694 linked_jv = frappe.db.sql_list(
695 """select parent from `tabJournal Entry Account`
696 where reference_type=%s and reference_name=%s and docstatus < 2""",
697 (ref_type, ref_no),
698 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530699
700 if linked_jv:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530701 frappe.db.sql(
702 """update `tabJournal Entry Account`
Rushabh Mehta1828c122015-08-10 17:04:07 +0530703 set reference_type=null, reference_name = null,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530704 modified=%s, modified_by=%s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530705 where reference_type=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530706 and docstatus < 2""",
707 (now(), frappe.session.user, ref_type, ref_no),
708 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530709
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530710 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530711
Ankush Menat494bd9e2022-03-28 18:52:46 +0530712
Nabin Haite0cc87d2016-07-21 18:30:03 +0530713def remove_ref_doc_link_from_pe(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530714 linked_pe = frappe.db.sql_list(
715 """select parent from `tabPayment Entry Reference`
716 where reference_doctype=%s and reference_name=%s and docstatus < 2""",
717 (ref_type, ref_no),
718 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530719
Nabin Haite0cc87d2016-07-21 18:30:03 +0530720 if linked_pe:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530721 frappe.db.sql(
722 """update `tabPayment Entry Reference`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530723 set allocated_amount=0, modified=%s, modified_by=%s
724 where reference_doctype=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530725 and docstatus < 2""",
726 (now(), frappe.session.user, ref_type, ref_no),
727 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530728
Nabin Haite0cc87d2016-07-21 18:30:03 +0530729 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530730 try:
731 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530732 pe_doc.set_amounts()
Deepesh Gargb5162392021-08-10 14:52:24 +0530733 pe_doc.clear_unallocated_reference_document_rows()
734 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530735 except Exception as e:
736 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530737 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530738 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530739 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530740
Ankush Menat494bd9e2022-03-28 18:52:46 +0530741 frappe.db.sql(
742 """update `tabPayment Entry` set total_allocated_amount=%s,
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530743 base_total_allocated_amount=%s, unallocated_amount=%s, modified=%s, modified_by=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530744 where name=%s""",
745 (
746 pe_doc.total_allocated_amount,
747 pe_doc.base_total_allocated_amount,
748 pe_doc.unallocated_amount,
749 now(),
750 frappe.session.user,
751 pe,
752 ),
753 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530754
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530755 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530756
Ankush Menat494bd9e2022-03-28 18:52:46 +0530757
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530758@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530759def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530760 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530761
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530762 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530763 throw(
764 _("Please set default {0} in Company {1}").format(
765 frappe.get_meta("Company").get_label(fieldname), company
766 )
767 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530768
Nabin Hait0fc24542013-03-25 11:06:00 +0530769 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530770
Ankush Menat494bd9e2022-03-28 18:52:46 +0530771
Nabin Hait8b509f52013-05-28 16:52:30 +0530772def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530773 vouchers = frappe.db.sql(
774 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530775 sum(debit) - sum(credit) as diff
776 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530777 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530778 having sum(debit) != sum(credit)""",
779 as_dict=1,
780 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530781
Nabin Hait8b509f52013-05-28 16:52:30 +0530782 for d in vouchers:
783 if abs(d.diff) > 0:
784 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530785
Ankush Menat494bd9e2022-03-28 18:52:46 +0530786 frappe.db.sql(
787 """update `tabGL Entry` set %s = %s + %s
788 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
789 % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
790 (d.diff, d.voucher_type, d.voucher_no),
791 )
792
Anand Doshicd71e1d2014-04-08 13:53:35 +0530793
Rushabh Mehtad50da782017-07-28 11:39:01 +0530794def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530795 precision = cint(frappe.db.get_default("currency_precision"))
796 if not precision:
797 number_format = frappe.db.get_default("number_format") or "#,###.##"
798 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530799
Nabin Hait9b20e072017-04-25 12:10:24 +0530800 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530801
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530802
Ankush Menat494bd9e2022-03-28 18:52:46 +0530803def get_stock_rbnb_difference(posting_date, company):
804 stock_items = frappe.db.sql_list(
805 """select distinct item_code
806 from `tabStock Ledger Entry` where company=%s""",
807 company,
808 )
809
810 pr_valuation_amount = frappe.db.sql(
811 """
Anand Doshi602e8252015-11-16 19:05:46 +0530812 select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530813 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
Suraj Shetty084b0b32018-05-26 09:12:59 +0530814 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530815 and pr.posting_date <= %s and pr_item.item_code in (%s)"""
816 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
817 tuple([company, posting_date] + stock_items),
818 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530819
Ankush Menat494bd9e2022-03-28 18:52:46 +0530820 pi_valuation_amount = frappe.db.sql(
821 """
Anand Doshi602e8252015-11-16 19:05:46 +0530822 select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530823 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
Suraj Shetty084b0b32018-05-26 09:12:59 +0530824 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530825 and pi.posting_date <= %s and pi_item.item_code in (%s)"""
826 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
827 tuple([company, posting_date] + stock_items),
828 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530829
830 # Balance should be
831 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
832
833 # Balance as per system
Ankush Menat494bd9e2022-03-28 18:52:46 +0530834 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.get_cached_value(
835 "Company", company, "abbr"
836 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530837 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530838
839 # Amount should be credited
840 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530841
tundec4b0d172017-09-26 00:48:30 +0100842
tundebabzyad08d4c2018-05-16 07:01:41 +0100843def get_held_invoices(party_type, party):
844 """
845 Returns a list of names Purchase Invoices for the given party that are on hold
846 """
847 held_invoices = None
848
Ankush Menat494bd9e2022-03-28 18:52:46 +0530849 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +0100850 held_invoices = frappe.db.sql(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530851 "select name from `tabPurchase Invoice` where release_date IS NOT NULL and release_date > CURDATE()",
852 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +0100853 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530854 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +0100855
856 return held_invoices
857
858
ruthra kumar8c876742022-06-14 17:46:04 +0530859def get_outstanding_invoices(
ruthra kumar5f1562c2022-07-28 11:57:27 +0530860 party_type,
861 party,
862 account,
863 common_filter=None,
864 posting_date=None,
865 min_outstanding=None,
866 max_outstanding=None,
ruthra kumar6d9d7302022-12-14 16:05:15 +0530867 accounting_dimensions=None,
ruthra kumar8c876742022-06-14 17:46:04 +0530868):
869
870 ple = qb.DocType("Payment Ledger Entry")
Anand Doshid40d1e92015-11-12 17:05:29 +0530871 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +0530872 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +0530873
Nabin Hait9db9edc2019-11-19 18:44:32 +0530874 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530875 root_type, account_type = frappe.get_cached_value(
876 "Account", account, ["root_type", "account_type"]
877 )
Nabin Hait9db9edc2019-11-19 18:44:32 +0530878 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +0530879 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +0530880 else:
881 party_account_type = erpnext.get_party_account_type(party_type)
882
tundebabzyad08d4c2018-05-16 07:01:41 +0100883 held_invoices = get_held_invoices(party_type, party)
884
ruthra kumar8c876742022-06-14 17:46:04 +0530885 common_filter = common_filter or []
886 common_filter.append(ple.account_type == party_account_type)
887 common_filter.append(ple.account == account)
888 common_filter.append(ple.party_type == party_type)
889 common_filter.append(ple.party == party)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530890
ruthra kumar8c876742022-06-14 17:46:04 +0530891 ple_query = QueryPaymentLedger()
892 invoice_list = ple_query.get_voucher_outstandings(
893 common_filter=common_filter,
ruthra kumar5f1562c2022-07-28 11:57:27 +0530894 posting_date=posting_date,
ruthra kumar8c876742022-06-14 17:46:04 +0530895 min_outstanding=min_outstanding,
896 max_outstanding=max_outstanding,
897 get_invoices=True,
ruthra kumar6d9d7302022-12-14 16:05:15 +0530898 accounting_dimensions=accounting_dimensions or [],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530899 )
tundec4b0d172017-09-26 00:48:30 +0100900
Nabin Haitac184982019-02-04 21:13:43 +0530901 for d in invoice_list:
ruthra kumar21985532022-06-30 15:14:38 +0530902 payment_amount = d.invoice_amount_in_account_currency - d.outstanding_in_account_currency
903 outstanding_amount = d.outstanding_in_account_currency
Nabin Haitac184982019-02-04 21:13:43 +0530904 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530905 if (
ruthra kumar8c876742022-06-14 17:46:04 +0530906 min_outstanding
907 and max_outstanding
908 and not (outstanding_amount >= min_outstanding and outstanding_amount <= max_outstanding)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530909 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530910 continue
Nabin Haitac184982019-02-04 21:13:43 +0530911
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530912 if not d.voucher_type == "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +0530913 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530914 frappe._dict(
915 {
916 "voucher_no": d.voucher_no,
917 "voucher_type": d.voucher_type,
918 "posting_date": d.posting_date,
ruthra kumar21985532022-06-30 15:14:38 +0530919 "invoice_amount": flt(d.invoice_amount_in_account_currency),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530920 "payment_amount": payment_amount,
921 "outstanding_amount": outstanding_amount,
922 "due_date": d.due_date,
923 "currency": d.currency,
924 }
925 )
Nabin Haitac184982019-02-04 21:13:43 +0530926 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530927
Ankush Menat494bd9e2022-03-28 18:52:46 +0530928 outstanding_invoices = sorted(
929 outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
930 )
Anand Doshid40d1e92015-11-12 17:05:29 +0530931 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +0530932
933
Ankush Menat494bd9e2022-03-28 18:52:46 +0530934def get_account_name(
935 account_type=None, root_type=None, is_group=None, account_currency=None, company=None
936):
Saurabh3a268292016-02-22 15:18:40 +0530937 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530938 return frappe.db.get_value(
939 "Account",
940 {
941 "account_type": account_type or "",
942 "root_type": root_type or "",
943 "is_group": is_group or 0,
944 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
945 "company": company or frappe.defaults.get_defaults().company,
946 },
947 "name",
948 )
949
Saurabha9ba7342016-06-21 12:33:12 +0530950
951@frappe.whitelist()
952def get_companies():
953 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530954 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
955
Saurabha9ba7342016-06-21 12:33:12 +0530956
957@frappe.whitelist()
Rushabh Mehta43133262017-11-10 18:52:21 +0530958def get_children(doctype, parent, company, is_root=False):
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530959 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +0530960
Ankush Menat494bd9e2022-03-28 18:52:46 +0530961 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
962 fields = ["name as value", "is_group as expandable"]
963 filters = [["docstatus", "<", 2]]
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +0530964
Ankush Menat494bd9e2022-03-28 18:52:46 +0530965 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530966
Rushabh Mehta43133262017-11-10 18:52:21 +0530967 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530968 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
969 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530970
Saurabha9ba7342016-06-21 12:33:12 +0530971 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530972 fields += ["root_type", "account_currency"] if doctype == "Account" else []
973 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +0530974
975 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +0530976
Ankush Menat494bd9e2022-03-28 18:52:46 +0530977 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530978 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +0530979
980 return acc
Saurabhb835fef2016-09-09 11:19:22 +0530981
Ankush Menat494bd9e2022-03-28 18:52:46 +0530982
Saqib90517352021-10-04 11:44:46 +0530983@frappe.whitelist()
984def get_account_balances(accounts, company):
985
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530986 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +0530987 accounts = loads(accounts)
988
989 if not accounts:
990 return []
991
Ankush Menat494bd9e2022-03-28 18:52:46 +0530992 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +0530993
994 for account in accounts:
995 account["company_currency"] = company_currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530996 account["balance"] = flt(
997 get_balance_on(account["value"], in_account_currency=False, company=company)
998 )
Saqib90517352021-10-04 11:44:46 +0530999 if account["account_currency"] and account["account_currency"] != company_currency:
1000 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
1001
1002 return accounts
1003
Ankush Menat494bd9e2022-03-28 18:52:46 +05301004
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +05301005def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +05301006 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +05301007
Daizy Modifdfe5cb2022-11-17 19:14:10 +05301008 company = frappe.get_cached_value("Global Defaults", "Global Defaults", "default_company")
Saurabhb835fef2016-09-09 11:19:22 +05301009 if not company:
1010 return
1011
1012 # 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 +05301013 bank_account = frappe.db.get_value(
1014 "Account",
1015 {"account_name": _(gateway), "company": company},
1016 ["name", "account_currency"],
1017 as_dict=1,
1018 )
Saurabhb835fef2016-09-09 11:19:22 +05301019
1020 if not bank_account:
1021 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301022 bank_account = frappe.db.get_value(
1023 "Account",
1024 {"account_name": gateway, "company": company},
1025 ["name", "account_currency"],
1026 as_dict=1,
1027 )
Saurabhb835fef2016-09-09 11:19:22 +05301028
1029 if not bank_account:
1030 # try creating one
1031 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1032
1033 if not bank_account:
1034 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1035 return
1036
1037 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301038 if frappe.db.exists(
1039 "Payment Gateway Account",
1040 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1041 ):
Saurabhb835fef2016-09-09 11:19:22 +05301042 return
1043
1044 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301045 frappe.get_doc(
1046 {
1047 "doctype": "Payment Gateway Account",
1048 "is_default": 1,
1049 "payment_gateway": gateway,
1050 "payment_account": bank_account.name,
1051 "currency": bank_account.account_currency,
1052 "payment_channel": payment_channel,
1053 }
1054 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301055
1056 except frappe.DuplicateEntryError:
1057 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001058 pass
Zarrar44175902018-06-08 16:35:21 +05301059
Ankush Menat494bd9e2022-03-28 18:52:46 +05301060
Zarrar44175902018-06-08 16:35:21 +05301061@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301062def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301063 """
1064 Renames the document by adding the number as a prefix to the current name and updates
1065 all transaction where it was present.
1066 """
Saqiba8779872020-04-30 11:28:43 +05301067 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301068
Saqiba8779872020-04-30 11:28:43 +05301069 if cost_center_number:
1070 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1071 else:
1072 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301073
Saqiba8779872020-04-30 11:28:43 +05301074 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301075
Nabin Haitaf21a112022-09-15 12:09:18 +05301076 new_name = get_autoname_with_number(cost_center_number, cost_center_name, company)
Saqiba8779872020-04-30 11:28:43 +05301077 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301078 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301079 return new_name
1080
Ankush Menat494bd9e2022-03-28 18:52:46 +05301081
Saqiba8779872020-04-30 11:28:43 +05301082def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301083 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301084 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301085 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301086 if company:
Saqiba8779872020-04-30 11:28:43 +05301087 filters["company"] = company
1088
1089 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1090
Zarrar44175902018-06-08 16:35:21 +05301091 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301092 frappe.throw(
1093 _("{0} Number {1} is already used in {2} {3}").format(
1094 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1095 )
1096 )
1097
Zarrar44175902018-06-08 16:35:21 +05301098
Nabin Haitaf21a112022-09-15 12:09:18 +05301099def get_autoname_with_number(number_value, doc_title, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301100 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Nabin Haitaf21a112022-09-15 12:09:18 +05301101 company_abbr = frappe.get_cached_value("Company", company, "abbr")
1102 parts = [doc_title.strip(), company_abbr]
1103
Zlash651aeca1d2018-07-06 17:15:33 +05301104 if cstr(number_value).strip():
1105 parts.insert(0, cstr(number_value).strip())
Nabin Haitaf21a112022-09-15 12:09:18 +05301106
Ankush Menat494bd9e2022-03-28 18:52:46 +05301107 return " - ".join(parts)
1108
Zarrar254ce642018-06-28 14:15:34 +05301109
1110@frappe.whitelist()
1111def get_coa(doctype, parent, is_root, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301112 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1113 build_tree_from_json,
1114 )
Zarrar254ce642018-06-28 14:15:34 +05301115
1116 # add chart to flags to retrieve when called from expand all function
1117 chart = chart if chart else frappe.flags.chart
1118 frappe.flags.chart = chart
1119
Ankush Menat494bd9e2022-03-28 18:52:46 +05301120 parent = None if parent == _("All Accounts") else parent
1121 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301122
1123 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301124 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301125
1126 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001127
Ankush Menat494bd9e2022-03-28 18:52:46 +05301128
1129def update_gl_entries_after(
1130 posting_date,
1131 posting_time,
1132 for_warehouses=None,
1133 for_items=None,
1134 warehouse_account=None,
1135 company=None,
1136):
1137 stock_vouchers = get_future_stock_vouchers(
1138 posting_date, posting_time, for_warehouses, for_items, company
1139 )
Nabin Hait9b178bc2021-02-16 14:57:00 +05301140 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1141
1142
Ankush Menat494bd9e2022-03-28 18:52:46 +05301143def repost_gle_for_stock_vouchers(
Ankush Menat2535d5e2022-06-14 18:20:33 +05301144 stock_vouchers: List[Tuple[str, str]],
1145 posting_date: str,
1146 company: Optional[str] = None,
1147 warehouse_account=None,
1148 repost_doc: Optional["RepostItemValuation"] = None,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301149):
Ankush Menat67c26322022-06-04 14:46:35 +05301150
1151 from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative
1152
Ankush Menat700e8642022-04-19 13:24:29 +05301153 if not stock_vouchers:
1154 return
1155
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301156 if not warehouse_account:
1157 warehouse_account = get_warehouse_account_map(company)
1158
Ankush Menat2535d5e2022-06-14 18:20:33 +05301159 stock_vouchers = sort_stock_vouchers_by_posting_date(stock_vouchers)
1160 if repost_doc and repost_doc.gl_reposting_index:
1161 # Restore progress
1162 stock_vouchers = stock_vouchers[cint(repost_doc.gl_reposting_index) :]
1163
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301164 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1165
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301166 for stock_vouchers_chunk in create_batch(stock_vouchers, GL_REPOSTING_CHUNK):
Ankush Menat2535d5e2022-06-14 18:20:33 +05301167 gle = get_voucherwise_gl_entries(stock_vouchers_chunk, posting_date)
1168
1169 for voucher_type, voucher_no in stock_vouchers_chunk:
1170 existing_gle = gle.get((voucher_type, voucher_no), [])
1171 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
1172 # Some transactions post credit as negative debit, this is handled while posting GLE
1173 # but while comparing we need to make sure it's flipped so comparisons are accurate
1174 expected_gle = toggle_debit_credit_if_negative(voucher_obj.get_gl_entries(warehouse_account))
1175 if expected_gle:
1176 if not existing_gle or not compare_existing_and_expected_gle(
1177 existing_gle, expected_gle, precision
1178 ):
ruthra kumar9209ec52022-10-21 15:18:40 +05301179 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301180 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
1181 else:
ruthra kumar9209ec52022-10-21 15:18:40 +05301182 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat86919d22022-06-15 21:19:09 +05301183
1184 if not frappe.flags.in_test:
1185 frappe.db.commit()
Ankush Menat2535d5e2022-06-14 18:20:33 +05301186
1187 if repost_doc:
1188 repost_doc.db_set(
1189 "gl_reposting_index",
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301190 cint(repost_doc.gl_reposting_index) + len(stock_vouchers_chunk),
Ankush Menat2535d5e2022-06-14 18:20:33 +05301191 )
1192
1193
ruthra kumar9209ec52022-10-21 15:18:40 +05301194def _delete_pl_entries(voucher_type, voucher_no):
ruthra kumar65992302022-10-04 16:17:56 +05301195 ple = qb.DocType("Payment Ledger Entry")
1196 qb.from_(ple).delete().where(
1197 (ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)
1198 ).run()
Ankush Menateb53a972022-06-04 18:19:44 +05301199
Ankush Menat494bd9e2022-03-28 18:52:46 +05301200
ruthra kumar9209ec52022-10-21 15:18:40 +05301201def _delete_gl_entries(voucher_type, voucher_no):
1202 gle = qb.DocType("GL Entry")
1203 qb.from_(gle).delete().where(
1204 (gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)
1205 ).run()
1206
1207
1208def _delete_accounting_ledger_entries(voucher_type, voucher_no):
1209 """
1210 Remove entries from both General and Payment Ledger for specified Voucher
1211 """
1212 _delete_gl_entries(voucher_type, voucher_no)
1213 _delete_pl_entries(voucher_type, voucher_no)
1214
1215
Ankush Menat700e8642022-04-19 13:24:29 +05301216def sort_stock_vouchers_by_posting_date(
1217 stock_vouchers: List[Tuple[str, str]]
1218) -> List[Tuple[str, str]]:
1219 sle = frappe.qb.DocType("Stock Ledger Entry")
1220 voucher_nos = [v[1] for v in stock_vouchers]
1221
1222 sles = (
1223 frappe.qb.from_(sle)
1224 .select(sle.voucher_type, sle.voucher_no, sle.posting_date, sle.posting_time, sle.creation)
1225 .where((sle.is_cancelled == 0) & (sle.voucher_no.isin(voucher_nos)))
1226 .groupby(sle.voucher_type, sle.voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301227 .orderby(sle.posting_date)
1228 .orderby(sle.posting_time)
1229 .orderby(sle.creation)
Ankush Menat700e8642022-04-19 13:24:29 +05301230 ).run(as_dict=True)
1231 sorted_vouchers = [(sle.voucher_type, sle.voucher_no) for sle in sles]
1232
1233 unknown_vouchers = set(stock_vouchers) - set(sorted_vouchers)
1234 if unknown_vouchers:
1235 sorted_vouchers.extend(unknown_vouchers)
1236
1237 return sorted_vouchers
1238
1239
Ankush Menat494bd9e2022-03-28 18:52:46 +05301240def get_future_stock_vouchers(
1241 posting_date, posting_time, for_warehouses=None, for_items=None, company=None
1242):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301243
1244 values = []
1245 condition = ""
1246 if for_items:
1247 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1248 values += for_items
1249
1250 if for_warehouses:
1251 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1252 values += for_warehouses
1253
rohitwaghchaured60ff832021-02-16 09:12:27 +05301254 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301255 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301256 values.append(company)
1257
Ankush Menat494bd9e2022-03-28 18:52:46 +05301258 future_stock_vouchers = frappe.db.sql(
1259 """select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301260 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301261 where
1262 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1263 and is_cancelled = 0
1264 {condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301265 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
1266 condition=condition
1267 ),
1268 tuple([posting_date, posting_time] + values),
1269 as_dict=True,
1270 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301271
Ankush91527152021-08-11 11:17:50 +05301272 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301273
Ankush Menat494bd9e2022-03-28 18:52:46 +05301274
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301275def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301276 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301277
1278 Only fetches GLE fields required for comparing with new GLE.
1279 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301280
1281 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301282 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301283 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301284 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301285 if not future_stock_vouchers:
1286 return gl_entries
1287
1288 voucher_nos = [d[1] for d in future_stock_vouchers]
1289
Ankush Menat494bd9e2022-03-28 18:52:46 +05301290 gles = frappe.db.sql(
1291 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301292 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301293 from `tabGL Entry`
1294 where
Ankush Menat494bd9e2022-03-28 18:52:46 +05301295 posting_date >= %s and voucher_no in (%s)"""
1296 % ("%s", ", ".join(["%s"] * len(voucher_nos))),
1297 tuple([posting_date] + voucher_nos),
1298 as_dict=1,
1299 )
Ankush91527152021-08-11 11:17:50 +05301300
1301 for d in gles:
1302 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301303
Prssanna Desai82ddef52020-06-18 18:18:41 +05301304 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301305
Ankush Menat494bd9e2022-03-28 18:52:46 +05301306
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301307def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301308 if len(existing_gle) != len(expected_gle):
1309 return False
1310
Nabin Haita77b8c92020-12-21 14:45:50 +05301311 matched = True
1312 for entry in expected_gle:
1313 account_existed = False
1314 for e in existing_gle:
1315 if entry.account == e.account:
1316 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301317 if (
1318 entry.account == e.account
1319 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1320 and (
1321 flt(entry.debit, precision) != flt(e.debit, precision)
1322 or flt(entry.credit, precision) != flt(e.credit, precision)
1323 )
1324 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301325 matched = False
1326 break
1327 if not account_existed:
1328 matched = False
1329 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301330 return matched
1331
Ankush Menat494bd9e2022-03-28 18:52:46 +05301332
Nabin Haitb99c77b2020-12-25 18:12:35 +05301333def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301334 stock_accounts = [
1335 d.name
1336 for d in frappe.db.get_all(
1337 "Account", {"account_type": "Stock", "company": company, "is_group": 0}
1338 )
1339 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301340 if voucher_type and voucher_no:
1341 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301342 stock_accounts = [
1343 d.account
1344 for d in frappe.db.get_all(
1345 "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
1346 )
1347 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301348
1349 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301350 stock_accounts = [
1351 d.account
1352 for d in frappe.db.get_all(
1353 "GL Entry",
1354 {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
1355 "account",
1356 )
1357 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301358
1359 return stock_accounts
1360
Ankush Menat494bd9e2022-03-28 18:52:46 +05301361
Nabin Haitb99c77b2020-12-25 18:12:35 +05301362def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301363 if not posting_date:
1364 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301365
1366 warehouse_account = get_warehouse_account_map(company)
1367
Ankush Menat494bd9e2022-03-28 18:52:46 +05301368 account_balance = get_balance_on(
1369 account, posting_date, in_account_currency=False, ignore_account_permission=True
1370 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301371
Ankush Menat494bd9e2022-03-28 18:52:46 +05301372 related_warehouses = [
1373 wh
1374 for wh, wh_details in warehouse_account.items()
1375 if wh_details.account == account and not wh_details.is_group
1376 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301377
s-aga-re782a052023-04-25 13:54:36 +05301378 total_stock_value = get_stock_value_on(related_warehouses, posting_date)
Nabin Haitb99c77b2020-12-25 18:12:35 +05301379
1380 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1381 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1382
Ankush Menat494bd9e2022-03-28 18:52:46 +05301383
Nabin Haitb99c77b2020-12-25 18:12:35 +05301384def get_journal_entry(account, stock_adjustment_account, amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301385 db_or_cr_warehouse_account = (
1386 "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
1387 )
1388 db_or_cr_stock_adjustment_account = (
1389 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1390 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301391
1392 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301393 "accounts": [
1394 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1395 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1396 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301397 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301398
Ankush Menat494bd9e2022-03-28 18:52:46 +05301399
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301400def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301401 """Check if reports are referenced in Desktop Icon"""
1402 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301403 if icons:
1404 for icon in icons:
1405 frappe.delete_doc("Desktop Icon", icon)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301406
1407
ruthra kumar9b502212022-10-13 14:13:48 +05301408def get_payment_ledger_entries(gl_entries, cancel=0):
1409 ple_map = []
ruthra kumar451cf3a2022-05-16 14:29:58 +05301410 if gl_entries:
1411 ple = None
1412
1413 # companies
1414 account = qb.DocType("Account")
1415 companies = list(set([x.company for x in gl_entries]))
1416
1417 # receivable/payable account
1418 accounts_with_types = (
1419 qb.from_(account)
1420 .select(account.name, account.account_type)
1421 .where(
1422 (account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
1423 )
1424 .run(as_dict=True)
1425 )
1426 receivable_or_payable_accounts = [y.name for y in accounts_with_types]
1427
1428 def get_account_type(account):
1429 for entry in accounts_with_types:
1430 if entry.name == account:
1431 return entry.account_type
1432
1433 dr_or_cr = 0
1434 account_type = None
1435 for gle in gl_entries:
1436 if gle.account in receivable_or_payable_accounts:
1437 account_type = get_account_type(gle.account)
1438 if account_type == "Receivable":
1439 dr_or_cr = gle.debit - gle.credit
1440 dr_or_cr_account_currency = gle.debit_in_account_currency - gle.credit_in_account_currency
1441 elif account_type == "Payable":
1442 dr_or_cr = gle.credit - gle.debit
1443 dr_or_cr_account_currency = gle.credit_in_account_currency - gle.debit_in_account_currency
1444
1445 if cancel:
1446 dr_or_cr *= -1
1447 dr_or_cr_account_currency *= -1
1448
ruthra kumar9b502212022-10-13 14:13:48 +05301449 ple = frappe._dict(
1450 doctype="Payment Ledger Entry",
1451 posting_date=gle.posting_date,
1452 company=gle.company,
1453 account_type=account_type,
1454 account=gle.account,
1455 party_type=gle.party_type,
1456 party=gle.party,
1457 cost_center=gle.cost_center,
1458 finance_book=gle.finance_book,
1459 due_date=gle.due_date,
1460 voucher_type=gle.voucher_type,
1461 voucher_no=gle.voucher_no,
1462 against_voucher_type=gle.against_voucher_type
1463 if gle.against_voucher_type
1464 else gle.voucher_type,
1465 against_voucher_no=gle.against_voucher if gle.against_voucher else gle.voucher_no,
1466 account_currency=gle.account_currency,
1467 amount=dr_or_cr,
1468 amount_in_account_currency=dr_or_cr_account_currency,
1469 delinked=True if cancel else False,
1470 remarks=gle.remarks,
ruthra kumar451cf3a2022-05-16 14:29:58 +05301471 )
1472
1473 dimensions_and_defaults = get_dimensions()
1474 if dimensions_and_defaults:
1475 for dimension in dimensions_and_defaults[0]:
ruthra kumar9b502212022-10-13 14:13:48 +05301476 ple[dimension.fieldname] = gle.get(dimension.fieldname)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301477
ruthra kumar9b502212022-10-13 14:13:48 +05301478 ple_map.append(ple)
1479 return ple_map
1480
1481
1482def create_payment_ledger_entry(
1483 gl_entries, cancel=0, adv_adj=0, update_outstanding="Yes", from_repost=0
1484):
1485 if gl_entries:
1486 ple_map = get_payment_ledger_entries(gl_entries, cancel=cancel)
1487
1488 for entry in ple_map:
1489
1490 ple = frappe.get_doc(entry)
1491
1492 if cancel:
1493 delink_original_entry(ple)
1494
1495 ple.flags.ignore_permissions = 1
1496 ple.flags.adv_adj = adv_adj
1497 ple.flags.from_repost = from_repost
1498 ple.flags.update_outstanding = update_outstanding
1499 ple.submit()
ruthra kumar451cf3a2022-05-16 14:29:58 +05301500
1501
ruthra kumar7312f222022-05-29 21:33:08 +05301502def update_voucher_outstanding(voucher_type, voucher_no, account, party_type, party):
1503 ple = frappe.qb.DocType("Payment Ledger Entry")
1504 vouchers = [frappe._dict({"voucher_type": voucher_type, "voucher_no": voucher_no})]
1505 common_filter = []
1506 if account:
1507 common_filter.append(ple.account == account)
1508
1509 if party_type:
1510 common_filter.append(ple.party_type == party_type)
1511
1512 if party:
1513 common_filter.append(ple.party == party)
1514
1515 ple_query = QueryPaymentLedger()
1516
1517 # on cancellation outstanding can be an empty list
1518 voucher_outstanding = ple_query.get_voucher_outstandings(vouchers, common_filter=common_filter)
ruthra kumar43b80682022-10-18 09:33:37 +05301519 if (
1520 voucher_type in ["Sales Invoice", "Purchase Invoice", "Fees"]
1521 and party_type
1522 and party
1523 and voucher_outstanding
1524 ):
ruthra kumar7312f222022-05-29 21:33:08 +05301525 outstanding = voucher_outstanding[0]
1526 ref_doc = frappe.get_doc(voucher_type, voucher_no)
1527
1528 # Didn't use db_set for optimisation purpose
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301529 ref_doc.outstanding_amount = outstanding["outstanding_in_account_currency"] or 0.0
ruthra kumar7312f222022-05-29 21:33:08 +05301530 frappe.db.set_value(
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301531 voucher_type,
1532 voucher_no,
1533 "outstanding_amount",
1534 outstanding["outstanding_in_account_currency"] or 0.0,
ruthra kumar7312f222022-05-29 21:33:08 +05301535 )
1536
1537 ref_doc.set_status(update=True)
1538
1539
ruthra kumar451cf3a2022-05-16 14:29:58 +05301540def delink_original_entry(pl_entry):
1541 if pl_entry:
1542 ple = qb.DocType("Payment Ledger Entry")
1543 query = (
1544 qb.update(ple)
1545 .set(ple.delinked, True)
1546 .set(ple.modified, now())
1547 .set(ple.modified_by, frappe.session.user)
1548 .where(
1549 (ple.company == pl_entry.company)
1550 & (ple.account_type == pl_entry.account_type)
1551 & (ple.account == pl_entry.account)
1552 & (ple.party_type == pl_entry.party_type)
1553 & (ple.party == pl_entry.party)
1554 & (ple.voucher_type == pl_entry.voucher_type)
1555 & (ple.voucher_no == pl_entry.voucher_no)
1556 & (ple.against_voucher_type == pl_entry.against_voucher_type)
1557 & (ple.against_voucher_no == pl_entry.against_voucher_no)
1558 )
1559 )
1560 query.run()
ruthra kumar7b383882022-05-25 15:51:16 +05301561
1562
1563class QueryPaymentLedger(object):
1564 """
1565 Helper Class for Querying Payment Ledger Entry
1566 """
1567
1568 def __init__(self):
1569 self.ple = qb.DocType("Payment Ledger Entry")
1570
1571 # query result
1572 self.voucher_outstandings = []
1573
1574 # query filters
1575 self.vouchers = []
1576 self.common_filter = []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301577 self.voucher_posting_date = []
ruthra kumar7b383882022-05-25 15:51:16 +05301578 self.min_outstanding = None
1579 self.max_outstanding = None
1580
1581 def reset(self):
1582 # clear filters
1583 self.vouchers.clear()
1584 self.common_filter.clear()
1585 self.min_outstanding = self.max_outstanding = None
1586
1587 # clear result
1588 self.voucher_outstandings.clear()
1589
1590 def query_for_outstanding(self):
1591 """
1592 Database query to fetch voucher amount and voucher outstanding using Common Table Expression
1593 """
1594
1595 ple = self.ple
1596
1597 filter_on_voucher_no = []
1598 filter_on_against_voucher_no = []
1599 if self.vouchers:
1600 voucher_types = set([x.voucher_type for x in self.vouchers])
1601 voucher_nos = set([x.voucher_no for x in self.vouchers])
1602
1603 filter_on_voucher_no.append(ple.voucher_type.isin(voucher_types))
1604 filter_on_voucher_no.append(ple.voucher_no.isin(voucher_nos))
1605
1606 filter_on_against_voucher_no.append(ple.against_voucher_type.isin(voucher_types))
1607 filter_on_against_voucher_no.append(ple.against_voucher_no.isin(voucher_nos))
1608
1609 # build outstanding amount filter
1610 filter_on_outstanding_amount = []
1611 if self.min_outstanding:
1612 if self.min_outstanding > 0:
1613 filter_on_outstanding_amount.append(
1614 Table("outstanding").amount_in_account_currency >= self.min_outstanding
1615 )
1616 else:
1617 filter_on_outstanding_amount.append(
1618 Table("outstanding").amount_in_account_currency <= self.min_outstanding
1619 )
1620 if self.max_outstanding:
1621 if self.max_outstanding > 0:
1622 filter_on_outstanding_amount.append(
1623 Table("outstanding").amount_in_account_currency <= self.max_outstanding
1624 )
1625 else:
1626 filter_on_outstanding_amount.append(
1627 Table("outstanding").amount_in_account_currency >= self.max_outstanding
1628 )
1629
1630 # build query for voucher amount
1631 query_voucher_amount = (
1632 qb.from_(ple)
1633 .select(
1634 ple.account,
1635 ple.voucher_type,
1636 ple.voucher_no,
1637 ple.party_type,
1638 ple.party,
1639 ple.posting_date,
1640 ple.due_date,
1641 ple.account_currency.as_("currency"),
1642 Sum(ple.amount).as_("amount"),
1643 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1644 )
1645 .where(ple.delinked == 0)
1646 .where(Criterion.all(filter_on_voucher_no))
1647 .where(Criterion.all(self.common_filter))
ruthra kumar6d9d7302022-12-14 16:05:15 +05301648 .where(Criterion.all(self.dimensions_filter))
ruthra kumar5f1562c2022-07-28 11:57:27 +05301649 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar7b383882022-05-25 15:51:16 +05301650 .groupby(ple.voucher_type, ple.voucher_no, ple.party_type, ple.party)
1651 )
1652
1653 # build query for voucher outstanding
1654 query_voucher_outstanding = (
1655 qb.from_(ple)
1656 .select(
1657 ple.account,
1658 ple.against_voucher_type.as_("voucher_type"),
1659 ple.against_voucher_no.as_("voucher_no"),
1660 ple.party_type,
1661 ple.party,
1662 ple.posting_date,
1663 ple.due_date,
1664 ple.account_currency.as_("currency"),
1665 Sum(ple.amount).as_("amount"),
1666 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1667 )
1668 .where(ple.delinked == 0)
1669 .where(Criterion.all(filter_on_against_voucher_no))
1670 .where(Criterion.all(self.common_filter))
1671 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1672 )
1673
1674 # build CTE for combining voucher amount and outstanding
1675 self.cte_query_voucher_amount_and_outstanding = (
1676 qb.with_(query_voucher_amount, "vouchers")
1677 .with_(query_voucher_outstanding, "outstanding")
1678 .from_(AliasedQuery("vouchers"))
1679 .left_join(AliasedQuery("outstanding"))
1680 .on(
1681 (AliasedQuery("vouchers").account == AliasedQuery("outstanding").account)
1682 & (AliasedQuery("vouchers").voucher_type == AliasedQuery("outstanding").voucher_type)
1683 & (AliasedQuery("vouchers").voucher_no == AliasedQuery("outstanding").voucher_no)
1684 & (AliasedQuery("vouchers").party_type == AliasedQuery("outstanding").party_type)
1685 & (AliasedQuery("vouchers").party == AliasedQuery("outstanding").party)
1686 )
1687 .select(
1688 Table("vouchers").account,
1689 Table("vouchers").voucher_type,
1690 Table("vouchers").voucher_no,
1691 Table("vouchers").party_type,
1692 Table("vouchers").party,
1693 Table("vouchers").posting_date,
1694 Table("vouchers").amount.as_("invoice_amount"),
1695 Table("vouchers").amount_in_account_currency.as_("invoice_amount_in_account_currency"),
1696 Table("outstanding").amount.as_("outstanding"),
1697 Table("outstanding").amount_in_account_currency.as_("outstanding_in_account_currency"),
1698 (Table("vouchers").amount - Table("outstanding").amount).as_("paid_amount"),
1699 (
1700 Table("vouchers").amount_in_account_currency - Table("outstanding").amount_in_account_currency
1701 ).as_("paid_amount_in_account_currency"),
1702 Table("vouchers").due_date,
1703 Table("vouchers").currency,
1704 )
1705 .where(Criterion.all(filter_on_outstanding_amount))
1706 )
1707
1708 # build CTE filter
1709 # only fetch invoices
1710 if self.get_invoices:
1711 self.cte_query_voucher_amount_and_outstanding = (
1712 self.cte_query_voucher_amount_and_outstanding.having(
1713 qb.Field("outstanding_in_account_currency") > 0
1714 )
1715 )
1716 # only fetch payments
1717 elif self.get_payments:
1718 self.cte_query_voucher_amount_and_outstanding = (
1719 self.cte_query_voucher_amount_and_outstanding.having(
1720 qb.Field("outstanding_in_account_currency") < 0
1721 )
1722 )
1723
1724 # execute SQL
1725 self.voucher_outstandings = self.cte_query_voucher_amount_and_outstanding.run(as_dict=True)
1726
1727 def get_voucher_outstandings(
1728 self,
1729 vouchers=None,
1730 common_filter=None,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301731 posting_date=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301732 min_outstanding=None,
1733 max_outstanding=None,
1734 get_payments=False,
1735 get_invoices=False,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301736 accounting_dimensions=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301737 ):
1738 """
1739 Fetch voucher amount and outstanding amount from Payment Ledger using Database CTE
1740
1741 vouchers - dict of vouchers to get
1742 common_filter - array of criterions
1743 min_outstanding - filter on minimum total outstanding amount
1744 max_outstanding - filter on maximum total outstanding amount
1745 get_invoices - only fetch vouchers(ledger entries with +ve outstanding)
1746 get_payments - only fetch payments(ledger entries with -ve outstanding)
1747 """
1748
1749 self.reset()
1750 self.vouchers = vouchers
1751 self.common_filter = common_filter or []
ruthra kumar6d9d7302022-12-14 16:05:15 +05301752 self.dimensions_filter = accounting_dimensions or []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301753 self.voucher_posting_date = posting_date or []
ruthra kumar7b383882022-05-25 15:51:16 +05301754 self.min_outstanding = min_outstanding
1755 self.max_outstanding = max_outstanding
1756 self.get_payments = get_payments
1757 self.get_invoices = get_invoices
1758 self.query_for_outstanding()
1759
1760 return self.voucher_outstandings