blob: 0611f880c5ec267ab36f8f6b5c79d78fba9ce01e [file] [log] [blame]
Zarrare83ff382018-09-21 15:45:40 +05301import frappe
2from frappe import _
Nabin Hait0a90ce52019-03-28 19:43:02 +05303from frappe.email import sendmail_to_system_managers
Chillar Anand915b3432021-09-02 16:44:59 +05304from frappe.utils import (
5 add_days,
6 add_months,
7 cint,
8 date_diff,
9 flt,
10 get_first_day,
11 get_last_day,
12 get_link_to_form,
13 getdate,
14 rounded,
15 today,
16)
17
18from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
19 get_accounting_dimensions,
20)
21from erpnext.accounts.utils import get_account_currency
22
Zarrare83ff382018-09-21 15:45:40 +053023
24def validate_service_stop_date(doc):
Ankush Menat494bd9e2022-03-28 18:52:46 +053025 """Validates service_stop_date for Purchase Invoice and Sales Invoice"""
Zarrare83ff382018-09-21 15:45:40 +053026
Ankush Menat494bd9e2022-03-28 18:52:46 +053027 enable_check = (
28 "enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense"
29 )
Zarrare83ff382018-09-21 15:45:40 +053030
31 old_stop_dates = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +053032 old_doc = frappe.db.get_all(
33 "{0} Item".format(doc.doctype), {"parent": doc.name}, ["name", "service_stop_date"]
34 )
Zarrare83ff382018-09-21 15:45:40 +053035
36 for d in old_doc:
37 old_stop_dates[d.name] = d.service_stop_date or ""
38
39 for item in doc.items:
Ankush Menat494bd9e2022-03-28 18:52:46 +053040 if not item.get(enable_check):
41 continue
Zarrare83ff382018-09-21 15:45:40 +053042
43 if item.service_stop_date:
44 if date_diff(item.service_stop_date, item.service_start_date) < 0:
45 frappe.throw(_("Service Stop Date cannot be before Service Start Date"))
46
47 if date_diff(item.service_stop_date, item.service_end_date) > 0:
48 frappe.throw(_("Service Stop Date cannot be after Service End Date"))
49
Ankush Menat494bd9e2022-03-28 18:52:46 +053050 if (
51 old_stop_dates
52 and old_stop_dates.get(item.name)
53 and item.service_stop_date != old_stop_dates.get(item.name)
54 ):
Suraj Shetty48e9bc32020-01-29 15:06:18 +053055 frappe.throw(_("Cannot change Service Stop Date for item in row {0}").format(item.idx))
Zarrare83ff382018-09-21 15:45:40 +053056
Ankush Menat494bd9e2022-03-28 18:52:46 +053057
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053058def build_conditions(process_type, account, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +053059 conditions = ""
60 deferred_account = (
61 "item.deferred_revenue_account" if process_type == "Income" else "item.deferred_expense_account"
62 )
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053063
64 if account:
Ankush Menat494bd9e2022-03-28 18:52:46 +053065 conditions += "AND %s='%s'" % (deferred_account, account)
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053066 elif company:
Ankush Menatf3b3d812021-05-17 16:43:38 +053067 conditions += f"AND p.company = {frappe.db.escape(company)}"
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053068
69 return conditions
70
Ankush Menat494bd9e2022-03-28 18:52:46 +053071
72def convert_deferred_expense_to_expense(
73 deferred_process, start_date=None, end_date=None, conditions=""
74):
Nabin Hait0a90ce52019-03-28 19:43:02 +053075 # 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 +053076
Nabin Hait0a90ce52019-03-28 19:43:02 +053077 if not start_date:
78 start_date = add_months(today(), -1)
79 if not end_date:
80 end_date = add_days(today(), -1)
81
Zarrare83ff382018-09-21 15:45:40 +053082 # check for the purchase invoice for which GL entries has to be done
Ankush Menat494bd9e2022-03-28 18:52:46 +053083 invoices = frappe.db.sql_list(
84 """
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +053085 select distinct item.parent
86 from `tabPurchase Invoice Item` item, `tabPurchase Invoice` p
87 where item.service_start_date<=%s and item.service_end_date>=%s
88 and item.enable_deferred_expense = 1 and item.parent=p.name
89 and item.docstatus = 1 and ifnull(item.amount, 0) > 0
90 {0}
Ankush Menat494bd9e2022-03-28 18:52:46 +053091 """.format(
92 conditions
93 ),
94 (end_date, start_date),
95 ) # nosec
Zarrare83ff382018-09-21 15:45:40 +053096
97 # For each invoice, book deferred expense
98 for invoice in invoices:
99 doc = frappe.get_doc("Purchase Invoice", invoice)
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530100 book_deferred_income_or_expense(doc, deferred_process, end_date)
Zarrare83ff382018-09-21 15:45:40 +0530101
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530102 if frappe.flags.deferred_accounting_error:
103 send_mail(deferred_process)
104
Ankush Menat494bd9e2022-03-28 18:52:46 +0530105
106def convert_deferred_revenue_to_income(
107 deferred_process, start_date=None, end_date=None, conditions=""
108):
Nabin Hait0a90ce52019-03-28 19:43:02 +0530109 # 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 +0530110
Nabin Hait0a90ce52019-03-28 19:43:02 +0530111 if not start_date:
112 start_date = add_months(today(), -1)
113 if not end_date:
114 end_date = add_days(today(), -1)
115
Zarrare83ff382018-09-21 15:45:40 +0530116 # check for the sales invoice for which GL entries has to be done
Ankush Menat494bd9e2022-03-28 18:52:46 +0530117 invoices = frappe.db.sql_list(
118 """
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530119 select distinct item.parent
120 from `tabSales Invoice Item` item, `tabSales Invoice` p
121 where item.service_start_date<=%s and item.service_end_date>=%s
122 and item.enable_deferred_revenue = 1 and item.parent=p.name
123 and item.docstatus = 1 and ifnull(item.amount, 0) > 0
124 {0}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530125 """.format(
126 conditions
127 ),
128 (end_date, start_date),
129 ) # nosec
Zarrare83ff382018-09-21 15:45:40 +0530130
Zarrare83ff382018-09-21 15:45:40 +0530131 for invoice in invoices:
132 doc = frappe.get_doc("Sales Invoice", invoice)
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530133 book_deferred_income_or_expense(doc, deferred_process, end_date)
134
135 if frappe.flags.deferred_accounting_error:
136 send_mail(deferred_process)
Zarrare83ff382018-09-21 15:45:40 +0530137
Ankush Menat494bd9e2022-03-28 18:52:46 +0530138
Nabin Hait0a90ce52019-03-28 19:43:02 +0530139def get_booking_dates(doc, item, posting_date=None):
140 if not posting_date:
141 posting_date = add_days(today(), -1)
142
143 last_gl_entry = False
144
Ankush Menat494bd9e2022-03-28 18:52:46 +0530145 deferred_account = (
146 "deferred_revenue_account" if doc.doctype == "Sales Invoice" else "deferred_expense_account"
147 )
Zarrare83ff382018-09-21 15:45:40 +0530148
Ankush Menat494bd9e2022-03-28 18:52:46 +0530149 prev_gl_entry = frappe.db.sql(
150 """
Zarrare83ff382018-09-21 15:45:40 +0530151 select name, posting_date from `tabGL Entry` where company=%s and account=%s and
152 voucher_type=%s and voucher_no=%s and voucher_detail_no=%s
Deepesh Garg366120f2022-03-01 11:56:20 +0530153 and is_cancelled = 0
Zarrare83ff382018-09-21 15:45:40 +0530154 order by posting_date desc limit 1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 """,
156 (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
157 as_dict=True,
158 )
Zarrare83ff382018-09-21 15:45:40 +0530159
Ankush Menat494bd9e2022-03-28 18:52:46 +0530160 prev_gl_via_je = frappe.db.sql(
161 """
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530162 SELECT p.name, p.posting_date FROM `tabJournal Entry` p, `tabJournal Entry Account` c
163 WHERE p.name = c.parent and p.company=%s and c.account=%s
164 and c.reference_type=%s and c.reference_name=%s
165 and c.reference_detail_no=%s and c.docstatus < 2 order by posting_date desc limit 1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530166 """,
167 (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
168 as_dict=True,
169 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530170
171 if prev_gl_via_je:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530172 if (not prev_gl_entry) or (
173 prev_gl_entry and prev_gl_entry[0].posting_date < prev_gl_via_je[0].posting_date
174 ):
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530175 prev_gl_entry = prev_gl_via_je
176
Nabin Hait0a90ce52019-03-28 19:43:02 +0530177 if prev_gl_entry:
178 start_date = getdate(add_days(prev_gl_entry[0].posting_date, 1))
179 else:
180 start_date = item.service_start_date
Zarrare83ff382018-09-21 15:45:40 +0530181
Nabin Hait0a90ce52019-03-28 19:43:02 +0530182 end_date = get_last_day(start_date)
183 if end_date >= item.service_end_date:
184 end_date = item.service_end_date
185 last_gl_entry = True
Nabin Hait66d07c22019-03-29 13:25:11 +0530186 elif item.service_stop_date and end_date >= item.service_stop_date:
187 end_date = item.service_stop_date
188 last_gl_entry = True
Zarrare83ff382018-09-21 15:45:40 +0530189
Nabin Hait0a90ce52019-03-28 19:43:02 +0530190 if end_date > getdate(posting_date):
191 end_date = posting_date
Zarrare83ff382018-09-21 15:45:40 +0530192
Nabin Hait0a90ce52019-03-28 19:43:02 +0530193 if getdate(start_date) <= getdate(end_date):
194 return start_date, end_date, last_gl_entry
195 else:
196 return None, None, None
197
Ankush Menat494bd9e2022-03-28 18:52:46 +0530198
199def calculate_monthly_amount(
200 doc, item, last_gl_entry, start_date, end_date, total_days, total_booking_days, account_currency
201):
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530202 amount, base_amount = 0, 0
Zarrare83ff382018-09-21 15:45:40 +0530203
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530204 if not last_gl_entry:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530205 total_months = (
206 (item.service_end_date.year - item.service_start_date.year) * 12
207 + (item.service_end_date.month - item.service_start_date.month)
208 + 1
209 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530210
Ankush Menat494bd9e2022-03-28 18:52:46 +0530211 prorate_factor = flt(date_diff(item.service_end_date, item.service_start_date)) / flt(
212 date_diff(get_last_day(item.service_end_date), get_first_day(item.service_start_date))
213 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530214
215 actual_months = rounded(total_months * prorate_factor, 1)
216
Ankush Menat494bd9e2022-03-28 18:52:46 +0530217 already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount(
218 doc, item
219 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530220 base_amount = flt(item.base_net_amount / actual_months, item.precision("base_net_amount"))
221
222 if base_amount + already_booked_amount > item.base_net_amount:
223 base_amount = item.base_net_amount - already_booked_amount
224
Ankush Menat494bd9e2022-03-28 18:52:46 +0530225 if account_currency == doc.company_currency:
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530226 amount = base_amount
227 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530228 amount = flt(item.net_amount / actual_months, item.precision("net_amount"))
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530229 if amount + already_booked_amount_in_account_currency > item.net_amount:
230 amount = item.net_amount - already_booked_amount_in_account_currency
231
232 if not (get_first_day(start_date) == start_date and get_last_day(end_date) == end_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 partial_month = flt(date_diff(end_date, start_date)) / flt(
234 date_diff(get_last_day(end_date), get_first_day(start_date))
235 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530236
237 base_amount = rounded(partial_month, 1) * base_amount
238 amount = rounded(partial_month, 1) * amount
239 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530240 already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount(
241 doc, item
242 )
243 base_amount = flt(
244 item.base_net_amount - already_booked_amount, item.precision("base_net_amount")
245 )
246 if account_currency == doc.company_currency:
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530247 amount = base_amount
248 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530249 amount = flt(
250 item.net_amount - already_booked_amount_in_account_currency, item.precision("net_amount")
251 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530252
253 return amount, base_amount
254
Ankush Menat494bd9e2022-03-28 18:52:46 +0530255
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530256def calculate_amount(doc, item, last_gl_entry, total_days, total_booking_days, account_currency):
Zarrare83ff382018-09-21 15:45:40 +0530257 amount, base_amount = 0, 0
258 if not last_gl_entry:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530259 base_amount = flt(
260 item.base_net_amount * total_booking_days / flt(total_days), item.precision("base_net_amount")
261 )
262 if account_currency == doc.company_currency:
Zarrare83ff382018-09-21 15:45:40 +0530263 amount = base_amount
264 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530265 amount = flt(
266 item.net_amount * total_booking_days / flt(total_days), item.precision("net_amount")
267 )
Zarrare83ff382018-09-21 15:45:40 +0530268 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530269 already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount(
270 doc, item
271 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530272
Ankush Menat494bd9e2022-03-28 18:52:46 +0530273 base_amount = flt(
274 item.base_net_amount - already_booked_amount, item.precision("base_net_amount")
275 )
276 if account_currency == doc.company_currency:
Zarrare83ff382018-09-21 15:45:40 +0530277 amount = base_amount
278 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530279 amount = flt(
280 item.net_amount - already_booked_amount_in_account_currency, item.precision("net_amount")
281 )
Zarrare83ff382018-09-21 15:45:40 +0530282
283 return amount, base_amount
284
Ankush Menat494bd9e2022-03-28 18:52:46 +0530285
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530286def get_already_booked_amount(doc, item):
287 if doc.doctype == "Sales Invoice":
288 total_credit_debit, total_credit_debit_currency = "debit", "debit_in_account_currency"
289 deferred_account = "deferred_revenue_account"
290 else:
291 total_credit_debit, total_credit_debit_currency = "credit", "credit_in_account_currency"
292 deferred_account = "deferred_expense_account"
293
Ankush Menat494bd9e2022-03-28 18:52:46 +0530294 gl_entries_details = frappe.db.sql(
295 """
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530296 select sum({0}) as total_credit, sum({1}) as total_credit_in_account_currency, voucher_detail_no
297 from `tabGL Entry` where company=%s and account=%s and voucher_type=%s and voucher_no=%s and voucher_detail_no=%s
Deepesh Garg366120f2022-03-01 11:56:20 +0530298 and is_cancelled = 0
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530299 group by voucher_detail_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530300 """.format(
301 total_credit_debit, total_credit_debit_currency
302 ),
303 (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
304 as_dict=True,
305 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530306
Ankush Menat494bd9e2022-03-28 18:52:46 +0530307 journal_entry_details = frappe.db.sql(
308 """
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530309 SELECT sum(c.{0}) as total_credit, sum(c.{1}) as total_credit_in_account_currency, reference_detail_no
310 FROM `tabJournal Entry` p , `tabJournal Entry Account` c WHERE p.name = c.parent and
311 p.company = %s and c.account=%s and c.reference_type=%s and c.reference_name=%s and c.reference_detail_no=%s
312 and p.docstatus < 2 group by reference_detail_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530313 """.format(
314 total_credit_debit, total_credit_debit_currency
315 ),
316 (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
317 as_dict=True,
318 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530319
320 already_booked_amount = gl_entries_details[0].total_credit if gl_entries_details else 0
321 already_booked_amount += journal_entry_details[0].total_credit if journal_entry_details else 0
322
323 if doc.currency == doc.company_currency:
324 already_booked_amount_in_account_currency = already_booked_amount
325 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530326 already_booked_amount_in_account_currency = (
327 gl_entries_details[0].total_credit_in_account_currency if gl_entries_details else 0
328 )
329 already_booked_amount_in_account_currency += (
330 journal_entry_details[0].total_credit_in_account_currency if journal_entry_details else 0
331 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530332
333 return already_booked_amount, already_booked_amount_in_account_currency
334
Ankush Menat494bd9e2022-03-28 18:52:46 +0530335
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530336def book_deferred_income_or_expense(doc, deferred_process, posting_date=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530337 enable_check = (
338 "enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense"
339 )
Zarrare83ff382018-09-21 15:45:40 +0530340
Ankush Menat494bd9e2022-03-28 18:52:46 +0530341 accounts_frozen_upto = frappe.get_cached_value("Accounts Settings", "None", "acc_frozen_upto")
Deepesh Garg30a647f2022-01-07 19:52:38 +0530342
Ankush Menat494bd9e2022-03-28 18:52:46 +0530343 def _book_deferred_revenue_or_expense(
344 item, via_journal_entry, submit_journal_entry, book_deferred_entries_based_on
345 ):
Nabin Hait0a90ce52019-03-28 19:43:02 +0530346 start_date, end_date, last_gl_entry = get_booking_dates(doc, item, posting_date=posting_date)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530347 if not (start_date and end_date):
348 return
Zarrare83ff382018-09-21 15:45:40 +0530349
Deepesh Garg98f294a2022-01-03 19:40:47 +0530350 account_currency = get_account_currency(item.expense_account or item.income_account)
Zarrare83ff382018-09-21 15:45:40 +0530351 if doc.doctype == "Sales Invoice":
352 against, project = doc.customer, doc.project
353 credit_account, debit_account = item.income_account, item.deferred_revenue_account
354 else:
355 against, project = doc.supplier, item.project
356 credit_account, debit_account = item.deferred_expense_account, item.expense_account
357
Nabin Hait0a90ce52019-03-28 19:43:02 +0530358 total_days = date_diff(item.service_end_date, item.service_start_date) + 1
359 total_booking_days = date_diff(end_date, start_date) + 1
360
Ankush Menat494bd9e2022-03-28 18:52:46 +0530361 if book_deferred_entries_based_on == "Months":
362 amount, base_amount = calculate_monthly_amount(
363 doc,
364 item,
365 last_gl_entry,
366 start_date,
367 end_date,
368 total_days,
369 total_booking_days,
370 account_currency,
371 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530372 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530373 amount, base_amount = calculate_amount(
374 doc, item, last_gl_entry, total_days, total_booking_days, account_currency
375 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530376
Deepesh Gargf79a72d2021-06-24 14:14:46 +0530377 if not amount:
378 return
379
Deepesh Garg30a647f2022-01-07 19:52:38 +0530380 # check if books nor frozen till endate:
Deepesh Garg366120f2022-03-01 11:56:20 +0530381 if accounts_frozen_upto and (end_date) <= getdate(accounts_frozen_upto):
Deepesh Garg30a647f2022-01-07 19:52:38 +0530382 end_date = get_last_day(add_days(accounts_frozen_upto, 1))
383
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530384 if via_journal_entry:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530385 book_revenue_via_journal_entry(
386 doc,
387 credit_account,
388 debit_account,
389 against,
390 amount,
391 base_amount,
392 end_date,
393 project,
394 account_currency,
395 item.cost_center,
396 item,
397 deferred_process,
398 submit_journal_entry,
399 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530400 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530401 make_gl_entries(
402 doc,
403 credit_account,
404 debit_account,
405 against,
406 amount,
407 base_amount,
408 end_date,
409 project,
410 account_currency,
411 item.cost_center,
412 item,
413 deferred_process,
414 )
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530415
416 # Returned in case of any errors because it tries to submit the same record again and again in case of errors
417 if frappe.flags.deferred_accounting_error:
418 return
Nabin Hait0a90ce52019-03-28 19:43:02 +0530419
420 if getdate(end_date) < getdate(posting_date) and not last_gl_entry:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530421 _book_deferred_revenue_or_expense(
422 item, via_journal_entry, submit_journal_entry, book_deferred_entries_based_on
423 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530424
Ankush Menat494bd9e2022-03-28 18:52:46 +0530425 via_journal_entry = cint(
426 frappe.db.get_singles_value("Accounts Settings", "book_deferred_entries_via_journal_entry")
427 )
428 submit_journal_entry = cint(
429 frappe.db.get_singles_value("Accounts Settings", "submit_journal_entries")
430 )
431 book_deferred_entries_based_on = frappe.db.get_singles_value(
432 "Accounts Settings", "book_deferred_entries_based_on"
433 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530434
Ankush Menat494bd9e2022-03-28 18:52:46 +0530435 for item in doc.get("items"):
Nabin Hait0a90ce52019-03-28 19:43:02 +0530436 if item.get(enable_check):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530437 _book_deferred_revenue_or_expense(
438 item, via_journal_entry, submit_journal_entry, book_deferred_entries_based_on
439 )
440
Nabin Hait0a90ce52019-03-28 19:43:02 +0530441
Chinmay D. Pai0d147b02020-05-24 00:54:04 +0530442def process_deferred_accounting(posting_date=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530443 """Converts deferred income/expense into income/expense
444 Executed via background jobs on every month end"""
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530445
Chinmay D. Pai0d147b02020-05-24 00:54:04 +0530446 if not posting_date:
447 posting_date = today()
448
Ankush Menat494bd9e2022-03-28 18:52:46 +0530449 if not cint(
450 frappe.db.get_singles_value(
451 "Accounts Settings", "automatically_process_deferred_accounting_entry"
452 )
453 ):
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530454 return
455
456 start_date = add_months(today(), -1)
457 end_date = add_days(today(), -1)
458
Ankush Menat494bd9e2022-03-28 18:52:46 +0530459 companies = frappe.get_all("Company")
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530460
Deepesh Garg50690952021-07-01 09:31:31 +0530461 for company in companies:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530462 for record_type in ("Income", "Expense"):
463 doc = frappe.get_doc(
464 dict(
465 doctype="Process Deferred Accounting",
466 company=company.name,
467 posting_date=posting_date,
468 start_date=start_date,
469 end_date=end_date,
470 type=record_type,
471 )
472 )
Deepesh Garg50690952021-07-01 09:31:31 +0530473
474 doc.insert()
475 doc.submit()
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530476
Ankush Menat494bd9e2022-03-28 18:52:46 +0530477
478def make_gl_entries(
479 doc,
480 credit_account,
481 debit_account,
482 against,
483 amount,
484 base_amount,
485 posting_date,
486 project,
487 account_currency,
488 cost_center,
489 item,
490 deferred_process=None,
491):
Nabin Hait0a90ce52019-03-28 19:43:02 +0530492 # GL Entry for crediting the amount in the deferred expense
493 from erpnext.accounts.general_ledger import make_gl_entries
494
Ankush Menat494bd9e2022-03-28 18:52:46 +0530495 if amount == 0:
496 return
rohitwaghchauree123ec62019-11-06 15:25:00 +0530497
Nabin Hait0a90ce52019-03-28 19:43:02 +0530498 gl_entries = []
499 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530500 doc.get_gl_dict(
501 {
502 "account": credit_account,
503 "against": against,
504 "credit": base_amount,
505 "credit_in_account_currency": amount,
506 "cost_center": cost_center,
507 "voucher_detail_no": item.name,
508 "posting_date": posting_date,
509 "project": project,
510 "against_voucher_type": "Process Deferred Accounting",
511 "against_voucher": deferred_process,
512 },
513 account_currency,
514 item=item,
515 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530516 )
517 # GL Entry to debit the amount from the expense
518 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530519 doc.get_gl_dict(
520 {
521 "account": debit_account,
522 "against": against,
523 "debit": base_amount,
524 "debit_in_account_currency": amount,
525 "cost_center": cost_center,
526 "voucher_detail_no": item.name,
527 "posting_date": posting_date,
528 "project": project,
529 "against_voucher_type": "Process Deferred Accounting",
530 "against_voucher": deferred_process,
531 },
532 account_currency,
533 item=item,
534 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530535 )
536
Zarrare83ff382018-09-21 15:45:40 +0530537 if gl_entries:
Nabin Hait29fcb142019-02-13 17:18:12 +0530538 try:
539 make_gl_entries(gl_entries, cancel=(doc.docstatus == 2), merge_entries=True)
540 frappe.db.commit()
Deepesh Gargf1a669c2021-09-29 22:26:33 +0530541 except Exception as e:
542 if frappe.flags.in_test:
Deepesh Garg67a001d2021-12-04 19:19:03 +0530543 traceback = frappe.get_traceback()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530544 frappe.log_error(
545 title=_("Error while processing deferred accounting for Invoice {0}").format(doc.name),
546 message=traceback,
547 )
Deepesh Garg3c64e202021-12-04 20:05:37 +0530548 raise e
Deepesh Gargf1a669c2021-09-29 22:26:33 +0530549 else:
550 frappe.db.rollback()
551 traceback = frappe.get_traceback()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530552 frappe.log_error(
553 title=_("Error while processing deferred accounting for Invoice {0}").format(doc.name),
554 message=traceback,
555 )
Deepesh Gargf1a669c2021-09-29 22:26:33 +0530556 frappe.flags.deferred_accounting_error = True
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530557
Ankush Menat494bd9e2022-03-28 18:52:46 +0530558
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530559def send_mail(deferred_process):
Ankush Menatb6783b12021-05-17 17:06:12 +0530560 title = _("Error while processing deferred accounting for {0}").format(deferred_process)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530561 link = get_link_to_form("Process Deferred Accounting", deferred_process)
Ankush Menatb6783b12021-05-17 17:06:12 +0530562 content = _("Deferred accounting failed for some invoices:") + "\n"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530563 content += _(
564 "Please check Process Deferred Accounting {0} and submit manually after resolving errors."
565 ).format(link)
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530566 sendmail_to_system_managers(title, content)
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530567
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530568
Ankush Menat494bd9e2022-03-28 18:52:46 +0530569def book_revenue_via_journal_entry(
570 doc,
571 credit_account,
572 debit_account,
573 against,
574 amount,
575 base_amount,
576 posting_date,
577 project,
578 account_currency,
579 cost_center,
580 item,
581 deferred_process=None,
582 submit="No",
583):
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530584
Ankush Menat494bd9e2022-03-28 18:52:46 +0530585 if amount == 0:
586 return
587
588 journal_entry = frappe.new_doc("Journal Entry")
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530589 journal_entry.posting_date = posting_date
590 journal_entry.company = doc.company
Ankush Menat494bd9e2022-03-28 18:52:46 +0530591 journal_entry.voucher_type = (
592 "Deferred Revenue" if doc.doctype == "Sales Invoice" else "Deferred Expense"
593 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530594
595 debit_entry = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530596 "account": credit_account,
597 "credit": base_amount,
598 "credit_in_account_currency": amount,
599 "account_currency": account_currency,
600 "reference_name": doc.name,
601 "reference_type": doc.doctype,
602 "reference_detail_no": item.name,
603 "cost_center": cost_center,
604 "project": project,
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530605 }
606
607 credit_entry = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530608 "account": debit_account,
609 "debit": base_amount,
610 "debit_in_account_currency": amount,
611 "account_currency": account_currency,
612 "reference_name": doc.name,
613 "reference_type": doc.doctype,
614 "reference_detail_no": item.name,
615 "cost_center": cost_center,
616 "project": project,
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530617 }
618
619 for dimension in get_accounting_dimensions():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530620 debit_entry.update({dimension: item.get(dimension)})
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530621
Ankush Menat494bd9e2022-03-28 18:52:46 +0530622 credit_entry.update({dimension: item.get(dimension)})
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530623
Ankush Menat494bd9e2022-03-28 18:52:46 +0530624 journal_entry.append("accounts", debit_entry)
625 journal_entry.append("accounts", credit_entry)
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530626
627 try:
628 journal_entry.save()
629
630 if submit:
631 journal_entry.submit()
Deepesh Garg0ba4fce2021-12-04 19:25:44 +0530632
633 frappe.db.commit()
Ankush Menat694ae812021-09-01 14:40:56 +0530634 except Exception:
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530635 frappe.db.rollback()
636 traceback = frappe.get_traceback()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530637 frappe.log_error(
638 title=_("Error while processing deferred accounting for Invoice {0}").format(doc.name),
639 message=traceback,
640 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530641
642 frappe.flags.deferred_accounting_error = True
643
Ankush Menat494bd9e2022-03-28 18:52:46 +0530644
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530645def get_deferred_booking_accounts(doctype, voucher_detail_no, dr_or_cr):
646
Ankush Menat494bd9e2022-03-28 18:52:46 +0530647 if doctype == "Sales Invoice":
648 credit_account, debit_account = frappe.db.get_value(
649 "Sales Invoice Item",
650 {"name": voucher_detail_no},
651 ["income_account", "deferred_revenue_account"],
652 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530653 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530654 credit_account, debit_account = frappe.db.get_value(
655 "Purchase Invoice Item",
656 {"name": voucher_detail_no},
657 ["deferred_expense_account", "expense_account"],
658 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530659
Ankush Menat494bd9e2022-03-28 18:52:46 +0530660 if dr_or_cr == "Debit":
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530661 return debit_account
662 else:
663 return credit_account