blob: 005a2f176c415d3132301ea5600ecb4c27bafe85 [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(
54 date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False
55):
Anand Doshic75c1d72016-03-11 14:56:19 +053056 return get_fiscal_years(date, fiscal_year, label, verbose, company, as_dict=as_dict)[0]
Nabin Hait23941aa2013-01-29 11:32:38 +053057
Ankush Menat494bd9e2022-03-28 18:52:46 +053058
59def get_fiscal_years(
60 transaction_date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False
61):
Nabin Hait9784d272016-12-30 16:21:35 +053062 fiscal_years = frappe.cache().hget("fiscal_years", company) or []
Rushabh Mehtad50da782017-07-28 11:39:01 +053063
64 if not fiscal_years:
Nabin Hait9784d272016-12-30 16:21:35 +053065 # 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 +053066 FY = DocType("Fiscal Year")
Nabin Haitfff3ab72015-01-14 16:27:13 +053067
Gavin D'souza0727d1d2022-06-13 12:39:28 +053068 query = (
69 frappe.qb.from_(FY)
70 .select(FY.name, FY.year_start_date, FY.year_end_date)
71 .where(FY.disabled == 0)
Ankush Menat494bd9e2022-03-28 18:52:46 +053072 )
Rushabh Mehtad50da782017-07-28 11:39:01 +053073
Gavin D'souza0727d1d2022-06-13 12:39:28 +053074 if fiscal_year:
75 query = query.where(FY.name == fiscal_year)
76
77 if company:
78 FYC = DocType("Fiscal Year Company")
79 query = query.where(
80 ExistsCriterion(frappe.qb.from_(FYC).select(FYC.name).where(FYC.parent == FY.name)).negate()
81 | ExistsCriterion(
82 frappe.qb.from_(FYC)
83 .select(FYC.company)
84 .where(FYC.parent == FY.name)
85 .where(FYC.company == company)
86 )
87 )
88
Shridhar Patil69efd2e2022-10-03 11:07:24 +053089 query = query.orderby(FY.year_start_date, order=Order.desc)
Gavin D'souza0727d1d2022-06-13 12:39:28 +053090 fiscal_years = query.run(as_dict=True)
91
Nabin Hait9784d272016-12-30 16:21:35 +053092 frappe.cache().hset("fiscal_years", company, fiscal_years)
Nabin Haitfff3ab72015-01-14 16:27:13 +053093
Prssanna Desai82ddef52020-06-18 18:18:41 +053094 if not transaction_date and not fiscal_year:
95 return fiscal_years
96
Nabin Hait9784d272016-12-30 16:21:35 +053097 if transaction_date:
98 transaction_date = getdate(transaction_date)
Anand Doshicd71e1d2014-04-08 13:53:35 +053099
Nabin Hait9784d272016-12-30 16:21:35 +0530100 for fy in fiscal_years:
101 matched = False
102 if fiscal_year and fy.name == fiscal_year:
103 matched = True
Anand Doshicd71e1d2014-04-08 13:53:35 +0530104
Ankush Menat494bd9e2022-03-28 18:52:46 +0530105 if (
106 transaction_date
107 and getdate(fy.year_start_date) <= transaction_date
108 and getdate(fy.year_end_date) >= transaction_date
109 ):
Nabin Hait9784d272016-12-30 16:21:35 +0530110 matched = True
Rushabh Mehtad50da782017-07-28 11:39:01 +0530111
Nabin Hait9784d272016-12-30 16:21:35 +0530112 if matched:
113 if as_dict:
114 return (fy,)
115 else:
116 return ((fy.name, fy.year_start_date, fy.year_end_date),)
117
Ankush Menat494bd9e2022-03-28 18:52:46 +0530118 error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(
119 label, formatdate(transaction_date)
120 )
Anuja P2e4faf92020-12-05 13:36:43 +0530121 if company:
Anuja P550cb9c2020-12-07 11:11:00 +0530122 error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company))
rohitwaghchaured60ff832021-02-16 09:12:27 +0530123
Ankush Menat494bd9e2022-03-28 18:52:46 +0530124 if verbose == 1:
125 frappe.msgprint(error_msg)
cclauss68487082017-07-27 07:08:35 +0200126 raise FiscalYearError(error_msg)
Nabin Hait9784d272016-12-30 16:21:35 +0530127
Ankush Menat494bd9e2022-03-28 18:52:46 +0530128
Prssanna Desai82ddef52020-06-18 18:18:41 +0530129@frappe.whitelist()
130def get_fiscal_year_filter_field(company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530131 field = {"fieldtype": "Select", "options": [], "operator": "Between", "query_value": True}
Prssanna Desai82ddef52020-06-18 18:18:41 +0530132 fiscal_years = get_fiscal_years(company=company)
133 for fiscal_year in fiscal_years:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530134 field["options"].append(
135 {
136 "label": fiscal_year.name,
137 "value": fiscal_year.name,
138 "query_value": [
139 fiscal_year.year_start_date.strftime("%Y-%m-%d"),
140 fiscal_year.year_end_date.strftime("%Y-%m-%d"),
141 ],
142 }
143 )
Prssanna Desai82ddef52020-06-18 18:18:41 +0530144 return field
145
Ankush Menat494bd9e2022-03-28 18:52:46 +0530146
Nabin Hait8bf58362017-03-27 12:30:01 +0530147def validate_fiscal_year(date, fiscal_year, company, label="Date", doc=None):
148 years = [f[0] for f in get_fiscal_years(date, label=_(label), company=company)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +0530149 if fiscal_year not in years:
Rushabh Mehtad60acb92015-02-19 14:51:58 +0530150 if doc:
151 doc.fiscal_year = years[0]
152 else:
153 throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
Nabin Hait23941aa2013-01-29 11:32:38 +0530154
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530156@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530157def get_balance_on(
158 account=None,
159 date=None,
160 party_type=None,
161 party=None,
162 company=None,
163 in_account_currency=True,
164 cost_center=None,
165 ignore_account_permission=False,
166):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530167 if not account and frappe.form_dict.get("account"):
168 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530169 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530170 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530171 if not party_type and frappe.form_dict.get("party_type"):
172 party_type = frappe.form_dict.get("party_type")
173 if not party and frappe.form_dict.get("party"):
174 party = frappe.form_dict.get("party")
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400175 if not cost_center and frappe.form_dict.get("cost_center"):
176 cost_center = frappe.form_dict.get("cost_center")
177
Nabin Hait98372852020-07-30 20:52:20 +0530178 cond = ["is_cancelled=0"]
Nabin Hait23941aa2013-01-29 11:32:38 +0530179 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530180 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530181 else:
182 # get balance of all entries that exist
183 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530184
Deepesh Garg8c217032019-07-16 09:41:01 +0530185 if account:
186 acc = frappe.get_doc("Account", account)
187
Nabin Hait23941aa2013-01-29 11:32:38 +0530188 try:
Deepesh Garg96d40ec2020-07-03 22:59:00 +0530189 year_start_date = get_fiscal_year(date, company=company, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530190 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +0530191 if getdate(date) > getdate(nowdate()):
192 # if fiscal year not found and the date is greater than today
193 # get fiscal year for today's date and its corresponding year start date
194 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
195 else:
196 # this indicates that it is a date older than any existing fiscal year.
197 # hence, assuming balance as 0.0
198 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530199
deepeshgarg0072ddbebf2019-07-20 14:52:59 +0530200 if account:
deepeshgarg007e097d4f2019-07-20 14:49:32 +0530201 report_type = acc.report_type
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530202 else:
203 report_type = ""
204
Ankush Menat494bd9e2022-03-28 18:52:46 +0530205 if cost_center and report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400206 cc = frappe.get_doc("Cost Center", cost_center)
207 if cc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530208 cond.append(
209 """ exists (
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400210 select 1 from `tabCost Center` cc where cc.name = gle.cost_center
211 and cc.lft >= %s and cc.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530212 )"""
213 % (cc.lft, cc.rgt)
214 )
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400215
216 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530217 cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center, percent=False),))
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400218
Nabin Hait6f17cf92014-09-17 14:11:22 +0530219 if account:
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400220
Ankush Menat494bd9e2022-03-28 18:52:46 +0530221 if not (frappe.flags.ignore_account_permission or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530222 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530223
Ankush Menat494bd9e2022-03-28 18:52:46 +0530224 if report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400225 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530226 cond.append(
227 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
228 )
Nabin Hait6f17cf92014-09-17 14:11:22 +0530229 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530230 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530231 cond.append(
232 """exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530233 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530234 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530235 )"""
236 % (acc.lft, acc.rgt)
237 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530238
239 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530240 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530241 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530242 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530243 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530244 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
Anand Doshic75c1d72016-03-11 14:56:19 +0530245
Nabin Hait6f17cf92014-09-17 14:11:22 +0530246 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530247 cond.append(
248 """gle.party_type = %s and gle.party = %s """
249 % (frappe.db.escape(party_type), frappe.db.escape(party, percent=False))
250 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530251
Nabin Hait85648d92016-07-20 11:26:45 +0530252 if company:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530253 cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530254
Nabin Haitdc768232015-08-17 11:27:00 +0530255 if account or (party_type and party):
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530256 if in_account_currency:
Anand Doshi602e8252015-11-16 19:05:46 +0530257 select_field = "sum(debit_in_account_currency) - sum(credit_in_account_currency)"
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530258 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530259 select_field = "sum(debit) - sum(credit)"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530260 bal = frappe.db.sql(
261 """
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530262 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530263 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530264 WHERE {1}""".format(
265 select_field, " and ".join(cond)
266 )
267 )[0][0]
Anand Doshicd71e1d2014-04-08 13:53:35 +0530268
Nabin Haitdc768232015-08-17 11:27:00 +0530269 # if bal is None, return 0
270 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530271
Ankush Menat494bd9e2022-03-28 18:52:46 +0530272
RobertSchouten8d43b322016-09-20 13:41:39 +0800273def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530274 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800275 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530276 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800277 else:
278 # get balance of all entries that exist
279 date = nowdate()
280
281 try:
282 year_start_date = get_fiscal_year(date, verbose=0)[1]
283 except FiscalYearError:
284 if getdate(date) > getdate(nowdate()):
285 # if fiscal year not found and the date is greater than today
286 # get fiscal year for today's date and its corresponding year start date
287 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
288 else:
289 # this indicates that it is a date older than any existing fiscal year.
290 # hence, assuming balance as 0.0
291 return 0.0
292
293 if account:
294 acc = frappe.get_doc("Account", account)
295
296 if not frappe.flags.ignore_account_permission:
297 acc.check_permission("read")
298
299 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530300 if acc.report_type == "Profit and Loss":
301 cond.append(
302 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
303 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800304
305 # different filter for group and ledger - improved performance
306 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530307 cond.append(
308 """exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800309 select name from `tabAccount` ac where ac.name = gle.account
310 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530311 )"""
312 % (acc.lft, acc.rgt)
313 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800314 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530315 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
RobertSchouten8d43b322016-09-20 13:41:39 +0800316
Ankush Menat494bd9e2022-03-28 18:52:46 +0530317 entries = frappe.db.sql(
318 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800319 SELECT name, posting_date, account, party_type, party,debit,credit,
320 voucher_type, voucher_no, against_voucher_type, against_voucher
321 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530322 WHERE {0}""".format(
323 " and ".join(cond)
324 ),
325 as_dict=True,
326 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530327
RobertSchouten8d43b322016-09-20 13:41:39 +0800328 count = 0
329 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530330 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800331 count += 1
332 else:
333 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
334 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530335 select_fields = (
336 "ifnull(sum(credit-debit),0)"
337 if fieldname == "invoiced_amount"
338 else "ifnull(sum(debit-credit),0)"
339 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800340
Ankush Menat494bd9e2022-03-28 18:52:46 +0530341 if (
342 (not gle.against_voucher)
343 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
344 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
345 ):
346 payment_amount = frappe.db.sql(
347 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800348 SELECT {0}
349 FROM `tabGL Entry` gle
350 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530351 and party = %(party)s and name != %(name)s""".format(
352 select_fields
353 ),
354 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
355 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530356
RobertSchouten8d43b322016-09-20 13:41:39 +0800357 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
358 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530359 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800360 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530361
RobertSchouten8d43b322016-09-20 13:41:39 +0800362 return count
363
Ankush Menat494bd9e2022-03-28 18:52:46 +0530364
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530365@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530366def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530367 from frappe.desk.treeview import make_tree_args
368
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530369 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530370 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530371
Nabin Hait02d987e2017-02-17 15:50:26 +0530372 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530373 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530374
Anand Doshi3e41fd12014-04-22 18:54:54 +0530375 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530376
Nabin Hait665568d2016-05-13 15:56:00 +0530377 if args.get("ignore_permissions"):
378 ac.flags.ignore_permissions = True
379 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530380
Anand Doshi3e41fd12014-04-22 18:54:54 +0530381 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530382
383 if not ac.parent_account:
384 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530385
Anand Doshif78d1ae2014-03-28 13:55:00 +0530386 ac.old_parent = ""
387 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530388 if cint(ac.get("is_root")):
389 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530390 ac.flags.ignore_mandatory = True
391
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530392 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530393
Anand Doshif78d1ae2014-03-28 13:55:00 +0530394 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530395
Ankush Menat494bd9e2022-03-28 18:52:46 +0530396
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530397@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530398def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530399 from frappe.desk.treeview import make_tree_args
400
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530401 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530402 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530403
Nabin Hait02d987e2017-02-17 15:50:26 +0530404 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530405 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530406
Zarrar7ab70ca2018-06-08 14:33:15 +0530407 if args.parent_cost_center == args.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530408 args.parent_cost_center = "{0} - {1}".format(
409 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
410 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530411
Anand Doshi3e41fd12014-04-22 18:54:54 +0530412 cc = frappe.new_doc("Cost Center")
413 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530414
415 if not cc.parent_cost_center:
416 cc.parent_cost_center = args.get("parent")
417
Anand Doshif78d1ae2014-03-28 13:55:00 +0530418 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530419 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530420 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530421
Ankush Menat494bd9e2022-03-28 18:52:46 +0530422
Rucha Mahabal108cce22022-07-07 19:00:19 +0530423def reconcile_against_document(args): # nosemgrep
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530424 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530425 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530426 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530427 # To optimize making GL Entry for PE or JV with multiple references
428 reconciled_entries = {}
429 for row in args:
430 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
431 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530432
Anuja Pawar3e404f12021-08-31 18:59:29 +0530433 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
434
435 for key, entries in reconciled_entries.items():
436 voucher_type = key[0]
437 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530438
Nabin Hait28a05282016-06-27 17:41:39 +0530439 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530440 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530441 frappe.flags.ignore_party_validation = True
ruthra kumar11cf6942023-01-14 12:22:22 +0530442 _delete_pl_entries(voucher_type, voucher_no)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530443
Anuja Pawar3e404f12021-08-31 18:59:29 +0530444 for entry in entries:
445 check_if_advance_entry_modified(entry)
446 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530447
Anuja Pawar3e404f12021-08-31 18:59:29 +0530448 # update ref in advance entry
449 if voucher_type == "Journal Entry":
450 update_reference_in_journal_entry(entry, doc, do_not_save=True)
451 else:
452 update_reference_in_payment_entry(entry, doc, do_not_save=True)
453
ruthra kumar11cf6942023-01-14 12:22:22 +0530454 if doc.doctype == "Journal Entry":
455 try:
456 doc.validate_total_debit_and_credit()
457 except Exception as validation_exception:
Dannyca10e2b2023-03-17 06:43:32 -0400458 raise frappe.ValidationError(
459 _("Validation Error for {0}").format(doc.name)
460 ) from validation_exception
ruthra kumar11cf6942023-01-14 12:22:22 +0530461
Anuja Pawar3e404f12021-08-31 18:59:29 +0530462 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530463 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530464 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
ruthra kumar524c1752022-05-26 16:00:40 +0530465 gl_map = doc.build_gl_map()
ruthra kumar11cf6942023-01-14 12:22:22 +0530466 create_payment_ledger_entry(gl_map, update_outstanding="No", cancel=0, adv_adj=1)
467
468 # Only update outstanding for newly linked vouchers
469 for entry in entries:
470 update_voucher_outstanding(
471 entry.against_voucher_type, entry.against_voucher, entry.account, entry.party_type, entry.party
472 )
ruthra kumar524c1752022-05-26 16:00:40 +0530473
Subin Tomb8845b92021-07-30 16:30:18 +0530474 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530475
Ankush Menat494bd9e2022-03-28 18:52:46 +0530476
Nabin Hait28a05282016-06-27 17:41:39 +0530477def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530478 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530479 check if there is already a voucher reference
480 check if amount is same
481 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530482 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530483 if not args.get("unreconciled_amount"):
484 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530485
Nabin Hait28a05282016-06-27 17:41:39 +0530486 ret = None
487 if args.voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530488 ret = frappe.db.sql(
489 """
Nabin Hait28a05282016-06-27 17:41:39 +0530490 select t2.{dr_or_cr} from `tabJournal Entry` t1, `tabJournal Entry Account` t2
491 where t1.name = t2.parent and t2.account = %(account)s
492 and t2.party_type = %(party_type)s and t2.party = %(party)s
Conor74a782d2022-06-17 06:31:27 -0500493 and (t2.reference_type is null or t2.reference_type in ('', 'Sales Order', 'Purchase Order'))
Nabin Hait28a05282016-06-27 17:41:39 +0530494 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530495 and t1.docstatus=1 """.format(
496 dr_or_cr=args.get("dr_or_cr")
497 ),
498 args,
499 )
Nabin Hait28a05282016-06-27 17:41:39 +0530500 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530501 party_account_field = (
502 "paid_from" if erpnext.get_party_account_type(args.party_type) == "Receivable" else "paid_to"
503 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530504
Nabin Hait28a05282016-06-27 17:41:39 +0530505 if args.voucher_detail_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530506 ret = frappe.db.sql(
507 """select t1.name
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530508 from `tabPayment Entry` t1, `tabPayment Entry Reference` t2
Nabin Hait28a05282016-06-27 17:41:39 +0530509 where
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530510 t1.name = t2.parent and t1.docstatus = 1
Nabin Hait28a05282016-06-27 17:41:39 +0530511 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
512 and t1.party_type = %(party_type)s and t1.party = %(party)s and t1.{0} = %(account)s
Conor74a782d2022-06-17 06:31:27 -0500513 and t2.reference_doctype in ('', 'Sales Order', 'Purchase Order')
Anuja Pawar3e404f12021-08-31 18:59:29 +0530514 and t2.allocated_amount = %(unreconciled_amount)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530515 """.format(
516 party_account_field
517 ),
518 args,
519 )
Nabin Hait28a05282016-06-27 17:41:39 +0530520 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530521 ret = frappe.db.sql(
522 """select name from `tabPayment Entry`
Nabin Hait28a05282016-06-27 17:41:39 +0530523 where
524 name = %(voucher_no)s and docstatus = 1
525 and party_type = %(party_type)s and party = %(party)s and {0} = %(account)s
Anuja Pawar3e404f12021-08-31 18:59:29 +0530526 and unallocated_amount = %(unreconciled_amount)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530527 """.format(
528 party_account_field
529 ),
530 args,
531 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530532
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530533 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530534 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530535
Ankush Menat494bd9e2022-03-28 18:52:46 +0530536
Nabin Hait576f0252014-04-30 19:30:50 +0530537def validate_allocated_amount(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530538 precision = args.get("precision") or frappe.db.get_single_value(
539 "System Settings", "currency_precision"
540 )
Nabin Hait28a05282016-06-27 17:41:39 +0530541 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530542 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530543 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530544 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530545
Ankush Menat494bd9e2022-03-28 18:52:46 +0530546
Anuja Pawar3e404f12021-08-31 18:59:29 +0530547def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530548 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530549 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530550 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530551 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530552
Ankush Menat494bd9e2022-03-28 18:52:46 +0530553 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530554 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530555 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530556 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530557 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
558 jv_detail.set(
559 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
560 amount_in_company_currency,
561 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530562 else:
563 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530564
Anuja Pawar3e404f12021-08-31 18:59:29 +0530565 # new row with references
566 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530567
568 new_row.update((frappe.copy_doc(jv_detail)).as_dict())
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530569
Anuja Pawar3e404f12021-08-31 18:59:29 +0530570 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530571 new_row.set(
572 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
573 d["allocated_amount"] * flt(jv_detail.exchange_rate),
574 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530575
Ankush Menat494bd9e2022-03-28 18:52:46 +0530576 new_row.set(
577 "credit_in_account_currency"
578 if d["dr_or_cr"] == "debit_in_account_currency"
579 else "debit_in_account_currency",
580 0,
581 )
582 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530583
Anuja Pawar3e404f12021-08-31 18:59:29 +0530584 new_row.set("reference_type", d["against_voucher_type"])
585 new_row.set("reference_name", d["against_voucher"])
586
587 new_row.against_account = cstr(jv_detail.against_account)
588 new_row.is_advance = cstr(jv_detail.is_advance)
589 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530590
591 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530592 journal_entry.flags.ignore_validate_update_after_submit = True
593 if not do_not_save:
594 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530595
Ankush Menat494bd9e2022-03-28 18:52:46 +0530596
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530597def update_reference_in_payment_entry(d, payment_entry, do_not_save=False):
Nabin Hait28a05282016-06-27 17:41:39 +0530598 reference_details = {
599 "reference_doctype": d.against_voucher_type,
600 "reference_name": d.against_voucher,
601 "total_amount": d.grand_total,
602 "outstanding_amount": d.outstanding_amount,
603 "allocated_amount": d.allocated_amount,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530604 "exchange_rate": d.exchange_rate
605 if not d.exchange_gain_loss
606 else payment_entry.get_exchange_rate(),
607 "exchange_gain_loss": d.exchange_gain_loss, # only populated from invoice in case of advance allocation
Nabin Hait28a05282016-06-27 17:41:39 +0530608 }
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530609
Nabin Hait28a05282016-06-27 17:41:39 +0530610 if d.voucher_detail_no:
611 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
612 original_row = existing_row.as_dict().copy()
613 existing_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530614
Nabin Hait28a05282016-06-27 17:41:39 +0530615 if d.allocated_amount < original_row.allocated_amount:
616 new_row = payment_entry.append("references")
617 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500618 for field in list(reference_details):
Nabin Hait28a05282016-06-27 17:41:39 +0530619 new_row.set(field, original_row[field])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530620
Nabin Hait28a05282016-06-27 17:41:39 +0530621 new_row.allocated_amount = original_row.allocated_amount - d.allocated_amount
622 else:
623 new_row = payment_entry.append("references")
624 new_row.docstatus = 1
625 new_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530626
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530627 if d.difference_amount and d.difference_account:
Saqiba20999c2021-07-12 14:33:23 +0530628 account_details = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530629 "account": d.difference_account,
630 "cost_center": payment_entry.cost_center
631 or frappe.get_cached_value("Company", payment_entry.company, "cost_center"),
Saqiba20999c2021-07-12 14:33:23 +0530632 }
633 if d.difference_amount:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530634 account_details["amount"] = d.difference_amount
Saqiba20999c2021-07-12 14:33:23 +0530635
636 payment_entry.set_gain_or_loss(account_details=account_details)
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530637
Devin Slauenwhite98c39c42023-01-01 22:25:12 -0500638 payment_entry.flags.ignore_validate_update_after_submit = True
639 payment_entry.setup_party_account_field()
640 payment_entry.set_missing_values()
641 payment_entry.set_amounts()
642
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530643 if not do_not_save:
644 payment_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530645
Ankush Menat494bd9e2022-03-28 18:52:46 +0530646
Nabin Hait297d74a2016-11-23 15:58:51 +0530647def unlink_ref_doc_from_payment_entries(ref_doc):
648 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name)
649 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530650
Ankush Menat494bd9e2022-03-28 18:52:46 +0530651 frappe.db.sql(
652 """update `tabGL Entry`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530653 set against_voucher_type=null, against_voucher=null,
654 modified=%s, modified_by=%s
655 where against_voucher_type=%s and against_voucher=%s
656 and voucher_no != ifnull(against_voucher, '')""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530657 (now(), frappe.session.user, ref_doc.doctype, ref_doc.name),
658 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530659
ruthra kumar537d9532022-10-10 10:17:19 +0530660 ple = qb.DocType("Payment Ledger Entry")
661
662 qb.update(ple).set(ple.against_voucher_type, ple.voucher_type).set(
663 ple.against_voucher_no, ple.voucher_no
664 ).set(ple.modified, now()).set(ple.modified_by, frappe.session.user).where(
665 (ple.against_voucher_type == ref_doc.doctype)
666 & (ple.against_voucher_no == ref_doc.name)
667 & (ple.delinked == 0)
668 ).run()
669
Nabin Hait297d74a2016-11-23 15:58:51 +0530670 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
671 ref_doc.set("advances", [])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530672
Ankush Menat494bd9e2022-03-28 18:52:46 +0530673 frappe.db.sql(
674 """delete from `tab{0} Advance` where parent = %s""".format(ref_doc.doctype), ref_doc.name
675 )
676
Anand Doshicd71e1d2014-04-08 13:53:35 +0530677
Nabin Haite0cc87d2016-07-21 18:30:03 +0530678def remove_ref_doc_link_from_jv(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530679 linked_jv = frappe.db.sql_list(
680 """select parent from `tabJournal Entry Account`
681 where reference_type=%s and reference_name=%s and docstatus < 2""",
682 (ref_type, ref_no),
683 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530684
685 if linked_jv:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530686 frappe.db.sql(
687 """update `tabJournal Entry Account`
Rushabh Mehta1828c122015-08-10 17:04:07 +0530688 set reference_type=null, reference_name = null,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530689 modified=%s, modified_by=%s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530690 where reference_type=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530691 and docstatus < 2""",
692 (now(), frappe.session.user, ref_type, ref_no),
693 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530694
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530695 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530696
Ankush Menat494bd9e2022-03-28 18:52:46 +0530697
Nabin Haite0cc87d2016-07-21 18:30:03 +0530698def remove_ref_doc_link_from_pe(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530699 linked_pe = frappe.db.sql_list(
700 """select parent from `tabPayment Entry Reference`
701 where reference_doctype=%s and reference_name=%s and docstatus < 2""",
702 (ref_type, ref_no),
703 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530704
Nabin Haite0cc87d2016-07-21 18:30:03 +0530705 if linked_pe:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530706 frappe.db.sql(
707 """update `tabPayment Entry Reference`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530708 set allocated_amount=0, modified=%s, modified_by=%s
709 where reference_doctype=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530710 and docstatus < 2""",
711 (now(), frappe.session.user, ref_type, ref_no),
712 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530713
Nabin Haite0cc87d2016-07-21 18:30:03 +0530714 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530715 try:
716 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530717 pe_doc.set_amounts()
Deepesh Gargb5162392021-08-10 14:52:24 +0530718 pe_doc.clear_unallocated_reference_document_rows()
719 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530720 except Exception as e:
721 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530722 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530723 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530724 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530725
Ankush Menat494bd9e2022-03-28 18:52:46 +0530726 frappe.db.sql(
727 """update `tabPayment Entry` set total_allocated_amount=%s,
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530728 base_total_allocated_amount=%s, unallocated_amount=%s, modified=%s, modified_by=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530729 where name=%s""",
730 (
731 pe_doc.total_allocated_amount,
732 pe_doc.base_total_allocated_amount,
733 pe_doc.unallocated_amount,
734 now(),
735 frappe.session.user,
736 pe,
737 ),
738 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530739
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530740 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530741
Ankush Menat494bd9e2022-03-28 18:52:46 +0530742
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530743@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530744def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530745 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530746
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530747 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530748 throw(
749 _("Please set default {0} in Company {1}").format(
750 frappe.get_meta("Company").get_label(fieldname), company
751 )
752 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530753
Nabin Hait0fc24542013-03-25 11:06:00 +0530754 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530755
Ankush Menat494bd9e2022-03-28 18:52:46 +0530756
Nabin Hait8b509f52013-05-28 16:52:30 +0530757def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530758 vouchers = frappe.db.sql(
759 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530760 sum(debit) - sum(credit) as diff
761 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530762 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530763 having sum(debit) != sum(credit)""",
764 as_dict=1,
765 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530766
Nabin Hait8b509f52013-05-28 16:52:30 +0530767 for d in vouchers:
768 if abs(d.diff) > 0:
769 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530770
Ankush Menat494bd9e2022-03-28 18:52:46 +0530771 frappe.db.sql(
772 """update `tabGL Entry` set %s = %s + %s
773 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
774 % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
775 (d.diff, d.voucher_type, d.voucher_no),
776 )
777
Anand Doshicd71e1d2014-04-08 13:53:35 +0530778
Rushabh Mehtad50da782017-07-28 11:39:01 +0530779def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530780 precision = cint(frappe.db.get_default("currency_precision"))
781 if not precision:
782 number_format = frappe.db.get_default("number_format") or "#,###.##"
783 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530784
Nabin Hait9b20e072017-04-25 12:10:24 +0530785 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530786
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530787
Ankush Menat494bd9e2022-03-28 18:52:46 +0530788def get_stock_rbnb_difference(posting_date, company):
789 stock_items = frappe.db.sql_list(
790 """select distinct item_code
791 from `tabStock Ledger Entry` where company=%s""",
792 company,
793 )
794
795 pr_valuation_amount = frappe.db.sql(
796 """
Anand Doshi602e8252015-11-16 19:05:46 +0530797 select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530798 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
Suraj Shetty084b0b32018-05-26 09:12:59 +0530799 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530800 and pr.posting_date <= %s and pr_item.item_code in (%s)"""
801 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
802 tuple([company, posting_date] + stock_items),
803 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530804
Ankush Menat494bd9e2022-03-28 18:52:46 +0530805 pi_valuation_amount = frappe.db.sql(
806 """
Anand Doshi602e8252015-11-16 19:05:46 +0530807 select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530808 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
Suraj Shetty084b0b32018-05-26 09:12:59 +0530809 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530810 and pi.posting_date <= %s and pi_item.item_code in (%s)"""
811 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
812 tuple([company, posting_date] + stock_items),
813 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530814
815 # Balance should be
816 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
817
818 # Balance as per system
Ankush Menat494bd9e2022-03-28 18:52:46 +0530819 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.get_cached_value(
820 "Company", company, "abbr"
821 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530822 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530823
824 # Amount should be credited
825 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530826
tundec4b0d172017-09-26 00:48:30 +0100827
tundebabzyad08d4c2018-05-16 07:01:41 +0100828def get_held_invoices(party_type, party):
829 """
830 Returns a list of names Purchase Invoices for the given party that are on hold
831 """
832 held_invoices = None
833
Ankush Menat494bd9e2022-03-28 18:52:46 +0530834 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +0100835 held_invoices = frappe.db.sql(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530836 "select name from `tabPurchase Invoice` where release_date IS NOT NULL and release_date > CURDATE()",
837 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +0100838 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530839 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +0100840
841 return held_invoices
842
843
ruthra kumar8c876742022-06-14 17:46:04 +0530844def get_outstanding_invoices(
ruthra kumar5f1562c2022-07-28 11:57:27 +0530845 party_type,
846 party,
847 account,
848 common_filter=None,
849 posting_date=None,
850 min_outstanding=None,
851 max_outstanding=None,
ruthra kumar6d9d7302022-12-14 16:05:15 +0530852 accounting_dimensions=None,
ruthra kumar8c876742022-06-14 17:46:04 +0530853):
854
855 ple = qb.DocType("Payment Ledger Entry")
Anand Doshid40d1e92015-11-12 17:05:29 +0530856 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +0530857 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +0530858
Nabin Hait9db9edc2019-11-19 18:44:32 +0530859 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530860 root_type, account_type = frappe.get_cached_value(
861 "Account", account, ["root_type", "account_type"]
862 )
Nabin Hait9db9edc2019-11-19 18:44:32 +0530863 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +0530864 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +0530865 else:
866 party_account_type = erpnext.get_party_account_type(party_type)
867
tundebabzyad08d4c2018-05-16 07:01:41 +0100868 held_invoices = get_held_invoices(party_type, party)
869
ruthra kumar8c876742022-06-14 17:46:04 +0530870 common_filter = common_filter or []
871 common_filter.append(ple.account_type == party_account_type)
872 common_filter.append(ple.account == account)
873 common_filter.append(ple.party_type == party_type)
874 common_filter.append(ple.party == party)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530875
ruthra kumar8c876742022-06-14 17:46:04 +0530876 ple_query = QueryPaymentLedger()
877 invoice_list = ple_query.get_voucher_outstandings(
878 common_filter=common_filter,
ruthra kumar5f1562c2022-07-28 11:57:27 +0530879 posting_date=posting_date,
ruthra kumar8c876742022-06-14 17:46:04 +0530880 min_outstanding=min_outstanding,
881 max_outstanding=max_outstanding,
882 get_invoices=True,
ruthra kumar6d9d7302022-12-14 16:05:15 +0530883 accounting_dimensions=accounting_dimensions or [],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530884 )
tundec4b0d172017-09-26 00:48:30 +0100885
Nabin Haitac184982019-02-04 21:13:43 +0530886 for d in invoice_list:
ruthra kumar21985532022-06-30 15:14:38 +0530887 payment_amount = d.invoice_amount_in_account_currency - d.outstanding_in_account_currency
888 outstanding_amount = d.outstanding_in_account_currency
Nabin Haitac184982019-02-04 21:13:43 +0530889 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530890 if (
ruthra kumar8c876742022-06-14 17:46:04 +0530891 min_outstanding
892 and max_outstanding
893 and not (outstanding_amount >= min_outstanding and outstanding_amount <= max_outstanding)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530894 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530895 continue
Nabin Haitac184982019-02-04 21:13:43 +0530896
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530897 if not d.voucher_type == "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +0530898 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530899 frappe._dict(
900 {
901 "voucher_no": d.voucher_no,
902 "voucher_type": d.voucher_type,
903 "posting_date": d.posting_date,
ruthra kumar21985532022-06-30 15:14:38 +0530904 "invoice_amount": flt(d.invoice_amount_in_account_currency),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530905 "payment_amount": payment_amount,
906 "outstanding_amount": outstanding_amount,
907 "due_date": d.due_date,
908 "currency": d.currency,
909 }
910 )
Nabin Haitac184982019-02-04 21:13:43 +0530911 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530912
Ankush Menat494bd9e2022-03-28 18:52:46 +0530913 outstanding_invoices = sorted(
914 outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
915 )
Anand Doshid40d1e92015-11-12 17:05:29 +0530916 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +0530917
918
Ankush Menat494bd9e2022-03-28 18:52:46 +0530919def get_account_name(
920 account_type=None, root_type=None, is_group=None, account_currency=None, company=None
921):
Saurabh3a268292016-02-22 15:18:40 +0530922 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530923 return frappe.db.get_value(
924 "Account",
925 {
926 "account_type": account_type or "",
927 "root_type": root_type or "",
928 "is_group": is_group or 0,
929 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
930 "company": company or frappe.defaults.get_defaults().company,
931 },
932 "name",
933 )
934
Saurabha9ba7342016-06-21 12:33:12 +0530935
936@frappe.whitelist()
937def get_companies():
938 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530939 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
940
Saurabha9ba7342016-06-21 12:33:12 +0530941
942@frappe.whitelist()
Rushabh Mehta43133262017-11-10 18:52:21 +0530943def get_children(doctype, parent, company, is_root=False):
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530944 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +0530945
Ankush Menat494bd9e2022-03-28 18:52:46 +0530946 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
947 fields = ["name as value", "is_group as expandable"]
948 filters = [["docstatus", "<", 2]]
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +0530949
Ankush Menat494bd9e2022-03-28 18:52:46 +0530950 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530951
Rushabh Mehta43133262017-11-10 18:52:21 +0530952 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530953 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
954 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530955
Saurabha9ba7342016-06-21 12:33:12 +0530956 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530957 fields += ["root_type", "account_currency"] if doctype == "Account" else []
958 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +0530959
960 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +0530961
Ankush Menat494bd9e2022-03-28 18:52:46 +0530962 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530963 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +0530964
965 return acc
Saurabhb835fef2016-09-09 11:19:22 +0530966
Ankush Menat494bd9e2022-03-28 18:52:46 +0530967
Saqib90517352021-10-04 11:44:46 +0530968@frappe.whitelist()
969def get_account_balances(accounts, company):
970
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530971 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +0530972 accounts = loads(accounts)
973
974 if not accounts:
975 return []
976
Ankush Menat494bd9e2022-03-28 18:52:46 +0530977 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +0530978
979 for account in accounts:
980 account["company_currency"] = company_currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530981 account["balance"] = flt(
982 get_balance_on(account["value"], in_account_currency=False, company=company)
983 )
Saqib90517352021-10-04 11:44:46 +0530984 if account["account_currency"] and account["account_currency"] != company_currency:
985 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
986
987 return accounts
988
Ankush Menat494bd9e2022-03-28 18:52:46 +0530989
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +0530990def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +0530991 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +0530992
Daizy Modifdfe5cb2022-11-17 19:14:10 +0530993 company = frappe.get_cached_value("Global Defaults", "Global Defaults", "default_company")
Saurabhb835fef2016-09-09 11:19:22 +0530994 if not company:
995 return
996
997 # 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 +0530998 bank_account = frappe.db.get_value(
999 "Account",
1000 {"account_name": _(gateway), "company": company},
1001 ["name", "account_currency"],
1002 as_dict=1,
1003 )
Saurabhb835fef2016-09-09 11:19:22 +05301004
1005 if not bank_account:
1006 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301007 bank_account = frappe.db.get_value(
1008 "Account",
1009 {"account_name": gateway, "company": company},
1010 ["name", "account_currency"],
1011 as_dict=1,
1012 )
Saurabhb835fef2016-09-09 11:19:22 +05301013
1014 if not bank_account:
1015 # try creating one
1016 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1017
1018 if not bank_account:
1019 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1020 return
1021
1022 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301023 if frappe.db.exists(
1024 "Payment Gateway Account",
1025 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1026 ):
Saurabhb835fef2016-09-09 11:19:22 +05301027 return
1028
1029 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301030 frappe.get_doc(
1031 {
1032 "doctype": "Payment Gateway Account",
1033 "is_default": 1,
1034 "payment_gateway": gateway,
1035 "payment_account": bank_account.name,
1036 "currency": bank_account.account_currency,
1037 "payment_channel": payment_channel,
1038 }
1039 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301040
1041 except frappe.DuplicateEntryError:
1042 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001043 pass
Zarrar44175902018-06-08 16:35:21 +05301044
Ankush Menat494bd9e2022-03-28 18:52:46 +05301045
Zarrar44175902018-06-08 16:35:21 +05301046@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301047def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301048 """
1049 Renames the document by adding the number as a prefix to the current name and updates
1050 all transaction where it was present.
1051 """
Saqiba8779872020-04-30 11:28:43 +05301052 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301053
Saqiba8779872020-04-30 11:28:43 +05301054 if cost_center_number:
1055 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1056 else:
1057 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301058
Saqiba8779872020-04-30 11:28:43 +05301059 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301060
Nabin Haitaf21a112022-09-15 12:09:18 +05301061 new_name = get_autoname_with_number(cost_center_number, cost_center_name, company)
Saqiba8779872020-04-30 11:28:43 +05301062 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301063 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301064 return new_name
1065
Ankush Menat494bd9e2022-03-28 18:52:46 +05301066
Saqiba8779872020-04-30 11:28:43 +05301067def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301068 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301069 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301070 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301071 if company:
Saqiba8779872020-04-30 11:28:43 +05301072 filters["company"] = company
1073
1074 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1075
Zarrar44175902018-06-08 16:35:21 +05301076 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301077 frappe.throw(
1078 _("{0} Number {1} is already used in {2} {3}").format(
1079 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1080 )
1081 )
1082
Zarrar44175902018-06-08 16:35:21 +05301083
Nabin Haitaf21a112022-09-15 12:09:18 +05301084def get_autoname_with_number(number_value, doc_title, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301085 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Nabin Haitaf21a112022-09-15 12:09:18 +05301086 company_abbr = frappe.get_cached_value("Company", company, "abbr")
1087 parts = [doc_title.strip(), company_abbr]
1088
Zlash651aeca1d2018-07-06 17:15:33 +05301089 if cstr(number_value).strip():
1090 parts.insert(0, cstr(number_value).strip())
Nabin Haitaf21a112022-09-15 12:09:18 +05301091
Ankush Menat494bd9e2022-03-28 18:52:46 +05301092 return " - ".join(parts)
1093
Zarrar254ce642018-06-28 14:15:34 +05301094
1095@frappe.whitelist()
1096def get_coa(doctype, parent, is_root, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301097 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1098 build_tree_from_json,
1099 )
Zarrar254ce642018-06-28 14:15:34 +05301100
1101 # add chart to flags to retrieve when called from expand all function
1102 chart = chart if chart else frappe.flags.chart
1103 frappe.flags.chart = chart
1104
Ankush Menat494bd9e2022-03-28 18:52:46 +05301105 parent = None if parent == _("All Accounts") else parent
1106 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301107
1108 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301109 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301110
1111 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001112
Ankush Menat494bd9e2022-03-28 18:52:46 +05301113
1114def update_gl_entries_after(
1115 posting_date,
1116 posting_time,
1117 for_warehouses=None,
1118 for_items=None,
1119 warehouse_account=None,
1120 company=None,
1121):
1122 stock_vouchers = get_future_stock_vouchers(
1123 posting_date, posting_time, for_warehouses, for_items, company
1124 )
Nabin Hait9b178bc2021-02-16 14:57:00 +05301125 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1126
1127
Ankush Menat494bd9e2022-03-28 18:52:46 +05301128def repost_gle_for_stock_vouchers(
Ankush Menat2535d5e2022-06-14 18:20:33 +05301129 stock_vouchers: List[Tuple[str, str]],
1130 posting_date: str,
1131 company: Optional[str] = None,
1132 warehouse_account=None,
1133 repost_doc: Optional["RepostItemValuation"] = None,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301134):
Ankush Menat67c26322022-06-04 14:46:35 +05301135
1136 from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative
1137
Ankush Menat700e8642022-04-19 13:24:29 +05301138 if not stock_vouchers:
1139 return
1140
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301141 if not warehouse_account:
1142 warehouse_account = get_warehouse_account_map(company)
1143
Ankush Menat2535d5e2022-06-14 18:20:33 +05301144 stock_vouchers = sort_stock_vouchers_by_posting_date(stock_vouchers)
1145 if repost_doc and repost_doc.gl_reposting_index:
1146 # Restore progress
1147 stock_vouchers = stock_vouchers[cint(repost_doc.gl_reposting_index) :]
1148
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301149 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1150
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301151 for stock_vouchers_chunk in create_batch(stock_vouchers, GL_REPOSTING_CHUNK):
Ankush Menat2535d5e2022-06-14 18:20:33 +05301152 gle = get_voucherwise_gl_entries(stock_vouchers_chunk, posting_date)
1153
1154 for voucher_type, voucher_no in stock_vouchers_chunk:
1155 existing_gle = gle.get((voucher_type, voucher_no), [])
1156 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
1157 # Some transactions post credit as negative debit, this is handled while posting GLE
1158 # but while comparing we need to make sure it's flipped so comparisons are accurate
1159 expected_gle = toggle_debit_credit_if_negative(voucher_obj.get_gl_entries(warehouse_account))
1160 if expected_gle:
1161 if not existing_gle or not compare_existing_and_expected_gle(
1162 existing_gle, expected_gle, precision
1163 ):
ruthra kumar9209ec52022-10-21 15:18:40 +05301164 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301165 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
1166 else:
ruthra kumar9209ec52022-10-21 15:18:40 +05301167 _delete_accounting_ledger_entries(voucher_type, voucher_no)
Ankush Menat86919d22022-06-15 21:19:09 +05301168
1169 if not frappe.flags.in_test:
1170 frappe.db.commit()
Ankush Menat2535d5e2022-06-14 18:20:33 +05301171
1172 if repost_doc:
1173 repost_doc.db_set(
1174 "gl_reposting_index",
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301175 cint(repost_doc.gl_reposting_index) + len(stock_vouchers_chunk),
Ankush Menat2535d5e2022-06-14 18:20:33 +05301176 )
1177
1178
ruthra kumar9209ec52022-10-21 15:18:40 +05301179def _delete_pl_entries(voucher_type, voucher_no):
ruthra kumar65992302022-10-04 16:17:56 +05301180 ple = qb.DocType("Payment Ledger Entry")
1181 qb.from_(ple).delete().where(
1182 (ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)
1183 ).run()
Ankush Menateb53a972022-06-04 18:19:44 +05301184
Ankush Menat494bd9e2022-03-28 18:52:46 +05301185
ruthra kumar9209ec52022-10-21 15:18:40 +05301186def _delete_gl_entries(voucher_type, voucher_no):
1187 gle = qb.DocType("GL Entry")
1188 qb.from_(gle).delete().where(
1189 (gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)
1190 ).run()
1191
1192
1193def _delete_accounting_ledger_entries(voucher_type, voucher_no):
1194 """
1195 Remove entries from both General and Payment Ledger for specified Voucher
1196 """
1197 _delete_gl_entries(voucher_type, voucher_no)
1198 _delete_pl_entries(voucher_type, voucher_no)
1199
1200
Ankush Menat700e8642022-04-19 13:24:29 +05301201def sort_stock_vouchers_by_posting_date(
1202 stock_vouchers: List[Tuple[str, str]]
1203) -> List[Tuple[str, str]]:
1204 sle = frappe.qb.DocType("Stock Ledger Entry")
1205 voucher_nos = [v[1] for v in stock_vouchers]
1206
1207 sles = (
1208 frappe.qb.from_(sle)
1209 .select(sle.voucher_type, sle.voucher_no, sle.posting_date, sle.posting_time, sle.creation)
1210 .where((sle.is_cancelled == 0) & (sle.voucher_no.isin(voucher_nos)))
1211 .groupby(sle.voucher_type, sle.voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301212 .orderby(sle.posting_date)
1213 .orderby(sle.posting_time)
1214 .orderby(sle.creation)
Ankush Menat700e8642022-04-19 13:24:29 +05301215 ).run(as_dict=True)
1216 sorted_vouchers = [(sle.voucher_type, sle.voucher_no) for sle in sles]
1217
1218 unknown_vouchers = set(stock_vouchers) - set(sorted_vouchers)
1219 if unknown_vouchers:
1220 sorted_vouchers.extend(unknown_vouchers)
1221
1222 return sorted_vouchers
1223
1224
Ankush Menat494bd9e2022-03-28 18:52:46 +05301225def get_future_stock_vouchers(
1226 posting_date, posting_time, for_warehouses=None, for_items=None, company=None
1227):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301228
1229 values = []
1230 condition = ""
1231 if for_items:
1232 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1233 values += for_items
1234
1235 if for_warehouses:
1236 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1237 values += for_warehouses
1238
rohitwaghchaured60ff832021-02-16 09:12:27 +05301239 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301240 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301241 values.append(company)
1242
Ankush Menat494bd9e2022-03-28 18:52:46 +05301243 future_stock_vouchers = frappe.db.sql(
1244 """select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301245 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301246 where
1247 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1248 and is_cancelled = 0
1249 {condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301250 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
1251 condition=condition
1252 ),
1253 tuple([posting_date, posting_time] + values),
1254 as_dict=True,
1255 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301256
Ankush91527152021-08-11 11:17:50 +05301257 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301258
Ankush Menat494bd9e2022-03-28 18:52:46 +05301259
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301260def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301261 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301262
1263 Only fetches GLE fields required for comparing with new GLE.
1264 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301265
1266 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301267 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301268 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301269 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301270 if not future_stock_vouchers:
1271 return gl_entries
1272
1273 voucher_nos = [d[1] for d in future_stock_vouchers]
1274
Ankush Menat494bd9e2022-03-28 18:52:46 +05301275 gles = frappe.db.sql(
1276 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301277 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301278 from `tabGL Entry`
1279 where
Ankush Menat494bd9e2022-03-28 18:52:46 +05301280 posting_date >= %s and voucher_no in (%s)"""
1281 % ("%s", ", ".join(["%s"] * len(voucher_nos))),
1282 tuple([posting_date] + voucher_nos),
1283 as_dict=1,
1284 )
Ankush91527152021-08-11 11:17:50 +05301285
1286 for d in gles:
1287 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301288
Prssanna Desai82ddef52020-06-18 18:18:41 +05301289 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301290
Ankush Menat494bd9e2022-03-28 18:52:46 +05301291
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301292def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301293 if len(existing_gle) != len(expected_gle):
1294 return False
1295
Nabin Haita77b8c92020-12-21 14:45:50 +05301296 matched = True
1297 for entry in expected_gle:
1298 account_existed = False
1299 for e in existing_gle:
1300 if entry.account == e.account:
1301 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301302 if (
1303 entry.account == e.account
1304 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1305 and (
1306 flt(entry.debit, precision) != flt(e.debit, precision)
1307 or flt(entry.credit, precision) != flt(e.credit, precision)
1308 )
1309 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301310 matched = False
1311 break
1312 if not account_existed:
1313 matched = False
1314 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301315 return matched
1316
Ankush Menat494bd9e2022-03-28 18:52:46 +05301317
Nabin Haitb99c77b2020-12-25 18:12:35 +05301318def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301319 stock_accounts = [
1320 d.name
1321 for d in frappe.db.get_all(
1322 "Account", {"account_type": "Stock", "company": company, "is_group": 0}
1323 )
1324 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301325 if voucher_type and voucher_no:
1326 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301327 stock_accounts = [
1328 d.account
1329 for d in frappe.db.get_all(
1330 "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
1331 )
1332 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301333
1334 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301335 stock_accounts = [
1336 d.account
1337 for d in frappe.db.get_all(
1338 "GL Entry",
1339 {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
1340 "account",
1341 )
1342 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301343
1344 return stock_accounts
1345
Ankush Menat494bd9e2022-03-28 18:52:46 +05301346
Nabin Haitb99c77b2020-12-25 18:12:35 +05301347def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301348 if not posting_date:
1349 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301350
1351 warehouse_account = get_warehouse_account_map(company)
1352
Ankush Menat494bd9e2022-03-28 18:52:46 +05301353 account_balance = get_balance_on(
1354 account, posting_date, in_account_currency=False, ignore_account_permission=True
1355 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301356
Ankush Menat494bd9e2022-03-28 18:52:46 +05301357 related_warehouses = [
1358 wh
1359 for wh, wh_details in warehouse_account.items()
1360 if wh_details.account == account and not wh_details.is_group
1361 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301362
1363 total_stock_value = 0.0
1364 for warehouse in related_warehouses:
1365 value = get_stock_value_on(warehouse, posting_date)
1366 total_stock_value += value
1367
1368 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1369 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1370
Ankush Menat494bd9e2022-03-28 18:52:46 +05301371
Nabin Haitb99c77b2020-12-25 18:12:35 +05301372def get_journal_entry(account, stock_adjustment_account, amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301373 db_or_cr_warehouse_account = (
1374 "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
1375 )
1376 db_or_cr_stock_adjustment_account = (
1377 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1378 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301379
1380 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301381 "accounts": [
1382 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1383 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1384 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301385 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301386
Ankush Menat494bd9e2022-03-28 18:52:46 +05301387
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301388def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301389 """Check if reports are referenced in Desktop Icon"""
1390 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301391 if icons:
1392 for icon in icons:
1393 frappe.delete_doc("Desktop Icon", icon)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301394
1395
ruthra kumar9b502212022-10-13 14:13:48 +05301396def get_payment_ledger_entries(gl_entries, cancel=0):
1397 ple_map = []
ruthra kumar451cf3a2022-05-16 14:29:58 +05301398 if gl_entries:
1399 ple = None
1400
1401 # companies
1402 account = qb.DocType("Account")
1403 companies = list(set([x.company for x in gl_entries]))
1404
1405 # receivable/payable account
1406 accounts_with_types = (
1407 qb.from_(account)
1408 .select(account.name, account.account_type)
1409 .where(
1410 (account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
1411 )
1412 .run(as_dict=True)
1413 )
1414 receivable_or_payable_accounts = [y.name for y in accounts_with_types]
1415
1416 def get_account_type(account):
1417 for entry in accounts_with_types:
1418 if entry.name == account:
1419 return entry.account_type
1420
1421 dr_or_cr = 0
1422 account_type = None
1423 for gle in gl_entries:
1424 if gle.account in receivable_or_payable_accounts:
1425 account_type = get_account_type(gle.account)
1426 if account_type == "Receivable":
1427 dr_or_cr = gle.debit - gle.credit
1428 dr_or_cr_account_currency = gle.debit_in_account_currency - gle.credit_in_account_currency
1429 elif account_type == "Payable":
1430 dr_or_cr = gle.credit - gle.debit
1431 dr_or_cr_account_currency = gle.credit_in_account_currency - gle.debit_in_account_currency
1432
1433 if cancel:
1434 dr_or_cr *= -1
1435 dr_or_cr_account_currency *= -1
1436
ruthra kumar9b502212022-10-13 14:13:48 +05301437 ple = frappe._dict(
1438 doctype="Payment Ledger Entry",
1439 posting_date=gle.posting_date,
1440 company=gle.company,
1441 account_type=account_type,
1442 account=gle.account,
1443 party_type=gle.party_type,
1444 party=gle.party,
1445 cost_center=gle.cost_center,
1446 finance_book=gle.finance_book,
1447 due_date=gle.due_date,
1448 voucher_type=gle.voucher_type,
1449 voucher_no=gle.voucher_no,
1450 against_voucher_type=gle.against_voucher_type
1451 if gle.against_voucher_type
1452 else gle.voucher_type,
1453 against_voucher_no=gle.against_voucher if gle.against_voucher else gle.voucher_no,
1454 account_currency=gle.account_currency,
1455 amount=dr_or_cr,
1456 amount_in_account_currency=dr_or_cr_account_currency,
1457 delinked=True if cancel else False,
1458 remarks=gle.remarks,
ruthra kumar451cf3a2022-05-16 14:29:58 +05301459 )
1460
1461 dimensions_and_defaults = get_dimensions()
1462 if dimensions_and_defaults:
1463 for dimension in dimensions_and_defaults[0]:
ruthra kumar9b502212022-10-13 14:13:48 +05301464 ple[dimension.fieldname] = gle.get(dimension.fieldname)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301465
ruthra kumar9b502212022-10-13 14:13:48 +05301466 ple_map.append(ple)
1467 return ple_map
1468
1469
1470def create_payment_ledger_entry(
1471 gl_entries, cancel=0, adv_adj=0, update_outstanding="Yes", from_repost=0
1472):
1473 if gl_entries:
1474 ple_map = get_payment_ledger_entries(gl_entries, cancel=cancel)
1475
1476 for entry in ple_map:
1477
1478 ple = frappe.get_doc(entry)
1479
1480 if cancel:
1481 delink_original_entry(ple)
1482
1483 ple.flags.ignore_permissions = 1
1484 ple.flags.adv_adj = adv_adj
1485 ple.flags.from_repost = from_repost
1486 ple.flags.update_outstanding = update_outstanding
1487 ple.submit()
ruthra kumar451cf3a2022-05-16 14:29:58 +05301488
1489
ruthra kumar7312f222022-05-29 21:33:08 +05301490def update_voucher_outstanding(voucher_type, voucher_no, account, party_type, party):
1491 ple = frappe.qb.DocType("Payment Ledger Entry")
1492 vouchers = [frappe._dict({"voucher_type": voucher_type, "voucher_no": voucher_no})]
1493 common_filter = []
1494 if account:
1495 common_filter.append(ple.account == account)
1496
1497 if party_type:
1498 common_filter.append(ple.party_type == party_type)
1499
1500 if party:
1501 common_filter.append(ple.party == party)
1502
1503 ple_query = QueryPaymentLedger()
1504
1505 # on cancellation outstanding can be an empty list
1506 voucher_outstanding = ple_query.get_voucher_outstandings(vouchers, common_filter=common_filter)
ruthra kumar43b80682022-10-18 09:33:37 +05301507 if (
1508 voucher_type in ["Sales Invoice", "Purchase Invoice", "Fees"]
1509 and party_type
1510 and party
1511 and voucher_outstanding
1512 ):
ruthra kumar7312f222022-05-29 21:33:08 +05301513 outstanding = voucher_outstanding[0]
1514 ref_doc = frappe.get_doc(voucher_type, voucher_no)
1515
1516 # Didn't use db_set for optimisation purpose
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301517 ref_doc.outstanding_amount = outstanding["outstanding_in_account_currency"] or 0.0
ruthra kumar7312f222022-05-29 21:33:08 +05301518 frappe.db.set_value(
ruthra kumarb9a7ff72023-02-12 14:06:40 +05301519 voucher_type,
1520 voucher_no,
1521 "outstanding_amount",
1522 outstanding["outstanding_in_account_currency"] or 0.0,
ruthra kumar7312f222022-05-29 21:33:08 +05301523 )
1524
1525 ref_doc.set_status(update=True)
1526
1527
ruthra kumar451cf3a2022-05-16 14:29:58 +05301528def delink_original_entry(pl_entry):
1529 if pl_entry:
1530 ple = qb.DocType("Payment Ledger Entry")
1531 query = (
1532 qb.update(ple)
1533 .set(ple.delinked, True)
1534 .set(ple.modified, now())
1535 .set(ple.modified_by, frappe.session.user)
1536 .where(
1537 (ple.company == pl_entry.company)
1538 & (ple.account_type == pl_entry.account_type)
1539 & (ple.account == pl_entry.account)
1540 & (ple.party_type == pl_entry.party_type)
1541 & (ple.party == pl_entry.party)
1542 & (ple.voucher_type == pl_entry.voucher_type)
1543 & (ple.voucher_no == pl_entry.voucher_no)
1544 & (ple.against_voucher_type == pl_entry.against_voucher_type)
1545 & (ple.against_voucher_no == pl_entry.against_voucher_no)
1546 )
1547 )
1548 query.run()
ruthra kumar7b383882022-05-25 15:51:16 +05301549
1550
1551class QueryPaymentLedger(object):
1552 """
1553 Helper Class for Querying Payment Ledger Entry
1554 """
1555
1556 def __init__(self):
1557 self.ple = qb.DocType("Payment Ledger Entry")
1558
1559 # query result
1560 self.voucher_outstandings = []
1561
1562 # query filters
1563 self.vouchers = []
1564 self.common_filter = []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301565 self.voucher_posting_date = []
ruthra kumar7b383882022-05-25 15:51:16 +05301566 self.min_outstanding = None
1567 self.max_outstanding = None
1568
1569 def reset(self):
1570 # clear filters
1571 self.vouchers.clear()
1572 self.common_filter.clear()
1573 self.min_outstanding = self.max_outstanding = None
1574
1575 # clear result
1576 self.voucher_outstandings.clear()
1577
1578 def query_for_outstanding(self):
1579 """
1580 Database query to fetch voucher amount and voucher outstanding using Common Table Expression
1581 """
1582
1583 ple = self.ple
1584
1585 filter_on_voucher_no = []
1586 filter_on_against_voucher_no = []
1587 if self.vouchers:
1588 voucher_types = set([x.voucher_type for x in self.vouchers])
1589 voucher_nos = set([x.voucher_no for x in self.vouchers])
1590
1591 filter_on_voucher_no.append(ple.voucher_type.isin(voucher_types))
1592 filter_on_voucher_no.append(ple.voucher_no.isin(voucher_nos))
1593
1594 filter_on_against_voucher_no.append(ple.against_voucher_type.isin(voucher_types))
1595 filter_on_against_voucher_no.append(ple.against_voucher_no.isin(voucher_nos))
1596
1597 # build outstanding amount filter
1598 filter_on_outstanding_amount = []
1599 if self.min_outstanding:
1600 if self.min_outstanding > 0:
1601 filter_on_outstanding_amount.append(
1602 Table("outstanding").amount_in_account_currency >= self.min_outstanding
1603 )
1604 else:
1605 filter_on_outstanding_amount.append(
1606 Table("outstanding").amount_in_account_currency <= self.min_outstanding
1607 )
1608 if self.max_outstanding:
1609 if self.max_outstanding > 0:
1610 filter_on_outstanding_amount.append(
1611 Table("outstanding").amount_in_account_currency <= self.max_outstanding
1612 )
1613 else:
1614 filter_on_outstanding_amount.append(
1615 Table("outstanding").amount_in_account_currency >= self.max_outstanding
1616 )
1617
1618 # build query for voucher amount
1619 query_voucher_amount = (
1620 qb.from_(ple)
1621 .select(
1622 ple.account,
1623 ple.voucher_type,
1624 ple.voucher_no,
1625 ple.party_type,
1626 ple.party,
1627 ple.posting_date,
1628 ple.due_date,
1629 ple.account_currency.as_("currency"),
1630 Sum(ple.amount).as_("amount"),
1631 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1632 )
1633 .where(ple.delinked == 0)
1634 .where(Criterion.all(filter_on_voucher_no))
1635 .where(Criterion.all(self.common_filter))
ruthra kumar6d9d7302022-12-14 16:05:15 +05301636 .where(Criterion.all(self.dimensions_filter))
ruthra kumar5f1562c2022-07-28 11:57:27 +05301637 .where(Criterion.all(self.voucher_posting_date))
ruthra kumar7b383882022-05-25 15:51:16 +05301638 .groupby(ple.voucher_type, ple.voucher_no, ple.party_type, ple.party)
1639 )
1640
1641 # build query for voucher outstanding
1642 query_voucher_outstanding = (
1643 qb.from_(ple)
1644 .select(
1645 ple.account,
1646 ple.against_voucher_type.as_("voucher_type"),
1647 ple.against_voucher_no.as_("voucher_no"),
1648 ple.party_type,
1649 ple.party,
1650 ple.posting_date,
1651 ple.due_date,
1652 ple.account_currency.as_("currency"),
1653 Sum(ple.amount).as_("amount"),
1654 Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"),
1655 )
1656 .where(ple.delinked == 0)
1657 .where(Criterion.all(filter_on_against_voucher_no))
1658 .where(Criterion.all(self.common_filter))
1659 .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party)
1660 )
1661
1662 # build CTE for combining voucher amount and outstanding
1663 self.cte_query_voucher_amount_and_outstanding = (
1664 qb.with_(query_voucher_amount, "vouchers")
1665 .with_(query_voucher_outstanding, "outstanding")
1666 .from_(AliasedQuery("vouchers"))
1667 .left_join(AliasedQuery("outstanding"))
1668 .on(
1669 (AliasedQuery("vouchers").account == AliasedQuery("outstanding").account)
1670 & (AliasedQuery("vouchers").voucher_type == AliasedQuery("outstanding").voucher_type)
1671 & (AliasedQuery("vouchers").voucher_no == AliasedQuery("outstanding").voucher_no)
1672 & (AliasedQuery("vouchers").party_type == AliasedQuery("outstanding").party_type)
1673 & (AliasedQuery("vouchers").party == AliasedQuery("outstanding").party)
1674 )
1675 .select(
1676 Table("vouchers").account,
1677 Table("vouchers").voucher_type,
1678 Table("vouchers").voucher_no,
1679 Table("vouchers").party_type,
1680 Table("vouchers").party,
1681 Table("vouchers").posting_date,
1682 Table("vouchers").amount.as_("invoice_amount"),
1683 Table("vouchers").amount_in_account_currency.as_("invoice_amount_in_account_currency"),
1684 Table("outstanding").amount.as_("outstanding"),
1685 Table("outstanding").amount_in_account_currency.as_("outstanding_in_account_currency"),
1686 (Table("vouchers").amount - Table("outstanding").amount).as_("paid_amount"),
1687 (
1688 Table("vouchers").amount_in_account_currency - Table("outstanding").amount_in_account_currency
1689 ).as_("paid_amount_in_account_currency"),
1690 Table("vouchers").due_date,
1691 Table("vouchers").currency,
1692 )
1693 .where(Criterion.all(filter_on_outstanding_amount))
1694 )
1695
1696 # build CTE filter
1697 # only fetch invoices
1698 if self.get_invoices:
1699 self.cte_query_voucher_amount_and_outstanding = (
1700 self.cte_query_voucher_amount_and_outstanding.having(
1701 qb.Field("outstanding_in_account_currency") > 0
1702 )
1703 )
1704 # only fetch payments
1705 elif self.get_payments:
1706 self.cte_query_voucher_amount_and_outstanding = (
1707 self.cte_query_voucher_amount_and_outstanding.having(
1708 qb.Field("outstanding_in_account_currency") < 0
1709 )
1710 )
1711
1712 # execute SQL
1713 self.voucher_outstandings = self.cte_query_voucher_amount_and_outstanding.run(as_dict=True)
1714
1715 def get_voucher_outstandings(
1716 self,
1717 vouchers=None,
1718 common_filter=None,
ruthra kumar5f1562c2022-07-28 11:57:27 +05301719 posting_date=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301720 min_outstanding=None,
1721 max_outstanding=None,
1722 get_payments=False,
1723 get_invoices=False,
ruthra kumar6d9d7302022-12-14 16:05:15 +05301724 accounting_dimensions=None,
ruthra kumar7b383882022-05-25 15:51:16 +05301725 ):
1726 """
1727 Fetch voucher amount and outstanding amount from Payment Ledger using Database CTE
1728
1729 vouchers - dict of vouchers to get
1730 common_filter - array of criterions
1731 min_outstanding - filter on minimum total outstanding amount
1732 max_outstanding - filter on maximum total outstanding amount
1733 get_invoices - only fetch vouchers(ledger entries with +ve outstanding)
1734 get_payments - only fetch payments(ledger entries with -ve outstanding)
1735 """
1736
1737 self.reset()
1738 self.vouchers = vouchers
1739 self.common_filter = common_filter or []
ruthra kumar6d9d7302022-12-14 16:05:15 +05301740 self.dimensions_filter = accounting_dimensions or []
ruthra kumar5f1562c2022-07-28 11:57:27 +05301741 self.voucher_posting_date = posting_date or []
ruthra kumar7b383882022-05-25 15:51:16 +05301742 self.min_outstanding = min_outstanding
1743 self.max_outstanding = max_outstanding
1744 self.get_payments = get_payments
1745 self.get_invoices = get_invoices
1746 self.query_for_outstanding()
1747
1748 return self.voucher_outstandings