blob: ccf4b402465ba3c64eb78bb24a2edb81dd22b697 [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
Gavin D'souza0727d1d2022-06-13 12:39:28 +053012from frappe.query_builder.utils import DocType
Ankush Menat5c6f22f2022-06-15 19:30:26 +053013from frappe.utils import (
14 cint,
15 create_batch,
16 cstr,
17 flt,
18 formatdate,
19 get_number_format_info,
20 getdate,
21 now,
22 nowdate,
23)
Gavin D'souza0727d1d2022-06-13 12:39:28 +053024from pypika import Order
25from pypika.terms import ExistsCriterion
Anand Doshicd0989e2015-09-28 13:31:17 +053026
Chillar Anand915b3432021-09-02 16:44:59 +053027import erpnext
28
29# imported to enable erpnext.accounts.utils.get_account_currency
30from erpnext.accounts.doctype.account.account import get_account_currency # noqa
ruthra kumar451cf3a2022-05-16 14:29:58 +053031from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_dimensions
Anurag Mishraa11e7382019-10-31 15:55:03 +053032from erpnext.stock import get_warehouse_account_map
Chillar Anand915b3432021-09-02 16:44:59 +053033from erpnext.stock.utils import get_stock_value_on
34
Ankush Menat2535d5e2022-06-14 18:20:33 +053035if TYPE_CHECKING:
36 from erpnext.stock.doctype.repost_item_valuation.repost_item_valuation import RepostItemValuation
37
Anurag Mishraa11e7382019-10-31 15:55:03 +053038
Ankush Menat494bd9e2022-03-28 18:52:46 +053039class FiscalYearError(frappe.ValidationError):
40 pass
41
42
43class PaymentEntryUnlinkError(frappe.ValidationError):
44 pass
45
Nabin Hait2b06aaa2013-08-22 18:25:43 +053046
Ankush Menat2535d5e2022-06-14 18:20:33 +053047GL_REPOSTING_CHUNK = 100
48
49
Neil Trini Lasrado78fa6952014-10-03 17:43:02 +053050@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +053051def get_fiscal_year(
52 date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False
53):
Anand Doshic75c1d72016-03-11 14:56:19 +053054 return get_fiscal_years(date, fiscal_year, label, verbose, company, as_dict=as_dict)[0]
Nabin Hait23941aa2013-01-29 11:32:38 +053055
Ankush Menat494bd9e2022-03-28 18:52:46 +053056
57def get_fiscal_years(
58 transaction_date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False
59):
Nabin Hait9784d272016-12-30 16:21:35 +053060 fiscal_years = frappe.cache().hget("fiscal_years", company) or []
Rushabh Mehtad50da782017-07-28 11:39:01 +053061
62 if not fiscal_years:
Nabin Hait9784d272016-12-30 16:21:35 +053063 # 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 +053064 FY = DocType("Fiscal Year")
Nabin Haitfff3ab72015-01-14 16:27:13 +053065
Gavin D'souza0727d1d2022-06-13 12:39:28 +053066 query = (
67 frappe.qb.from_(FY)
68 .select(FY.name, FY.year_start_date, FY.year_end_date)
69 .where(FY.disabled == 0)
Ankush Menat494bd9e2022-03-28 18:52:46 +053070 )
Rushabh Mehtad50da782017-07-28 11:39:01 +053071
Gavin D'souza0727d1d2022-06-13 12:39:28 +053072 if fiscal_year:
73 query = query.where(FY.name == fiscal_year)
74
75 if company:
76 FYC = DocType("Fiscal Year Company")
77 query = query.where(
78 ExistsCriterion(frappe.qb.from_(FYC).select(FYC.name).where(FYC.parent == FY.name)).negate()
79 | ExistsCriterion(
80 frappe.qb.from_(FYC)
81 .select(FYC.company)
82 .where(FYC.parent == FY.name)
83 .where(FYC.company == company)
84 )
85 )
86
87 query = query.orderby(FY.year_start_date, Order.desc)
88 fiscal_years = query.run(as_dict=True)
89
Nabin Hait9784d272016-12-30 16:21:35 +053090 frappe.cache().hset("fiscal_years", company, fiscal_years)
Nabin Haitfff3ab72015-01-14 16:27:13 +053091
Prssanna Desai82ddef52020-06-18 18:18:41 +053092 if not transaction_date and not fiscal_year:
93 return fiscal_years
94
Nabin Hait9784d272016-12-30 16:21:35 +053095 if transaction_date:
96 transaction_date = getdate(transaction_date)
Anand Doshicd71e1d2014-04-08 13:53:35 +053097
Nabin Hait9784d272016-12-30 16:21:35 +053098 for fy in fiscal_years:
99 matched = False
100 if fiscal_year and fy.name == fiscal_year:
101 matched = True
Anand Doshicd71e1d2014-04-08 13:53:35 +0530102
Ankush Menat494bd9e2022-03-28 18:52:46 +0530103 if (
104 transaction_date
105 and getdate(fy.year_start_date) <= transaction_date
106 and getdate(fy.year_end_date) >= transaction_date
107 ):
Nabin Hait9784d272016-12-30 16:21:35 +0530108 matched = True
Rushabh Mehtad50da782017-07-28 11:39:01 +0530109
Nabin Hait9784d272016-12-30 16:21:35 +0530110 if matched:
111 if as_dict:
112 return (fy,)
113 else:
114 return ((fy.name, fy.year_start_date, fy.year_end_date),)
115
Ankush Menat494bd9e2022-03-28 18:52:46 +0530116 error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(
117 label, formatdate(transaction_date)
118 )
Anuja P2e4faf92020-12-05 13:36:43 +0530119 if company:
Anuja P550cb9c2020-12-07 11:11:00 +0530120 error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company))
rohitwaghchaured60ff832021-02-16 09:12:27 +0530121
Ankush Menat494bd9e2022-03-28 18:52:46 +0530122 if verbose == 1:
123 frappe.msgprint(error_msg)
cclauss68487082017-07-27 07:08:35 +0200124 raise FiscalYearError(error_msg)
Nabin Hait9784d272016-12-30 16:21:35 +0530125
Ankush Menat494bd9e2022-03-28 18:52:46 +0530126
Prssanna Desai82ddef52020-06-18 18:18:41 +0530127@frappe.whitelist()
128def get_fiscal_year_filter_field(company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530129 field = {"fieldtype": "Select", "options": [], "operator": "Between", "query_value": True}
Prssanna Desai82ddef52020-06-18 18:18:41 +0530130 fiscal_years = get_fiscal_years(company=company)
131 for fiscal_year in fiscal_years:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530132 field["options"].append(
133 {
134 "label": fiscal_year.name,
135 "value": fiscal_year.name,
136 "query_value": [
137 fiscal_year.year_start_date.strftime("%Y-%m-%d"),
138 fiscal_year.year_end_date.strftime("%Y-%m-%d"),
139 ],
140 }
141 )
Prssanna Desai82ddef52020-06-18 18:18:41 +0530142 return field
143
Ankush Menat494bd9e2022-03-28 18:52:46 +0530144
Nabin Hait8bf58362017-03-27 12:30:01 +0530145def validate_fiscal_year(date, fiscal_year, company, label="Date", doc=None):
146 years = [f[0] for f in get_fiscal_years(date, label=_(label), company=company)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +0530147 if fiscal_year not in years:
Rushabh Mehtad60acb92015-02-19 14:51:58 +0530148 if doc:
149 doc.fiscal_year = years[0]
150 else:
151 throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
Nabin Hait23941aa2013-01-29 11:32:38 +0530152
Ankush Menat494bd9e2022-03-28 18:52:46 +0530153
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530154@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155def get_balance_on(
156 account=None,
157 date=None,
158 party_type=None,
159 party=None,
160 company=None,
161 in_account_currency=True,
162 cost_center=None,
163 ignore_account_permission=False,
164):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530165 if not account and frappe.form_dict.get("account"):
166 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530167 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530168 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530169 if not party_type and frappe.form_dict.get("party_type"):
170 party_type = frappe.form_dict.get("party_type")
171 if not party and frappe.form_dict.get("party"):
172 party = frappe.form_dict.get("party")
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400173 if not cost_center and frappe.form_dict.get("cost_center"):
174 cost_center = frappe.form_dict.get("cost_center")
175
Nabin Hait98372852020-07-30 20:52:20 +0530176 cond = ["is_cancelled=0"]
Nabin Hait23941aa2013-01-29 11:32:38 +0530177 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530178 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530179 else:
180 # get balance of all entries that exist
181 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530182
Deepesh Garg8c217032019-07-16 09:41:01 +0530183 if account:
184 acc = frappe.get_doc("Account", account)
185
Nabin Hait23941aa2013-01-29 11:32:38 +0530186 try:
Deepesh Garg96d40ec2020-07-03 22:59:00 +0530187 year_start_date = get_fiscal_year(date, company=company, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530188 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +0530189 if getdate(date) > getdate(nowdate()):
190 # if fiscal year not found and the date is greater than today
191 # get fiscal year for today's date and its corresponding year start date
192 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
193 else:
194 # this indicates that it is a date older than any existing fiscal year.
195 # hence, assuming balance as 0.0
196 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530197
deepeshgarg0072ddbebf2019-07-20 14:52:59 +0530198 if account:
deepeshgarg007e097d4f2019-07-20 14:49:32 +0530199 report_type = acc.report_type
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530200 else:
201 report_type = ""
202
Ankush Menat494bd9e2022-03-28 18:52:46 +0530203 if cost_center and report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400204 cc = frappe.get_doc("Cost Center", cost_center)
205 if cc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530206 cond.append(
207 """ exists (
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400208 select 1 from `tabCost Center` cc where cc.name = gle.cost_center
209 and cc.lft >= %s and cc.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530210 )"""
211 % (cc.lft, cc.rgt)
212 )
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400213
214 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530215 cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center, percent=False),))
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400216
Nabin Hait6f17cf92014-09-17 14:11:22 +0530217 if account:
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400218
Ankush Menat494bd9e2022-03-28 18:52:46 +0530219 if not (frappe.flags.ignore_account_permission or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530220 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530221
Ankush Menat494bd9e2022-03-28 18:52:46 +0530222 if report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400223 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530224 cond.append(
225 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
226 )
Nabin Hait6f17cf92014-09-17 14:11:22 +0530227 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530228 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530229 cond.append(
230 """exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530231 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530232 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 )"""
234 % (acc.lft, acc.rgt)
235 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530236
237 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530238 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530239 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530240 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530241 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530242 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
Anand Doshic75c1d72016-03-11 14:56:19 +0530243
Nabin Hait6f17cf92014-09-17 14:11:22 +0530244 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530245 cond.append(
246 """gle.party_type = %s and gle.party = %s """
247 % (frappe.db.escape(party_type), frappe.db.escape(party, percent=False))
248 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530249
Nabin Hait85648d92016-07-20 11:26:45 +0530250 if company:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530251 cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530252
Nabin Haitdc768232015-08-17 11:27:00 +0530253 if account or (party_type and party):
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530254 if in_account_currency:
Anand Doshi602e8252015-11-16 19:05:46 +0530255 select_field = "sum(debit_in_account_currency) - sum(credit_in_account_currency)"
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530256 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530257 select_field = "sum(debit) - sum(credit)"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530258 bal = frappe.db.sql(
259 """
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530260 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530261 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530262 WHERE {1}""".format(
263 select_field, " and ".join(cond)
264 )
265 )[0][0]
Anand Doshicd71e1d2014-04-08 13:53:35 +0530266
Nabin Haitdc768232015-08-17 11:27:00 +0530267 # if bal is None, return 0
268 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530269
Ankush Menat494bd9e2022-03-28 18:52:46 +0530270
RobertSchouten8d43b322016-09-20 13:41:39 +0800271def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530272 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800273 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530274 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800275 else:
276 # get balance of all entries that exist
277 date = nowdate()
278
279 try:
280 year_start_date = get_fiscal_year(date, verbose=0)[1]
281 except FiscalYearError:
282 if getdate(date) > getdate(nowdate()):
283 # if fiscal year not found and the date is greater than today
284 # get fiscal year for today's date and its corresponding year start date
285 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
286 else:
287 # this indicates that it is a date older than any existing fiscal year.
288 # hence, assuming balance as 0.0
289 return 0.0
290
291 if account:
292 acc = frappe.get_doc("Account", account)
293
294 if not frappe.flags.ignore_account_permission:
295 acc.check_permission("read")
296
297 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530298 if acc.report_type == "Profit and Loss":
299 cond.append(
300 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
301 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800302
303 # different filter for group and ledger - improved performance
304 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530305 cond.append(
306 """exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800307 select name from `tabAccount` ac where ac.name = gle.account
308 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530309 )"""
310 % (acc.lft, acc.rgt)
311 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800312 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530313 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
RobertSchouten8d43b322016-09-20 13:41:39 +0800314
Ankush Menat494bd9e2022-03-28 18:52:46 +0530315 entries = frappe.db.sql(
316 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800317 SELECT name, posting_date, account, party_type, party,debit,credit,
318 voucher_type, voucher_no, against_voucher_type, against_voucher
319 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530320 WHERE {0}""".format(
321 " and ".join(cond)
322 ),
323 as_dict=True,
324 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530325
RobertSchouten8d43b322016-09-20 13:41:39 +0800326 count = 0
327 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530328 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800329 count += 1
330 else:
331 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
332 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530333 select_fields = (
334 "ifnull(sum(credit-debit),0)"
335 if fieldname == "invoiced_amount"
336 else "ifnull(sum(debit-credit),0)"
337 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800338
Ankush Menat494bd9e2022-03-28 18:52:46 +0530339 if (
340 (not gle.against_voucher)
341 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
342 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
343 ):
344 payment_amount = frappe.db.sql(
345 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800346 SELECT {0}
347 FROM `tabGL Entry` gle
348 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530349 and party = %(party)s and name != %(name)s""".format(
350 select_fields
351 ),
352 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
353 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530354
RobertSchouten8d43b322016-09-20 13:41:39 +0800355 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
356 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530357 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800358 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530359
RobertSchouten8d43b322016-09-20 13:41:39 +0800360 return count
361
Ankush Menat494bd9e2022-03-28 18:52:46 +0530362
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530363@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530364def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530365 from frappe.desk.treeview import make_tree_args
366
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530367 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530368 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530369
Nabin Hait02d987e2017-02-17 15:50:26 +0530370 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530371 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530372
Anand Doshi3e41fd12014-04-22 18:54:54 +0530373 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530374
Nabin Hait665568d2016-05-13 15:56:00 +0530375 if args.get("ignore_permissions"):
376 ac.flags.ignore_permissions = True
377 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530378
Anand Doshi3e41fd12014-04-22 18:54:54 +0530379 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530380
381 if not ac.parent_account:
382 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530383
Anand Doshif78d1ae2014-03-28 13:55:00 +0530384 ac.old_parent = ""
385 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530386 if cint(ac.get("is_root")):
387 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530388 ac.flags.ignore_mandatory = True
389
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530390 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530391
Anand Doshif78d1ae2014-03-28 13:55:00 +0530392 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530393
Ankush Menat494bd9e2022-03-28 18:52:46 +0530394
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530395@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530396def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530397 from frappe.desk.treeview import make_tree_args
398
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530399 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530400 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530401
Nabin Hait02d987e2017-02-17 15:50:26 +0530402 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530403 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530404
Zarrar7ab70ca2018-06-08 14:33:15 +0530405 if args.parent_cost_center == args.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530406 args.parent_cost_center = "{0} - {1}".format(
407 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
408 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530409
Anand Doshi3e41fd12014-04-22 18:54:54 +0530410 cc = frappe.new_doc("Cost Center")
411 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530412
413 if not cc.parent_cost_center:
414 cc.parent_cost_center = args.get("parent")
415
Anand Doshif78d1ae2014-03-28 13:55:00 +0530416 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530417 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530418 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530419
Ankush Menat494bd9e2022-03-28 18:52:46 +0530420
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530421def reconcile_against_document(args):
422 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530423 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530424 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530425 # To optimize making GL Entry for PE or JV with multiple references
426 reconciled_entries = {}
427 for row in args:
428 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
429 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530430
Anuja Pawar3e404f12021-08-31 18:59:29 +0530431 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
432
433 for key, entries in reconciled_entries.items():
434 voucher_type = key[0]
435 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530436
Nabin Hait28a05282016-06-27 17:41:39 +0530437 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530438 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530439 frappe.flags.ignore_party_validation = True
Nabin Hait28a05282016-06-27 17:41:39 +0530440 doc.make_gl_entries(cancel=1, adv_adj=1)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530441
Anuja Pawar3e404f12021-08-31 18:59:29 +0530442 for entry in entries:
443 check_if_advance_entry_modified(entry)
444 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530445
Anuja Pawar3e404f12021-08-31 18:59:29 +0530446 # update ref in advance entry
447 if voucher_type == "Journal Entry":
448 update_reference_in_journal_entry(entry, doc, do_not_save=True)
449 else:
450 update_reference_in_payment_entry(entry, doc, do_not_save=True)
451
452 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530453 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530454 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530455 doc.make_gl_entries(cancel=0, adv_adj=1)
Subin Tomb8845b92021-07-30 16:30:18 +0530456 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530457
Ankush Menat494bd9e2022-03-28 18:52:46 +0530458 if entry.voucher_type in ("Payment Entry", "Journal Entry"):
Nabin Hait5cd04a62019-05-27 11:44:06 +0530459 doc.update_expense_claim()
460
Ankush Menat494bd9e2022-03-28 18:52:46 +0530461
Nabin Hait28a05282016-06-27 17:41:39 +0530462def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530463 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530464 check if there is already a voucher reference
465 check if amount is same
466 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530467 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530468 if not args.get("unreconciled_amount"):
469 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530470
Nabin Hait28a05282016-06-27 17:41:39 +0530471 ret = None
472 if args.voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530473 ret = frappe.db.sql(
474 """
Nabin Hait28a05282016-06-27 17:41:39 +0530475 select t2.{dr_or_cr} from `tabJournal Entry` t1, `tabJournal Entry Account` t2
476 where t1.name = t2.parent and t2.account = %(account)s
477 and t2.party_type = %(party_type)s and t2.party = %(party)s
478 and (t2.reference_type is null or t2.reference_type in ("", "Sales Order", "Purchase Order"))
479 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530480 and t1.docstatus=1 """.format(
481 dr_or_cr=args.get("dr_or_cr")
482 ),
483 args,
484 )
Nabin Hait28a05282016-06-27 17:41:39 +0530485 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530486 party_account_field = (
487 "paid_from" if erpnext.get_party_account_type(args.party_type) == "Receivable" else "paid_to"
488 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530489
Nabin Hait28a05282016-06-27 17:41:39 +0530490 if args.voucher_detail_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530491 ret = frappe.db.sql(
492 """select t1.name
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530493 from `tabPayment Entry` t1, `tabPayment Entry Reference` t2
Nabin Hait28a05282016-06-27 17:41:39 +0530494 where
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530495 t1.name = t2.parent and t1.docstatus = 1
Nabin Hait28a05282016-06-27 17:41:39 +0530496 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
497 and t1.party_type = %(party_type)s and t1.party = %(party)s and t1.{0} = %(account)s
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530498 and t2.reference_doctype in ("", "Sales Order", "Purchase Order")
Anuja Pawar3e404f12021-08-31 18:59:29 +0530499 and t2.allocated_amount = %(unreconciled_amount)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530500 """.format(
501 party_account_field
502 ),
503 args,
504 )
Nabin Hait28a05282016-06-27 17:41:39 +0530505 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530506 ret = frappe.db.sql(
507 """select name from `tabPayment Entry`
Nabin Hait28a05282016-06-27 17:41:39 +0530508 where
509 name = %(voucher_no)s and docstatus = 1
510 and party_type = %(party_type)s and party = %(party)s and {0} = %(account)s
Anuja Pawar3e404f12021-08-31 18:59:29 +0530511 and unallocated_amount = %(unreconciled_amount)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530512 """.format(
513 party_account_field
514 ),
515 args,
516 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530517
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530518 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530519 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530520
Ankush Menat494bd9e2022-03-28 18:52:46 +0530521
Nabin Hait576f0252014-04-30 19:30:50 +0530522def validate_allocated_amount(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530523 precision = args.get("precision") or frappe.db.get_single_value(
524 "System Settings", "currency_precision"
525 )
Nabin Hait28a05282016-06-27 17:41:39 +0530526 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530527 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530528 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530529 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530530
Ankush Menat494bd9e2022-03-28 18:52:46 +0530531
Anuja Pawar3e404f12021-08-31 18:59:29 +0530532def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530533 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530534 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530535 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530536 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530537
Ankush Menat494bd9e2022-03-28 18:52:46 +0530538 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530539 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530541 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530542 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
543 jv_detail.set(
544 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
545 amount_in_company_currency,
546 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530547 else:
548 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530549
Anuja Pawar3e404f12021-08-31 18:59:29 +0530550 # new row with references
551 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530552
553 new_row.update((frappe.copy_doc(jv_detail)).as_dict())
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530554
Anuja Pawar3e404f12021-08-31 18:59:29 +0530555 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530556 new_row.set(
557 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
558 d["allocated_amount"] * flt(jv_detail.exchange_rate),
559 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530560
Ankush Menat494bd9e2022-03-28 18:52:46 +0530561 new_row.set(
562 "credit_in_account_currency"
563 if d["dr_or_cr"] == "debit_in_account_currency"
564 else "debit_in_account_currency",
565 0,
566 )
567 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530568
Anuja Pawar3e404f12021-08-31 18:59:29 +0530569 new_row.set("reference_type", d["against_voucher_type"])
570 new_row.set("reference_name", d["against_voucher"])
571
572 new_row.against_account = cstr(jv_detail.against_account)
573 new_row.is_advance = cstr(jv_detail.is_advance)
574 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530575
576 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530577 journal_entry.flags.ignore_validate_update_after_submit = True
578 if not do_not_save:
579 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530580
Ankush Menat494bd9e2022-03-28 18:52:46 +0530581
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530582def update_reference_in_payment_entry(d, payment_entry, do_not_save=False):
Nabin Hait28a05282016-06-27 17:41:39 +0530583 reference_details = {
584 "reference_doctype": d.against_voucher_type,
585 "reference_name": d.against_voucher,
586 "total_amount": d.grand_total,
587 "outstanding_amount": d.outstanding_amount,
588 "allocated_amount": d.allocated_amount,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530589 "exchange_rate": d.exchange_rate
590 if not d.exchange_gain_loss
591 else payment_entry.get_exchange_rate(),
592 "exchange_gain_loss": d.exchange_gain_loss, # only populated from invoice in case of advance allocation
Nabin Hait28a05282016-06-27 17:41:39 +0530593 }
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530594
Nabin Hait28a05282016-06-27 17:41:39 +0530595 if d.voucher_detail_no:
596 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
597 original_row = existing_row.as_dict().copy()
598 existing_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530599
Nabin Hait28a05282016-06-27 17:41:39 +0530600 if d.allocated_amount < original_row.allocated_amount:
601 new_row = payment_entry.append("references")
602 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500603 for field in list(reference_details):
Nabin Hait28a05282016-06-27 17:41:39 +0530604 new_row.set(field, original_row[field])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530605
Nabin Hait28a05282016-06-27 17:41:39 +0530606 new_row.allocated_amount = original_row.allocated_amount - d.allocated_amount
607 else:
608 new_row = payment_entry.append("references")
609 new_row.docstatus = 1
610 new_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530611
Nabin Hait28a05282016-06-27 17:41:39 +0530612 payment_entry.flags.ignore_validate_update_after_submit = True
Nabin Hait05aefbb2016-06-28 19:42:19 +0530613 payment_entry.setup_party_account_field()
Nabin Hait1991c7b2016-06-27 20:09:05 +0530614 payment_entry.set_missing_values()
Nabin Hait28a05282016-06-27 17:41:39 +0530615 payment_entry.set_amounts()
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530616
617 if d.difference_amount and d.difference_account:
Saqiba20999c2021-07-12 14:33:23 +0530618 account_details = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530619 "account": d.difference_account,
620 "cost_center": payment_entry.cost_center
621 or frappe.get_cached_value("Company", payment_entry.company, "cost_center"),
Saqiba20999c2021-07-12 14:33:23 +0530622 }
623 if d.difference_amount:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530624 account_details["amount"] = d.difference_amount
Saqiba20999c2021-07-12 14:33:23 +0530625
626 payment_entry.set_gain_or_loss(account_details=account_details)
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530627
628 if not do_not_save:
629 payment_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530630
Ankush Menat494bd9e2022-03-28 18:52:46 +0530631
Nabin Hait297d74a2016-11-23 15:58:51 +0530632def unlink_ref_doc_from_payment_entries(ref_doc):
633 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name)
634 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530635
Ankush Menat494bd9e2022-03-28 18:52:46 +0530636 frappe.db.sql(
637 """update `tabGL Entry`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530638 set against_voucher_type=null, against_voucher=null,
639 modified=%s, modified_by=%s
640 where against_voucher_type=%s and against_voucher=%s
641 and voucher_no != ifnull(against_voucher, '')""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530642 (now(), frappe.session.user, ref_doc.doctype, ref_doc.name),
643 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530644
Nabin Hait297d74a2016-11-23 15:58:51 +0530645 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
646 ref_doc.set("advances", [])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530647
Ankush Menat494bd9e2022-03-28 18:52:46 +0530648 frappe.db.sql(
649 """delete from `tab{0} Advance` where parent = %s""".format(ref_doc.doctype), ref_doc.name
650 )
651
Anand Doshicd71e1d2014-04-08 13:53:35 +0530652
Nabin Haite0cc87d2016-07-21 18:30:03 +0530653def remove_ref_doc_link_from_jv(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530654 linked_jv = frappe.db.sql_list(
655 """select parent from `tabJournal Entry Account`
656 where reference_type=%s and reference_name=%s and docstatus < 2""",
657 (ref_type, ref_no),
658 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530659
660 if linked_jv:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530661 frappe.db.sql(
662 """update `tabJournal Entry Account`
Rushabh Mehta1828c122015-08-10 17:04:07 +0530663 set reference_type=null, reference_name = null,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530664 modified=%s, modified_by=%s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530665 where reference_type=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530666 and docstatus < 2""",
667 (now(), frappe.session.user, ref_type, ref_no),
668 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530669
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530670 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530671
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672
Nabin Haite0cc87d2016-07-21 18:30:03 +0530673def remove_ref_doc_link_from_pe(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530674 linked_pe = frappe.db.sql_list(
675 """select parent from `tabPayment Entry Reference`
676 where reference_doctype=%s and reference_name=%s and docstatus < 2""",
677 (ref_type, ref_no),
678 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530679
Nabin Haite0cc87d2016-07-21 18:30:03 +0530680 if linked_pe:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530681 frappe.db.sql(
682 """update `tabPayment Entry Reference`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530683 set allocated_amount=0, modified=%s, modified_by=%s
684 where reference_doctype=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530685 and docstatus < 2""",
686 (now(), frappe.session.user, ref_type, ref_no),
687 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530688
Nabin Haite0cc87d2016-07-21 18:30:03 +0530689 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530690 try:
691 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530692 pe_doc.set_amounts()
Deepesh Gargb5162392021-08-10 14:52:24 +0530693 pe_doc.clear_unallocated_reference_document_rows()
694 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530695 except Exception as e:
696 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530697 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530698 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530699 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530700
Ankush Menat494bd9e2022-03-28 18:52:46 +0530701 frappe.db.sql(
702 """update `tabPayment Entry` set total_allocated_amount=%s,
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530703 base_total_allocated_amount=%s, unallocated_amount=%s, modified=%s, modified_by=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530704 where name=%s""",
705 (
706 pe_doc.total_allocated_amount,
707 pe_doc.base_total_allocated_amount,
708 pe_doc.unallocated_amount,
709 now(),
710 frappe.session.user,
711 pe,
712 ),
713 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530714
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530715 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530716
Ankush Menat494bd9e2022-03-28 18:52:46 +0530717
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530718@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530719def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530721
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530722 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530723 throw(
724 _("Please set default {0} in Company {1}").format(
725 frappe.get_meta("Company").get_label(fieldname), company
726 )
727 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530728
Nabin Hait0fc24542013-03-25 11:06:00 +0530729 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530730
Ankush Menat494bd9e2022-03-28 18:52:46 +0530731
Nabin Hait8b509f52013-05-28 16:52:30 +0530732def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530733 vouchers = frappe.db.sql(
734 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530735 sum(debit) - sum(credit) as diff
736 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530737 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530738 having sum(debit) != sum(credit)""",
739 as_dict=1,
740 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530741
Nabin Hait8b509f52013-05-28 16:52:30 +0530742 for d in vouchers:
743 if abs(d.diff) > 0:
744 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530745
Ankush Menat494bd9e2022-03-28 18:52:46 +0530746 frappe.db.sql(
747 """update `tabGL Entry` set %s = %s + %s
748 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
749 % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
750 (d.diff, d.voucher_type, d.voucher_no),
751 )
752
Anand Doshicd71e1d2014-04-08 13:53:35 +0530753
Rushabh Mehtad50da782017-07-28 11:39:01 +0530754def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530755 precision = cint(frappe.db.get_default("currency_precision"))
756 if not precision:
757 number_format = frappe.db.get_default("number_format") or "#,###.##"
758 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530759
Nabin Hait9b20e072017-04-25 12:10:24 +0530760 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530761
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530762
Ankush Menat494bd9e2022-03-28 18:52:46 +0530763def get_stock_rbnb_difference(posting_date, company):
764 stock_items = frappe.db.sql_list(
765 """select distinct item_code
766 from `tabStock Ledger Entry` where company=%s""",
767 company,
768 )
769
770 pr_valuation_amount = frappe.db.sql(
771 """
Anand Doshi602e8252015-11-16 19:05:46 +0530772 select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530773 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
Suraj Shetty084b0b32018-05-26 09:12:59 +0530774 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530775 and pr.posting_date <= %s and pr_item.item_code in (%s)"""
776 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
777 tuple([company, posting_date] + stock_items),
778 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530779
Ankush Menat494bd9e2022-03-28 18:52:46 +0530780 pi_valuation_amount = frappe.db.sql(
781 """
Anand Doshi602e8252015-11-16 19:05:46 +0530782 select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530783 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
Suraj Shetty084b0b32018-05-26 09:12:59 +0530784 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530785 and pi.posting_date <= %s and pi_item.item_code in (%s)"""
786 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
787 tuple([company, posting_date] + stock_items),
788 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530789
790 # Balance should be
791 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
792
793 # Balance as per system
Ankush Menat494bd9e2022-03-28 18:52:46 +0530794 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.get_cached_value(
795 "Company", company, "abbr"
796 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530797 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530798
799 # Amount should be credited
800 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530801
tundec4b0d172017-09-26 00:48:30 +0100802
tundebabzyad08d4c2018-05-16 07:01:41 +0100803def get_held_invoices(party_type, party):
804 """
805 Returns a list of names Purchase Invoices for the given party that are on hold
806 """
807 held_invoices = None
808
Ankush Menat494bd9e2022-03-28 18:52:46 +0530809 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +0100810 held_invoices = frappe.db.sql(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530811 "select name from `tabPurchase Invoice` where release_date IS NOT NULL and release_date > CURDATE()",
812 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +0100813 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530814 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +0100815
816 return held_invoices
817
818
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530819def get_outstanding_invoices(party_type, party, account, condition=None, filters=None):
Anand Doshid40d1e92015-11-12 17:05:29 +0530820 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +0530821 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +0530822
Nabin Hait9db9edc2019-11-19 18:44:32 +0530823 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530824 root_type, account_type = frappe.get_cached_value(
825 "Account", account, ["root_type", "account_type"]
826 )
Nabin Hait9db9edc2019-11-19 18:44:32 +0530827 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +0530828 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +0530829 else:
830 party_account_type = erpnext.get_party_account_type(party_type)
831
Ankush Menat494bd9e2022-03-28 18:52:46 +0530832 if party_account_type == "Receivable":
Anand Doshi602e8252015-11-16 19:05:46 +0530833 dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
Nabin Haitac184982019-02-04 21:13:43 +0530834 payment_dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
Anand Doshid40d1e92015-11-12 17:05:29 +0530835 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530836 dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
Nabin Haitac184982019-02-04 21:13:43 +0530837 payment_dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
Anand Doshid40d1e92015-11-12 17:05:29 +0530838
tundebabzyad08d4c2018-05-16 07:01:41 +0100839 held_invoices = get_held_invoices(party_type, party)
840
Ankush Menat494bd9e2022-03-28 18:52:46 +0530841 invoice_list = frappe.db.sql(
842 """
Nabin Haite4bbb692016-07-04 16:16:24 +0530843 select
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530844 voucher_no, voucher_type, posting_date, due_date,
Deepesh Gargc7eadfc2020-07-22 17:59:37 +0530845 ifnull(sum({dr_or_cr}), 0) as invoice_amount,
846 account_currency as currency
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530847 from
Nabin Haitac184982019-02-04 21:13:43 +0530848 `tabGL Entry`
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530849 where
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530850 party_type = %(party_type)s and party = %(party)s
Nabin Haite4bbb692016-07-04 16:16:24 +0530851 and account = %(account)s and {dr_or_cr} > 0
aakvatech38ccf822020-10-03 19:41:38 +0300852 and is_cancelled=0
Anand Doshid40d1e92015-11-12 17:05:29 +0530853 {condition}
854 and ((voucher_type = 'Journal Entry'
Nabin Hait56548cb2016-07-01 15:58:39 +0530855 and (against_voucher = '' or against_voucher is null))
856 or (voucher_type not in ('Journal Entry', 'Payment Entry')))
Nabin Haita5cc84f2017-12-21 11:37:18 +0530857 group by voucher_type, voucher_no
Nabin Hait34c551d2019-07-03 10:34:31 +0530858 order by posting_date, name""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530859 dr_or_cr=dr_or_cr, condition=condition or ""
860 ),
861 {
Anand Doshid40d1e92015-11-12 17:05:29 +0530862 "party_type": party_type,
863 "party": party,
864 "account": account,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530865 },
866 as_dict=True,
867 )
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530868
Ankush Menat494bd9e2022-03-28 18:52:46 +0530869 payment_entries = frappe.db.sql(
870 """
Nabin Haitac184982019-02-04 21:13:43 +0530871 select against_voucher_type, against_voucher,
872 ifnull(sum({payment_dr_or_cr}), 0) as payment_amount
873 from `tabGL Entry`
874 where party_type = %(party_type)s and party = %(party)s
875 and account = %(account)s
876 and {payment_dr_or_cr} > 0
877 and against_voucher is not null and against_voucher != ''
aakvatech38ccf822020-10-03 19:41:38 +0300878 and is_cancelled=0
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530879 group by against_voucher_type, against_voucher
Ankush Menat494bd9e2022-03-28 18:52:46 +0530880 """.format(
881 payment_dr_or_cr=payment_dr_or_cr
882 ),
883 {"party_type": party_type, "party": party, "account": account},
884 as_dict=True,
885 )
tundec4b0d172017-09-26 00:48:30 +0100886
Nabin Haitac184982019-02-04 21:13:43 +0530887 pe_map = frappe._dict()
888 for d in payment_entries:
889 pe_map.setdefault((d.against_voucher_type, d.against_voucher), d.payment_amount)
890
891 for d in invoice_list:
892 payment_amount = pe_map.get((d.voucher_type, d.voucher_no), 0)
893 outstanding_amount = flt(d.invoice_amount - payment_amount, precision)
894 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530895 if (
896 filters
897 and filters.get("outstanding_amt_greater_than")
898 and not (
899 outstanding_amount >= filters.get("outstanding_amt_greater_than")
900 and outstanding_amount <= filters.get("outstanding_amt_less_than")
901 )
902 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530903 continue
Nabin Haitac184982019-02-04 21:13:43 +0530904
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530905 if not d.voucher_type == "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +0530906 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530907 frappe._dict(
908 {
909 "voucher_no": d.voucher_no,
910 "voucher_type": d.voucher_type,
911 "posting_date": d.posting_date,
912 "invoice_amount": flt(d.invoice_amount),
913 "payment_amount": payment_amount,
914 "outstanding_amount": outstanding_amount,
915 "due_date": d.due_date,
916 "currency": d.currency,
917 }
918 )
Nabin Haitac184982019-02-04 21:13:43 +0530919 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530920
Ankush Menat494bd9e2022-03-28 18:52:46 +0530921 outstanding_invoices = sorted(
922 outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
923 )
Anand Doshid40d1e92015-11-12 17:05:29 +0530924 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +0530925
926
Ankush Menat494bd9e2022-03-28 18:52:46 +0530927def get_account_name(
928 account_type=None, root_type=None, is_group=None, account_currency=None, company=None
929):
Saurabh3a268292016-02-22 15:18:40 +0530930 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530931 return frappe.db.get_value(
932 "Account",
933 {
934 "account_type": account_type or "",
935 "root_type": root_type or "",
936 "is_group": is_group or 0,
937 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
938 "company": company or frappe.defaults.get_defaults().company,
939 },
940 "name",
941 )
942
Saurabha9ba7342016-06-21 12:33:12 +0530943
944@frappe.whitelist()
945def get_companies():
946 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530947 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
948
Saurabha9ba7342016-06-21 12:33:12 +0530949
950@frappe.whitelist()
Rushabh Mehta43133262017-11-10 18:52:21 +0530951def get_children(doctype, parent, company, is_root=False):
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530952 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +0530953
Ankush Menat494bd9e2022-03-28 18:52:46 +0530954 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
955 fields = ["name as value", "is_group as expandable"]
956 filters = [["docstatus", "<", 2]]
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +0530957
Ankush Menat494bd9e2022-03-28 18:52:46 +0530958 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530959
Rushabh Mehta43133262017-11-10 18:52:21 +0530960 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530961 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
962 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530963
Saurabha9ba7342016-06-21 12:33:12 +0530964 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530965 fields += ["root_type", "account_currency"] if doctype == "Account" else []
966 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +0530967
968 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +0530969
Ankush Menat494bd9e2022-03-28 18:52:46 +0530970 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530971 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +0530972
973 return acc
Saurabhb835fef2016-09-09 11:19:22 +0530974
Ankush Menat494bd9e2022-03-28 18:52:46 +0530975
Saqib90517352021-10-04 11:44:46 +0530976@frappe.whitelist()
977def get_account_balances(accounts, company):
978
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530979 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +0530980 accounts = loads(accounts)
981
982 if not accounts:
983 return []
984
Ankush Menat494bd9e2022-03-28 18:52:46 +0530985 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +0530986
987 for account in accounts:
988 account["company_currency"] = company_currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530989 account["balance"] = flt(
990 get_balance_on(account["value"], in_account_currency=False, company=company)
991 )
Saqib90517352021-10-04 11:44:46 +0530992 if account["account_currency"] and account["account_currency"] != company_currency:
993 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
994
995 return accounts
996
Ankush Menat494bd9e2022-03-28 18:52:46 +0530997
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +0530998def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +0530999 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +05301000
1001 company = frappe.db.get_value("Global Defaults", None, "default_company")
1002 if not company:
1003 return
1004
1005 # 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 +05301006 bank_account = frappe.db.get_value(
1007 "Account",
1008 {"account_name": _(gateway), "company": company},
1009 ["name", "account_currency"],
1010 as_dict=1,
1011 )
Saurabhb835fef2016-09-09 11:19:22 +05301012
1013 if not bank_account:
1014 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301015 bank_account = frappe.db.get_value(
1016 "Account",
1017 {"account_name": gateway, "company": company},
1018 ["name", "account_currency"],
1019 as_dict=1,
1020 )
Saurabhb835fef2016-09-09 11:19:22 +05301021
1022 if not bank_account:
1023 # try creating one
1024 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1025
1026 if not bank_account:
1027 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1028 return
1029
1030 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301031 if frappe.db.exists(
1032 "Payment Gateway Account",
1033 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1034 ):
Saurabhb835fef2016-09-09 11:19:22 +05301035 return
1036
1037 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301038 frappe.get_doc(
1039 {
1040 "doctype": "Payment Gateway Account",
1041 "is_default": 1,
1042 "payment_gateway": gateway,
1043 "payment_account": bank_account.name,
1044 "currency": bank_account.account_currency,
1045 "payment_channel": payment_channel,
1046 }
1047 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301048
1049 except frappe.DuplicateEntryError:
1050 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001051 pass
Zarrar44175902018-06-08 16:35:21 +05301052
Ankush Menat494bd9e2022-03-28 18:52:46 +05301053
Zarrar44175902018-06-08 16:35:21 +05301054@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301055def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301056 """
1057 Renames the document by adding the number as a prefix to the current name and updates
1058 all transaction where it was present.
1059 """
Saqiba8779872020-04-30 11:28:43 +05301060 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301061
Saqiba8779872020-04-30 11:28:43 +05301062 if cost_center_number:
1063 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1064 else:
1065 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301066
Saqiba8779872020-04-30 11:28:43 +05301067 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301068
Saqiba8779872020-04-30 11:28:43 +05301069 new_name = get_autoname_with_number(cost_center_number, cost_center_name, docname, company)
1070 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301071 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301072 return new_name
1073
Ankush Menat494bd9e2022-03-28 18:52:46 +05301074
Saqiba8779872020-04-30 11:28:43 +05301075def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301076 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301077 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301078 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301079 if company:
Saqiba8779872020-04-30 11:28:43 +05301080 filters["company"] = company
1081
1082 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1083
Zarrar44175902018-06-08 16:35:21 +05301084 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301085 frappe.throw(
1086 _("{0} Number {1} is already used in {2} {3}").format(
1087 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1088 )
1089 )
1090
Zarrar44175902018-06-08 16:35:21 +05301091
Zarrar17705f92018-07-06 14:44:44 +05301092def get_autoname_with_number(number_value, doc_title, name, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301093 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Zarrar88a90ff2018-06-11 11:21:17 +05301094 if name:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301095 name_split = name.split("-")
1096 parts = [doc_title.strip(), name_split[len(name_split) - 1].strip()]
Zarrar44175902018-06-08 16:35:21 +05301097 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301098 abbr = frappe.get_cached_value("Company", company, ["abbr"], as_dict=True)
Zarrar88a90ff2018-06-11 11:21:17 +05301099 parts = [doc_title.strip(), abbr.abbr]
Zlash651aeca1d2018-07-06 17:15:33 +05301100 if cstr(number_value).strip():
1101 parts.insert(0, cstr(number_value).strip())
Ankush Menat494bd9e2022-03-28 18:52:46 +05301102 return " - ".join(parts)
1103
Zarrar254ce642018-06-28 14:15:34 +05301104
1105@frappe.whitelist()
1106def get_coa(doctype, parent, is_root, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301107 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1108 build_tree_from_json,
1109 )
Zarrar254ce642018-06-28 14:15:34 +05301110
1111 # add chart to flags to retrieve when called from expand all function
1112 chart = chart if chart else frappe.flags.chart
1113 frappe.flags.chart = chart
1114
Ankush Menat494bd9e2022-03-28 18:52:46 +05301115 parent = None if parent == _("All Accounts") else parent
1116 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301117
1118 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301119 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301120
1121 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001122
Ankush Menat494bd9e2022-03-28 18:52:46 +05301123
1124def update_gl_entries_after(
1125 posting_date,
1126 posting_time,
1127 for_warehouses=None,
1128 for_items=None,
1129 warehouse_account=None,
1130 company=None,
1131):
1132 stock_vouchers = get_future_stock_vouchers(
1133 posting_date, posting_time, for_warehouses, for_items, company
1134 )
Nabin Hait9b178bc2021-02-16 14:57:00 +05301135 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1136
1137
Ankush Menat494bd9e2022-03-28 18:52:46 +05301138def repost_gle_for_stock_vouchers(
Ankush Menat2535d5e2022-06-14 18:20:33 +05301139 stock_vouchers: List[Tuple[str, str]],
1140 posting_date: str,
1141 company: Optional[str] = None,
1142 warehouse_account=None,
1143 repost_doc: Optional["RepostItemValuation"] = None,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301144):
Ankush Menat67c26322022-06-04 14:46:35 +05301145
1146 from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative
1147
Ankush Menat700e8642022-04-19 13:24:29 +05301148 if not stock_vouchers:
1149 return
1150
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301151 if not warehouse_account:
1152 warehouse_account = get_warehouse_account_map(company)
1153
Ankush Menat2535d5e2022-06-14 18:20:33 +05301154 stock_vouchers = sort_stock_vouchers_by_posting_date(stock_vouchers)
1155 if repost_doc and repost_doc.gl_reposting_index:
1156 # Restore progress
1157 stock_vouchers = stock_vouchers[cint(repost_doc.gl_reposting_index) :]
1158
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301159 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1160
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301161 for stock_vouchers_chunk in create_batch(stock_vouchers, GL_REPOSTING_CHUNK):
Ankush Menat2535d5e2022-06-14 18:20:33 +05301162 gle = get_voucherwise_gl_entries(stock_vouchers_chunk, posting_date)
1163
1164 for voucher_type, voucher_no in stock_vouchers_chunk:
1165 existing_gle = gle.get((voucher_type, voucher_no), [])
1166 voucher_obj = frappe.get_doc(voucher_type, voucher_no)
1167 # Some transactions post credit as negative debit, this is handled while posting GLE
1168 # but while comparing we need to make sure it's flipped so comparisons are accurate
1169 expected_gle = toggle_debit_credit_if_negative(voucher_obj.get_gl_entries(warehouse_account))
1170 if expected_gle:
1171 if not existing_gle or not compare_existing_and_expected_gle(
1172 existing_gle, expected_gle, precision
1173 ):
1174 _delete_gl_entries(voucher_type, voucher_no)
1175 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
1176 else:
1177 _delete_gl_entries(voucher_type, voucher_no)
Ankush Menat86919d22022-06-15 21:19:09 +05301178
1179 if not frappe.flags.in_test:
1180 frappe.db.commit()
Ankush Menat2535d5e2022-06-14 18:20:33 +05301181
1182 if repost_doc:
1183 repost_doc.db_set(
1184 "gl_reposting_index",
Ankush Menat5c6f22f2022-06-15 19:30:26 +05301185 cint(repost_doc.gl_reposting_index) + len(stock_vouchers_chunk),
Ankush Menat2535d5e2022-06-14 18:20:33 +05301186 )
1187
1188
1189def _delete_gl_entries(voucher_type, voucher_no):
1190 frappe.db.sql(
1191 """delete from `tabGL Entry`
1192 where voucher_type=%s and voucher_no=%s""",
1193 (voucher_type, voucher_no),
1194 )
Ankush Menateb53a972022-06-04 18:19:44 +05301195
Ankush Menat494bd9e2022-03-28 18:52:46 +05301196
Ankush Menat700e8642022-04-19 13:24:29 +05301197def sort_stock_vouchers_by_posting_date(
1198 stock_vouchers: List[Tuple[str, str]]
1199) -> List[Tuple[str, str]]:
1200 sle = frappe.qb.DocType("Stock Ledger Entry")
1201 voucher_nos = [v[1] for v in stock_vouchers]
1202
1203 sles = (
1204 frappe.qb.from_(sle)
1205 .select(sle.voucher_type, sle.voucher_no, sle.posting_date, sle.posting_time, sle.creation)
1206 .where((sle.is_cancelled == 0) & (sle.voucher_no.isin(voucher_nos)))
1207 .groupby(sle.voucher_type, sle.voucher_no)
Ankush Menat2535d5e2022-06-14 18:20:33 +05301208 .orderby(sle.posting_date)
1209 .orderby(sle.posting_time)
1210 .orderby(sle.creation)
Ankush Menat700e8642022-04-19 13:24:29 +05301211 ).run(as_dict=True)
1212 sorted_vouchers = [(sle.voucher_type, sle.voucher_no) for sle in sles]
1213
1214 unknown_vouchers = set(stock_vouchers) - set(sorted_vouchers)
1215 if unknown_vouchers:
1216 sorted_vouchers.extend(unknown_vouchers)
1217
1218 return sorted_vouchers
1219
1220
Ankush Menat494bd9e2022-03-28 18:52:46 +05301221def get_future_stock_vouchers(
1222 posting_date, posting_time, for_warehouses=None, for_items=None, company=None
1223):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301224
1225 values = []
1226 condition = ""
1227 if for_items:
1228 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1229 values += for_items
1230
1231 if for_warehouses:
1232 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1233 values += for_warehouses
1234
rohitwaghchaured60ff832021-02-16 09:12:27 +05301235 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301236 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301237 values.append(company)
1238
Ankush Menat494bd9e2022-03-28 18:52:46 +05301239 future_stock_vouchers = frappe.db.sql(
1240 """select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301241 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301242 where
1243 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1244 and is_cancelled = 0
1245 {condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301246 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
1247 condition=condition
1248 ),
1249 tuple([posting_date, posting_time] + values),
1250 as_dict=True,
1251 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301252
Ankush91527152021-08-11 11:17:50 +05301253 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301254
Ankush Menat494bd9e2022-03-28 18:52:46 +05301255
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301256def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301257 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301258
1259 Only fetches GLE fields required for comparing with new GLE.
1260 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301261
1262 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301263 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301264 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301265 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301266 if not future_stock_vouchers:
1267 return gl_entries
1268
1269 voucher_nos = [d[1] for d in future_stock_vouchers]
1270
Ankush Menat494bd9e2022-03-28 18:52:46 +05301271 gles = frappe.db.sql(
1272 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301273 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301274 from `tabGL Entry`
1275 where
Ankush Menat494bd9e2022-03-28 18:52:46 +05301276 posting_date >= %s and voucher_no in (%s)"""
1277 % ("%s", ", ".join(["%s"] * len(voucher_nos))),
1278 tuple([posting_date] + voucher_nos),
1279 as_dict=1,
1280 )
Ankush91527152021-08-11 11:17:50 +05301281
1282 for d in gles:
1283 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301284
Prssanna Desai82ddef52020-06-18 18:18:41 +05301285 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301286
Ankush Menat494bd9e2022-03-28 18:52:46 +05301287
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301288def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301289 if len(existing_gle) != len(expected_gle):
1290 return False
1291
Nabin Haita77b8c92020-12-21 14:45:50 +05301292 matched = True
1293 for entry in expected_gle:
1294 account_existed = False
1295 for e in existing_gle:
1296 if entry.account == e.account:
1297 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301298 if (
1299 entry.account == e.account
1300 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1301 and (
1302 flt(entry.debit, precision) != flt(e.debit, precision)
1303 or flt(entry.credit, precision) != flt(e.credit, precision)
1304 )
1305 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301306 matched = False
1307 break
1308 if not account_existed:
1309 matched = False
1310 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301311 return matched
1312
Ankush Menat494bd9e2022-03-28 18:52:46 +05301313
Nabin Haitb99c77b2020-12-25 18:12:35 +05301314def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301315 stock_accounts = [
1316 d.name
1317 for d in frappe.db.get_all(
1318 "Account", {"account_type": "Stock", "company": company, "is_group": 0}
1319 )
1320 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301321 if voucher_type and voucher_no:
1322 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301323 stock_accounts = [
1324 d.account
1325 for d in frappe.db.get_all(
1326 "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
1327 )
1328 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301329
1330 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301331 stock_accounts = [
1332 d.account
1333 for d in frappe.db.get_all(
1334 "GL Entry",
1335 {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
1336 "account",
1337 )
1338 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301339
1340 return stock_accounts
1341
Ankush Menat494bd9e2022-03-28 18:52:46 +05301342
Nabin Haitb99c77b2020-12-25 18:12:35 +05301343def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301344 if not posting_date:
1345 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301346
1347 warehouse_account = get_warehouse_account_map(company)
1348
Ankush Menat494bd9e2022-03-28 18:52:46 +05301349 account_balance = get_balance_on(
1350 account, posting_date, in_account_currency=False, ignore_account_permission=True
1351 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301352
Ankush Menat494bd9e2022-03-28 18:52:46 +05301353 related_warehouses = [
1354 wh
1355 for wh, wh_details in warehouse_account.items()
1356 if wh_details.account == account and not wh_details.is_group
1357 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301358
1359 total_stock_value = 0.0
1360 for warehouse in related_warehouses:
1361 value = get_stock_value_on(warehouse, posting_date)
1362 total_stock_value += value
1363
1364 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1365 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1366
Ankush Menat494bd9e2022-03-28 18:52:46 +05301367
Nabin Haitb99c77b2020-12-25 18:12:35 +05301368def get_journal_entry(account, stock_adjustment_account, amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301369 db_or_cr_warehouse_account = (
1370 "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
1371 )
1372 db_or_cr_stock_adjustment_account = (
1373 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1374 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301375
1376 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301377 "accounts": [
1378 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1379 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1380 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301381 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301382
Ankush Menat494bd9e2022-03-28 18:52:46 +05301383
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301384def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301385 """Check if reports are referenced in Desktop Icon"""
1386 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301387 if icons:
1388 for icon in icons:
1389 frappe.delete_doc("Desktop Icon", icon)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301390
1391
1392def create_payment_ledger_entry(gl_entries, cancel=0):
1393 if gl_entries:
1394 ple = None
1395
1396 # companies
1397 account = qb.DocType("Account")
1398 companies = list(set([x.company for x in gl_entries]))
1399
1400 # receivable/payable account
1401 accounts_with_types = (
1402 qb.from_(account)
1403 .select(account.name, account.account_type)
1404 .where(
1405 (account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
1406 )
1407 .run(as_dict=True)
1408 )
1409 receivable_or_payable_accounts = [y.name for y in accounts_with_types]
1410
1411 def get_account_type(account):
1412 for entry in accounts_with_types:
1413 if entry.name == account:
1414 return entry.account_type
1415
1416 dr_or_cr = 0
1417 account_type = None
1418 for gle in gl_entries:
1419 if gle.account in receivable_or_payable_accounts:
1420 account_type = get_account_type(gle.account)
1421 if account_type == "Receivable":
1422 dr_or_cr = gle.debit - gle.credit
1423 dr_or_cr_account_currency = gle.debit_in_account_currency - gle.credit_in_account_currency
1424 elif account_type == "Payable":
1425 dr_or_cr = gle.credit - gle.debit
1426 dr_or_cr_account_currency = gle.credit_in_account_currency - gle.debit_in_account_currency
1427
1428 if cancel:
1429 dr_or_cr *= -1
1430 dr_or_cr_account_currency *= -1
1431
1432 ple = frappe.get_doc(
1433 {
1434 "doctype": "Payment Ledger Entry",
1435 "posting_date": gle.posting_date,
1436 "company": gle.company,
1437 "account_type": account_type,
1438 "account": gle.account,
1439 "party_type": gle.party_type,
1440 "party": gle.party,
1441 "cost_center": gle.cost_center,
1442 "finance_book": gle.finance_book,
1443 "due_date": gle.due_date,
1444 "voucher_type": gle.voucher_type,
1445 "voucher_no": gle.voucher_no,
1446 "against_voucher_type": gle.against_voucher_type
1447 if gle.against_voucher_type
1448 else gle.voucher_type,
1449 "against_voucher_no": gle.against_voucher if gle.against_voucher else gle.voucher_no,
1450 "currency": gle.currency,
1451 "amount": dr_or_cr,
1452 "amount_in_account_currency": dr_or_cr_account_currency,
1453 "delinked": True if cancel else False,
1454 }
1455 )
1456
1457 dimensions_and_defaults = get_dimensions()
1458 if dimensions_and_defaults:
1459 for dimension in dimensions_and_defaults[0]:
1460 ple.set(dimension.fieldname, gle.get(dimension.fieldname))
1461
1462 if cancel:
1463 delink_original_entry(ple)
1464 ple.flags.ignore_permissions = 1
1465 ple.submit()
1466
1467
1468def delink_original_entry(pl_entry):
1469 if pl_entry:
1470 ple = qb.DocType("Payment Ledger Entry")
1471 query = (
1472 qb.update(ple)
1473 .set(ple.delinked, True)
1474 .set(ple.modified, now())
1475 .set(ple.modified_by, frappe.session.user)
1476 .where(
1477 (ple.company == pl_entry.company)
1478 & (ple.account_type == pl_entry.account_type)
1479 & (ple.account == pl_entry.account)
1480 & (ple.party_type == pl_entry.party_type)
1481 & (ple.party == pl_entry.party)
1482 & (ple.voucher_type == pl_entry.voucher_type)
1483 & (ple.voucher_no == pl_entry.voucher_no)
1484 & (ple.against_voucher_type == pl_entry.against_voucher_type)
1485 & (ple.against_voucher_no == pl_entry.against_voucher_no)
1486 )
1487 )
1488 query.run()