blob: 1869cc7b290a91553f16754c35f7da772226b829 [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 Menat700e8642022-04-19 13:24:29 +05306from typing import List, 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
Chillar Anand915b3432021-09-02 16:44:59 +053012from frappe.utils import cint, cstr, flt, formatdate, get_number_format_info, getdate, now, nowdate
Anand Doshicd0989e2015-09-28 13:31:17 +053013
Chillar Anand915b3432021-09-02 16:44:59 +053014import erpnext
15
16# imported to enable erpnext.accounts.utils.get_account_currency
17from erpnext.accounts.doctype.account.account import get_account_currency # noqa
ruthra kumar451cf3a2022-05-16 14:29:58 +053018from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_dimensions
Anurag Mishraa11e7382019-10-31 15:55:03 +053019from erpnext.stock import get_warehouse_account_map
Chillar Anand915b3432021-09-02 16:44:59 +053020from erpnext.stock.utils import get_stock_value_on
21
Anurag Mishraa11e7382019-10-31 15:55:03 +053022
Ankush Menat494bd9e2022-03-28 18:52:46 +053023class FiscalYearError(frappe.ValidationError):
24 pass
25
26
27class PaymentEntryUnlinkError(frappe.ValidationError):
28 pass
29
Nabin Hait2b06aaa2013-08-22 18:25:43 +053030
Neil Trini Lasrado78fa6952014-10-03 17:43:02 +053031@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +053032def get_fiscal_year(
33 date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False
34):
Anand Doshic75c1d72016-03-11 14:56:19 +053035 return get_fiscal_years(date, fiscal_year, label, verbose, company, as_dict=as_dict)[0]
Nabin Hait23941aa2013-01-29 11:32:38 +053036
Ankush Menat494bd9e2022-03-28 18:52:46 +053037
38def get_fiscal_years(
39 transaction_date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False
40):
Nabin Hait9784d272016-12-30 16:21:35 +053041 fiscal_years = frappe.cache().hget("fiscal_years", company) or []
Rushabh Mehtad50da782017-07-28 11:39:01 +053042
43 if not fiscal_years:
Nabin Hait9784d272016-12-30 16:21:35 +053044 # if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
45 cond = ""
46 if fiscal_year:
47 cond += " and fy.name = {0}".format(frappe.db.escape(fiscal_year))
48 if company:
49 cond += """
Rushabh Mehtad50da782017-07-28 11:39:01 +053050 and (not exists (select name
51 from `tabFiscal Year Company` fyc
52 where fyc.parent = fy.name)
53 or exists(select company
54 from `tabFiscal Year Company` fyc
55 where fyc.parent = fy.name
Nabin Hait9784d272016-12-30 16:21:35 +053056 and fyc.company=%(company)s)
57 )
58 """
Nabin Haitfff3ab72015-01-14 16:27:13 +053059
Ankush Menat494bd9e2022-03-28 18:52:46 +053060 fiscal_years = frappe.db.sql(
61 """
Rushabh Mehtad50da782017-07-28 11:39:01 +053062 select
63 fy.name, fy.year_start_date, fy.year_end_date
64 from
Nabin Hait9784d272016-12-30 16:21:35 +053065 `tabFiscal Year` fy
Rushabh Mehtad50da782017-07-28 11:39:01 +053066 where
Nabin Hait9784d272016-12-30 16:21:35 +053067 disabled = 0 {0}
Rushabh Mehtad50da782017-07-28 11:39:01 +053068 order by
Ankush Menat494bd9e2022-03-28 18:52:46 +053069 fy.year_start_date desc""".format(
70 cond
71 ),
72 {"company": company},
73 as_dict=True,
74 )
Rushabh Mehtad50da782017-07-28 11:39:01 +053075
Nabin Hait9784d272016-12-30 16:21:35 +053076 frappe.cache().hset("fiscal_years", company, fiscal_years)
Nabin Haitfff3ab72015-01-14 16:27:13 +053077
Prssanna Desai82ddef52020-06-18 18:18:41 +053078 if not transaction_date and not fiscal_year:
79 return fiscal_years
80
Nabin Hait9784d272016-12-30 16:21:35 +053081 if transaction_date:
82 transaction_date = getdate(transaction_date)
Anand Doshicd71e1d2014-04-08 13:53:35 +053083
Nabin Hait9784d272016-12-30 16:21:35 +053084 for fy in fiscal_years:
85 matched = False
86 if fiscal_year and fy.name == fiscal_year:
87 matched = True
Anand Doshicd71e1d2014-04-08 13:53:35 +053088
Ankush Menat494bd9e2022-03-28 18:52:46 +053089 if (
90 transaction_date
91 and getdate(fy.year_start_date) <= transaction_date
92 and getdate(fy.year_end_date) >= transaction_date
93 ):
Nabin Hait9784d272016-12-30 16:21:35 +053094 matched = True
Rushabh Mehtad50da782017-07-28 11:39:01 +053095
Nabin Hait9784d272016-12-30 16:21:35 +053096 if matched:
97 if as_dict:
98 return (fy,)
99 else:
100 return ((fy.name, fy.year_start_date, fy.year_end_date),)
101
Ankush Menat494bd9e2022-03-28 18:52:46 +0530102 error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(
103 label, formatdate(transaction_date)
104 )
Anuja P2e4faf92020-12-05 13:36:43 +0530105 if company:
Anuja P550cb9c2020-12-07 11:11:00 +0530106 error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company))
rohitwaghchaured60ff832021-02-16 09:12:27 +0530107
Ankush Menat494bd9e2022-03-28 18:52:46 +0530108 if verbose == 1:
109 frappe.msgprint(error_msg)
cclauss68487082017-07-27 07:08:35 +0200110 raise FiscalYearError(error_msg)
Nabin Hait9784d272016-12-30 16:21:35 +0530111
Ankush Menat494bd9e2022-03-28 18:52:46 +0530112
Prssanna Desai82ddef52020-06-18 18:18:41 +0530113@frappe.whitelist()
114def get_fiscal_year_filter_field(company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530115 field = {"fieldtype": "Select", "options": [], "operator": "Between", "query_value": True}
Prssanna Desai82ddef52020-06-18 18:18:41 +0530116 fiscal_years = get_fiscal_years(company=company)
117 for fiscal_year in fiscal_years:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530118 field["options"].append(
119 {
120 "label": fiscal_year.name,
121 "value": fiscal_year.name,
122 "query_value": [
123 fiscal_year.year_start_date.strftime("%Y-%m-%d"),
124 fiscal_year.year_end_date.strftime("%Y-%m-%d"),
125 ],
126 }
127 )
Prssanna Desai82ddef52020-06-18 18:18:41 +0530128 return field
129
Ankush Menat494bd9e2022-03-28 18:52:46 +0530130
Nabin Hait8bf58362017-03-27 12:30:01 +0530131def validate_fiscal_year(date, fiscal_year, company, label="Date", doc=None):
132 years = [f[0] for f in get_fiscal_years(date, label=_(label), company=company)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +0530133 if fiscal_year not in years:
Rushabh Mehtad60acb92015-02-19 14:51:58 +0530134 if doc:
135 doc.fiscal_year = years[0]
136 else:
137 throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
Nabin Hait23941aa2013-01-29 11:32:38 +0530138
Ankush Menat494bd9e2022-03-28 18:52:46 +0530139
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530140@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530141def get_balance_on(
142 account=None,
143 date=None,
144 party_type=None,
145 party=None,
146 company=None,
147 in_account_currency=True,
148 cost_center=None,
149 ignore_account_permission=False,
150):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530151 if not account and frappe.form_dict.get("account"):
152 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530153 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530154 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530155 if not party_type and frappe.form_dict.get("party_type"):
156 party_type = frappe.form_dict.get("party_type")
157 if not party and frappe.form_dict.get("party"):
158 party = frappe.form_dict.get("party")
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400159 if not cost_center and frappe.form_dict.get("cost_center"):
160 cost_center = frappe.form_dict.get("cost_center")
161
Nabin Hait98372852020-07-30 20:52:20 +0530162 cond = ["is_cancelled=0"]
Nabin Hait23941aa2013-01-29 11:32:38 +0530163 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530164 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530165 else:
166 # get balance of all entries that exist
167 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530168
Deepesh Garg8c217032019-07-16 09:41:01 +0530169 if account:
170 acc = frappe.get_doc("Account", account)
171
Nabin Hait23941aa2013-01-29 11:32:38 +0530172 try:
Deepesh Garg96d40ec2020-07-03 22:59:00 +0530173 year_start_date = get_fiscal_year(date, company=company, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530174 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +0530175 if getdate(date) > getdate(nowdate()):
176 # if fiscal year not found and the date is greater than today
177 # get fiscal year for today's date and its corresponding year start date
178 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
179 else:
180 # this indicates that it is a date older than any existing fiscal year.
181 # hence, assuming balance as 0.0
182 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530183
deepeshgarg0072ddbebf2019-07-20 14:52:59 +0530184 if account:
deepeshgarg007e097d4f2019-07-20 14:49:32 +0530185 report_type = acc.report_type
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530186 else:
187 report_type = ""
188
Ankush Menat494bd9e2022-03-28 18:52:46 +0530189 if cost_center and report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400190 cc = frappe.get_doc("Cost Center", cost_center)
191 if cc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530192 cond.append(
193 """ exists (
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400194 select 1 from `tabCost Center` cc where cc.name = gle.cost_center
195 and cc.lft >= %s and cc.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530196 )"""
197 % (cc.lft, cc.rgt)
198 )
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400199
200 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530201 cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center, percent=False),))
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400202
Nabin Hait6f17cf92014-09-17 14:11:22 +0530203 if account:
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400204
Ankush Menat494bd9e2022-03-28 18:52:46 +0530205 if not (frappe.flags.ignore_account_permission or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530206 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530207
Ankush Menat494bd9e2022-03-28 18:52:46 +0530208 if report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400209 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530210 cond.append(
211 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
212 )
Nabin Hait6f17cf92014-09-17 14:11:22 +0530213 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530214 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530215 cond.append(
216 """exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530217 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530218 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530219 )"""
220 % (acc.lft, acc.rgt)
221 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530222
223 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530224 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530225 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530226 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530227 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530228 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
Anand Doshic75c1d72016-03-11 14:56:19 +0530229
Nabin Hait6f17cf92014-09-17 14:11:22 +0530230 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530231 cond.append(
232 """gle.party_type = %s and gle.party = %s """
233 % (frappe.db.escape(party_type), frappe.db.escape(party, percent=False))
234 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530235
Nabin Hait85648d92016-07-20 11:26:45 +0530236 if company:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530237 cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530238
Nabin Haitdc768232015-08-17 11:27:00 +0530239 if account or (party_type and party):
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530240 if in_account_currency:
Anand Doshi602e8252015-11-16 19:05:46 +0530241 select_field = "sum(debit_in_account_currency) - sum(credit_in_account_currency)"
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530242 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530243 select_field = "sum(debit) - sum(credit)"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530244 bal = frappe.db.sql(
245 """
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530246 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530247 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530248 WHERE {1}""".format(
249 select_field, " and ".join(cond)
250 )
251 )[0][0]
Anand Doshicd71e1d2014-04-08 13:53:35 +0530252
Nabin Haitdc768232015-08-17 11:27:00 +0530253 # if bal is None, return 0
254 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530255
Ankush Menat494bd9e2022-03-28 18:52:46 +0530256
RobertSchouten8d43b322016-09-20 13:41:39 +0800257def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530258 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800259 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530260 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800261 else:
262 # get balance of all entries that exist
263 date = nowdate()
264
265 try:
266 year_start_date = get_fiscal_year(date, verbose=0)[1]
267 except FiscalYearError:
268 if getdate(date) > getdate(nowdate()):
269 # if fiscal year not found and the date is greater than today
270 # get fiscal year for today's date and its corresponding year start date
271 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
272 else:
273 # this indicates that it is a date older than any existing fiscal year.
274 # hence, assuming balance as 0.0
275 return 0.0
276
277 if account:
278 acc = frappe.get_doc("Account", account)
279
280 if not frappe.flags.ignore_account_permission:
281 acc.check_permission("read")
282
283 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530284 if acc.report_type == "Profit and Loss":
285 cond.append(
286 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
287 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800288
289 # different filter for group and ledger - improved performance
290 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530291 cond.append(
292 """exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800293 select name from `tabAccount` ac where ac.name = gle.account
294 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530295 )"""
296 % (acc.lft, acc.rgt)
297 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800298 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530299 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
RobertSchouten8d43b322016-09-20 13:41:39 +0800300
Ankush Menat494bd9e2022-03-28 18:52:46 +0530301 entries = frappe.db.sql(
302 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800303 SELECT name, posting_date, account, party_type, party,debit,credit,
304 voucher_type, voucher_no, against_voucher_type, against_voucher
305 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530306 WHERE {0}""".format(
307 " and ".join(cond)
308 ),
309 as_dict=True,
310 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530311
RobertSchouten8d43b322016-09-20 13:41:39 +0800312 count = 0
313 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530314 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800315 count += 1
316 else:
317 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
318 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530319 select_fields = (
320 "ifnull(sum(credit-debit),0)"
321 if fieldname == "invoiced_amount"
322 else "ifnull(sum(debit-credit),0)"
323 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800324
Ankush Menat494bd9e2022-03-28 18:52:46 +0530325 if (
326 (not gle.against_voucher)
327 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
328 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
329 ):
330 payment_amount = frappe.db.sql(
331 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800332 SELECT {0}
333 FROM `tabGL Entry` gle
334 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530335 and party = %(party)s and name != %(name)s""".format(
336 select_fields
337 ),
338 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
339 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530340
RobertSchouten8d43b322016-09-20 13:41:39 +0800341 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
342 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530343 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800344 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530345
RobertSchouten8d43b322016-09-20 13:41:39 +0800346 return count
347
Ankush Menat494bd9e2022-03-28 18:52:46 +0530348
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530349@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530350def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530351 from frappe.desk.treeview import make_tree_args
352
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530353 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530354 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530355
Nabin Hait02d987e2017-02-17 15:50:26 +0530356 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530357 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530358
Anand Doshi3e41fd12014-04-22 18:54:54 +0530359 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530360
Nabin Hait665568d2016-05-13 15:56:00 +0530361 if args.get("ignore_permissions"):
362 ac.flags.ignore_permissions = True
363 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530364
Anand Doshi3e41fd12014-04-22 18:54:54 +0530365 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530366
367 if not ac.parent_account:
368 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530369
Anand Doshif78d1ae2014-03-28 13:55:00 +0530370 ac.old_parent = ""
371 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530372 if cint(ac.get("is_root")):
373 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530374 ac.flags.ignore_mandatory = True
375
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530376 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530377
Anand Doshif78d1ae2014-03-28 13:55:00 +0530378 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530379
Ankush Menat494bd9e2022-03-28 18:52:46 +0530380
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530381@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530382def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530383 from frappe.desk.treeview import make_tree_args
384
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530385 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530386 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530387
Nabin Hait02d987e2017-02-17 15:50:26 +0530388 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530389 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530390
Zarrar7ab70ca2018-06-08 14:33:15 +0530391 if args.parent_cost_center == args.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530392 args.parent_cost_center = "{0} - {1}".format(
393 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
394 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530395
Anand Doshi3e41fd12014-04-22 18:54:54 +0530396 cc = frappe.new_doc("Cost Center")
397 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530398
399 if not cc.parent_cost_center:
400 cc.parent_cost_center = args.get("parent")
401
Anand Doshif78d1ae2014-03-28 13:55:00 +0530402 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530403 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530404 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530405
Ankush Menat494bd9e2022-03-28 18:52:46 +0530406
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530407def reconcile_against_document(args):
408 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530409 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530410 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530411 # To optimize making GL Entry for PE or JV with multiple references
412 reconciled_entries = {}
413 for row in args:
414 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
415 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530416
Anuja Pawar3e404f12021-08-31 18:59:29 +0530417 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
418
419 for key, entries in reconciled_entries.items():
420 voucher_type = key[0]
421 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530422
Nabin Hait28a05282016-06-27 17:41:39 +0530423 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530424 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530425 frappe.flags.ignore_party_validation = True
Nabin Hait28a05282016-06-27 17:41:39 +0530426 doc.make_gl_entries(cancel=1, adv_adj=1)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530427
Anuja Pawar3e404f12021-08-31 18:59:29 +0530428 for entry in entries:
429 check_if_advance_entry_modified(entry)
430 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530431
Anuja Pawar3e404f12021-08-31 18:59:29 +0530432 # update ref in advance entry
433 if voucher_type == "Journal Entry":
434 update_reference_in_journal_entry(entry, doc, do_not_save=True)
435 else:
436 update_reference_in_payment_entry(entry, doc, do_not_save=True)
437
438 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530439 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530440 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530441 doc.make_gl_entries(cancel=0, adv_adj=1)
Subin Tomb8845b92021-07-30 16:30:18 +0530442 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530443
Ankush Menat494bd9e2022-03-28 18:52:46 +0530444 if entry.voucher_type in ("Payment Entry", "Journal Entry"):
Nabin Hait5cd04a62019-05-27 11:44:06 +0530445 doc.update_expense_claim()
446
Ankush Menat494bd9e2022-03-28 18:52:46 +0530447
Nabin Hait28a05282016-06-27 17:41:39 +0530448def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530449 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530450 check if there is already a voucher reference
451 check if amount is same
452 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530453 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530454 if not args.get("unreconciled_amount"):
455 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530456
Nabin Hait28a05282016-06-27 17:41:39 +0530457 ret = None
458 if args.voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530459 ret = frappe.db.sql(
460 """
Nabin Hait28a05282016-06-27 17:41:39 +0530461 select t2.{dr_or_cr} from `tabJournal Entry` t1, `tabJournal Entry Account` t2
462 where t1.name = t2.parent and t2.account = %(account)s
463 and t2.party_type = %(party_type)s and t2.party = %(party)s
464 and (t2.reference_type is null or t2.reference_type in ("", "Sales Order", "Purchase Order"))
465 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530466 and t1.docstatus=1 """.format(
467 dr_or_cr=args.get("dr_or_cr")
468 ),
469 args,
470 )
Nabin Hait28a05282016-06-27 17:41:39 +0530471 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530472 party_account_field = (
473 "paid_from" if erpnext.get_party_account_type(args.party_type) == "Receivable" else "paid_to"
474 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530475
Nabin Hait28a05282016-06-27 17:41:39 +0530476 if args.voucher_detail_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530477 ret = frappe.db.sql(
478 """select t1.name
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530479 from `tabPayment Entry` t1, `tabPayment Entry Reference` t2
Nabin Hait28a05282016-06-27 17:41:39 +0530480 where
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530481 t1.name = t2.parent and t1.docstatus = 1
Nabin Hait28a05282016-06-27 17:41:39 +0530482 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
483 and t1.party_type = %(party_type)s and t1.party = %(party)s and t1.{0} = %(account)s
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530484 and t2.reference_doctype in ("", "Sales Order", "Purchase Order")
Anuja Pawar3e404f12021-08-31 18:59:29 +0530485 and t2.allocated_amount = %(unreconciled_amount)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530486 """.format(
487 party_account_field
488 ),
489 args,
490 )
Nabin Hait28a05282016-06-27 17:41:39 +0530491 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530492 ret = frappe.db.sql(
493 """select name from `tabPayment Entry`
Nabin Hait28a05282016-06-27 17:41:39 +0530494 where
495 name = %(voucher_no)s and docstatus = 1
496 and party_type = %(party_type)s and party = %(party)s and {0} = %(account)s
Anuja Pawar3e404f12021-08-31 18:59:29 +0530497 and unallocated_amount = %(unreconciled_amount)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530498 """.format(
499 party_account_field
500 ),
501 args,
502 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530503
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530504 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530505 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530506
Ankush Menat494bd9e2022-03-28 18:52:46 +0530507
Nabin Hait576f0252014-04-30 19:30:50 +0530508def validate_allocated_amount(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530509 precision = args.get("precision") or frappe.db.get_single_value(
510 "System Settings", "currency_precision"
511 )
Nabin Hait28a05282016-06-27 17:41:39 +0530512 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530513 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530514 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530515 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530516
Ankush Menat494bd9e2022-03-28 18:52:46 +0530517
Anuja Pawar3e404f12021-08-31 18:59:29 +0530518def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530519 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530520 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530521 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530522 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530523
Ankush Menat494bd9e2022-03-28 18:52:46 +0530524 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530525 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530526 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530527 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530528 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
529 jv_detail.set(
530 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
531 amount_in_company_currency,
532 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530533 else:
534 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530535
Anuja Pawar3e404f12021-08-31 18:59:29 +0530536 # new row with references
537 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530538
539 new_row.update((frappe.copy_doc(jv_detail)).as_dict())
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530540
Anuja Pawar3e404f12021-08-31 18:59:29 +0530541 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530542 new_row.set(
543 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
544 d["allocated_amount"] * flt(jv_detail.exchange_rate),
545 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530546
Ankush Menat494bd9e2022-03-28 18:52:46 +0530547 new_row.set(
548 "credit_in_account_currency"
549 if d["dr_or_cr"] == "debit_in_account_currency"
550 else "debit_in_account_currency",
551 0,
552 )
553 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530554
Anuja Pawar3e404f12021-08-31 18:59:29 +0530555 new_row.set("reference_type", d["against_voucher_type"])
556 new_row.set("reference_name", d["against_voucher"])
557
558 new_row.against_account = cstr(jv_detail.against_account)
559 new_row.is_advance = cstr(jv_detail.is_advance)
560 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530561
562 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530563 journal_entry.flags.ignore_validate_update_after_submit = True
564 if not do_not_save:
565 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530566
Ankush Menat494bd9e2022-03-28 18:52:46 +0530567
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530568def update_reference_in_payment_entry(d, payment_entry, do_not_save=False):
Nabin Hait28a05282016-06-27 17:41:39 +0530569 reference_details = {
570 "reference_doctype": d.against_voucher_type,
571 "reference_name": d.against_voucher,
572 "total_amount": d.grand_total,
573 "outstanding_amount": d.outstanding_amount,
574 "allocated_amount": d.allocated_amount,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530575 "exchange_rate": d.exchange_rate
576 if not d.exchange_gain_loss
577 else payment_entry.get_exchange_rate(),
578 "exchange_gain_loss": d.exchange_gain_loss, # only populated from invoice in case of advance allocation
Nabin Hait28a05282016-06-27 17:41:39 +0530579 }
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530580
Nabin Hait28a05282016-06-27 17:41:39 +0530581 if d.voucher_detail_no:
582 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
583 original_row = existing_row.as_dict().copy()
584 existing_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530585
Nabin Hait28a05282016-06-27 17:41:39 +0530586 if d.allocated_amount < original_row.allocated_amount:
587 new_row = payment_entry.append("references")
588 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500589 for field in list(reference_details):
Nabin Hait28a05282016-06-27 17:41:39 +0530590 new_row.set(field, original_row[field])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530591
Nabin Hait28a05282016-06-27 17:41:39 +0530592 new_row.allocated_amount = original_row.allocated_amount - d.allocated_amount
593 else:
594 new_row = payment_entry.append("references")
595 new_row.docstatus = 1
596 new_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530597
Nabin Hait28a05282016-06-27 17:41:39 +0530598 payment_entry.flags.ignore_validate_update_after_submit = True
Nabin Hait05aefbb2016-06-28 19:42:19 +0530599 payment_entry.setup_party_account_field()
Nabin Hait1991c7b2016-06-27 20:09:05 +0530600 payment_entry.set_missing_values()
Nabin Hait28a05282016-06-27 17:41:39 +0530601 payment_entry.set_amounts()
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530602
603 if d.difference_amount and d.difference_account:
Saqiba20999c2021-07-12 14:33:23 +0530604 account_details = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530605 "account": d.difference_account,
606 "cost_center": payment_entry.cost_center
607 or frappe.get_cached_value("Company", payment_entry.company, "cost_center"),
Saqiba20999c2021-07-12 14:33:23 +0530608 }
609 if d.difference_amount:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530610 account_details["amount"] = d.difference_amount
Saqiba20999c2021-07-12 14:33:23 +0530611
612 payment_entry.set_gain_or_loss(account_details=account_details)
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530613
614 if not do_not_save:
615 payment_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530616
Ankush Menat494bd9e2022-03-28 18:52:46 +0530617
Nabin Hait297d74a2016-11-23 15:58:51 +0530618def unlink_ref_doc_from_payment_entries(ref_doc):
619 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name)
620 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530621
Ankush Menat494bd9e2022-03-28 18:52:46 +0530622 frappe.db.sql(
623 """update `tabGL Entry`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530624 set against_voucher_type=null, against_voucher=null,
625 modified=%s, modified_by=%s
626 where against_voucher_type=%s and against_voucher=%s
627 and voucher_no != ifnull(against_voucher, '')""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530628 (now(), frappe.session.user, ref_doc.doctype, ref_doc.name),
629 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530630
Nabin Hait297d74a2016-11-23 15:58:51 +0530631 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
632 ref_doc.set("advances", [])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530633
Ankush Menat494bd9e2022-03-28 18:52:46 +0530634 frappe.db.sql(
635 """delete from `tab{0} Advance` where parent = %s""".format(ref_doc.doctype), ref_doc.name
636 )
637
Anand Doshicd71e1d2014-04-08 13:53:35 +0530638
Nabin Haite0cc87d2016-07-21 18:30:03 +0530639def remove_ref_doc_link_from_jv(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530640 linked_jv = frappe.db.sql_list(
641 """select parent from `tabJournal Entry Account`
642 where reference_type=%s and reference_name=%s and docstatus < 2""",
643 (ref_type, ref_no),
644 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530645
646 if linked_jv:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530647 frappe.db.sql(
648 """update `tabJournal Entry Account`
Rushabh Mehta1828c122015-08-10 17:04:07 +0530649 set reference_type=null, reference_name = null,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530650 modified=%s, modified_by=%s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530651 where reference_type=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530652 and docstatus < 2""",
653 (now(), frappe.session.user, ref_type, ref_no),
654 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530655
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530656 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530657
Ankush Menat494bd9e2022-03-28 18:52:46 +0530658
Nabin Haite0cc87d2016-07-21 18:30:03 +0530659def remove_ref_doc_link_from_pe(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530660 linked_pe = frappe.db.sql_list(
661 """select parent from `tabPayment Entry Reference`
662 where reference_doctype=%s and reference_name=%s and docstatus < 2""",
663 (ref_type, ref_no),
664 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530665
Nabin Haite0cc87d2016-07-21 18:30:03 +0530666 if linked_pe:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530667 frappe.db.sql(
668 """update `tabPayment Entry Reference`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530669 set allocated_amount=0, modified=%s, modified_by=%s
670 where reference_doctype=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530671 and docstatus < 2""",
672 (now(), frappe.session.user, ref_type, ref_no),
673 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530674
Nabin Haite0cc87d2016-07-21 18:30:03 +0530675 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530676 try:
677 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530678 pe_doc.set_amounts()
Deepesh Gargb5162392021-08-10 14:52:24 +0530679 pe_doc.clear_unallocated_reference_document_rows()
680 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530681 except Exception as e:
682 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530683 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530684 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530685 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530686
Ankush Menat494bd9e2022-03-28 18:52:46 +0530687 frappe.db.sql(
688 """update `tabPayment Entry` set total_allocated_amount=%s,
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530689 base_total_allocated_amount=%s, unallocated_amount=%s, modified=%s, modified_by=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530690 where name=%s""",
691 (
692 pe_doc.total_allocated_amount,
693 pe_doc.base_total_allocated_amount,
694 pe_doc.unallocated_amount,
695 now(),
696 frappe.session.user,
697 pe,
698 ),
699 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530700
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530701 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530702
Ankush Menat494bd9e2022-03-28 18:52:46 +0530703
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530704@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530705def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530706 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530707
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530708 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530709 throw(
710 _("Please set default {0} in Company {1}").format(
711 frappe.get_meta("Company").get_label(fieldname), company
712 )
713 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530714
Nabin Hait0fc24542013-03-25 11:06:00 +0530715 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530716
Ankush Menat494bd9e2022-03-28 18:52:46 +0530717
Nabin Hait8b509f52013-05-28 16:52:30 +0530718def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530719 vouchers = frappe.db.sql(
720 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530721 sum(debit) - sum(credit) as diff
722 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530723 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530724 having sum(debit) != sum(credit)""",
725 as_dict=1,
726 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530727
Nabin Hait8b509f52013-05-28 16:52:30 +0530728 for d in vouchers:
729 if abs(d.diff) > 0:
730 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530731
Ankush Menat494bd9e2022-03-28 18:52:46 +0530732 frappe.db.sql(
733 """update `tabGL Entry` set %s = %s + %s
734 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
735 % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
736 (d.diff, d.voucher_type, d.voucher_no),
737 )
738
Anand Doshicd71e1d2014-04-08 13:53:35 +0530739
Rushabh Mehtad50da782017-07-28 11:39:01 +0530740def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530741 precision = cint(frappe.db.get_default("currency_precision"))
742 if not precision:
743 number_format = frappe.db.get_default("number_format") or "#,###.##"
744 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530745
Nabin Hait9b20e072017-04-25 12:10:24 +0530746 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530747
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530748
Ankush Menat494bd9e2022-03-28 18:52:46 +0530749def get_stock_rbnb_difference(posting_date, company):
750 stock_items = frappe.db.sql_list(
751 """select distinct item_code
752 from `tabStock Ledger Entry` where company=%s""",
753 company,
754 )
755
756 pr_valuation_amount = frappe.db.sql(
757 """
Anand Doshi602e8252015-11-16 19:05:46 +0530758 select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530759 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
Suraj Shetty084b0b32018-05-26 09:12:59 +0530760 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530761 and pr.posting_date <= %s and pr_item.item_code in (%s)"""
762 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
763 tuple([company, posting_date] + stock_items),
764 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530765
Ankush Menat494bd9e2022-03-28 18:52:46 +0530766 pi_valuation_amount = frappe.db.sql(
767 """
Anand Doshi602e8252015-11-16 19:05:46 +0530768 select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530769 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
Suraj Shetty084b0b32018-05-26 09:12:59 +0530770 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530771 and pi.posting_date <= %s and pi_item.item_code in (%s)"""
772 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
773 tuple([company, posting_date] + stock_items),
774 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530775
776 # Balance should be
777 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
778
779 # Balance as per system
Ankush Menat494bd9e2022-03-28 18:52:46 +0530780 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.get_cached_value(
781 "Company", company, "abbr"
782 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530783 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530784
785 # Amount should be credited
786 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530787
tundec4b0d172017-09-26 00:48:30 +0100788
tundebabzyad08d4c2018-05-16 07:01:41 +0100789def get_held_invoices(party_type, party):
790 """
791 Returns a list of names Purchase Invoices for the given party that are on hold
792 """
793 held_invoices = None
794
Ankush Menat494bd9e2022-03-28 18:52:46 +0530795 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +0100796 held_invoices = frappe.db.sql(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530797 "select name from `tabPurchase Invoice` where release_date IS NOT NULL and release_date > CURDATE()",
798 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +0100799 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530800 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +0100801
802 return held_invoices
803
804
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530805def get_outstanding_invoices(party_type, party, account, condition=None, filters=None):
Anand Doshid40d1e92015-11-12 17:05:29 +0530806 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +0530807 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +0530808
Nabin Hait9db9edc2019-11-19 18:44:32 +0530809 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530810 root_type, account_type = frappe.get_cached_value(
811 "Account", account, ["root_type", "account_type"]
812 )
Nabin Hait9db9edc2019-11-19 18:44:32 +0530813 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +0530814 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +0530815 else:
816 party_account_type = erpnext.get_party_account_type(party_type)
817
Ankush Menat494bd9e2022-03-28 18:52:46 +0530818 if party_account_type == "Receivable":
Anand Doshi602e8252015-11-16 19:05:46 +0530819 dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
Nabin Haitac184982019-02-04 21:13:43 +0530820 payment_dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
Anand Doshid40d1e92015-11-12 17:05:29 +0530821 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530822 dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
Nabin Haitac184982019-02-04 21:13:43 +0530823 payment_dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
Anand Doshid40d1e92015-11-12 17:05:29 +0530824
tundebabzyad08d4c2018-05-16 07:01:41 +0100825 held_invoices = get_held_invoices(party_type, party)
826
Ankush Menat494bd9e2022-03-28 18:52:46 +0530827 invoice_list = frappe.db.sql(
828 """
Nabin Haite4bbb692016-07-04 16:16:24 +0530829 select
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530830 voucher_no, voucher_type, posting_date, due_date,
Deepesh Gargc7eadfc2020-07-22 17:59:37 +0530831 ifnull(sum({dr_or_cr}), 0) as invoice_amount,
832 account_currency as currency
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530833 from
Nabin Haitac184982019-02-04 21:13:43 +0530834 `tabGL Entry`
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530835 where
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530836 party_type = %(party_type)s and party = %(party)s
Nabin Haite4bbb692016-07-04 16:16:24 +0530837 and account = %(account)s and {dr_or_cr} > 0
aakvatech38ccf822020-10-03 19:41:38 +0300838 and is_cancelled=0
Anand Doshid40d1e92015-11-12 17:05:29 +0530839 {condition}
840 and ((voucher_type = 'Journal Entry'
Nabin Hait56548cb2016-07-01 15:58:39 +0530841 and (against_voucher = '' or against_voucher is null))
842 or (voucher_type not in ('Journal Entry', 'Payment Entry')))
Nabin Haita5cc84f2017-12-21 11:37:18 +0530843 group by voucher_type, voucher_no
Nabin Hait34c551d2019-07-03 10:34:31 +0530844 order by posting_date, name""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530845 dr_or_cr=dr_or_cr, condition=condition or ""
846 ),
847 {
Anand Doshid40d1e92015-11-12 17:05:29 +0530848 "party_type": party_type,
849 "party": party,
850 "account": account,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530851 },
852 as_dict=True,
853 )
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530854
Ankush Menat494bd9e2022-03-28 18:52:46 +0530855 payment_entries = frappe.db.sql(
856 """
Nabin Haitac184982019-02-04 21:13:43 +0530857 select against_voucher_type, against_voucher,
858 ifnull(sum({payment_dr_or_cr}), 0) as payment_amount
859 from `tabGL Entry`
860 where party_type = %(party_type)s and party = %(party)s
861 and account = %(account)s
862 and {payment_dr_or_cr} > 0
863 and against_voucher is not null and against_voucher != ''
aakvatech38ccf822020-10-03 19:41:38 +0300864 and is_cancelled=0
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530865 group by against_voucher_type, against_voucher
Ankush Menat494bd9e2022-03-28 18:52:46 +0530866 """.format(
867 payment_dr_or_cr=payment_dr_or_cr
868 ),
869 {"party_type": party_type, "party": party, "account": account},
870 as_dict=True,
871 )
tundec4b0d172017-09-26 00:48:30 +0100872
Nabin Haitac184982019-02-04 21:13:43 +0530873 pe_map = frappe._dict()
874 for d in payment_entries:
875 pe_map.setdefault((d.against_voucher_type, d.against_voucher), d.payment_amount)
876
877 for d in invoice_list:
878 payment_amount = pe_map.get((d.voucher_type, d.voucher_no), 0)
879 outstanding_amount = flt(d.invoice_amount - payment_amount, precision)
880 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530881 if (
882 filters
883 and filters.get("outstanding_amt_greater_than")
884 and not (
885 outstanding_amount >= filters.get("outstanding_amt_greater_than")
886 and outstanding_amount <= filters.get("outstanding_amt_less_than")
887 )
888 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530889 continue
Nabin Haitac184982019-02-04 21:13:43 +0530890
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530891 if not d.voucher_type == "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +0530892 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530893 frappe._dict(
894 {
895 "voucher_no": d.voucher_no,
896 "voucher_type": d.voucher_type,
897 "posting_date": d.posting_date,
898 "invoice_amount": flt(d.invoice_amount),
899 "payment_amount": payment_amount,
900 "outstanding_amount": outstanding_amount,
901 "due_date": d.due_date,
902 "currency": d.currency,
903 }
904 )
Nabin Haitac184982019-02-04 21:13:43 +0530905 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530906
Ankush Menat494bd9e2022-03-28 18:52:46 +0530907 outstanding_invoices = sorted(
908 outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
909 )
Anand Doshid40d1e92015-11-12 17:05:29 +0530910 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +0530911
912
Ankush Menat494bd9e2022-03-28 18:52:46 +0530913def get_account_name(
914 account_type=None, root_type=None, is_group=None, account_currency=None, company=None
915):
Saurabh3a268292016-02-22 15:18:40 +0530916 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530917 return frappe.db.get_value(
918 "Account",
919 {
920 "account_type": account_type or "",
921 "root_type": root_type or "",
922 "is_group": is_group or 0,
923 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
924 "company": company or frappe.defaults.get_defaults().company,
925 },
926 "name",
927 )
928
Saurabha9ba7342016-06-21 12:33:12 +0530929
930@frappe.whitelist()
931def get_companies():
932 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530933 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
934
Saurabha9ba7342016-06-21 12:33:12 +0530935
936@frappe.whitelist()
Rushabh Mehta43133262017-11-10 18:52:21 +0530937def get_children(doctype, parent, company, is_root=False):
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530938 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +0530939
Ankush Menat494bd9e2022-03-28 18:52:46 +0530940 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
941 fields = ["name as value", "is_group as expandable"]
942 filters = [["docstatus", "<", 2]]
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +0530943
Ankush Menat494bd9e2022-03-28 18:52:46 +0530944 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530945
Rushabh Mehta43133262017-11-10 18:52:21 +0530946 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530947 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
948 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530949
Saurabha9ba7342016-06-21 12:33:12 +0530950 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530951 fields += ["root_type", "account_currency"] if doctype == "Account" else []
952 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +0530953
954 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +0530955
Ankush Menat494bd9e2022-03-28 18:52:46 +0530956 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530957 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +0530958
959 return acc
Saurabhb835fef2016-09-09 11:19:22 +0530960
Ankush Menat494bd9e2022-03-28 18:52:46 +0530961
Saqib90517352021-10-04 11:44:46 +0530962@frappe.whitelist()
963def get_account_balances(accounts, company):
964
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530965 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +0530966 accounts = loads(accounts)
967
968 if not accounts:
969 return []
970
Ankush Menat494bd9e2022-03-28 18:52:46 +0530971 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +0530972
973 for account in accounts:
974 account["company_currency"] = company_currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530975 account["balance"] = flt(
976 get_balance_on(account["value"], in_account_currency=False, company=company)
977 )
Saqib90517352021-10-04 11:44:46 +0530978 if account["account_currency"] and account["account_currency"] != company_currency:
979 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
980
981 return accounts
982
Ankush Menat494bd9e2022-03-28 18:52:46 +0530983
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +0530984def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +0530985 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +0530986
987 company = frappe.db.get_value("Global Defaults", None, "default_company")
988 if not company:
989 return
990
991 # 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 +0530992 bank_account = frappe.db.get_value(
993 "Account",
994 {"account_name": _(gateway), "company": company},
995 ["name", "account_currency"],
996 as_dict=1,
997 )
Saurabhb835fef2016-09-09 11:19:22 +0530998
999 if not bank_account:
1000 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301001 bank_account = frappe.db.get_value(
1002 "Account",
1003 {"account_name": gateway, "company": company},
1004 ["name", "account_currency"],
1005 as_dict=1,
1006 )
Saurabhb835fef2016-09-09 11:19:22 +05301007
1008 if not bank_account:
1009 # try creating one
1010 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1011
1012 if not bank_account:
1013 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1014 return
1015
1016 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301017 if frappe.db.exists(
1018 "Payment Gateway Account",
1019 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1020 ):
Saurabhb835fef2016-09-09 11:19:22 +05301021 return
1022
1023 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301024 frappe.get_doc(
1025 {
1026 "doctype": "Payment Gateway Account",
1027 "is_default": 1,
1028 "payment_gateway": gateway,
1029 "payment_account": bank_account.name,
1030 "currency": bank_account.account_currency,
1031 "payment_channel": payment_channel,
1032 }
1033 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301034
1035 except frappe.DuplicateEntryError:
1036 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001037 pass
Zarrar44175902018-06-08 16:35:21 +05301038
Ankush Menat494bd9e2022-03-28 18:52:46 +05301039
Zarrar44175902018-06-08 16:35:21 +05301040@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301041def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301042 """
1043 Renames the document by adding the number as a prefix to the current name and updates
1044 all transaction where it was present.
1045 """
Saqiba8779872020-04-30 11:28:43 +05301046 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301047
Saqiba8779872020-04-30 11:28:43 +05301048 if cost_center_number:
1049 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1050 else:
1051 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301052
Saqiba8779872020-04-30 11:28:43 +05301053 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301054
Saqiba8779872020-04-30 11:28:43 +05301055 new_name = get_autoname_with_number(cost_center_number, cost_center_name, docname, company)
1056 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301057 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301058 return new_name
1059
Ankush Menat494bd9e2022-03-28 18:52:46 +05301060
Saqiba8779872020-04-30 11:28:43 +05301061def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301062 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301063 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301064 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301065 if company:
Saqiba8779872020-04-30 11:28:43 +05301066 filters["company"] = company
1067
1068 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1069
Zarrar44175902018-06-08 16:35:21 +05301070 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301071 frappe.throw(
1072 _("{0} Number {1} is already used in {2} {3}").format(
1073 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1074 )
1075 )
1076
Zarrar44175902018-06-08 16:35:21 +05301077
Zarrar17705f92018-07-06 14:44:44 +05301078def get_autoname_with_number(number_value, doc_title, name, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301079 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Zarrar88a90ff2018-06-11 11:21:17 +05301080 if name:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301081 name_split = name.split("-")
1082 parts = [doc_title.strip(), name_split[len(name_split) - 1].strip()]
Zarrar44175902018-06-08 16:35:21 +05301083 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301084 abbr = frappe.get_cached_value("Company", company, ["abbr"], as_dict=True)
Zarrar88a90ff2018-06-11 11:21:17 +05301085 parts = [doc_title.strip(), abbr.abbr]
Zlash651aeca1d2018-07-06 17:15:33 +05301086 if cstr(number_value).strip():
1087 parts.insert(0, cstr(number_value).strip())
Ankush Menat494bd9e2022-03-28 18:52:46 +05301088 return " - ".join(parts)
1089
Zarrar254ce642018-06-28 14:15:34 +05301090
1091@frappe.whitelist()
1092def get_coa(doctype, parent, is_root, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301093 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1094 build_tree_from_json,
1095 )
Zarrar254ce642018-06-28 14:15:34 +05301096
1097 # add chart to flags to retrieve when called from expand all function
1098 chart = chart if chart else frappe.flags.chart
1099 frappe.flags.chart = chart
1100
Ankush Menat494bd9e2022-03-28 18:52:46 +05301101 parent = None if parent == _("All Accounts") else parent
1102 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301103
1104 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301105 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301106
1107 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001108
Ankush Menat494bd9e2022-03-28 18:52:46 +05301109
1110def update_gl_entries_after(
1111 posting_date,
1112 posting_time,
1113 for_warehouses=None,
1114 for_items=None,
1115 warehouse_account=None,
1116 company=None,
1117):
1118 stock_vouchers = get_future_stock_vouchers(
1119 posting_date, posting_time, for_warehouses, for_items, company
1120 )
Nabin Hait9b178bc2021-02-16 14:57:00 +05301121 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1122
1123
Ankush Menat494bd9e2022-03-28 18:52:46 +05301124def repost_gle_for_stock_vouchers(
1125 stock_vouchers, posting_date, company=None, warehouse_account=None
1126):
Ankush Menat700e8642022-04-19 13:24:29 +05301127 if not stock_vouchers:
1128 return
1129
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301130 def _delete_gl_entries(voucher_type, voucher_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301131 frappe.db.sql(
1132 """delete from `tabGL Entry`
1133 where voucher_type=%s and voucher_no=%s""",
1134 (voucher_type, voucher_no),
1135 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301136
Ankush Menat700e8642022-04-19 13:24:29 +05301137 stock_vouchers = sort_stock_vouchers_by_posting_date(stock_vouchers)
1138
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301139 if not warehouse_account:
1140 warehouse_account = get_warehouse_account_map(company)
1141
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301142 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1143
Nabin Hait9b178bc2021-02-16 14:57:00 +05301144 gle = get_voucherwise_gl_entries(stock_vouchers, posting_date)
Nabin Hait9b178bc2021-02-16 14:57:00 +05301145 for voucher_type, voucher_no in stock_vouchers:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301146 existing_gle = gle.get((voucher_type, voucher_no), [])
Nabin Hait19f8fa52021-02-22 22:27:22 +05301147 voucher_obj = frappe.get_cached_doc(voucher_type, voucher_no)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301148 expected_gle = voucher_obj.get_gl_entries(warehouse_account)
1149 if expected_gle:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301150 if not existing_gle or not compare_existing_and_expected_gle(
1151 existing_gle, expected_gle, precision
1152 ):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301153 _delete_gl_entries(voucher_type, voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +05301154 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301155 else:
1156 _delete_gl_entries(voucher_type, voucher_no)
1157
Ankush Menat494bd9e2022-03-28 18:52:46 +05301158
Ankush Menat700e8642022-04-19 13:24:29 +05301159def sort_stock_vouchers_by_posting_date(
1160 stock_vouchers: List[Tuple[str, str]]
1161) -> List[Tuple[str, str]]:
1162 sle = frappe.qb.DocType("Stock Ledger Entry")
1163 voucher_nos = [v[1] for v in stock_vouchers]
1164
1165 sles = (
1166 frappe.qb.from_(sle)
1167 .select(sle.voucher_type, sle.voucher_no, sle.posting_date, sle.posting_time, sle.creation)
1168 .where((sle.is_cancelled == 0) & (sle.voucher_no.isin(voucher_nos)))
1169 .groupby(sle.voucher_type, sle.voucher_no)
1170 ).run(as_dict=True)
1171 sorted_vouchers = [(sle.voucher_type, sle.voucher_no) for sle in sles]
1172
1173 unknown_vouchers = set(stock_vouchers) - set(sorted_vouchers)
1174 if unknown_vouchers:
1175 sorted_vouchers.extend(unknown_vouchers)
1176
1177 return sorted_vouchers
1178
1179
Ankush Menat494bd9e2022-03-28 18:52:46 +05301180def get_future_stock_vouchers(
1181 posting_date, posting_time, for_warehouses=None, for_items=None, company=None
1182):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301183
1184 values = []
1185 condition = ""
1186 if for_items:
1187 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1188 values += for_items
1189
1190 if for_warehouses:
1191 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1192 values += for_warehouses
1193
rohitwaghchaured60ff832021-02-16 09:12:27 +05301194 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301195 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301196 values.append(company)
1197
Ankush Menat494bd9e2022-03-28 18:52:46 +05301198 future_stock_vouchers = frappe.db.sql(
1199 """select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301200 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301201 where
1202 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1203 and is_cancelled = 0
1204 {condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301205 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
1206 condition=condition
1207 ),
1208 tuple([posting_date, posting_time] + values),
1209 as_dict=True,
1210 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301211
Ankush91527152021-08-11 11:17:50 +05301212 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301213
Ankush Menat494bd9e2022-03-28 18:52:46 +05301214
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301215def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301216 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301217
1218 Only fetches GLE fields required for comparing with new GLE.
1219 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301220
1221 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301222 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301223 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301224 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301225 if not future_stock_vouchers:
1226 return gl_entries
1227
1228 voucher_nos = [d[1] for d in future_stock_vouchers]
1229
Ankush Menat494bd9e2022-03-28 18:52:46 +05301230 gles = frappe.db.sql(
1231 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301232 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301233 from `tabGL Entry`
1234 where
Ankush Menat494bd9e2022-03-28 18:52:46 +05301235 posting_date >= %s and voucher_no in (%s)"""
1236 % ("%s", ", ".join(["%s"] * len(voucher_nos))),
1237 tuple([posting_date] + voucher_nos),
1238 as_dict=1,
1239 )
Ankush91527152021-08-11 11:17:50 +05301240
1241 for d in gles:
1242 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301243
Prssanna Desai82ddef52020-06-18 18:18:41 +05301244 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301245
Ankush Menat494bd9e2022-03-28 18:52:46 +05301246
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301247def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301248 if len(existing_gle) != len(expected_gle):
1249 return False
1250
Nabin Haita77b8c92020-12-21 14:45:50 +05301251 matched = True
1252 for entry in expected_gle:
1253 account_existed = False
1254 for e in existing_gle:
1255 if entry.account == e.account:
1256 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301257 if (
1258 entry.account == e.account
1259 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1260 and (
1261 flt(entry.debit, precision) != flt(e.debit, precision)
1262 or flt(entry.credit, precision) != flt(e.credit, precision)
1263 )
1264 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301265 matched = False
1266 break
1267 if not account_existed:
1268 matched = False
1269 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301270 return matched
1271
Ankush Menat494bd9e2022-03-28 18:52:46 +05301272
Nabin Haitb99c77b2020-12-25 18:12:35 +05301273def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301274 stock_accounts = [
1275 d.name
1276 for d in frappe.db.get_all(
1277 "Account", {"account_type": "Stock", "company": company, "is_group": 0}
1278 )
1279 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301280 if voucher_type and voucher_no:
1281 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301282 stock_accounts = [
1283 d.account
1284 for d in frappe.db.get_all(
1285 "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
1286 )
1287 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301288
1289 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301290 stock_accounts = [
1291 d.account
1292 for d in frappe.db.get_all(
1293 "GL Entry",
1294 {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
1295 "account",
1296 )
1297 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301298
1299 return stock_accounts
1300
Ankush Menat494bd9e2022-03-28 18:52:46 +05301301
Nabin Haitb99c77b2020-12-25 18:12:35 +05301302def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301303 if not posting_date:
1304 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301305
1306 warehouse_account = get_warehouse_account_map(company)
1307
Ankush Menat494bd9e2022-03-28 18:52:46 +05301308 account_balance = get_balance_on(
1309 account, posting_date, in_account_currency=False, ignore_account_permission=True
1310 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301311
Ankush Menat494bd9e2022-03-28 18:52:46 +05301312 related_warehouses = [
1313 wh
1314 for wh, wh_details in warehouse_account.items()
1315 if wh_details.account == account and not wh_details.is_group
1316 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301317
1318 total_stock_value = 0.0
1319 for warehouse in related_warehouses:
1320 value = get_stock_value_on(warehouse, posting_date)
1321 total_stock_value += value
1322
1323 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1324 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1325
Ankush Menat494bd9e2022-03-28 18:52:46 +05301326
Nabin Haitb99c77b2020-12-25 18:12:35 +05301327def get_journal_entry(account, stock_adjustment_account, amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301328 db_or_cr_warehouse_account = (
1329 "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
1330 )
1331 db_or_cr_stock_adjustment_account = (
1332 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1333 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301334
1335 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301336 "accounts": [
1337 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1338 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1339 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301340 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301341
Ankush Menat494bd9e2022-03-28 18:52:46 +05301342
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301343def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301344 """Check if reports are referenced in Desktop Icon"""
1345 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301346 if icons:
1347 for icon in icons:
1348 frappe.delete_doc("Desktop Icon", icon)
ruthra kumar451cf3a2022-05-16 14:29:58 +05301349
1350
1351def create_payment_ledger_entry(gl_entries, cancel=0):
1352 if gl_entries:
1353 ple = None
1354
1355 # companies
1356 account = qb.DocType("Account")
1357 companies = list(set([x.company for x in gl_entries]))
1358
1359 # receivable/payable account
1360 accounts_with_types = (
1361 qb.from_(account)
1362 .select(account.name, account.account_type)
1363 .where(
1364 (account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
1365 )
1366 .run(as_dict=True)
1367 )
1368 receivable_or_payable_accounts = [y.name for y in accounts_with_types]
1369
1370 def get_account_type(account):
1371 for entry in accounts_with_types:
1372 if entry.name == account:
1373 return entry.account_type
1374
1375 dr_or_cr = 0
1376 account_type = None
1377 for gle in gl_entries:
1378 if gle.account in receivable_or_payable_accounts:
1379 account_type = get_account_type(gle.account)
1380 if account_type == "Receivable":
1381 dr_or_cr = gle.debit - gle.credit
1382 dr_or_cr_account_currency = gle.debit_in_account_currency - gle.credit_in_account_currency
1383 elif account_type == "Payable":
1384 dr_or_cr = gle.credit - gle.debit
1385 dr_or_cr_account_currency = gle.credit_in_account_currency - gle.debit_in_account_currency
1386
1387 if cancel:
1388 dr_or_cr *= -1
1389 dr_or_cr_account_currency *= -1
1390
1391 ple = frappe.get_doc(
1392 {
1393 "doctype": "Payment Ledger Entry",
1394 "posting_date": gle.posting_date,
1395 "company": gle.company,
1396 "account_type": account_type,
1397 "account": gle.account,
1398 "party_type": gle.party_type,
1399 "party": gle.party,
1400 "cost_center": gle.cost_center,
1401 "finance_book": gle.finance_book,
1402 "due_date": gle.due_date,
1403 "voucher_type": gle.voucher_type,
1404 "voucher_no": gle.voucher_no,
1405 "against_voucher_type": gle.against_voucher_type
1406 if gle.against_voucher_type
1407 else gle.voucher_type,
1408 "against_voucher_no": gle.against_voucher if gle.against_voucher else gle.voucher_no,
1409 "currency": gle.currency,
1410 "amount": dr_or_cr,
1411 "amount_in_account_currency": dr_or_cr_account_currency,
1412 "delinked": True if cancel else False,
1413 }
1414 )
1415
1416 dimensions_and_defaults = get_dimensions()
1417 if dimensions_and_defaults:
1418 for dimension in dimensions_and_defaults[0]:
1419 ple.set(dimension.fieldname, gle.get(dimension.fieldname))
1420
1421 if cancel:
1422 delink_original_entry(ple)
1423 ple.flags.ignore_permissions = 1
1424 ple.submit()
1425
1426
1427def delink_original_entry(pl_entry):
1428 if pl_entry:
1429 ple = qb.DocType("Payment Ledger Entry")
1430 query = (
1431 qb.update(ple)
1432 .set(ple.delinked, True)
1433 .set(ple.modified, now())
1434 .set(ple.modified_by, frappe.session.user)
1435 .where(
1436 (ple.company == pl_entry.company)
1437 & (ple.account_type == pl_entry.account_type)
1438 & (ple.account == pl_entry.account)
1439 & (ple.party_type == pl_entry.party_type)
1440 & (ple.party == pl_entry.party)
1441 & (ple.voucher_type == pl_entry.voucher_type)
1442 & (ple.voucher_no == pl_entry.voucher_no)
1443 & (ple.against_voucher_type == pl_entry.against_voucher_type)
1444 & (ple.against_voucher_no == pl_entry.against_voucher_no)
1445 )
1446 )
1447 query.run()