blob: 2a77fa1465e27859760151d48cee676c5076d6a6 [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
4from __future__ import unicode_literals
5
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05306import frappe
7from frappe.utils import nowdate, cstr, flt, now, getdate, add_months
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05308from frappe import throw, _
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05309from frappe.utils import formatdate
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053010import frappe.desk.reportview
Nabin Hait23941aa2013-01-29 11:32:38 +053011
Anand Doshicd0989e2015-09-28 13:31:17 +053012# imported to enable erpnext.accounts.utils.get_account_currency
13from erpnext.accounts.doctype.account.account import get_account_currency
14
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053015class FiscalYearError(frappe.ValidationError): pass
16class BudgetError(frappe.ValidationError): pass
Nabin Hait2b06aaa2013-08-22 18:25:43 +053017
Neil Trini Lasrado78fa6952014-10-03 17:43:02 +053018@frappe.whitelist()
19def get_fiscal_year(date=None, fiscal_year=None, label="Date", verbose=1, company=None):
20 return get_fiscal_years(date, fiscal_year, label, verbose, company)[0]
Nabin Hait23941aa2013-01-29 11:32:38 +053021
Neil Trini Lasrado08662722015-01-12 16:41:46 +053022def get_fiscal_years(transaction_date=None, fiscal_year=None, label="Date", verbose=1, company=None):
Nabin Hait23941aa2013-01-29 11:32:38 +053023 # if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
Nabin Hait8d50eb32015-05-20 12:26:07 +053024 cond = " ifnull(disabled, 0) = 0"
Nabin Hait0930b942013-06-20 16:35:09 +053025 if fiscal_year:
Nabin Haita7bd8ee2015-05-20 12:53:04 +053026 cond += " and fy.name = %(fiscal_year)s"
Nabin Hait0930b942013-06-20 16:35:09 +053027 else:
Nabin Haita7bd8ee2015-05-20 12:53:04 +053028 cond += " and %(transaction_date)s >= fy.year_start_date and %(transaction_date)s <= fy.year_end_date"
Nabin Haitfff3ab72015-01-14 16:27:13 +053029
Neil Trini Lasrado08662722015-01-12 16:41:46 +053030 if company:
31 cond += """ and (not exists(select name from `tabFiscal Year Company` fyc where fyc.parent = fy.name)
32 or exists(select company from `tabFiscal Year Company` fyc where fyc.parent = fy.name and fyc.company=%(company)s ))"""
Nabin Haitfff3ab72015-01-14 16:27:13 +053033
34 fy = frappe.db.sql("""select fy.name, fy.year_start_date, fy.year_end_date from `tabFiscal Year` fy
Nabin Hait8d50eb32015-05-20 12:26:07 +053035 where %s order by fy.year_start_date desc""" % cond, {
Neil Trini Lasrado08662722015-01-12 16:41:46 +053036 "fiscal_year": fiscal_year,
37 "transaction_date": transaction_date,
38 "company": company
39 })
Anand Doshicd71e1d2014-04-08 13:53:35 +053040
Nabin Hait23941aa2013-01-29 11:32:38 +053041 if not fy:
Nabin Hait0cf94692015-05-19 18:43:45 +053042 error_msg = _("""{0} {1} not in any active Fiscal Year. For more details check {2}.""").format(label, formatdate(transaction_date), "https://erpnext.com/kb/accounts/fiscal-year-error")
Neil Trini Lasrado78fa6952014-10-03 17:43:02 +053043 if verbose==1: frappe.msgprint(error_msg)
Nabin Hait23941aa2013-01-29 11:32:38 +053044 raise FiscalYearError, error_msg
Rushabh Mehtac2563ef2013-02-05 23:25:37 +053045 return fy
Anand Doshicd71e1d2014-04-08 13:53:35 +053046
Rushabh Mehtad60acb92015-02-19 14:51:58 +053047def validate_fiscal_year(date, fiscal_year, label=_("Date"), doc=None):
Nabin Haitcfecd2b2013-07-11 17:49:18 +053048 years = [f[0] for f in get_fiscal_years(date, label=label)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +053049 if fiscal_year not in years:
Rushabh Mehtad60acb92015-02-19 14:51:58 +053050 if doc:
51 doc.fiscal_year = years[0]
52 else:
53 throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
Nabin Hait23941aa2013-01-29 11:32:38 +053054
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053055@frappe.whitelist()
Nabin Haitc0e3b1a2015-09-04 13:26:23 +053056def get_balance_on(account=None, date=None, party_type=None, party=None, in_account_currency=True):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053057 if not account and frappe.form_dict.get("account"):
58 account = frappe.form_dict.get("account")
Nabin Hait6f17cf92014-09-17 14:11:22 +053059 if not date and frappe.form_dict.get("date"):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053060 date = frappe.form_dict.get("date")
Nabin Hait6f17cf92014-09-17 14:11:22 +053061 if not party_type and frappe.form_dict.get("party_type"):
62 party_type = frappe.form_dict.get("party_type")
63 if not party and frappe.form_dict.get("party"):
64 party = frappe.form_dict.get("party")
Anand Doshi9365b612014-04-21 12:42:21 +053065
Nabin Hait23941aa2013-01-29 11:32:38 +053066 cond = []
67 if date:
68 cond.append("posting_date <= '%s'" % date)
69 else:
70 # get balance of all entries that exist
71 date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +053072
Nabin Hait23941aa2013-01-29 11:32:38 +053073 try:
74 year_start_date = get_fiscal_year(date, verbose=0)[1]
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053075 except FiscalYearError:
Nabin Hait23941aa2013-01-29 11:32:38 +053076 if getdate(date) > getdate(nowdate()):
77 # if fiscal year not found and the date is greater than today
78 # get fiscal year for today's date and its corresponding year start date
79 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
80 else:
81 # this indicates that it is a date older than any existing fiscal year.
82 # hence, assuming balance as 0.0
83 return 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +053084
Nabin Hait6f17cf92014-09-17 14:11:22 +053085 if account:
86 acc = frappe.get_doc("Account", account)
87 acc.check_permission("read")
Anand Doshicd71e1d2014-04-08 13:53:35 +053088
Nabin Hait6f17cf92014-09-17 14:11:22 +053089 # for pl accounts, get balance within a fiscal year
90 if acc.report_type == 'Profit and Loss':
91 cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
92 % year_start_date)
93
94 # different filter for group and ledger - improved performance
Rushabh Mehta38c6b522015-04-23 13:14:17 +053095 if acc.is_group:
Nabin Hait6f17cf92014-09-17 14:11:22 +053096 cond.append("""exists (
Nabin Hait6b01abe2015-06-14 17:49:29 +053097 select name from `tabAccount` ac where ac.name = gle.account
Nabin Hait6f17cf92014-09-17 14:11:22 +053098 and ac.lft >= %s and ac.rgt <= %s
99 )""" % (acc.lft, acc.rgt))
Anand Doshicd0989e2015-09-28 13:31:17 +0530100
101 # If group and currency same as company,
Nabin Hait59f4fa92015-09-17 13:57:42 +0530102 # always return balance based on debit and credit in company currency
103 if acc.account_currency == frappe.db.get_value("Company", acc.company, "default_currency"):
104 in_account_currency = False
Nabin Hait6f17cf92014-09-17 14:11:22 +0530105 else:
106 cond.append("""gle.account = "%s" """ % (account.replace('"', '\\"'), ))
107
108 if party_type and party:
109 cond.append("""gle.party_type = "%s" and gle.party = "%s" """ %
110 (party_type.replace('"', '\\"'), party.replace('"', '\\"')))
Anand Doshi0b031cd2015-09-16 12:46:54 +0530111
Nabin Haitdc768232015-08-17 11:27:00 +0530112 if account or (party_type and party):
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530113 if in_account_currency:
114 select_field = "sum(ifnull(debit_in_account_currency, 0)) - sum(ifnull(credit_in_account_currency, 0))"
115 else:
116 select_field = "sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))"
Nabin Haitdc768232015-08-17 11:27:00 +0530117 bal = frappe.db.sql("""
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530118 SELECT {0}
Nabin Haitdc768232015-08-17 11:27:00 +0530119 FROM `tabGL Entry` gle
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530120 WHERE {1}""".format(select_field, " and ".join(cond)))[0][0]
Anand Doshicd71e1d2014-04-08 13:53:35 +0530121
Nabin Haitdc768232015-08-17 11:27:00 +0530122 # if bal is None, return 0
123 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530124
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530125@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530126def add_ac(args=None):
127 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530128 args = frappe.local.form_dict
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530129 args.pop("cmd")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530130
Anand Doshi3e41fd12014-04-22 18:54:54 +0530131 ac = frappe.new_doc("Account")
132 ac.update(args)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530133 ac.old_parent = ""
134 ac.freeze_account = "No"
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530135 ac.insert()
Anand Doshi3e41fd12014-04-22 18:54:54 +0530136
Anand Doshif78d1ae2014-03-28 13:55:00 +0530137 return ac.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530138
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530139@frappe.whitelist()
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530140def add_cc(args=None):
141 if not args:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530142 args = frappe.local.form_dict
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530143 args.pop("cmd")
Anand Doshicd71e1d2014-04-08 13:53:35 +0530144
Anand Doshi3e41fd12014-04-22 18:54:54 +0530145 cc = frappe.new_doc("Cost Center")
146 cc.update(args)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530147 cc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530148 cc.insert()
Anand Doshif78d1ae2014-03-28 13:55:00 +0530149 return cc.name
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530150
151def reconcile_against_document(args):
152 """
153 Cancel JV, Update aginst document, split if required and resubmit jv
154 """
155 for d in args:
156 check_if_jv_modified(d)
Nabin Hait576f0252014-04-30 19:30:50 +0530157 validate_allocated_amount(d)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530158
159 # cancel JV
Nabin Hait23d2a532014-12-25 17:14:18 +0530160 jv_obj = frappe.get_doc('Journal Entry', d['voucher_no'])
Anand Doshicd71e1d2014-04-08 13:53:35 +0530161
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530162 jv_obj.make_gl_entries(cancel=1, adv_adj=1)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530163
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530164 # update ref in JV Detail
165 update_against_doc(d, jv_obj)
166
167 # re-submit JV
Nabin Hait23d2a532014-12-25 17:14:18 +0530168 jv_obj = frappe.get_doc('Journal Entry', d['voucher_no'])
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530169 jv_obj.make_gl_entries(cancel = 0, adv_adj =1)
170
171
172def check_if_jv_modified(args):
173 """
174 check if there is already a voucher reference
175 check if amount is same
176 check if jv is submitted
177 """
Anand Doshie9baaa62014-02-26 12:35:33 +0530178 ret = frappe.db.sql("""
Nabin Hait23d2a532014-12-25 17:14:18 +0530179 select t2.{dr_or_cr} from `tabJournal Entry` t1, `tabJournal Entry Account` t2
nabinhait97ab9022014-07-21 19:22:02 +0530180 where t1.name = t2.parent and t2.account = %(account)s
Nabin Hait32251022014-08-29 11:18:32 +0530181 and t2.party_type = %(party_type)s and t2.party = %(party)s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530182 and ifnull(t2.reference_type, '') in ("", "Sales Order", "Purchase Order")
nabinhait97ab9022014-07-21 19:22:02 +0530183 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s
184 and t1.docstatus=1 """.format(dr_or_cr = args.get("dr_or_cr")), args)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530185
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530186 if not ret:
Akhilesh Darjee4f721562014-01-29 16:31:38 +0530187 throw(_("""Payment Entry has been modified after you pulled it. Please pull it again."""))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530188
Nabin Hait576f0252014-04-30 19:30:50 +0530189def validate_allocated_amount(args):
190 if args.get("allocated_amt") < 0:
191 throw(_("Allocated amount can not be negative"))
192 elif args.get("allocated_amt") > args.get("unadjusted_amt"):
193 throw(_("Allocated amount can not greater than unadusted amount"))
194
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530195def update_against_doc(d, jv_obj):
196 """
197 Updates against document, if partial amount splits into rows
198 """
Nabin Hait4b8185d2014-12-25 18:19:39 +0530199 jv_detail = jv_obj.get("accounts", {"name": d["voucher_detail_no"]})[0]
Anand Doshicd71e1d2014-04-08 13:53:35 +0530200 jv_detail.set(d["dr_or_cr"], d["allocated_amt"])
Rushabh Mehta1828c122015-08-10 17:04:07 +0530201
202 original_reference_type = jv_detail.reference_type
203 original_reference_name = jv_detail.reference_name
204
205 jv_detail.set("reference_type", d["against_voucher_type"])
206 jv_detail.set("reference_name", d["against_voucher"])
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530207
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530208 if d['allocated_amt'] < d['unadjusted_amt']:
Nabin Haite3ae05a2015-09-09 18:43:12 +0530209 jvd = frappe.db.sql("""
210 select cost_center, balance, against_account, is_advance, account_type, exchange_rate
211 from `tabJournal Entry Account` where name = %s
212 """, d['voucher_detail_no'], as_dict=True)
Anand Doshi0b031cd2015-09-16 12:46:54 +0530213
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530214 # new entry with balance amount
Nabin Hait4b8185d2014-12-25 18:19:39 +0530215 ch = jv_obj.append("accounts")
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530216 ch.account = d['account']
Nabin Haite3ae05a2015-09-09 18:43:12 +0530217 ch.account_type = jvd[0]['account_type']
218 ch.exchange_rate = jvd[0]['exchange_rate']
Nabin Hait32251022014-08-29 11:18:32 +0530219 ch.party_type = d["party_type"]
220 ch.party = d["party"]
Nabin Haite3ae05a2015-09-09 18:43:12 +0530221 ch.cost_center = cstr(jvd[0]["cost_center"])
222 ch.balance = flt(jvd[0]["balance"])
Anand Doshif78d1ae2014-03-28 13:55:00 +0530223 ch.set(d['dr_or_cr'], flt(d['unadjusted_amt']) - flt(d['allocated_amt']))
224 ch.set(d['dr_or_cr']== 'debit' and 'credit' or 'debit', 0)
Nabin Haite3ae05a2015-09-09 18:43:12 +0530225 ch.against_account = cstr(jvd[0]["against_account"])
Rushabh Mehta1828c122015-08-10 17:04:07 +0530226 ch.reference_type = original_reference_type
227 ch.reference_name = original_reference_name
Nabin Haite3ae05a2015-09-09 18:43:12 +0530228 ch.is_advance = cstr(jvd[0]["is_advance"])
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530229 ch.docstatus = 1
Anand Doshicd71e1d2014-04-08 13:53:35 +0530230
231 # will work as update after submit
Anand Doshi6dfd4302015-02-10 14:41:27 +0530232 jv_obj.flags.ignore_validate_update_after_submit = True
Anand Doshicd71e1d2014-04-08 13:53:35 +0530233 jv_obj.save()
234
Rushabh Mehta1828c122015-08-10 17:04:07 +0530235def remove_against_link_from_jv(ref_type, ref_no):
Nabin Haite7d15362014-12-25 16:01:55 +0530236 linked_jv = frappe.db.sql_list("""select parent from `tabJournal Entry Account`
Rushabh Mehta1828c122015-08-10 17:04:07 +0530237 where reference_type=%s and reference_name=%s and docstatus < 2""", (ref_type, ref_no))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530238
239 if linked_jv:
Rushabh Mehta1828c122015-08-10 17:04:07 +0530240 frappe.db.sql("""update `tabJournal Entry Account`
241 set reference_type=null, reference_name = null,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530242 modified=%s, modified_by=%s
Rushabh Mehta1828c122015-08-10 17:04:07 +0530243 where reference_type=%s and reference_name=%s
244 and docstatus < 2""", (now(), frappe.session.user, ref_type, ref_no))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530245
Anand Doshie9baaa62014-02-26 12:35:33 +0530246 frappe.db.sql("""update `tabGL Entry`
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530247 set against_voucher_type=null, against_voucher=null,
248 modified=%s, modified_by=%s
249 where against_voucher_type=%s and against_voucher=%s
250 and voucher_no != ifnull(against_voucher, '')""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530251 (now(), frappe.session.user, ref_type, ref_no))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530252
Nabin Hait23d2a532014-12-25 17:14:18 +0530253 frappe.msgprint(_("Journal Entries {0} are un-linked".format("\n".join(linked_jv))))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530254
Nabin Hait0fc24542013-03-25 11:06:00 +0530255
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530256@frappe.whitelist()
Nabin Hait0fc24542013-03-25 11:06:00 +0530257def get_company_default(company, fieldname):
Anand Doshie9baaa62014-02-26 12:35:33 +0530258 value = frappe.db.get_value("Company", company, fieldname)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530259
Nabin Hait0fc24542013-03-25 11:06:00 +0530260 if not value:
Nabin Hait249bbbc2014-11-26 15:35:08 +0530261 throw(_("Please set default value {0} in Company {1}").format(frappe.get_meta("Company").get_label(fieldname), company))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530262
Nabin Hait0fc24542013-03-25 11:06:00 +0530263 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530264
265def fix_total_debit_credit():
Anand Doshicd71e1d2014-04-08 13:53:35 +0530266 vouchers = frappe.db.sql("""select voucher_type, voucher_no,
267 sum(debit) - sum(credit) as diff
268 from `tabGL Entry`
Nabin Hait8b509f52013-05-28 16:52:30 +0530269 group by voucher_type, voucher_no
270 having sum(ifnull(debit, 0)) != sum(ifnull(credit, 0))""", as_dict=1)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530271
Nabin Hait8b509f52013-05-28 16:52:30 +0530272 for d in vouchers:
273 if abs(d.diff) > 0:
274 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
Anand Doshicd71e1d2014-04-08 13:53:35 +0530275
Anand Doshie9baaa62014-02-26 12:35:33 +0530276 frappe.db.sql("""update `tabGL Entry` set %s = %s + %s
Nabin Hait8b509f52013-05-28 16:52:30 +0530277 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1""" %
Anand Doshicd71e1d2014-04-08 13:53:35 +0530278 (dr_or_cr, dr_or_cr, '%s', '%s', '%s', dr_or_cr),
Nabin Haitcac622e2013-08-02 11:44:29 +0530279 (d.diff, d.voucher_type, d.voucher_no))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530280
Nabin Hait27994c22013-08-26 16:53:30 +0530281def get_stock_and_account_difference(account_list=None, posting_date=None):
Rushabh Mehtac2d28572014-10-08 12:19:55 +0530282 from erpnext.stock.utils import get_stock_value_on
Anand Doshicd71e1d2014-04-08 13:53:35 +0530283
Nabin Hait27994c22013-08-26 16:53:30 +0530284 if not posting_date: posting_date = nowdate()
Anand Doshicd71e1d2014-04-08 13:53:35 +0530285
Nabin Haitcac622e2013-08-02 11:44:29 +0530286 difference = {}
Anand Doshicd71e1d2014-04-08 13:53:35 +0530287
Nabin Haitbe8ec392014-08-27 12:05:48 +0530288 account_warehouse = dict(frappe.db.sql("""select name, warehouse from tabAccount
289 where account_type = 'Warehouse' and ifnull(warehouse, '') != ''
Nabin Hait625da792013-09-25 10:32:51 +0530290 and name in (%s)""" % ', '.join(['%s']*len(account_list)), account_list))
Anand Doshicd71e1d2014-04-08 13:53:35 +0530291
Nabin Hait625da792013-09-25 10:32:51 +0530292 for account, warehouse in account_warehouse.items():
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530293 account_balance = get_balance_on(account, posting_date, in_account_currency=False)
Rushabh Mehtac2d28572014-10-08 12:19:55 +0530294 stock_value = get_stock_value_on(warehouse, posting_date)
Nabin Haitaa342012013-08-07 14:21:04 +0530295 if abs(flt(stock_value) - flt(account_balance)) > 0.005:
Nabin Hait469ee712013-08-07 12:33:37 +0530296 difference.setdefault(account, flt(stock_value) - flt(account_balance))
Nabin Haitaa342012013-08-07 14:21:04 +0530297
Nabin Haitcc0e2d12013-08-06 16:19:18 +0530298 return difference
Nabin Haitb4418a42013-08-22 14:38:46 +0530299
Nabin Haitb4418a42013-08-22 14:38:46 +0530300def validate_expense_against_budget(args):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530301 args = frappe._dict(args)
Nabin Hait0c21e2a2014-03-21 11:14:49 +0530302 if frappe.db.get_value("Account", {"name": args.account, "report_type": "Profit and Loss"}):
Anand Doshie9baaa62014-02-26 12:35:33 +0530303 budget = frappe.db.sql("""
Anand Doshicd71e1d2014-04-08 13:53:35 +0530304 select bd.budget_allocated, cc.distribution_id
Nabin Haitb4418a42013-08-22 14:38:46 +0530305 from `tabCost Center` cc, `tabBudget Detail` bd
306 where cc.name=bd.parent and cc.name=%s and account=%s and bd.fiscal_year=%s
307 """, (args.cost_center, args.account, args.fiscal_year), as_dict=True)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530308
Nabin Haitb4418a42013-08-22 14:38:46 +0530309 if budget and budget[0].budget_allocated:
Anand Doshicd71e1d2014-04-08 13:53:35 +0530310 yearly_action, monthly_action = frappe.db.get_value("Company", args.company,
Nabin Haitb4418a42013-08-22 14:38:46 +0530311 ["yearly_bgt_flag", "monthly_bgt_flag"])
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530312 action_for = action = ""
313
314 if monthly_action in ["Stop", "Warn"]:
Anand Doshicd71e1d2014-04-08 13:53:35 +0530315 budget_amount = get_allocated_budget(budget[0].distribution_id,
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530316 args.posting_date, args.fiscal_year, budget[0].budget_allocated)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530317
318 args["month_end_date"] = frappe.db.sql("select LAST_DAY(%s)",
Nabin Haita3916062013-08-23 10:46:41 +0530319 args.posting_date)[0][0]
Rushabh Mehta8a40c132014-04-15 16:30:55 +0530320 action_for, action = _("Monthly"), monthly_action
Anand Doshicd71e1d2014-04-08 13:53:35 +0530321
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530322 elif yearly_action in ["Stop", "Warn"]:
323 budget_amount = budget[0].budget_allocated
Rushabh Mehta8a40c132014-04-15 16:30:55 +0530324 action_for, action = _("Annual"), yearly_action
Nabin Haita3916062013-08-23 10:46:41 +0530325
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530326 if action_for:
327 actual_expense = get_actual_expense(args)
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530328 if actual_expense > budget_amount:
Rushabh Mehta8a40c132014-04-15 16:30:55 +0530329 frappe.msgprint(_("{0} budget for Account {1} against Cost Center {2} will exceed by {3}").format(
330 _(action_for), args.account, args.cost_center, cstr(actual_expense - budget_amount)))
331 if action=="Stop":
332 raise BudgetError
Anand Doshicd71e1d2014-04-08 13:53:35 +0530333
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530334def get_allocated_budget(distribution_id, posting_date, fiscal_year, yearly_budget):
335 if distribution_id:
336 distribution = {}
Nabin Haite8500ad2015-01-10 16:03:49 +0530337 for d in frappe.db.sql("""select mdp.month, mdp.percentage_allocation
338 from `tabMonthly Distribution Percentage` mdp, `tabMonthly Distribution` md
339 where mdp.parent=md.name and md.fiscal_year=%s""", fiscal_year, as_dict=1):
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530340 distribution.setdefault(d.month, d.percentage_allocation)
Nabin Haita3916062013-08-23 10:46:41 +0530341
Anand Doshie9baaa62014-02-26 12:35:33 +0530342 dt = frappe.db.get_value("Fiscal Year", fiscal_year, "year_start_date")
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530343 budget_percentage = 0.0
Anand Doshicd71e1d2014-04-08 13:53:35 +0530344
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530345 while(dt <= getdate(posting_date)):
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530346 if distribution_id:
Nabin Haita3916062013-08-23 10:46:41 +0530347 budget_percentage += distribution.get(getdate(dt).strftime("%B"), 0)
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530348 else:
349 budget_percentage += 100.0/12
Anand Doshicd71e1d2014-04-08 13:53:35 +0530350
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530351 dt = add_months(dt, 1)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530352
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530353 return yearly_budget * budget_percentage / 100
Anand Doshicd71e1d2014-04-08 13:53:35 +0530354
Nabin Haitb4418a42013-08-22 14:38:46 +0530355def get_actual_expense(args):
Nabin Haita3916062013-08-23 10:46:41 +0530356 args["condition"] = " and posting_date<='%s'" % args.month_end_date \
357 if args.get("month_end_date") else ""
Anand Doshicd71e1d2014-04-08 13:53:35 +0530358
Nabin Haitd3fd8962015-03-17 10:14:59 +0530359 return flt(frappe.db.sql("""
Nabin Haitb4418a42013-08-22 14:38:46 +0530360 select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
361 from `tabGL Entry`
Anand Doshicd71e1d2014-04-08 13:53:35 +0530362 where account='%(account)s' and cost_center='%(cost_center)s'
Nabin Haita3916062013-08-23 10:46:41 +0530363 and fiscal_year='%(fiscal_year)s' and company='%(company)s' %(condition)s
Nabin Haitd3fd8962015-03-17 10:14:59 +0530364 """ % (args))[0][0])
Anand Doshicd71e1d2014-04-08 13:53:35 +0530365
Anand Doshicb39e082014-01-24 21:44:36 +0530366def get_currency_precision(currency=None):
367 if not currency:
Anand Doshicd71e1d2014-04-08 13:53:35 +0530368 currency = frappe.db.get_value("Company",
Rushabh Mehta50ce9752015-04-27 13:13:38 +0530369 frappe.db.get_default("company"), "default_currency", cache=True)
370 currency_format = frappe.db.get_value("Currency", currency, "number_format", cache=True)
Anand Doshicd71e1d2014-04-08 13:53:35 +0530371
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530372 from frappe.utils import get_number_format_info
Anand Doshicb39e082014-01-24 21:44:36 +0530373 return get_number_format_info(currency_format)[2]
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530374
375def get_stock_rbnb_difference(posting_date, company):
376 stock_items = frappe.db.sql_list("""select distinct item_code
Nabin Hait849b7b12014-08-07 15:13:52 +0530377 from `tabStock Ledger Entry` where company=%s""", company)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530378
379 pr_valuation_amount = frappe.db.sql("""
380 select sum(ifnull(pr_item.valuation_rate, 0) * ifnull(pr_item.qty, 0) * ifnull(pr_item.conversion_factor, 0))
381 from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
382 where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s
383 and pr.posting_date <= %s and pr_item.item_code in (%s)""" %
384 ('%s', '%s', ', '.join(['%s']*len(stock_items))), tuple([company, posting_date] + stock_items))[0][0]
385
386 pi_valuation_amount = frappe.db.sql("""
387 select sum(ifnull(pi_item.valuation_rate, 0) * ifnull(pi_item.qty, 0) * ifnull(pi_item.conversion_factor, 0))
388 from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi
389 where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s
390 and pi.posting_date <= %s and pi_item.item_code in (%s)""" %
391 ('%s', '%s', ', '.join(['%s']*len(stock_items))), tuple([company, posting_date] + stock_items))[0][0]
392
393 # Balance should be
394 stock_rbnb = flt(pr_valuation_amount, 2) - flt(pi_valuation_amount, 2)
395
396 # Balance as per system
Nabin Hait849b7b12014-08-07 15:13:52 +0530397 stock_rbnb_account = "Stock Received But Not Billed - " + frappe.db.get_value("Company", company, "abbr")
Nabin Haitc0e3b1a2015-09-04 13:26:23 +0530398 sys_bal = get_balance_on(stock_rbnb_account, posting_date, in_account_currency=False)
Nabin Hait9a0c46f2014-08-07 15:10:05 +0530399
400 # Amount should be credited
401 return flt(stock_rbnb) + flt(sys_bal)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530402
Nabin Hait5b649522015-09-22 08:35:46 +0530403def get_outstanding_invoices(amount_query, account, party_type, party):
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530404 all_outstanding_vouchers = []
405 outstanding_voucher_list = frappe.db.sql("""
406 select
407 voucher_no, voucher_type, posting_date,
408 ifnull(sum({amount_query}), 0) as invoice_amount
409 from
410 `tabGL Entry`
411 where
Nabin Hait997a7a12014-09-16 11:08:08 +0530412 account = %s and party_type=%s and party=%s and {amount_query} > 0
Nabin Hait5b649522015-09-22 08:35:46 +0530413 and (CASE
414 WHEN voucher_type = 'Journal Entry'
415 THEN ifnull(against_voucher, '') = ''
416 ELSE 1=1
417 END)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530418 group by voucher_type, voucher_no
Nabin Hait997a7a12014-09-16 11:08:08 +0530419 """.format(amount_query = amount_query), (account, party_type, party), as_dict = True)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530420
421 for d in outstanding_voucher_list:
422 payment_amount = frappe.db.sql("""
Nabin Hait6b01abe2015-06-14 17:49:29 +0530423 select ifnull(sum({amount_query}), 0)
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530424 from
425 `tabGL Entry`
426 where
Nabin Hait997a7a12014-09-16 11:08:08 +0530427 account = %s and party_type=%s and party=%s and {amount_query} < 0
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530428 and against_voucher_type = %s and ifnull(against_voucher, '') = %s
429 """.format(**{
430 "amount_query": amount_query
Nabin Hait997a7a12014-09-16 11:08:08 +0530431 }), (account, party_type, party, d.voucher_type, d.voucher_no))
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530432
433 payment_amount = -1*payment_amount[0][0] if payment_amount else 0
Rushabh Mehtae027d3f2015-04-15 12:03:21 +0530434 precision = frappe.get_precision("Sales Invoice", "outstanding_amount")
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530435
436 if d.invoice_amount > payment_amount:
437
438 all_outstanding_vouchers.append({
439 'voucher_no': d.voucher_no,
440 'voucher_type': d.voucher_type,
441 'posting_date': d.posting_date,
Rushabh Mehtae027d3f2015-04-15 12:03:21 +0530442 'invoice_amount': flt(d.invoice_amount, precision),
443 'outstanding_amount': flt(d.invoice_amount - payment_amount, precision)
444 })
Ankit Javalkar8e7ca412014-09-12 15:18:53 +0530445
446 return all_outstanding_vouchers