blob: 448011016e760ad7bf6f36495845b53d1e944338 [file] [log] [blame]
Zarrare83ff382018-09-21 15:45:40 +05301from __future__ import unicode_literals
2
3import frappe
4from frappe import _
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +05305from frappe.utils import date_diff, add_months, today, getdate, add_days, flt, get_last_day, cint, get_link_to_form
Zarrare83ff382018-09-21 15:45:40 +05306from erpnext.accounts.utils import get_account_currency
Nabin Hait0a90ce52019-03-28 19:43:02 +05307from frappe.email import sendmail_to_system_managers
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +05308from frappe.utils.background_jobs import enqueue
Zarrare83ff382018-09-21 15:45:40 +05309
10def validate_service_stop_date(doc):
11 ''' Validates service_stop_date for Purchase Invoice and Sales Invoice '''
12
13 enable_check = "enable_deferred_revenue" \
14 if doc.doctype=="Sales Invoice" else "enable_deferred_expense"
15
16 old_stop_dates = {}
17 old_doc = frappe.db.get_all("{0} Item".format(doc.doctype),
18 {"parent": doc.name}, ["name", "service_stop_date"])
19
20 for d in old_doc:
21 old_stop_dates[d.name] = d.service_stop_date or ""
22
23 for item in doc.items:
24 if not item.get(enable_check): continue
25
26 if item.service_stop_date:
27 if date_diff(item.service_stop_date, item.service_start_date) < 0:
28 frappe.throw(_("Service Stop Date cannot be before Service Start Date"))
29
30 if date_diff(item.service_stop_date, item.service_end_date) > 0:
31 frappe.throw(_("Service Stop Date cannot be after Service End Date"))
32
Rohit Waghchaurec699b2a2018-09-24 11:57:48 +053033 if old_stop_dates and old_stop_dates.get(item.name) and item.service_stop_date!=old_stop_dates.get(item.name):
Suraj Shetty48e9bc32020-01-29 15:06:18 +053034 frappe.throw(_("Cannot change Service Stop Date for item in row {0}").format(item.idx))
Zarrare83ff382018-09-21 15:45:40 +053035
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053036def build_conditions(process_type, account, company):
37 conditions=''
38 deferred_account = "item.deferred_revenue_account" if process_type=="Income" else "item.deferred_expense_account"
39
40 if account:
41 conditions += "AND %s='%s'"%(deferred_account, account)
42 elif company:
43 conditions += "AND p.company='%s'"%(company)
44
45 return conditions
46
47def convert_deferred_expense_to_expense(deferred_process, start_date=None, end_date=None, conditions=''):
Nabin Hait0a90ce52019-03-28 19:43:02 +053048 # book the expense/income on the last day, but it will be trigger on the 1st of month at 12:00 AM
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053049
Nabin Hait0a90ce52019-03-28 19:43:02 +053050 if not start_date:
51 start_date = add_months(today(), -1)
52 if not end_date:
53 end_date = add_days(today(), -1)
54
Zarrare83ff382018-09-21 15:45:40 +053055 # check for the purchase invoice for which GL entries has to be done
56 invoices = frappe.db.sql_list('''
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053057 select distinct item.parent
58 from `tabPurchase Invoice Item` item, `tabPurchase Invoice` p
59 where item.service_start_date<=%s and item.service_end_date>=%s
60 and item.enable_deferred_expense = 1 and item.parent=p.name
61 and item.docstatus = 1 and ifnull(item.amount, 0) > 0
62 {0}
63 '''.format(conditions), (end_date, start_date)) #nosec
Zarrare83ff382018-09-21 15:45:40 +053064
65 # For each invoice, book deferred expense
66 for invoice in invoices:
67 doc = frappe.get_doc("Purchase Invoice", invoice)
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053068 book_deferred_income_or_expense(doc, deferred_process, end_date)
Zarrare83ff382018-09-21 15:45:40 +053069
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053070 if frappe.flags.deferred_accounting_error:
71 send_mail(deferred_process)
72
73def convert_deferred_revenue_to_income(deferred_process, start_date=None, end_date=None, conditions=''):
Nabin Hait0a90ce52019-03-28 19:43:02 +053074 # book the expense/income on the last day, but it will be trigger on the 1st of month at 12:00 AM
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053075
Nabin Hait0a90ce52019-03-28 19:43:02 +053076 if not start_date:
77 start_date = add_months(today(), -1)
78 if not end_date:
79 end_date = add_days(today(), -1)
80
Zarrare83ff382018-09-21 15:45:40 +053081 # check for the sales invoice for which GL entries has to be done
82 invoices = frappe.db.sql_list('''
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053083 select distinct item.parent
84 from `tabSales Invoice Item` item, `tabSales Invoice` p
85 where item.service_start_date<=%s and item.service_end_date>=%s
86 and item.enable_deferred_revenue = 1 and item.parent=p.name
87 and item.docstatus = 1 and ifnull(item.amount, 0) > 0
88 {0}
89 '''.format(conditions), (end_date, start_date)) #nosec
Zarrare83ff382018-09-21 15:45:40 +053090
Zarrare83ff382018-09-21 15:45:40 +053091 for invoice in invoices:
92 doc = frappe.get_doc("Sales Invoice", invoice)
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053093 book_deferred_income_or_expense(doc, deferred_process, end_date)
94
95 if frappe.flags.deferred_accounting_error:
96 send_mail(deferred_process)
Zarrare83ff382018-09-21 15:45:40 +053097
Nabin Hait0a90ce52019-03-28 19:43:02 +053098def get_booking_dates(doc, item, posting_date=None):
99 if not posting_date:
100 posting_date = add_days(today(), -1)
101
102 last_gl_entry = False
103
Zarrare83ff382018-09-21 15:45:40 +0530104 deferred_account = "deferred_revenue_account" if doc.doctype=="Sales Invoice" else "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530105
106 prev_gl_entry = frappe.db.sql('''
107 select name, posting_date from `tabGL Entry` where company=%s and account=%s and
108 voucher_type=%s and voucher_no=%s and voucher_detail_no=%s
109 order by posting_date desc limit 1
110 ''', (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name), as_dict=True)
111
Nabin Hait0a90ce52019-03-28 19:43:02 +0530112 if prev_gl_entry:
113 start_date = getdate(add_days(prev_gl_entry[0].posting_date, 1))
114 else:
115 start_date = item.service_start_date
Zarrare83ff382018-09-21 15:45:40 +0530116
Nabin Hait0a90ce52019-03-28 19:43:02 +0530117 end_date = get_last_day(start_date)
118 if end_date >= item.service_end_date:
119 end_date = item.service_end_date
120 last_gl_entry = True
Nabin Hait66d07c22019-03-29 13:25:11 +0530121 elif item.service_stop_date and end_date >= item.service_stop_date:
122 end_date = item.service_stop_date
123 last_gl_entry = True
Zarrare83ff382018-09-21 15:45:40 +0530124
Nabin Hait0a90ce52019-03-28 19:43:02 +0530125 if end_date > getdate(posting_date):
126 end_date = posting_date
Zarrare83ff382018-09-21 15:45:40 +0530127
Nabin Hait0a90ce52019-03-28 19:43:02 +0530128 if getdate(start_date) <= getdate(end_date):
129 return start_date, end_date, last_gl_entry
130 else:
131 return None, None, None
132
133def calculate_amount(doc, item, last_gl_entry, total_days, total_booking_days, account_currency):
Zarrare83ff382018-09-21 15:45:40 +0530134 if doc.doctype == "Sales Invoice":
135 total_credit_debit, total_credit_debit_currency = "debit", "debit_in_account_currency"
136 deferred_account = "deferred_revenue_account"
137 else:
138 total_credit_debit, total_credit_debit_currency = "credit", "credit_in_account_currency"
139 deferred_account = "deferred_expense_account"
140
141 amount, base_amount = 0, 0
142 if not last_gl_entry:
143 base_amount = flt(item.base_net_amount*total_booking_days/flt(total_days), item.precision("base_net_amount"))
144 if account_currency==doc.company_currency:
145 amount = base_amount
146 else:
147 amount = flt(item.net_amount*total_booking_days/flt(total_days), item.precision("net_amount"))
148 else:
149 gl_entries_details = frappe.db.sql('''
150 select sum({0}) as total_credit, sum({1}) as total_credit_in_account_currency, voucher_detail_no
151 from `tabGL Entry` where company=%s and account=%s and voucher_type=%s and voucher_no=%s and voucher_detail_no=%s
152 group by voucher_detail_no
153 '''.format(total_credit_debit, total_credit_debit_currency),
154 (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name), as_dict=True)
Zarrare83ff382018-09-21 15:45:40 +0530155 already_booked_amount = gl_entries_details[0].total_credit if gl_entries_details else 0
156 base_amount = flt(item.base_net_amount - already_booked_amount, item.precision("base_net_amount"))
157 if account_currency==doc.company_currency:
158 amount = base_amount
159 else:
160 already_booked_amount_in_account_currency = gl_entries_details[0].total_credit_in_account_currency if gl_entries_details else 0
161 amount = flt(item.net_amount - already_booked_amount_in_account_currency, item.precision("net_amount"))
162
163 return amount, base_amount
164
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530165def book_deferred_income_or_expense(doc, deferred_process, posting_date=None):
Nabin Hait27af6b32019-02-08 16:52:13 +0530166 enable_check = "enable_deferred_revenue" \
167 if doc.doctype=="Sales Invoice" else "enable_deferred_expense"
Zarrare83ff382018-09-21 15:45:40 +0530168
Nabin Hait0a90ce52019-03-28 19:43:02 +0530169 def _book_deferred_revenue_or_expense(item):
170 start_date, end_date, last_gl_entry = get_booking_dates(doc, item, posting_date=posting_date)
171 if not (start_date and end_date): return
Zarrare83ff382018-09-21 15:45:40 +0530172
173 account_currency = get_account_currency(item.expense_account)
Zarrare83ff382018-09-21 15:45:40 +0530174 if doc.doctype == "Sales Invoice":
175 against, project = doc.customer, doc.project
176 credit_account, debit_account = item.income_account, item.deferred_revenue_account
177 else:
178 against, project = doc.supplier, item.project
179 credit_account, debit_account = item.deferred_expense_account, item.expense_account
180
Nabin Hait0a90ce52019-03-28 19:43:02 +0530181 total_days = date_diff(item.service_end_date, item.service_start_date) + 1
182 total_booking_days = date_diff(end_date, start_date) + 1
183
184 amount, base_amount = calculate_amount(doc, item, last_gl_entry,
185 total_days, total_booking_days, account_currency)
186
187 make_gl_entries(doc, credit_account, debit_account, against,
Deepesh Garg7d61c032020-05-15 12:58:48 +0530188 amount, base_amount, end_date, project, account_currency, item.cost_center, item, deferred_process)
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530189
190 # Returned in case of any errors because it tries to submit the same record again and again in case of errors
191 if frappe.flags.deferred_accounting_error:
192 return
Nabin Hait0a90ce52019-03-28 19:43:02 +0530193
194 if getdate(end_date) < getdate(posting_date) and not last_gl_entry:
195 _book_deferred_revenue_or_expense(item)
196
197
198 for item in doc.get('items'):
199 if item.get(enable_check):
200 _book_deferred_revenue_or_expense(item)
201
Chinmay D. Pai0d147b02020-05-24 00:54:04 +0530202def process_deferred_accounting(posting_date=None):
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530203 ''' Converts deferred income/expense into income/expense
204 Executed via background jobs on every month end '''
205
Chinmay D. Pai0d147b02020-05-24 00:54:04 +0530206 if not posting_date:
207 posting_date = today()
208
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530209 if not cint(frappe.db.get_singles_value('Accounts Settings', 'automatically_process_deferred_accounting_entry')):
210 return
211
212 start_date = add_months(today(), -1)
213 end_date = add_days(today(), -1)
214
215 for record_type in ('Income', 'Expense'):
216 doc = frappe.get_doc(dict(
217 doctype='Process Deferred Accounting',
218 posting_date=posting_date,
219 start_date=start_date,
220 end_date=end_date,
221 type=record_type
222 ))
223
224 doc.insert()
225 doc.submit()
226
Nabin Hait0a90ce52019-03-28 19:43:02 +0530227def make_gl_entries(doc, credit_account, debit_account, against,
Deepesh Garg7d61c032020-05-15 12:58:48 +0530228 amount, base_amount, posting_date, project, account_currency, cost_center, item, deferred_process=None):
Nabin Hait0a90ce52019-03-28 19:43:02 +0530229 # GL Entry for crediting the amount in the deferred expense
230 from erpnext.accounts.general_ledger import make_gl_entries
231
rohitwaghchauree123ec62019-11-06 15:25:00 +0530232 if amount == 0: return
233
Nabin Hait0a90ce52019-03-28 19:43:02 +0530234 gl_entries = []
235 gl_entries.append(
236 doc.get_gl_dict({
237 "account": credit_account,
238 "against": against,
239 "credit": base_amount,
240 "credit_in_account_currency": amount,
241 "cost_center": cost_center,
Deepesh Garg7d61c032020-05-15 12:58:48 +0530242 "voucher_detail_no": item.name,
Nabin Hait0a90ce52019-03-28 19:43:02 +0530243 'posting_date': posting_date,
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530244 'project': project,
245 'against_voucher_type': 'Process Deferred Accounting',
246 'against_voucher': deferred_process
Deepesh Garg7d61c032020-05-15 12:58:48 +0530247 }, account_currency, item=item)
Nabin Hait0a90ce52019-03-28 19:43:02 +0530248 )
249 # GL Entry to debit the amount from the expense
250 gl_entries.append(
251 doc.get_gl_dict({
252 "account": debit_account,
253 "against": against,
254 "debit": base_amount,
255 "debit_in_account_currency": amount,
256 "cost_center": cost_center,
Deepesh Garg7d61c032020-05-15 12:58:48 +0530257 "voucher_detail_no": item.name,
Nabin Hait0a90ce52019-03-28 19:43:02 +0530258 'posting_date': posting_date,
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530259 'project': project,
260 'against_voucher_type': 'Process Deferred Accounting',
261 'against_voucher': deferred_process
Deepesh Garg7d61c032020-05-15 12:58:48 +0530262 }, account_currency, item=item)
Nabin Hait0a90ce52019-03-28 19:43:02 +0530263 )
264
Zarrare83ff382018-09-21 15:45:40 +0530265 if gl_entries:
Nabin Hait29fcb142019-02-13 17:18:12 +0530266 try:
267 make_gl_entries(gl_entries, cancel=(doc.docstatus == 2), merge_entries=True)
268 frappe.db.commit()
269 except:
270 frappe.db.rollback()
Nabin Hait0a90ce52019-03-28 19:43:02 +0530271 traceback = frappe.get_traceback()
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530272 frappe.log_error(message=traceback)
273
274 frappe.flags.deferred_accounting_error = True
275
276def send_mail(deferred_process):
277 title = _("Error while processing deferred accounting for {0}".format(deferred_process))
278 content = _("""
279 Deferred accounting failed for some invoices:
280 Please check Process Deferred Accounting {0}
281 and submit manually after resolving errors
282 """).format(get_link_to_form('Process Deferred Accounting', deferred_process))
283 sendmail_to_system_managers(title, content)