blob: d17207a70ae5a284b4d24a893d1831324bcd2f9a [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
6
Chillar Anand915b3432021-09-02 16:44:59 +05307import frappe
Nabin Hait9b20e072017-04-25 12:10:24 +05308import frappe.defaults
Chillar Anand915b3432021-09-02 16:44:59 +05309from frappe import _, throw
Nabin Haitb99c77b2020-12-25 18:12:35 +053010from frappe.model.meta import get_field_precision
Chillar Anand915b3432021-09-02 16:44:59 +053011from frappe.utils import cint, cstr, flt, formatdate, get_number_format_info, getdate, now, nowdate
Anand Doshicd0989e2015-09-28 13:31:17 +053012
Chillar Anand915b3432021-09-02 16:44:59 +053013import erpnext
14
15# imported to enable erpnext.accounts.utils.get_account_currency
16from erpnext.accounts.doctype.account.account import get_account_currency # noqa
Anurag Mishraa11e7382019-10-31 15:55:03 +053017from erpnext.stock import get_warehouse_account_map
Chillar Anand915b3432021-09-02 16:44:59 +053018from erpnext.stock.utils import get_stock_value_on
19
Anurag Mishraa11e7382019-10-31 15:55:03 +053020
Ankush Menat494bd9e2022-03-28 18:52:46 +053021class StockValueAndAccountBalanceOutOfSync(frappe.ValidationError):
22 pass
23
24
25class FiscalYearError(frappe.ValidationError):
26 pass
27
28
29class PaymentEntryUnlinkError(frappe.ValidationError):
30 pass
31
Nabin Hait2b06aaa2013-08-22 18:25:43 +053032
Neil Trini Lasrado78fa6952014-10-03 17:43:02 +053033@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +053034def get_fiscal_year(
35 date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False
36):
Anand Doshic75c1d72016-03-11 14:56:19 +053037 return get_fiscal_years(date, fiscal_year, label, verbose, company, as_dict=as_dict)[0]
Nabin Hait23941aa2013-01-29 11:32:38 +053038
Ankush Menat494bd9e2022-03-28 18:52:46 +053039
40def get_fiscal_years(
41 transaction_date=None, fiscal_year=None, label="Date", verbose=1, company=None, as_dict=False
42):
Nabin Hait9784d272016-12-30 16:21:35 +053043 fiscal_years = frappe.cache().hget("fiscal_years", company) or []
Rushabh Mehtad50da782017-07-28 11:39:01 +053044
45 if not fiscal_years:
Nabin Hait9784d272016-12-30 16:21:35 +053046 # if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
47 cond = ""
48 if fiscal_year:
49 cond += " and fy.name = {0}".format(frappe.db.escape(fiscal_year))
50 if company:
51 cond += """
Rushabh Mehtad50da782017-07-28 11:39:01 +053052 and (not exists (select name
53 from `tabFiscal Year Company` fyc
54 where fyc.parent = fy.name)
55 or exists(select company
56 from `tabFiscal Year Company` fyc
57 where fyc.parent = fy.name
Nabin Hait9784d272016-12-30 16:21:35 +053058 and fyc.company=%(company)s)
59 )
60 """
Nabin Haitfff3ab72015-01-14 16:27:13 +053061
Ankush Menat494bd9e2022-03-28 18:52:46 +053062 fiscal_years = frappe.db.sql(
63 """
Rushabh Mehtad50da782017-07-28 11:39:01 +053064 select
65 fy.name, fy.year_start_date, fy.year_end_date
66 from
Nabin Hait9784d272016-12-30 16:21:35 +053067 `tabFiscal Year` fy
Rushabh Mehtad50da782017-07-28 11:39:01 +053068 where
Nabin Hait9784d272016-12-30 16:21:35 +053069 disabled = 0 {0}
Rushabh Mehtad50da782017-07-28 11:39:01 +053070 order by
Ankush Menat494bd9e2022-03-28 18:52:46 +053071 fy.year_start_date desc""".format(
72 cond
73 ),
74 {"company": company},
75 as_dict=True,
76 )
Rushabh Mehtad50da782017-07-28 11:39:01 +053077
Nabin Hait9784d272016-12-30 16:21:35 +053078 frappe.cache().hset("fiscal_years", company, fiscal_years)
Nabin Haitfff3ab72015-01-14 16:27:13 +053079
Prssanna Desai82ddef52020-06-18 18:18:41 +053080 if not transaction_date and not fiscal_year:
81 return fiscal_years
82
Nabin Hait9784d272016-12-30 16:21:35 +053083 if transaction_date:
84 transaction_date = getdate(transaction_date)
Anand Doshicd71e1d2014-04-08 13:53:35 +053085
Nabin Hait9784d272016-12-30 16:21:35 +053086 for fy in fiscal_years:
87 matched = False
88 if fiscal_year and fy.name == fiscal_year:
89 matched = True
Anand Doshicd71e1d2014-04-08 13:53:35 +053090
Ankush Menat494bd9e2022-03-28 18:52:46 +053091 if (
92 transaction_date
93 and getdate(fy.year_start_date) <= transaction_date
94 and getdate(fy.year_end_date) >= transaction_date
95 ):
Nabin Hait9784d272016-12-30 16:21:35 +053096 matched = True
Rushabh Mehtad50da782017-07-28 11:39:01 +053097
Nabin Hait9784d272016-12-30 16:21:35 +053098 if matched:
99 if as_dict:
100 return (fy,)
101 else:
102 return ((fy.name, fy.year_start_date, fy.year_end_date),)
103
Ankush Menat494bd9e2022-03-28 18:52:46 +0530104 error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(
105 label, formatdate(transaction_date)
106 )
Anuja P2e4faf92020-12-05 13:36:43 +0530107 if company:
Anuja P550cb9c2020-12-07 11:11:00 +0530108 error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company))
rohitwaghchaured60ff832021-02-16 09:12:27 +0530109
Ankush Menat494bd9e2022-03-28 18:52:46 +0530110 if verbose == 1:
111 frappe.msgprint(error_msg)
cclauss68487082017-07-27 07:08:35 +0200112 raise FiscalYearError(error_msg)
Nabin Hait9784d272016-12-30 16:21:35 +0530113
Ankush Menat494bd9e2022-03-28 18:52:46 +0530114
Prssanna Desai82ddef52020-06-18 18:18:41 +0530115@frappe.whitelist()
116def get_fiscal_year_filter_field(company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530117 field = {"fieldtype": "Select", "options": [], "operator": "Between", "query_value": True}
Prssanna Desai82ddef52020-06-18 18:18:41 +0530118 fiscal_years = get_fiscal_years(company=company)
119 for fiscal_year in fiscal_years:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530120 field["options"].append(
121 {
122 "label": fiscal_year.name,
123 "value": fiscal_year.name,
124 "query_value": [
125 fiscal_year.year_start_date.strftime("%Y-%m-%d"),
126 fiscal_year.year_end_date.strftime("%Y-%m-%d"),
127 ],
128 }
129 )
Prssanna Desai82ddef52020-06-18 18:18:41 +0530130 return field
131
Ankush Menat494bd9e2022-03-28 18:52:46 +0530132
Nabin Hait8bf58362017-03-27 12:30:01 +0530133def validate_fiscal_year(date, fiscal_year, company, label="Date", doc=None):
134 years = [f[0] for f in get_fiscal_years(date, label=_(label), company=company)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +0530135 if fiscal_year not in years:
Rushabh Mehtad60acb92015-02-19 14:51:58 +0530136 if doc:
137 doc.fiscal_year = years[0]
138 else:
139 throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
Nabin Hait23941aa2013-01-29 11:32:38 +0530140
Ankush Menat494bd9e2022-03-28 18:52:46 +0530141
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530142@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530143def get_balance_on(
144 account=None,
145 date=None,
146 party_type=None,
147 party=None,
148 company=None,
149 in_account_currency=True,
150 cost_center=None,
151 ignore_account_permission=False,
152):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530153 if not account and frappe.form_dict.get("account"):
154 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530155 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530156 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +0530157 if not party_type and frappe.form_dict.get("party_type"):
158 party_type = frappe.form_dict.get("party_type")
159 if not party and frappe.form_dict.get("party"):
160 party = frappe.form_dict.get("party")
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400161 if not cost_center and frappe.form_dict.get("cost_center"):
162 cost_center = frappe.form_dict.get("cost_center")
163
Nabin Hait98372852020-07-30 20:52:20 +0530164 cond = ["is_cancelled=0"]
Nabin Hait23941aa2013-01-29 11:32:38 +0530165 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530166 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
Nabin Hait23941aa2013-01-29 11:32:38 +0530167 else:
168 # get balance of all entries that exist
169 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530170
Deepesh Garg8c217032019-07-16 09:41:01 +0530171 if account:
172 acc = frappe.get_doc("Account", account)
173
Nabin Hait23941aa2013-01-29 11:32:38 +0530174 try:
Deepesh Garg96d40ec2020-07-03 22:59:00 +0530175 year_start_date = get_fiscal_year(date, company=company, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530176 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +0530177 if getdate(date) > getdate(nowdate()):
178 # if fiscal year not found and the date is greater than today
179 # get fiscal year for today's date and its corresponding year start date
180 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
181 else:
182 # this indicates that it is a date older than any existing fiscal year.
183 # hence, assuming balance as 0.0
184 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530185
deepeshgarg0072ddbebf2019-07-20 14:52:59 +0530186 if account:
deepeshgarg007e097d4f2019-07-20 14:49:32 +0530187 report_type = acc.report_type
deepeshgarg0071ee3d042019-07-20 14:46:59 +0530188 else:
189 report_type = ""
190
Ankush Menat494bd9e2022-03-28 18:52:46 +0530191 if cost_center and report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400192 cc = frappe.get_doc("Cost Center", cost_center)
193 if cc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530194 cond.append(
195 """ exists (
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400196 select 1 from `tabCost Center` cc where cc.name = gle.cost_center
197 and cc.lft >= %s and cc.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530198 )"""
199 % (cc.lft, cc.rgt)
200 )
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400201
202 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530203 cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center, percent=False),))
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400204
Nabin Hait6f17cf92014-09-17 14:11:22 +0530205 if account:
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400206
Ankush Menat494bd9e2022-03-28 18:52:46 +0530207 if not (frappe.flags.ignore_account_permission or ignore_account_permission):
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530208 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530209
Ankush Menat494bd9e2022-03-28 18:52:46 +0530210 if report_type == "Profit and Loss":
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +0400211 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530212 cond.append(
213 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
214 )
Nabin Hait6f17cf92014-09-17 14:11:22 +0530215 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +0530216 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530217 cond.append(
218 """exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +0530219 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +0530220 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530221 )"""
222 % (acc.lft, acc.rgt)
223 )
Anand Doshicd0989e2015-09-28 13:31:17 +0530224
225 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530226 # always return balance based on debit and credit in company currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530227 if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
Nabin Hait59f4fa92015-09-17 13:57:42 +0530228 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530229 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530230 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
Anand Doshic75c1d72016-03-11 14:56:19 +0530231
Nabin Hait6f17cf92014-09-17 14:11:22 +0530232 if party_type and party:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 cond.append(
234 """gle.party_type = %s and gle.party = %s """
235 % (frappe.db.escape(party_type), frappe.db.escape(party, percent=False))
236 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530237
Nabin Hait85648d92016-07-20 11:26:45 +0530238 if company:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530239 cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530240
Nabin Haitdc768232015-08-17 11:27:00 +0530241 if account or (party_type and party):
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530242 if in_account_currency:
Anand Doshi602e8252015-11-16 19:05:46 +0530243 select_field = "sum(debit_in_account_currency) - sum(credit_in_account_currency)"
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530244 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530245 select_field = "sum(debit) - sum(credit)"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530246 bal = frappe.db.sql(
247 """
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530248 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530249 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530250 WHERE {1}""".format(
251 select_field, " and ".join(cond)
252 )
253 )[0][0]
Anand Doshicd71e1d2014-04-08 13:53:35 +0530254
Nabin Haitdc768232015-08-17 11:27:00 +0530255 # if bal is None, return 0
256 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530257
Ankush Menat494bd9e2022-03-28 18:52:46 +0530258
RobertSchouten8d43b322016-09-20 13:41:39 +0800259def get_count_on(account, fieldname, date):
Nabin Hait98372852020-07-30 20:52:20 +0530260 cond = ["is_cancelled=0"]
RobertSchouten8d43b322016-09-20 13:41:39 +0800261 if date:
Suraj Shettybfc195d2018-09-21 10:20:52 +0530262 cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
RobertSchouten8d43b322016-09-20 13:41:39 +0800263 else:
264 # get balance of all entries that exist
265 date = nowdate()
266
267 try:
268 year_start_date = get_fiscal_year(date, verbose=0)[1]
269 except FiscalYearError:
270 if getdate(date) > getdate(nowdate()):
271 # if fiscal year not found and the date is greater than today
272 # get fiscal year for today's date and its corresponding year start date
273 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
274 else:
275 # this indicates that it is a date older than any existing fiscal year.
276 # hence, assuming balance as 0.0
277 return 0.0
278
279 if account:
280 acc = frappe.get_doc("Account", account)
281
282 if not frappe.flags.ignore_account_permission:
283 acc.check_permission("read")
284
285 # for pl accounts, get balance within a fiscal year
Ankush Menat494bd9e2022-03-28 18:52:46 +0530286 if acc.report_type == "Profit and Loss":
287 cond.append(
288 "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
289 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800290
291 # different filter for group and ledger - improved performance
292 if acc.is_group:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530293 cond.append(
294 """exists (
RobertSchouten8d43b322016-09-20 13:41:39 +0800295 select name from `tabAccount` ac where ac.name = gle.account
296 and ac.lft >= %s and ac.rgt <= %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530297 )"""
298 % (acc.lft, acc.rgt)
299 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800300 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530301 cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),))
RobertSchouten8d43b322016-09-20 13:41:39 +0800302
Ankush Menat494bd9e2022-03-28 18:52:46 +0530303 entries = frappe.db.sql(
304 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800305 SELECT name, posting_date, account, party_type, party,debit,credit,
306 voucher_type, voucher_no, against_voucher_type, against_voucher
307 FROM `tabGL Entry` gle
Ankush Menat494bd9e2022-03-28 18:52:46 +0530308 WHERE {0}""".format(
309 " and ".join(cond)
310 ),
311 as_dict=True,
312 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530313
RobertSchouten8d43b322016-09-20 13:41:39 +0800314 count = 0
315 for gle in entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530316 if fieldname not in ("invoiced_amount", "payables"):
RobertSchouten8d43b322016-09-20 13:41:39 +0800317 count += 1
318 else:
319 dr_or_cr = "debit" if fieldname == "invoiced_amount" else "credit"
320 cr_or_dr = "credit" if fieldname == "invoiced_amount" else "debit"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530321 select_fields = (
322 "ifnull(sum(credit-debit),0)"
323 if fieldname == "invoiced_amount"
324 else "ifnull(sum(debit-credit),0)"
325 )
RobertSchouten8d43b322016-09-20 13:41:39 +0800326
Ankush Menat494bd9e2022-03-28 18:52:46 +0530327 if (
328 (not gle.against_voucher)
329 or (gle.against_voucher_type in ["Sales Order", "Purchase Order"])
330 or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
331 ):
332 payment_amount = frappe.db.sql(
333 """
RobertSchouten8d43b322016-09-20 13:41:39 +0800334 SELECT {0}
335 FROM `tabGL Entry` gle
336 WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530337 and party = %(party)s and name != %(name)s""".format(
338 select_fields
339 ),
340 {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
341 )[0][0]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530342
RobertSchouten8d43b322016-09-20 13:41:39 +0800343 outstanding_amount = flt(gle.get(dr_or_cr)) - flt(gle.get(cr_or_dr)) - payment_amount
344 currency_precision = get_currency_precision() or 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530345 if abs(flt(outstanding_amount)) > 0.1 / 10**currency_precision:
RobertSchouten8d43b322016-09-20 13:41:39 +0800346 count += 1
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530347
RobertSchouten8d43b322016-09-20 13:41:39 +0800348 return count
349
Ankush Menat494bd9e2022-03-28 18:52:46 +0530350
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530351@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530352def add_ac(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530353 from frappe.desk.treeview import make_tree_args
354
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530355 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530356 args = frappe.local.form_dict
Saurabh2f021012017-01-11 12:41:01 +0530357
Nabin Hait02d987e2017-02-17 15:50:26 +0530358 args.doctype = "Account"
Saurabh2f021012017-01-11 12:41:01 +0530359 args = make_tree_args(**args)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530360
Anand Doshi3e41fd12014-04-22 18:54:54 +0530361 ac = frappe.new_doc("Account")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530362
Nabin Hait665568d2016-05-13 15:56:00 +0530363 if args.get("ignore_permissions"):
364 ac.flags.ignore_permissions = True
365 args.pop("ignore_permissions")
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530366
Anand Doshi3e41fd12014-04-22 18:54:54 +0530367 ac.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530368
369 if not ac.parent_account:
370 ac.parent_account = args.get("parent")
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530371
Anand Doshif78d1ae2014-03-28 13:55:00 +0530372 ac.old_parent = ""
373 ac.freeze_account = "No"
Nabin Haita1ec7f12016-05-11 12:37:22 +0530374 if cint(ac.get("is_root")):
375 ac.parent_account = None
Rushabh Mehta0dcb8612016-05-31 07:22:37 +0530376 ac.flags.ignore_mandatory = True
377
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530378 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530379
Anand Doshif78d1ae2014-03-28 13:55:00 +0530380 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530381
Ankush Menat494bd9e2022-03-28 18:52:46 +0530382
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530383@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530384def add_cc(args=None):
Saurabh2f021012017-01-11 12:41:01 +0530385 from frappe.desk.treeview import make_tree_args
386
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530387 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530388 args = frappe.local.form_dict
Rushabh Mehtad50da782017-07-28 11:39:01 +0530389
Nabin Hait02d987e2017-02-17 15:50:26 +0530390 args.doctype = "Cost Center"
Saurabh2f021012017-01-11 12:41:01 +0530391 args = make_tree_args(**args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530392
Zarrar7ab70ca2018-06-08 14:33:15 +0530393 if args.parent_cost_center == args.company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530394 args.parent_cost_center = "{0} - {1}".format(
395 args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
396 )
Zarrar7ab70ca2018-06-08 14:33:15 +0530397
Anand Doshi3e41fd12014-04-22 18:54:54 +0530398 cc = frappe.new_doc("Cost Center")
399 cc.update(args)
Saurabh0e47bfe2016-05-30 17:54:16 +0530400
401 if not cc.parent_cost_center:
402 cc.parent_cost_center = args.get("parent")
403
Anand Doshif78d1ae2014-03-28 13:55:00 +0530404 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530405 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530406 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530407
Ankush Menat494bd9e2022-03-28 18:52:46 +0530408
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530409def reconcile_against_document(args):
410 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530411 Cancel PE or JV, Update against document, split if required and resubmit
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530412 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530413 # To optimize making GL Entry for PE or JV with multiple references
414 reconciled_entries = {}
415 for row in args:
416 if not reconciled_entries.get((row.voucher_type, row.voucher_no)):
417 reconciled_entries[(row.voucher_type, row.voucher_no)] = []
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530418
Anuja Pawar3e404f12021-08-31 18:59:29 +0530419 reconciled_entries[(row.voucher_type, row.voucher_no)].append(row)
420
421 for key, entries in reconciled_entries.items():
422 voucher_type = key[0]
423 voucher_no = key[1]
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530424
Nabin Hait28a05282016-06-27 17:41:39 +0530425 # cancel advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530426 doc = frappe.get_doc(voucher_type, voucher_no)
Subin Tomb8845b92021-07-30 16:30:18 +0530427 frappe.flags.ignore_party_validation = True
Nabin Hait28a05282016-06-27 17:41:39 +0530428 doc.make_gl_entries(cancel=1, adv_adj=1)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530429
Anuja Pawar3e404f12021-08-31 18:59:29 +0530430 for entry in entries:
431 check_if_advance_entry_modified(entry)
432 validate_allocated_amount(entry)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530433
Anuja Pawar3e404f12021-08-31 18:59:29 +0530434 # update ref in advance entry
435 if voucher_type == "Journal Entry":
436 update_reference_in_journal_entry(entry, doc, do_not_save=True)
437 else:
438 update_reference_in_payment_entry(entry, doc, do_not_save=True)
439
440 doc.save(ignore_permissions=True)
Nabin Hait28a05282016-06-27 17:41:39 +0530441 # re-submit advance entry
Anuja Pawar3e404f12021-08-31 18:59:29 +0530442 doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530443 doc.make_gl_entries(cancel=0, adv_adj=1)
Subin Tomb8845b92021-07-30 16:30:18 +0530444 frappe.flags.ignore_party_validation = False
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530445
Ankush Menat494bd9e2022-03-28 18:52:46 +0530446 if entry.voucher_type in ("Payment Entry", "Journal Entry"):
Nabin Hait5cd04a62019-05-27 11:44:06 +0530447 doc.update_expense_claim()
448
Ankush Menat494bd9e2022-03-28 18:52:46 +0530449
Nabin Hait28a05282016-06-27 17:41:39 +0530450def check_if_advance_entry_modified(args):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530451 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530452 check if there is already a voucher reference
453 check if amount is same
454 check if jv is submitted
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530455 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530456 if not args.get("unreconciled_amount"):
457 args.update({"unreconciled_amount": args.get("unadjusted_amount")})
Anuja Pawar3e404f12021-08-31 18:59:29 +0530458
Nabin Hait28a05282016-06-27 17:41:39 +0530459 ret = None
460 if args.voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530461 ret = frappe.db.sql(
462 """
Nabin Hait28a05282016-06-27 17:41:39 +0530463 select t2.{dr_or_cr} from `tabJournal Entry` t1, `tabJournal Entry Account` t2
464 where t1.name = t2.parent and t2.account = %(account)s
465 and t2.party_type = %(party_type)s and t2.party = %(party)s
466 and (t2.reference_type is null or t2.reference_type in ("", "Sales Order", "Purchase Order"))
467 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530468 and t1.docstatus=1 """.format(
469 dr_or_cr=args.get("dr_or_cr")
470 ),
471 args,
472 )
Nabin Hait28a05282016-06-27 17:41:39 +0530473 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530474 party_account_field = (
475 "paid_from" if erpnext.get_party_account_type(args.party_type) == "Receivable" else "paid_to"
476 )
rohitwaghchauree8358f32018-05-16 11:02:26 +0530477
Nabin Hait28a05282016-06-27 17:41:39 +0530478 if args.voucher_detail_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530479 ret = frappe.db.sql(
480 """select t1.name
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530481 from `tabPayment Entry` t1, `tabPayment Entry Reference` t2
Nabin Hait28a05282016-06-27 17:41:39 +0530482 where
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530483 t1.name = t2.parent and t1.docstatus = 1
Nabin Hait28a05282016-06-27 17:41:39 +0530484 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
485 and t1.party_type = %(party_type)s and t1.party = %(party)s and t1.{0} = %(account)s
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530486 and t2.reference_doctype in ("", "Sales Order", "Purchase Order")
Anuja Pawar3e404f12021-08-31 18:59:29 +0530487 and t2.allocated_amount = %(unreconciled_amount)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530488 """.format(
489 party_account_field
490 ),
491 args,
492 )
Nabin Hait28a05282016-06-27 17:41:39 +0530493 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530494 ret = frappe.db.sql(
495 """select name from `tabPayment Entry`
Nabin Hait28a05282016-06-27 17:41:39 +0530496 where
497 name = %(voucher_no)s and docstatus = 1
498 and party_type = %(party_type)s and party = %(party)s and {0} = %(account)s
Anuja Pawar3e404f12021-08-31 18:59:29 +0530499 and unallocated_amount = %(unreconciled_amount)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530500 """.format(
501 party_account_field
502 ),
503 args,
504 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530505
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530506 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530507 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530508
Ankush Menat494bd9e2022-03-28 18:52:46 +0530509
Nabin Hait576f0252014-04-30 19:30:50 +0530510def validate_allocated_amount(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530511 precision = args.get("precision") or frappe.db.get_single_value(
512 "System Settings", "currency_precision"
513 )
Nabin Hait28a05282016-06-27 17:41:39 +0530514 if args.get("allocated_amount") < 0:
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530515 throw(_("Allocated amount cannot be negative"))
Deepesh Gargf54d5962021-03-31 14:06:02 +0530516 elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
Kenneth Sequeiraa29ed402019-05-27 11:47:07 +0530517 throw(_("Allocated amount cannot be greater than unadjusted amount"))
Nabin Hait576f0252014-04-30 19:30:50 +0530518
Ankush Menat494bd9e2022-03-28 18:52:46 +0530519
Anuja Pawar3e404f12021-08-31 18:59:29 +0530520def update_reference_in_journal_entry(d, journal_entry, do_not_save=False):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530521 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530522 Updates against document, if partial amount splits into rows
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530523 """
Anuja Pawar3e404f12021-08-31 18:59:29 +0530524 jv_detail = journal_entry.get("accounts", {"name": d["voucher_detail_no"]})[0]
Rushabh Mehta1828c122015-08-10 17:04:07 +0530525
Ankush Menat494bd9e2022-03-28 18:52:46 +0530526 if flt(d["unadjusted_amount"]) - flt(d["allocated_amount"]) != 0:
Anuja Pawar3e404f12021-08-31 18:59:29 +0530527 # adjust the unreconciled balance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530528 amount_in_account_currency = flt(d["unadjusted_amount"]) - flt(d["allocated_amount"])
Anuja Pawar3e404f12021-08-31 18:59:29 +0530529 amount_in_company_currency = amount_in_account_currency * flt(jv_detail.exchange_rate)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530530 jv_detail.set(d["dr_or_cr"], amount_in_account_currency)
531 jv_detail.set(
532 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
533 amount_in_company_currency,
534 )
Anuja Pawar3e404f12021-08-31 18:59:29 +0530535 else:
536 journal_entry.remove(jv_detail)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530537
Anuja Pawar3e404f12021-08-31 18:59:29 +0530538 # new row with references
539 new_row = journal_entry.append("accounts")
Anuja Pawar1a6e98e2021-10-29 20:52:47 +0530540
541 new_row.update((frappe.copy_doc(jv_detail)).as_dict())
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530542
Anuja Pawar3e404f12021-08-31 18:59:29 +0530543 new_row.set(d["dr_or_cr"], d["allocated_amount"])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530544 new_row.set(
545 "debit" if d["dr_or_cr"] == "debit_in_account_currency" else "credit",
546 d["allocated_amount"] * flt(jv_detail.exchange_rate),
547 )
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530548
Ankush Menat494bd9e2022-03-28 18:52:46 +0530549 new_row.set(
550 "credit_in_account_currency"
551 if d["dr_or_cr"] == "debit_in_account_currency"
552 else "debit_in_account_currency",
553 0,
554 )
555 new_row.set("credit" if d["dr_or_cr"] == "debit_in_account_currency" else "debit", 0)
Rushabh Mehta2e7f9d22015-10-15 16:31:16 +0530556
Anuja Pawar3e404f12021-08-31 18:59:29 +0530557 new_row.set("reference_type", d["against_voucher_type"])
558 new_row.set("reference_name", d["against_voucher"])
559
560 new_row.against_account = cstr(jv_detail.against_account)
561 new_row.is_advance = cstr(jv_detail.is_advance)
562 new_row.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530563
564 # will work as update after submit
Anuja Pawar3e404f12021-08-31 18:59:29 +0530565 journal_entry.flags.ignore_validate_update_after_submit = True
566 if not do_not_save:
567 journal_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530568
Ankush Menat494bd9e2022-03-28 18:52:46 +0530569
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530570def update_reference_in_payment_entry(d, payment_entry, do_not_save=False):
Nabin Hait28a05282016-06-27 17:41:39 +0530571 reference_details = {
572 "reference_doctype": d.against_voucher_type,
573 "reference_name": d.against_voucher,
574 "total_amount": d.grand_total,
575 "outstanding_amount": d.outstanding_amount,
576 "allocated_amount": d.allocated_amount,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530577 "exchange_rate": d.exchange_rate
578 if not d.exchange_gain_loss
579 else payment_entry.get_exchange_rate(),
580 "exchange_gain_loss": d.exchange_gain_loss, # only populated from invoice in case of advance allocation
Nabin Hait28a05282016-06-27 17:41:39 +0530581 }
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530582
Nabin Hait28a05282016-06-27 17:41:39 +0530583 if d.voucher_detail_no:
584 existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
585 original_row = existing_row.as_dict().copy()
586 existing_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530587
Nabin Hait28a05282016-06-27 17:41:39 +0530588 if d.allocated_amount < original_row.allocated_amount:
589 new_row = payment_entry.append("references")
590 new_row.docstatus = 1
Achilles Rasquinhaefb73192018-05-23 01:01:24 -0500591 for field in list(reference_details):
Nabin Hait28a05282016-06-27 17:41:39 +0530592 new_row.set(field, original_row[field])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530593
Nabin Hait28a05282016-06-27 17:41:39 +0530594 new_row.allocated_amount = original_row.allocated_amount - d.allocated_amount
595 else:
596 new_row = payment_entry.append("references")
597 new_row.docstatus = 1
598 new_row.update(reference_details)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530599
Nabin Hait28a05282016-06-27 17:41:39 +0530600 payment_entry.flags.ignore_validate_update_after_submit = True
Nabin Hait05aefbb2016-06-28 19:42:19 +0530601 payment_entry.setup_party_account_field()
Nabin Hait1991c7b2016-06-27 20:09:05 +0530602 payment_entry.set_missing_values()
Nabin Hait28a05282016-06-27 17:41:39 +0530603 payment_entry.set_amounts()
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530604
605 if d.difference_amount and d.difference_account:
Saqiba20999c2021-07-12 14:33:23 +0530606 account_details = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530607 "account": d.difference_account,
608 "cost_center": payment_entry.cost_center
609 or frappe.get_cached_value("Company", payment_entry.company, "cost_center"),
Saqiba20999c2021-07-12 14:33:23 +0530610 }
611 if d.difference_amount:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530612 account_details["amount"] = d.difference_amount
Saqiba20999c2021-07-12 14:33:23 +0530613
614 payment_entry.set_gain_or_loss(account_details=account_details)
Rohit Waghchaurea2408a62019-06-24 01:52:48 +0530615
616 if not do_not_save:
617 payment_entry.save(ignore_permissions=True)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530618
Ankush Menat494bd9e2022-03-28 18:52:46 +0530619
Nabin Hait297d74a2016-11-23 15:58:51 +0530620def unlink_ref_doc_from_payment_entries(ref_doc):
621 remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name)
622 remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name)
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530623
Ankush Menat494bd9e2022-03-28 18:52:46 +0530624 frappe.db.sql(
625 """update `tabGL Entry`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530626 set against_voucher_type=null, against_voucher=null,
627 modified=%s, modified_by=%s
628 where against_voucher_type=%s and against_voucher=%s
629 and voucher_no != ifnull(against_voucher, '')""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530630 (now(), frappe.session.user, ref_doc.doctype, ref_doc.name),
631 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530632
Nabin Hait297d74a2016-11-23 15:58:51 +0530633 if ref_doc.doctype in ("Sales Invoice", "Purchase Invoice"):
634 ref_doc.set("advances", [])
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530635
Ankush Menat494bd9e2022-03-28 18:52:46 +0530636 frappe.db.sql(
637 """delete from `tab{0} Advance` where parent = %s""".format(ref_doc.doctype), ref_doc.name
638 )
639
Anand Doshicd71e1d2014-04-08 13:53:35 +0530640
Nabin Haite0cc87d2016-07-21 18:30:03 +0530641def remove_ref_doc_link_from_jv(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530642 linked_jv = frappe.db.sql_list(
643 """select parent from `tabJournal Entry Account`
644 where reference_type=%s and reference_name=%s and docstatus < 2""",
645 (ref_type, ref_no),
646 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530647
648 if linked_jv:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 frappe.db.sql(
650 """update `tabJournal Entry Account`
Rushabh Mehta1828c122015-08-10 17:04:07 +0530651 set reference_type=null, reference_name = null,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530652 modified=%s, modified_by=%s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530653 where reference_type=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530654 and docstatus < 2""",
655 (now(), frappe.session.user, ref_type, ref_no),
656 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530657
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530658 frappe.msgprint(_("Journal Entries {0} are un-linked").format("\n".join(linked_jv)))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530659
Ankush Menat494bd9e2022-03-28 18:52:46 +0530660
Nabin Haite0cc87d2016-07-21 18:30:03 +0530661def remove_ref_doc_link_from_pe(ref_type, ref_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530662 linked_pe = frappe.db.sql_list(
663 """select parent from `tabPayment Entry Reference`
664 where reference_doctype=%s and reference_name=%s and docstatus < 2""",
665 (ref_type, ref_no),
666 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530667
Nabin Haite0cc87d2016-07-21 18:30:03 +0530668 if linked_pe:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530669 frappe.db.sql(
670 """update `tabPayment Entry Reference`
Nabin Haite0cc87d2016-07-21 18:30:03 +0530671 set allocated_amount=0, modified=%s, modified_by=%s
672 where reference_doctype=%s and reference_name=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530673 and docstatus < 2""",
674 (now(), frappe.session.user, ref_type, ref_no),
675 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530676
Nabin Haite0cc87d2016-07-21 18:30:03 +0530677 for pe in linked_pe:
Deepesh Gargc5276f32021-08-01 17:48:50 +0530678 try:
679 pe_doc = frappe.get_doc("Payment Entry", pe)
Deepesh Garg71418602021-08-10 22:21:28 +0530680 pe_doc.set_amounts()
Deepesh Gargb5162392021-08-10 14:52:24 +0530681 pe_doc.clear_unallocated_reference_document_rows()
682 pe_doc.validate_payment_type_with_outstanding()
Deepesh Gargc5276f32021-08-01 17:48:50 +0530683 except Exception as e:
684 msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530685 msg += "<br>"
Deepesh Garg188bba82021-08-10 14:04:31 +0530686 msg += _("Please cancel payment entry manually first")
Deepesh Garg71418602021-08-10 22:21:28 +0530687 frappe.throw(msg, exc=PaymentEntryUnlinkError, title=_("Payment Unlink Error"))
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530688
Ankush Menat494bd9e2022-03-28 18:52:46 +0530689 frappe.db.sql(
690 """update `tabPayment Entry` set total_allocated_amount=%s,
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530691 base_total_allocated_amount=%s, unallocated_amount=%s, modified=%s, modified_by=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530692 where name=%s""",
693 (
694 pe_doc.total_allocated_amount,
695 pe_doc.base_total_allocated_amount,
696 pe_doc.unallocated_amount,
697 now(),
698 frappe.session.user,
699 pe,
700 ),
701 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530702
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530703 frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
Nabin Hait0fc24542013-03-25 11:06:00 +0530704
Ankush Menat494bd9e2022-03-28 18:52:46 +0530705
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530706@frappe.whitelist()
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530707def get_company_default(company, fieldname, ignore_validation=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530708 value = frappe.get_cached_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530709
Rohit Waghchaure2a14f252021-07-30 12:36:35 +0530710 if not ignore_validation and not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530711 throw(
712 _("Please set default {0} in Company {1}").format(
713 frappe.get_meta("Company").get_label(fieldname), company
714 )
715 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530716
Nabin Hait0fc24542013-03-25 11:06:00 +0530717 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530718
Ankush Menat494bd9e2022-03-28 18:52:46 +0530719
Nabin Hait8b509f52013-05-28 16:52:30 +0530720def fix_total_debit_credit():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530721 vouchers = frappe.db.sql(
722 """select voucher_type, voucher_no,
Anand Doshicd71e1d2014-04-08 13:53:35 +0530723 sum(debit) - sum(credit) as diff
724 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530725 group by voucher_type, voucher_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530726 having sum(debit) != sum(credit)""",
727 as_dict=1,
728 )
Anand Doshicd71e1d2014-04-08 13:53:35 +0530729
Nabin Hait8b509f52013-05-28 16:52:30 +0530730 for d in vouchers:
731 if abs(d.diff) > 0:
732 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530733
Ankush Menat494bd9e2022-03-28 18:52:46 +0530734 frappe.db.sql(
735 """update `tabGL Entry` set %s = %s + %s
736 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
737 % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
738 (d.diff, d.voucher_type, d.voucher_no),
739 )
740
Anand Doshicd71e1d2014-04-08 13:53:35 +0530741
Rushabh Mehtad50da782017-07-28 11:39:01 +0530742def get_currency_precision():
Nabin Hait9b20e072017-04-25 12:10:24 +0530743 precision = cint(frappe.db.get_default("currency_precision"))
744 if not precision:
745 number_format = frappe.db.get_default("number_format") or "#,###.##"
746 precision = get_number_format_info(number_format)[2]
Rushabh Mehtad50da782017-07-28 11:39:01 +0530747
Nabin Hait9b20e072017-04-25 12:10:24 +0530748 return precision
Rushabh Mehtad50da782017-07-28 11:39:01 +0530749
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530750
Ankush Menat494bd9e2022-03-28 18:52:46 +0530751def get_stock_rbnb_difference(posting_date, company):
752 stock_items = frappe.db.sql_list(
753 """select distinct item_code
754 from `tabStock Ledger Entry` where company=%s""",
755 company,
756 )
757
758 pr_valuation_amount = frappe.db.sql(
759 """
Anand Doshi602e8252015-11-16 19:05:46 +0530760 select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530761 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
Suraj Shetty084b0b32018-05-26 09:12:59 +0530762 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530763 and pr.posting_date <= %s and pr_item.item_code in (%s)"""
764 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
765 tuple([company, posting_date] + stock_items),
766 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530767
Ankush Menat494bd9e2022-03-28 18:52:46 +0530768 pi_valuation_amount = frappe.db.sql(
769 """
Anand Doshi602e8252015-11-16 19:05:46 +0530770 select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530771 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
Suraj Shetty084b0b32018-05-26 09:12:59 +0530772 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530773 and pi.posting_date <= %s and pi_item.item_code in (%s)"""
774 % ("%s", "%s", ", ".join(["%s"] * len(stock_items))),
775 tuple([company, posting_date] + stock_items),
776 )[0][0]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530777
778 # Balance should be
779 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
780
781 # Balance as per system
Ankush Menat494bd9e2022-03-28 18:52:46 +0530782 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.get_cached_value(
783 "Company", company, "abbr"
784 )
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530785 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530786
787 # Amount should be credited
788 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530789
tundec4b0d172017-09-26 00:48:30 +0100790
tundebabzyad08d4c2018-05-16 07:01:41 +0100791def get_held_invoices(party_type, party):
792 """
793 Returns a list of names Purchase Invoices for the given party that are on hold
794 """
795 held_invoices = None
796
Ankush Menat494bd9e2022-03-28 18:52:46 +0530797 if party_type == "Supplier":
tundebabzyad08d4c2018-05-16 07:01:41 +0100798 held_invoices = frappe.db.sql(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530799 "select name from `tabPurchase Invoice` where release_date IS NOT NULL and release_date > CURDATE()",
800 as_dict=1,
tundebabzyad08d4c2018-05-16 07:01:41 +0100801 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802 held_invoices = set(d["name"] for d in held_invoices)
tundebabzyad08d4c2018-05-16 07:01:41 +0100803
804 return held_invoices
805
806
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530807def get_outstanding_invoices(party_type, party, account, condition=None, filters=None):
Anand Doshid40d1e92015-11-12 17:05:29 +0530808 outstanding_invoices = []
Nabin Haitac184982019-02-04 21:13:43 +0530809 precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
Anand Doshid40d1e92015-11-12 17:05:29 +0530810
Nabin Hait9db9edc2019-11-19 18:44:32 +0530811 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530812 root_type, account_type = frappe.get_cached_value(
813 "Account", account, ["root_type", "account_type"]
814 )
Nabin Hait9db9edc2019-11-19 18:44:32 +0530815 party_account_type = "Receivable" if root_type == "Asset" else "Payable"
Saqib9291df42020-01-24 16:22:49 +0530816 party_account_type = account_type or party_account_type
Nabin Hait9db9edc2019-11-19 18:44:32 +0530817 else:
818 party_account_type = erpnext.get_party_account_type(party_type)
819
Ankush Menat494bd9e2022-03-28 18:52:46 +0530820 if party_account_type == "Receivable":
Anand Doshi602e8252015-11-16 19:05:46 +0530821 dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
Nabin Haitac184982019-02-04 21:13:43 +0530822 payment_dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
Anand Doshid40d1e92015-11-12 17:05:29 +0530823 else:
Anand Doshi602e8252015-11-16 19:05:46 +0530824 dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
Nabin Haitac184982019-02-04 21:13:43 +0530825 payment_dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
Anand Doshid40d1e92015-11-12 17:05:29 +0530826
tundebabzyad08d4c2018-05-16 07:01:41 +0100827 held_invoices = get_held_invoices(party_type, party)
828
Ankush Menat494bd9e2022-03-28 18:52:46 +0530829 invoice_list = frappe.db.sql(
830 """
Nabin Haite4bbb692016-07-04 16:16:24 +0530831 select
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530832 voucher_no, voucher_type, posting_date, due_date,
Deepesh Gargc7eadfc2020-07-22 17:59:37 +0530833 ifnull(sum({dr_or_cr}), 0) as invoice_amount,
834 account_currency as currency
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530835 from
Nabin Haitac184982019-02-04 21:13:43 +0530836 `tabGL Entry`
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530837 where
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530838 party_type = %(party_type)s and party = %(party)s
Nabin Haite4bbb692016-07-04 16:16:24 +0530839 and account = %(account)s and {dr_or_cr} > 0
aakvatech38ccf822020-10-03 19:41:38 +0300840 and is_cancelled=0
Anand Doshid40d1e92015-11-12 17:05:29 +0530841 {condition}
842 and ((voucher_type = 'Journal Entry'
Nabin Hait56548cb2016-07-01 15:58:39 +0530843 and (against_voucher = '' or against_voucher is null))
844 or (voucher_type not in ('Journal Entry', 'Payment Entry')))
Nabin Haita5cc84f2017-12-21 11:37:18 +0530845 group by voucher_type, voucher_no
Nabin Hait34c551d2019-07-03 10:34:31 +0530846 order by posting_date, name""".format(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530847 dr_or_cr=dr_or_cr, condition=condition or ""
848 ),
849 {
Anand Doshid40d1e92015-11-12 17:05:29 +0530850 "party_type": party_type,
851 "party": party,
852 "account": account,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530853 },
854 as_dict=True,
855 )
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530856
Ankush Menat494bd9e2022-03-28 18:52:46 +0530857 payment_entries = frappe.db.sql(
858 """
Nabin Haitac184982019-02-04 21:13:43 +0530859 select against_voucher_type, against_voucher,
860 ifnull(sum({payment_dr_or_cr}), 0) as payment_amount
861 from `tabGL Entry`
862 where party_type = %(party_type)s and party = %(party)s
863 and account = %(account)s
864 and {payment_dr_or_cr} > 0
865 and against_voucher is not null and against_voucher != ''
aakvatech38ccf822020-10-03 19:41:38 +0300866 and is_cancelled=0
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530867 group by against_voucher_type, against_voucher
Ankush Menat494bd9e2022-03-28 18:52:46 +0530868 """.format(
869 payment_dr_or_cr=payment_dr_or_cr
870 ),
871 {"party_type": party_type, "party": party, "account": account},
872 as_dict=True,
873 )
tundec4b0d172017-09-26 00:48:30 +0100874
Nabin Haitac184982019-02-04 21:13:43 +0530875 pe_map = frappe._dict()
876 for d in payment_entries:
877 pe_map.setdefault((d.against_voucher_type, d.against_voucher), d.payment_amount)
878
879 for d in invoice_list:
880 payment_amount = pe_map.get((d.voucher_type, d.voucher_no), 0)
881 outstanding_amount = flt(d.invoice_amount - payment_amount, precision)
882 if outstanding_amount > 0.5 / (10**precision):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530883 if (
884 filters
885 and filters.get("outstanding_amt_greater_than")
886 and not (
887 outstanding_amount >= filters.get("outstanding_amt_greater_than")
888 and outstanding_amount <= filters.get("outstanding_amt_less_than")
889 )
890 ):
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530891 continue
Nabin Haitac184982019-02-04 21:13:43 +0530892
Rohit Waghchaure0f065d52019-05-02 00:06:04 +0530893 if not d.voucher_type == "Purchase Invoice" or d.voucher_no not in held_invoices:
Nabin Haitac184982019-02-04 21:13:43 +0530894 outstanding_invoices.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530895 frappe._dict(
896 {
897 "voucher_no": d.voucher_no,
898 "voucher_type": d.voucher_type,
899 "posting_date": d.posting_date,
900 "invoice_amount": flt(d.invoice_amount),
901 "payment_amount": payment_amount,
902 "outstanding_amount": outstanding_amount,
903 "due_date": d.due_date,
904 "currency": d.currency,
905 }
906 )
Nabin Haitac184982019-02-04 21:13:43 +0530907 )
Rushabh Mehtae9d9b8e2016-12-15 11:27:35 +0530908
Ankush Menat494bd9e2022-03-28 18:52:46 +0530909 outstanding_invoices = sorted(
910 outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
911 )
Anand Doshid40d1e92015-11-12 17:05:29 +0530912 return outstanding_invoices
Saurabh3a268292016-02-22 15:18:40 +0530913
914
Ankush Menat494bd9e2022-03-28 18:52:46 +0530915def get_account_name(
916 account_type=None, root_type=None, is_group=None, account_currency=None, company=None
917):
Saurabh3a268292016-02-22 15:18:40 +0530918 """return account based on matching conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530919 return frappe.db.get_value(
920 "Account",
921 {
922 "account_type": account_type or "",
923 "root_type": root_type or "",
924 "is_group": is_group or 0,
925 "account_currency": account_currency or frappe.defaults.get_defaults().currency,
926 "company": company or frappe.defaults.get_defaults().company,
927 },
928 "name",
929 )
930
Saurabha9ba7342016-06-21 12:33:12 +0530931
932@frappe.whitelist()
933def get_companies():
934 """get a list of companies based on permission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530935 return [d.name for d in frappe.get_list("Company", fields=["name"], order_by="name")]
936
Saurabha9ba7342016-06-21 12:33:12 +0530937
938@frappe.whitelist()
Rushabh Mehta43133262017-11-10 18:52:21 +0530939def get_children(doctype, parent, company, is_root=False):
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530940 from erpnext.accounts.report.financial_statements import sort_accounts
Rushabh Mehtad50da782017-07-28 11:39:01 +0530941
Ankush Menat494bd9e2022-03-28 18:52:46 +0530942 parent_fieldname = "parent_" + doctype.lower().replace(" ", "_")
943 fields = ["name as value", "is_group as expandable"]
944 filters = [["docstatus", "<", 2]]
Suraj Shettyfbb6b3d2018-05-16 13:53:31 +0530945
Ankush Menat494bd9e2022-03-28 18:52:46 +0530946 filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530947
Rushabh Mehta43133262017-11-10 18:52:21 +0530948 if is_root:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530949 fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
950 filters.append(["company", "=", company])
Suraj Shetty084b0b32018-05-26 09:12:59 +0530951
Saurabha9ba7342016-06-21 12:33:12 +0530952 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530953 fields += ["root_type", "account_currency"] if doctype == "Account" else []
954 fields += [parent_fieldname + " as parent"]
Suraj Shetty084b0b32018-05-26 09:12:59 +0530955
956 acc = frappe.get_list(doctype, fields=fields, filters=filters)
Saurabha9ba7342016-06-21 12:33:12 +0530957
Ankush Menat494bd9e2022-03-28 18:52:46 +0530958 if doctype == "Account":
Nabin Haitaf98f5d2018-04-02 10:14:32 +0530959 sort_accounts(acc, is_root, key="value")
Saurabha9ba7342016-06-21 12:33:12 +0530960
961 return acc
Saurabhb835fef2016-09-09 11:19:22 +0530962
Ankush Menat494bd9e2022-03-28 18:52:46 +0530963
Saqib90517352021-10-04 11:44:46 +0530964@frappe.whitelist()
965def get_account_balances(accounts, company):
966
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530967 if isinstance(accounts, str):
Saqib90517352021-10-04 11:44:46 +0530968 accounts = loads(accounts)
969
970 if not accounts:
971 return []
972
Ankush Menat494bd9e2022-03-28 18:52:46 +0530973 company_currency = frappe.get_cached_value("Company", company, "default_currency")
Saqib90517352021-10-04 11:44:46 +0530974
975 for account in accounts:
976 account["company_currency"] = company_currency
Ankush Menat494bd9e2022-03-28 18:52:46 +0530977 account["balance"] = flt(
978 get_balance_on(account["value"], in_account_currency=False, company=company)
979 )
Saqib90517352021-10-04 11:44:46 +0530980 if account["account_currency"] and account["account_currency"] != company_currency:
981 account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
982
983 return accounts
984
Ankush Menat494bd9e2022-03-28 18:52:46 +0530985
Mangesh-Khairnar97ab96c2020-09-22 12:58:32 +0530986def create_payment_gateway_account(gateway, payment_channel="Email"):
Deepesh Garga72589c2021-05-29 23:54:51 +0530987 from erpnext.setup.setup_wizard.operations.install_fixtures import create_bank_account
Saurabhb835fef2016-09-09 11:19:22 +0530988
989 company = frappe.db.get_value("Global Defaults", None, "default_company")
990 if not company:
991 return
992
993 # 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 +0530994 bank_account = frappe.db.get_value(
995 "Account",
996 {"account_name": _(gateway), "company": company},
997 ["name", "account_currency"],
998 as_dict=1,
999 )
Saurabhb835fef2016-09-09 11:19:22 +05301000
1001 if not bank_account:
1002 # check for untranslated one
Ankush Menat494bd9e2022-03-28 18:52:46 +05301003 bank_account = frappe.db.get_value(
1004 "Account",
1005 {"account_name": gateway, "company": company},
1006 ["name", "account_currency"],
1007 as_dict=1,
1008 )
Saurabhb835fef2016-09-09 11:19:22 +05301009
1010 if not bank_account:
1011 # try creating one
1012 bank_account = create_bank_account({"company_name": company, "bank_account": _(gateway)})
1013
1014 if not bank_account:
1015 frappe.msgprint(_("Payment Gateway Account not created, please create one manually."))
1016 return
1017
1018 # if payment gateway account exists, return
Ankush Menat494bd9e2022-03-28 18:52:46 +05301019 if frappe.db.exists(
1020 "Payment Gateway Account",
1021 {"payment_gateway": gateway, "currency": bank_account.account_currency},
1022 ):
Saurabhb835fef2016-09-09 11:19:22 +05301023 return
1024
1025 try:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301026 frappe.get_doc(
1027 {
1028 "doctype": "Payment Gateway Account",
1029 "is_default": 1,
1030 "payment_gateway": gateway,
1031 "payment_account": bank_account.name,
1032 "currency": bank_account.account_currency,
1033 "payment_channel": payment_channel,
1034 }
1035 ).insert(ignore_permissions=True, ignore_if_duplicate=True)
Saurabhb835fef2016-09-09 11:19:22 +05301036
1037 except frappe.DuplicateEntryError:
1038 # already exists, due to a reinstall?
cclauss68487082017-07-27 07:08:35 +02001039 pass
Zarrar44175902018-06-08 16:35:21 +05301040
Ankush Menat494bd9e2022-03-28 18:52:46 +05301041
Zarrar44175902018-06-08 16:35:21 +05301042@frappe.whitelist()
Deepesh Garg817cbc42020-06-15 12:07:04 +05301043def update_cost_center(docname, cost_center_name, cost_center_number, company, merge):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301044 """
1045 Renames the document by adding the number as a prefix to the current name and updates
1046 all transaction where it was present.
1047 """
Saqiba8779872020-04-30 11:28:43 +05301048 validate_field_number("Cost Center", docname, cost_center_number, company, "cost_center_number")
Zarrar44175902018-06-08 16:35:21 +05301049
Saqiba8779872020-04-30 11:28:43 +05301050 if cost_center_number:
1051 frappe.db.set_value("Cost Center", docname, "cost_center_number", cost_center_number.strip())
1052 else:
1053 frappe.db.set_value("Cost Center", docname, "cost_center_number", "")
Zarrar44175902018-06-08 16:35:21 +05301054
Saqiba8779872020-04-30 11:28:43 +05301055 frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
Zarrar44175902018-06-08 16:35:21 +05301056
Saqiba8779872020-04-30 11:28:43 +05301057 new_name = get_autoname_with_number(cost_center_number, cost_center_name, docname, company)
1058 if docname != new_name:
Deepesh Garg817cbc42020-06-15 12:07:04 +05301059 frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
Zarrar44175902018-06-08 16:35:21 +05301060 return new_name
1061
Ankush Menat494bd9e2022-03-28 18:52:46 +05301062
Saqiba8779872020-04-30 11:28:43 +05301063def validate_field_number(doctype_name, docname, number_value, company, field_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301064 """Validate if the number entered isn't already assigned to some other document."""
Zlash651aeca1d2018-07-06 17:15:33 +05301065 if number_value:
Saqiba8779872020-04-30 11:28:43 +05301066 filters = {field_name: number_value, "name": ["!=", docname]}
Zarrar44175902018-06-08 16:35:21 +05301067 if company:
Saqiba8779872020-04-30 11:28:43 +05301068 filters["company"] = company
1069
1070 doctype_with_same_number = frappe.db.get_value(doctype_name, filters)
1071
Zarrar44175902018-06-08 16:35:21 +05301072 if doctype_with_same_number:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301073 frappe.throw(
1074 _("{0} Number {1} is already used in {2} {3}").format(
1075 doctype_name, number_value, doctype_name.lower(), doctype_with_same_number
1076 )
1077 )
1078
Zarrar44175902018-06-08 16:35:21 +05301079
Zarrar17705f92018-07-06 14:44:44 +05301080def get_autoname_with_number(number_value, doc_title, name, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301081 """append title with prefix as number and suffix as company's abbreviation separated by '-'"""
Zarrar88a90ff2018-06-11 11:21:17 +05301082 if name:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301083 name_split = name.split("-")
1084 parts = [doc_title.strip(), name_split[len(name_split) - 1].strip()]
Zarrar44175902018-06-08 16:35:21 +05301085 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301086 abbr = frappe.get_cached_value("Company", company, ["abbr"], as_dict=True)
Zarrar88a90ff2018-06-11 11:21:17 +05301087 parts = [doc_title.strip(), abbr.abbr]
Zlash651aeca1d2018-07-06 17:15:33 +05301088 if cstr(number_value).strip():
1089 parts.insert(0, cstr(number_value).strip())
Ankush Menat494bd9e2022-03-28 18:52:46 +05301090 return " - ".join(parts)
1091
Zarrar254ce642018-06-28 14:15:34 +05301092
1093@frappe.whitelist()
1094def get_coa(doctype, parent, is_root, chart=None):
Chillar Anand915b3432021-09-02 16:44:59 +05301095 from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import (
1096 build_tree_from_json,
1097 )
Zarrar254ce642018-06-28 14:15:34 +05301098
1099 # add chart to flags to retrieve when called from expand all function
1100 chart = chart if chart else frappe.flags.chart
1101 frappe.flags.chart = chart
1102
Ankush Menat494bd9e2022-03-28 18:52:46 +05301103 parent = None if parent == _("All Accounts") else parent
1104 accounts = build_tree_from_json(chart) # returns alist of dict in a tree render-able form
Zarrar254ce642018-06-28 14:15:34 +05301105
1106 # filter out to show data for the selected node only
Ankush Menat494bd9e2022-03-28 18:52:46 +05301107 accounts = [d for d in accounts if d["parent_account"] == parent]
Zarrar254ce642018-06-28 14:15:34 +05301108
1109 return accounts
Sanjay Kumar1b49f3a2018-09-06 13:09:35 +04001110
Ankush Menat494bd9e2022-03-28 18:52:46 +05301111
1112def update_gl_entries_after(
1113 posting_date,
1114 posting_time,
1115 for_warehouses=None,
1116 for_items=None,
1117 warehouse_account=None,
1118 company=None,
1119):
1120 stock_vouchers = get_future_stock_vouchers(
1121 posting_date, posting_time, for_warehouses, for_items, company
1122 )
Nabin Hait9b178bc2021-02-16 14:57:00 +05301123 repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
1124
1125
Ankush Menat494bd9e2022-03-28 18:52:46 +05301126def repost_gle_for_stock_vouchers(
1127 stock_vouchers, posting_date, company=None, warehouse_account=None
1128):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301129 def _delete_gl_entries(voucher_type, voucher_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301130 frappe.db.sql(
1131 """delete from `tabGL Entry`
1132 where voucher_type=%s and voucher_no=%s""",
1133 (voucher_type, voucher_no),
1134 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301135
1136 if not warehouse_account:
1137 warehouse_account = get_warehouse_account_map(company)
1138
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301139 precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit")) or 2
1140
Nabin Hait9b178bc2021-02-16 14:57:00 +05301141 gle = get_voucherwise_gl_entries(stock_vouchers, posting_date)
Nabin Hait9b178bc2021-02-16 14:57:00 +05301142 for voucher_type, voucher_no in stock_vouchers:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301143 existing_gle = gle.get((voucher_type, voucher_no), [])
Nabin Hait19f8fa52021-02-22 22:27:22 +05301144 voucher_obj = frappe.get_cached_doc(voucher_type, voucher_no)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301145 expected_gle = voucher_obj.get_gl_entries(warehouse_account)
1146 if expected_gle:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301147 if not existing_gle or not compare_existing_and_expected_gle(
1148 existing_gle, expected_gle, precision
1149 ):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301150 _delete_gl_entries(voucher_type, voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +05301151 voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301152 else:
1153 _delete_gl_entries(voucher_type, voucher_no)
1154
Ankush Menat494bd9e2022-03-28 18:52:46 +05301155
1156def get_future_stock_vouchers(
1157 posting_date, posting_time, for_warehouses=None, for_items=None, company=None
1158):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301159
1160 values = []
1161 condition = ""
1162 if for_items:
1163 condition += " and item_code in ({})".format(", ".join(["%s"] * len(for_items)))
1164 values += for_items
1165
1166 if for_warehouses:
1167 condition += " and warehouse in ({})".format(", ".join(["%s"] * len(for_warehouses)))
1168 values += for_warehouses
1169
rohitwaghchaured60ff832021-02-16 09:12:27 +05301170 if company:
Nabin Hait9b178bc2021-02-16 14:57:00 +05301171 condition += " and company = %s"
rohitwaghchaured60ff832021-02-16 09:12:27 +05301172 values.append(company)
1173
Ankush Menat494bd9e2022-03-28 18:52:46 +05301174 future_stock_vouchers = frappe.db.sql(
1175 """select distinct sle.voucher_type, sle.voucher_no
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301176 from `tabStock Ledger Entry` sle
Nabin Haita77b8c92020-12-21 14:45:50 +05301177 where
1178 timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
1179 and is_cancelled = 0
1180 {condition}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301181 order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
1182 condition=condition
1183 ),
1184 tuple([posting_date, posting_time] + values),
1185 as_dict=True,
1186 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301187
Ankush91527152021-08-11 11:17:50 +05301188 return [(d.voucher_type, d.voucher_no) for d in future_stock_vouchers]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301189
Ankush Menat494bd9e2022-03-28 18:52:46 +05301190
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301191def get_voucherwise_gl_entries(future_stock_vouchers, posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301192 """Get voucherwise list of GL entries.
Ankush91527152021-08-11 11:17:50 +05301193
1194 Only fetches GLE fields required for comparing with new GLE.
1195 Check compare_existing_and_expected_gle function below.
rohitwaghchaure058d9832021-09-07 12:14:40 +05301196
1197 returns:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301198 Dict[Tuple[voucher_type, voucher_no], List[GL Entries]]
Ankush91527152021-08-11 11:17:50 +05301199 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301200 gl_entries = {}
Ankush91527152021-08-11 11:17:50 +05301201 if not future_stock_vouchers:
1202 return gl_entries
1203
1204 voucher_nos = [d[1] for d in future_stock_vouchers]
1205
Ankush Menat494bd9e2022-03-28 18:52:46 +05301206 gles = frappe.db.sql(
1207 """
rohitwaghchaure058d9832021-09-07 12:14:40 +05301208 select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
Ankush91527152021-08-11 11:17:50 +05301209 from `tabGL Entry`
1210 where
Ankush Menat494bd9e2022-03-28 18:52:46 +05301211 posting_date >= %s and voucher_no in (%s)"""
1212 % ("%s", ", ".join(["%s"] * len(voucher_nos))),
1213 tuple([posting_date] + voucher_nos),
1214 as_dict=1,
1215 )
Ankush91527152021-08-11 11:17:50 +05301216
1217 for d in gles:
1218 gl_entries.setdefault((d.voucher_type, d.voucher_no), []).append(d)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301219
Prssanna Desai82ddef52020-06-18 18:18:41 +05301220 return gl_entries
Nabin Haita77b8c92020-12-21 14:45:50 +05301221
Ankush Menat494bd9e2022-03-28 18:52:46 +05301222
Rohit Waghchaurebc8c9de2021-02-23 17:50:49 +05301223def compare_existing_and_expected_gle(existing_gle, expected_gle, precision):
Ankush91527152021-08-11 11:17:50 +05301224 if len(existing_gle) != len(expected_gle):
1225 return False
1226
Nabin Haita77b8c92020-12-21 14:45:50 +05301227 matched = True
1228 for entry in expected_gle:
1229 account_existed = False
1230 for e in existing_gle:
1231 if entry.account == e.account:
1232 account_existed = True
Ankush Menat494bd9e2022-03-28 18:52:46 +05301233 if (
1234 entry.account == e.account
1235 and (not entry.cost_center or not e.cost_center or entry.cost_center == e.cost_center)
1236 and (
1237 flt(entry.debit, precision) != flt(e.debit, precision)
1238 or flt(entry.credit, precision) != flt(e.credit, precision)
1239 )
1240 ):
Nabin Haita77b8c92020-12-21 14:45:50 +05301241 matched = False
1242 break
1243 if not account_existed:
1244 matched = False
1245 break
Nabin Haitb99c77b2020-12-25 18:12:35 +05301246 return matched
1247
Ankush Menat494bd9e2022-03-28 18:52:46 +05301248
1249def check_if_stock_and_account_balance_synced(
1250 posting_date, company, voucher_type=None, voucher_no=None
1251):
Nabin Haitb99c77b2020-12-25 18:12:35 +05301252 if not cint(erpnext.is_perpetual_inventory_enabled(company)):
1253 return
1254
1255 accounts = get_stock_accounts(company, voucher_type, voucher_no)
1256 stock_adjustment_account = frappe.db.get_value("Company", company, "stock_adjustment_account")
1257
1258 for account in accounts:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301259 account_bal, stock_bal, warehouse_list = get_stock_and_account_balance(
1260 account, posting_date, company
1261 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301262
1263 if abs(account_bal - stock_bal) > 0.1:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301264 precision = get_field_precision(
1265 frappe.get_meta("GL Entry").get_field("debit"),
1266 currency=frappe.get_cached_value("Company", company, "default_currency"),
1267 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301268
1269 diff = flt(stock_bal - account_bal, precision)
1270
Ankush Menat494bd9e2022-03-28 18:52:46 +05301271 error_reason = _(
1272 "Stock Value ({0}) and Account Balance ({1}) are out of sync for account {2} and it's linked warehouses as on {3}."
1273 ).format(stock_bal, account_bal, frappe.bold(account), posting_date)
1274 error_resolution = _("Please create an adjustment Journal Entry for amount {0} on {1}").format(
1275 frappe.bold(diff), frappe.bold(posting_date)
1276 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301277
1278 frappe.msgprint(
1279 msg="""{0}<br></br>{1}<br></br>""".format(error_reason, error_resolution),
1280 raise_exception=StockValueAndAccountBalanceOutOfSync,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301281 title=_("Values Out Of Sync"),
Nabin Haitb99c77b2020-12-25 18:12:35 +05301282 primary_action={
Ankush Menat494bd9e2022-03-28 18:52:46 +05301283 "label": _("Make Journal Entry"),
1284 "client_action": "erpnext.route_to_adjustment_jv",
1285 "args": get_journal_entry(account, stock_adjustment_account, diff),
1286 },
1287 )
1288
Nabin Haitb99c77b2020-12-25 18:12:35 +05301289
1290def get_stock_accounts(company, voucher_type=None, voucher_no=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301291 stock_accounts = [
1292 d.name
1293 for d in frappe.db.get_all(
1294 "Account", {"account_type": "Stock", "company": company, "is_group": 0}
1295 )
1296 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301297 if voucher_type and voucher_no:
1298 if voucher_type == "Journal Entry":
Ankush Menat494bd9e2022-03-28 18:52:46 +05301299 stock_accounts = [
1300 d.account
1301 for d in frappe.db.get_all(
1302 "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
1303 )
1304 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301305
1306 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301307 stock_accounts = [
1308 d.account
1309 for d in frappe.db.get_all(
1310 "GL Entry",
1311 {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
1312 "account",
1313 )
1314 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301315
1316 return stock_accounts
1317
Ankush Menat494bd9e2022-03-28 18:52:46 +05301318
Nabin Haitb99c77b2020-12-25 18:12:35 +05301319def get_stock_and_account_balance(account=None, posting_date=None, company=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301320 if not posting_date:
1321 posting_date = nowdate()
Nabin Haitb99c77b2020-12-25 18:12:35 +05301322
1323 warehouse_account = get_warehouse_account_map(company)
1324
Ankush Menat494bd9e2022-03-28 18:52:46 +05301325 account_balance = get_balance_on(
1326 account, posting_date, in_account_currency=False, ignore_account_permission=True
1327 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301328
Ankush Menat494bd9e2022-03-28 18:52:46 +05301329 related_warehouses = [
1330 wh
1331 for wh, wh_details in warehouse_account.items()
1332 if wh_details.account == account and not wh_details.is_group
1333 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301334
1335 total_stock_value = 0.0
1336 for warehouse in related_warehouses:
1337 value = get_stock_value_on(warehouse, posting_date)
1338 total_stock_value += value
1339
1340 precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
1341 return flt(account_balance, precision), flt(total_stock_value, precision), related_warehouses
1342
Ankush Menat494bd9e2022-03-28 18:52:46 +05301343
Nabin Haitb99c77b2020-12-25 18:12:35 +05301344def get_journal_entry(account, stock_adjustment_account, amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301345 db_or_cr_warehouse_account = (
1346 "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
1347 )
1348 db_or_cr_stock_adjustment_account = (
1349 "debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
1350 )
Nabin Haitb99c77b2020-12-25 18:12:35 +05301351
1352 return {
Ankush Menat494bd9e2022-03-28 18:52:46 +05301353 "accounts": [
1354 {"account": account, db_or_cr_warehouse_account: abs(amount)},
1355 {"account": stock_adjustment_account, db_or_cr_stock_adjustment_account: abs(amount)},
1356 ]
Nabin Haitb99c77b2020-12-25 18:12:35 +05301357 }
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301358
Ankush Menat494bd9e2022-03-28 18:52:46 +05301359
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301360def check_and_delete_linked_reports(report):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301361 """Check if reports are referenced in Desktop Icon"""
1362 icons = frappe.get_all("Desktop Icon", fields=["name"], filters={"_report": report})
Shadrak Gurupnor74337572021-08-27 18:00:16 +05301363 if icons:
1364 for icon in icons:
1365 frappe.delete_doc("Desktop Icon", icon)