blob: 367b017969b357ae6df2e3b3117ea7dfad558e3a [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
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530139def get_booking_dates(doc, item, posting_date=None, prev_posting_date=None):
Nabin Hait0a90ce52019-03-28 19:43:02 +0530140 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
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530149 if not prev_posting_date:
150 prev_gl_entry = frappe.db.sql(
151 """
152 select name, posting_date from `tabGL Entry` where company=%s and account=%s and
153 voucher_type=%s and voucher_no=%s and voucher_detail_no=%s
154 and is_cancelled = 0
155 order by posting_date desc limit 1
156 """,
157 (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
158 as_dict=True,
159 )
Zarrare83ff382018-09-21 15:45:40 +0530160
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530161 prev_gl_via_je = frappe.db.sql(
162 """
163 SELECT p.name, p.posting_date FROM `tabJournal Entry` p, `tabJournal Entry Account` c
164 WHERE p.name = c.parent and p.company=%s and c.account=%s
165 and c.reference_type=%s and c.reference_name=%s
166 and c.reference_detail_no=%s and c.docstatus < 2 order by posting_date desc limit 1
167 """,
168 (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
169 as_dict=True,
170 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530171
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530172 if prev_gl_via_je:
173 if (not prev_gl_entry) or (
174 prev_gl_entry and prev_gl_entry[0].posting_date < prev_gl_via_je[0].posting_date
175 ):
176 prev_gl_entry = prev_gl_via_je
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530177
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530178 if prev_gl_entry:
179 start_date = getdate(add_days(prev_gl_entry[0].posting_date, 1))
180 else:
181 start_date = item.service_start_date
182
Nabin Hait0a90ce52019-03-28 19:43:02 +0530183 else:
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530184 start_date = getdate(add_days(prev_posting_date, 1))
Nabin Hait0a90ce52019-03-28 19:43:02 +0530185 end_date = get_last_day(start_date)
186 if end_date >= item.service_end_date:
187 end_date = item.service_end_date
188 last_gl_entry = True
Nabin Hait66d07c22019-03-29 13:25:11 +0530189 elif item.service_stop_date and end_date >= item.service_stop_date:
190 end_date = item.service_stop_date
191 last_gl_entry = True
Zarrare83ff382018-09-21 15:45:40 +0530192
Nabin Hait0a90ce52019-03-28 19:43:02 +0530193 if end_date > getdate(posting_date):
194 end_date = posting_date
Zarrare83ff382018-09-21 15:45:40 +0530195
Nabin Hait0a90ce52019-03-28 19:43:02 +0530196 if getdate(start_date) <= getdate(end_date):
197 return start_date, end_date, last_gl_entry
198 else:
199 return None, None, None
200
Ankush Menat494bd9e2022-03-28 18:52:46 +0530201
202def calculate_monthly_amount(
203 doc, item, last_gl_entry, start_date, end_date, total_days, total_booking_days, account_currency
204):
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530205 amount, base_amount = 0, 0
Zarrare83ff382018-09-21 15:45:40 +0530206
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530207 if not last_gl_entry:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530208 total_months = (
209 (item.service_end_date.year - item.service_start_date.year) * 12
210 + (item.service_end_date.month - item.service_start_date.month)
211 + 1
212 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530213
Ankush Menat494bd9e2022-03-28 18:52:46 +0530214 prorate_factor = flt(date_diff(item.service_end_date, item.service_start_date)) / flt(
215 date_diff(get_last_day(item.service_end_date), get_first_day(item.service_start_date))
216 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530217
218 actual_months = rounded(total_months * prorate_factor, 1)
219
Ankush Menat494bd9e2022-03-28 18:52:46 +0530220 already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount(
221 doc, item
222 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530223 base_amount = flt(item.base_net_amount / actual_months, item.precision("base_net_amount"))
224
225 if base_amount + already_booked_amount > item.base_net_amount:
226 base_amount = item.base_net_amount - already_booked_amount
227
Ankush Menat494bd9e2022-03-28 18:52:46 +0530228 if account_currency == doc.company_currency:
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530229 amount = base_amount
230 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530231 amount = flt(item.net_amount / actual_months, item.precision("net_amount"))
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530232 if amount + already_booked_amount_in_account_currency > item.net_amount:
233 amount = item.net_amount - already_booked_amount_in_account_currency
234
barredterraeb9ee3f2023-12-05 11:22:55 +0100235 if get_first_day(start_date) != start_date or get_last_day(end_date) != end_date:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530236 partial_month = flt(date_diff(end_date, start_date)) / flt(
237 date_diff(get_last_day(end_date), get_first_day(start_date))
238 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530239
240 base_amount = rounded(partial_month, 1) * base_amount
241 amount = rounded(partial_month, 1) * amount
242 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530243 already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount(
244 doc, item
245 )
246 base_amount = flt(
247 item.base_net_amount - already_booked_amount, item.precision("base_net_amount")
248 )
249 if account_currency == doc.company_currency:
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530250 amount = base_amount
251 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530252 amount = flt(
253 item.net_amount - already_booked_amount_in_account_currency, item.precision("net_amount")
254 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530255
256 return amount, base_amount
257
Ankush Menat494bd9e2022-03-28 18:52:46 +0530258
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530259def calculate_amount(doc, item, last_gl_entry, total_days, total_booking_days, account_currency):
Zarrare83ff382018-09-21 15:45:40 +0530260 amount, base_amount = 0, 0
261 if not last_gl_entry:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530262 base_amount = flt(
263 item.base_net_amount * total_booking_days / flt(total_days), item.precision("base_net_amount")
264 )
265 if account_currency == doc.company_currency:
Zarrare83ff382018-09-21 15:45:40 +0530266 amount = base_amount
267 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530268 amount = flt(
269 item.net_amount * total_booking_days / flt(total_days), item.precision("net_amount")
270 )
Zarrare83ff382018-09-21 15:45:40 +0530271 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530272 already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount(
273 doc, item
274 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530275
Ankush Menat494bd9e2022-03-28 18:52:46 +0530276 base_amount = flt(
277 item.base_net_amount - already_booked_amount, item.precision("base_net_amount")
278 )
279 if account_currency == doc.company_currency:
Zarrare83ff382018-09-21 15:45:40 +0530280 amount = base_amount
281 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530282 amount = flt(
283 item.net_amount - already_booked_amount_in_account_currency, item.precision("net_amount")
284 )
Zarrare83ff382018-09-21 15:45:40 +0530285
286 return amount, base_amount
287
Ankush Menat494bd9e2022-03-28 18:52:46 +0530288
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530289def get_already_booked_amount(doc, item):
290 if doc.doctype == "Sales Invoice":
291 total_credit_debit, total_credit_debit_currency = "debit", "debit_in_account_currency"
292 deferred_account = "deferred_revenue_account"
293 else:
294 total_credit_debit, total_credit_debit_currency = "credit", "credit_in_account_currency"
295 deferred_account = "deferred_expense_account"
296
Ankush Menat494bd9e2022-03-28 18:52:46 +0530297 gl_entries_details = frappe.db.sql(
298 """
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530299 select sum({0}) as total_credit, sum({1}) as total_credit_in_account_currency, voucher_detail_no
300 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 +0530301 and is_cancelled = 0
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530302 group by voucher_detail_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530303 """.format(
304 total_credit_debit, total_credit_debit_currency
305 ),
306 (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
307 as_dict=True,
308 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530309
Ankush Menat494bd9e2022-03-28 18:52:46 +0530310 journal_entry_details = frappe.db.sql(
311 """
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530312 SELECT sum(c.{0}) as total_credit, sum(c.{1}) as total_credit_in_account_currency, reference_detail_no
313 FROM `tabJournal Entry` p , `tabJournal Entry Account` c WHERE p.name = c.parent and
314 p.company = %s and c.account=%s and c.reference_type=%s and c.reference_name=%s and c.reference_detail_no=%s
315 and p.docstatus < 2 group by reference_detail_no
Ankush Menat494bd9e2022-03-28 18:52:46 +0530316 """.format(
317 total_credit_debit, total_credit_debit_currency
318 ),
319 (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
320 as_dict=True,
321 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530322
323 already_booked_amount = gl_entries_details[0].total_credit if gl_entries_details else 0
324 already_booked_amount += journal_entry_details[0].total_credit if journal_entry_details else 0
325
326 if doc.currency == doc.company_currency:
327 already_booked_amount_in_account_currency = already_booked_amount
328 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530329 already_booked_amount_in_account_currency = (
330 gl_entries_details[0].total_credit_in_account_currency if gl_entries_details else 0
331 )
332 already_booked_amount_in_account_currency += (
333 journal_entry_details[0].total_credit_in_account_currency if journal_entry_details else 0
334 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530335
336 return already_booked_amount, already_booked_amount_in_account_currency
337
Ankush Menat494bd9e2022-03-28 18:52:46 +0530338
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530339def book_deferred_income_or_expense(doc, deferred_process, posting_date=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530340 enable_check = (
341 "enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense"
342 )
Zarrare83ff382018-09-21 15:45:40 +0530343
ruthra kumarba158102023-08-01 07:58:09 +0530344 accounts_frozen_upto = frappe.db.get_single_value("Accounts Settings", "acc_frozen_upto")
Deepesh Garg30a647f2022-01-07 19:52:38 +0530345
Ankush Menat494bd9e2022-03-28 18:52:46 +0530346 def _book_deferred_revenue_or_expense(
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530347 item,
348 via_journal_entry,
349 submit_journal_entry,
350 book_deferred_entries_based_on,
351 prev_posting_date=None,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530352 ):
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530353 start_date, end_date, last_gl_entry = get_booking_dates(
354 doc, item, posting_date=posting_date, prev_posting_date=prev_posting_date
355 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530356 if not (start_date and end_date):
357 return
Zarrare83ff382018-09-21 15:45:40 +0530358
Deepesh Garg98f294a2022-01-03 19:40:47 +0530359 account_currency = get_account_currency(item.expense_account or item.income_account)
Zarrare83ff382018-09-21 15:45:40 +0530360 if doc.doctype == "Sales Invoice":
361 against, project = doc.customer, doc.project
362 credit_account, debit_account = item.income_account, item.deferred_revenue_account
363 else:
364 against, project = doc.supplier, item.project
365 credit_account, debit_account = item.deferred_expense_account, item.expense_account
366
Nabin Hait0a90ce52019-03-28 19:43:02 +0530367 total_days = date_diff(item.service_end_date, item.service_start_date) + 1
368 total_booking_days = date_diff(end_date, start_date) + 1
369
Ankush Menat494bd9e2022-03-28 18:52:46 +0530370 if book_deferred_entries_based_on == "Months":
371 amount, base_amount = calculate_monthly_amount(
372 doc,
373 item,
374 last_gl_entry,
375 start_date,
376 end_date,
377 total_days,
378 total_booking_days,
379 account_currency,
380 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530381 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530382 amount, base_amount = calculate_amount(
383 doc, item, last_gl_entry, total_days, total_booking_days, account_currency
384 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530385
Deepesh Gargf79a72d2021-06-24 14:14:46 +0530386 if not amount:
387 return
388
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530389 gl_posting_date = end_date
390 prev_posting_date = None
Deepesh Garg30a647f2022-01-07 19:52:38 +0530391 # check if books nor frozen till endate:
Deepesh Garga3ab8f92023-01-03 17:51:41 +0530392 if accounts_frozen_upto and getdate(end_date) <= getdate(accounts_frozen_upto):
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530393 gl_posting_date = get_last_day(add_days(accounts_frozen_upto, 1))
394 prev_posting_date = end_date
Deepesh Garg30a647f2022-01-07 19:52:38 +0530395
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530396 if via_journal_entry:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530397 book_revenue_via_journal_entry(
398 doc,
399 credit_account,
400 debit_account,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530401 amount,
402 base_amount,
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530403 gl_posting_date,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530404 project,
405 account_currency,
406 item.cost_center,
407 item,
408 deferred_process,
409 submit_journal_entry,
410 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530411 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530412 make_gl_entries(
413 doc,
414 credit_account,
415 debit_account,
416 against,
417 amount,
418 base_amount,
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530419 gl_posting_date,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530420 project,
421 account_currency,
422 item.cost_center,
423 item,
424 deferred_process,
425 )
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530426
427 # Returned in case of any errors because it tries to submit the same record again and again in case of errors
428 if frappe.flags.deferred_accounting_error:
429 return
Nabin Hait0a90ce52019-03-28 19:43:02 +0530430
431 if getdate(end_date) < getdate(posting_date) and not last_gl_entry:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530432 _book_deferred_revenue_or_expense(
Gursheen Kaur Anand674af152023-07-09 20:41:12 +0530433 item,
434 via_journal_entry,
435 submit_journal_entry,
436 book_deferred_entries_based_on,
437 prev_posting_date,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530438 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530439
Ankush Menat494bd9e2022-03-28 18:52:46 +0530440 via_journal_entry = cint(
441 frappe.db.get_singles_value("Accounts Settings", "book_deferred_entries_via_journal_entry")
442 )
443 submit_journal_entry = cint(
444 frappe.db.get_singles_value("Accounts Settings", "submit_journal_entries")
445 )
446 book_deferred_entries_based_on = frappe.db.get_singles_value(
447 "Accounts Settings", "book_deferred_entries_based_on"
448 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530449
Ankush Menat494bd9e2022-03-28 18:52:46 +0530450 for item in doc.get("items"):
Nabin Hait0a90ce52019-03-28 19:43:02 +0530451 if item.get(enable_check):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530452 _book_deferred_revenue_or_expense(
453 item, via_journal_entry, submit_journal_entry, book_deferred_entries_based_on
454 )
455
Nabin Hait0a90ce52019-03-28 19:43:02 +0530456
Chinmay D. Pai0d147b02020-05-24 00:54:04 +0530457def process_deferred_accounting(posting_date=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530458 """Converts deferred income/expense into income/expense
459 Executed via background jobs on every month end"""
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530460
Chinmay D. Pai0d147b02020-05-24 00:54:04 +0530461 if not posting_date:
462 posting_date = today()
463
Ankush Menat494bd9e2022-03-28 18:52:46 +0530464 if not cint(
465 frappe.db.get_singles_value(
466 "Accounts Settings", "automatically_process_deferred_accounting_entry"
467 )
468 ):
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530469 return
470
471 start_date = add_months(today(), -1)
472 end_date = add_days(today(), -1)
473
Ankush Menat494bd9e2022-03-28 18:52:46 +0530474 companies = frappe.get_all("Company")
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530475
Deepesh Garg50690952021-07-01 09:31:31 +0530476 for company in companies:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530477 for record_type in ("Income", "Expense"):
478 doc = frappe.get_doc(
479 dict(
480 doctype="Process Deferred Accounting",
481 company=company.name,
482 posting_date=posting_date,
483 start_date=start_date,
484 end_date=end_date,
485 type=record_type,
486 )
487 )
Deepesh Garg50690952021-07-01 09:31:31 +0530488
489 doc.insert()
490 doc.submit()
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530491
Ankush Menat494bd9e2022-03-28 18:52:46 +0530492
493def make_gl_entries(
494 doc,
495 credit_account,
496 debit_account,
497 against,
498 amount,
499 base_amount,
500 posting_date,
501 project,
502 account_currency,
503 cost_center,
504 item,
505 deferred_process=None,
506):
Nabin Hait0a90ce52019-03-28 19:43:02 +0530507 # GL Entry for crediting the amount in the deferred expense
508 from erpnext.accounts.general_ledger import make_gl_entries
509
Ankush Menat494bd9e2022-03-28 18:52:46 +0530510 if amount == 0:
511 return
rohitwaghchauree123ec62019-11-06 15:25:00 +0530512
Nabin Hait0a90ce52019-03-28 19:43:02 +0530513 gl_entries = []
514 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530515 doc.get_gl_dict(
516 {
517 "account": credit_account,
518 "against": against,
519 "credit": base_amount,
520 "credit_in_account_currency": amount,
521 "cost_center": cost_center,
522 "voucher_detail_no": item.name,
523 "posting_date": posting_date,
524 "project": project,
525 "against_voucher_type": "Process Deferred Accounting",
526 "against_voucher": deferred_process,
527 },
528 account_currency,
529 item=item,
530 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530531 )
532 # GL Entry to debit the amount from the expense
533 gl_entries.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530534 doc.get_gl_dict(
535 {
536 "account": debit_account,
537 "against": against,
538 "debit": base_amount,
539 "debit_in_account_currency": amount,
540 "cost_center": cost_center,
541 "voucher_detail_no": item.name,
542 "posting_date": posting_date,
543 "project": project,
544 "against_voucher_type": "Process Deferred Accounting",
545 "against_voucher": deferred_process,
546 },
547 account_currency,
548 item=item,
549 )
Nabin Hait0a90ce52019-03-28 19:43:02 +0530550 )
551
Zarrare83ff382018-09-21 15:45:40 +0530552 if gl_entries:
Nabin Hait29fcb142019-02-13 17:18:12 +0530553 try:
554 make_gl_entries(gl_entries, cancel=(doc.docstatus == 2), merge_entries=True)
555 frappe.db.commit()
Deepesh Gargf1a669c2021-09-29 22:26:33 +0530556 except Exception as e:
557 if frappe.flags.in_test:
Rushabh Mehta548afba2022-05-02 15:04:26 +0530558 doc.log_error(f"Error while processing deferred accounting for Invoice {doc.name}")
Deepesh Garg3c64e202021-12-04 20:05:37 +0530559 raise e
Deepesh Gargf1a669c2021-09-29 22:26:33 +0530560 else:
561 frappe.db.rollback()
Rushabh Mehta548afba2022-05-02 15:04:26 +0530562 doc.log_error(f"Error while processing deferred accounting for Invoice {doc.name}")
Deepesh Gargf1a669c2021-09-29 22:26:33 +0530563 frappe.flags.deferred_accounting_error = True
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530564
Ankush Menat494bd9e2022-03-28 18:52:46 +0530565
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530566def send_mail(deferred_process):
Ankush Menatb6783b12021-05-17 17:06:12 +0530567 title = _("Error while processing deferred accounting for {0}").format(deferred_process)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530568 link = get_link_to_form("Process Deferred Accounting", deferred_process)
Ankush Menatb6783b12021-05-17 17:06:12 +0530569 content = _("Deferred accounting failed for some invoices:") + "\n"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530570 content += _(
571 "Please check Process Deferred Accounting {0} and submit manually after resolving errors."
572 ).format(link)
Mangesh-Khairnar2f7861a2020-05-02 20:09:33 +0530573 sendmail_to_system_managers(title, content)
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530574
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530575
Ankush Menat494bd9e2022-03-28 18:52:46 +0530576def book_revenue_via_journal_entry(
577 doc,
578 credit_account,
579 debit_account,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530580 amount,
581 base_amount,
582 posting_date,
583 project,
584 account_currency,
585 cost_center,
586 item,
587 deferred_process=None,
588 submit="No",
589):
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530590
Ankush Menat494bd9e2022-03-28 18:52:46 +0530591 if amount == 0:
592 return
593
594 journal_entry = frappe.new_doc("Journal Entry")
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530595 journal_entry.posting_date = posting_date
596 journal_entry.company = doc.company
Ankush Menat494bd9e2022-03-28 18:52:46 +0530597 journal_entry.voucher_type = (
598 "Deferred Revenue" if doc.doctype == "Sales Invoice" else "Deferred Expense"
599 )
Deepesh Garg9bf5f762022-04-06 17:33:46 +0530600 journal_entry.process_deferred_accounting = deferred_process
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530601
602 debit_entry = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530603 "account": credit_account,
604 "credit": base_amount,
605 "credit_in_account_currency": amount,
606 "account_currency": account_currency,
607 "reference_name": doc.name,
608 "reference_type": doc.doctype,
609 "reference_detail_no": item.name,
610 "cost_center": cost_center,
611 "project": project,
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530612 }
613
614 credit_entry = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530615 "account": debit_account,
616 "debit": base_amount,
617 "debit_in_account_currency": amount,
618 "account_currency": account_currency,
619 "reference_name": doc.name,
620 "reference_type": doc.doctype,
621 "reference_detail_no": item.name,
622 "cost_center": cost_center,
623 "project": project,
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530624 }
625
626 for dimension in get_accounting_dimensions():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530627 debit_entry.update({dimension: item.get(dimension)})
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530628
Ankush Menat494bd9e2022-03-28 18:52:46 +0530629 credit_entry.update({dimension: item.get(dimension)})
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530630
Ankush Menat494bd9e2022-03-28 18:52:46 +0530631 journal_entry.append("accounts", debit_entry)
632 journal_entry.append("accounts", credit_entry)
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530633
634 try:
635 journal_entry.save()
636
637 if submit:
638 journal_entry.submit()
Deepesh Garg0ba4fce2021-12-04 19:25:44 +0530639
640 frappe.db.commit()
Ankush Menat694ae812021-09-01 14:40:56 +0530641 except Exception:
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530642 frappe.db.rollback()
Rushabh Mehta548afba2022-05-02 15:04:26 +0530643 doc.log_error(f"Error while processing deferred accounting for Invoice {doc.name}")
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530644 frappe.flags.deferred_accounting_error = True
645
Ankush Menat494bd9e2022-03-28 18:52:46 +0530646
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530647def get_deferred_booking_accounts(doctype, voucher_detail_no, dr_or_cr):
648
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 if doctype == "Sales Invoice":
650 credit_account, debit_account = frappe.db.get_value(
651 "Sales Invoice Item",
652 {"name": voucher_detail_no},
653 ["income_account", "deferred_revenue_account"],
654 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530655 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530656 credit_account, debit_account = frappe.db.get_value(
657 "Purchase Invoice Item",
658 {"name": voucher_detail_no},
659 ["deferred_expense_account", "expense_account"],
660 )
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530661
Ankush Menat494bd9e2022-03-28 18:52:46 +0530662 if dr_or_cr == "Debit":
Deepesh Garg7cc1cf32020-06-23 09:57:56 +0530663 return debit_account
664 else:
665 return credit_account