blob: 8b58a46cdf7ab7e86dfc79a430d68eca049d55d5 [file] [log] [blame]
tundebabzyc8978252018-02-12 10:34:50 +01001import frappe
Gursheen Anand6c11ca12023-07-12 14:43:18 +05302from frappe.query_builder.custom import ConstantColumn
Gursheen Anandf5027fd2023-07-12 16:42:58 +05303from frappe.query_builder.functions import Sum
Sagar Vora30e40522023-07-04 17:41:30 +05304from frappe.utils import flt, formatdate, get_datetime_str, get_table_name
Gursheen Anand6c11ca12023-07-12 14:43:18 +05305from pypika import Order
Chillar Anand915b3432021-09-02 16:44:59 +05306
tundebabzyc8978252018-02-12 10:34:50 +01007from erpnext import get_company_currency, get_default_company
Gursheen Anand6c11ca12023-07-12 14:43:18 +05308from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
9 get_dimension_with_children,
10)
Prateeksha Singh8ecfaaa2018-07-18 18:03:27 +053011from erpnext.accounts.doctype.fiscal_year.fiscal_year import get_from_and_to_date
Chillar Anand915b3432021-09-02 16:44:59 +053012from erpnext.setup.utils import get_exchange_rate
tundebabzyc8978252018-02-12 10:34:50 +010013
14__exchange_rates = {}
tundebabzyc8978252018-02-12 10:34:50 +010015
Ankush Menat494bd9e2022-03-28 18:52:46 +053016
tundebabzyc8978252018-02-12 10:34:50 +010017def get_currency(filters):
18 """
19 Returns a dictionary containing currency information. The keys of the dict are
20 - company: The company for which we are fetching currency information. if no
21 company is specified, it will fallback to the default company.
22 - company currency: The functional currency of the said company.
23 - presentation currency: The presentation currency to use. Only currencies that
24 have been used for transactions will be allowed.
25 - report date: The report date.
26 :param filters: Report filters
27 :type filters: dict
28
29 :return: str - Currency
30 """
31 company = get_appropriate_company(filters)
32 company_currency = get_company_currency(company)
Ankush Menat494bd9e2022-03-28 18:52:46 +053033 presentation_currency = (
34 filters["presentation_currency"] if filters.get("presentation_currency") else company_currency
35 )
Prateeksha Singh8ecfaaa2018-07-18 18:03:27 +053036
ruthra kumara6794c32022-12-06 13:44:54 +053037 report_date = filters.get("to_date") or filters.get("period_end_date")
Prateeksha Singh8ecfaaa2018-07-18 18:03:27 +053038
39 if not report_date:
Ankush Menat494bd9e2022-03-28 18:52:46 +053040 fiscal_year_to_date = get_from_and_to_date(filters.get("to_fiscal_year"))["to_date"]
Prateeksha Singh8ecfaaa2018-07-18 18:03:27 +053041 report_date = formatdate(get_datetime_str(fiscal_year_to_date), "dd-MM-yyyy")
tundebabzyc8978252018-02-12 10:34:50 +010042
Ankush Menat494bd9e2022-03-28 18:52:46 +053043 currency_map = dict(
44 company=company,
45 company_currency=company_currency,
46 presentation_currency=presentation_currency,
47 report_date=report_date,
48 )
tundebabzyc8978252018-02-12 10:34:50 +010049
50 return currency_map
51
52
53def convert(value, from_, to, date):
54 """
55 convert `value` from `from_` to `to` on `date`
56 :param value: Amount to be converted
57 :param from_: Currency of `value`
58 :param to: Currency to convert to
59 :param date: exchange rate as at this date
60 :return: Result of converting `value`
61 """
62 rate = get_rate_as_at(date, from_, to)
Zarrar3523b772018-08-14 16:28:14 +053063 converted_value = flt(value) / (rate or 1)
tundebabzyc8978252018-02-12 10:34:50 +010064 return converted_value
65
66
67def get_rate_as_at(date, from_currency, to_currency):
68 """
69 Gets exchange rate as at `date` for `from_currency` - `to_currency` exchange rate.
70 This calls `get_exchange_rate` so that we can get the correct exchange rate as per
71 the user's Accounts Settings.
72 It is made efficient by memoising results to `__exchange_rates`
73 :param date: exchange rate as at this date
74 :param from_currency: Base currency
75 :param to_currency: Quote currency
76 :return: Retrieved exchange rate
77 """
Prateeksha Singh8ecfaaa2018-07-18 18:03:27 +053078
Ankush Menat494bd9e2022-03-28 18:52:46 +053079 rate = __exchange_rates.get("{0}-{1}@{2}".format(from_currency, to_currency, date))
tundebabzyc8978252018-02-12 10:34:50 +010080 if not rate:
81 rate = get_exchange_rate(from_currency, to_currency, date) or 1
Ankush Menat494bd9e2022-03-28 18:52:46 +053082 __exchange_rates["{0}-{1}@{2}".format(from_currency, to_currency, date)] = rate
tundebabzyc8978252018-02-12 10:34:50 +010083
84 return rate
85
Ankush Menat494bd9e2022-03-28 18:52:46 +053086
Deepesh Garg4d07e202023-07-09 20:16:12 +053087def convert_to_presentation_currency(gl_entries, currency_info):
tundebabzyc8978252018-02-12 10:34:50 +010088 """
89 Take a list of GL Entries and change the 'debit' and 'credit' values to currencies
90 in `currency_info`.
91 :param gl_entries:
92 :param currency_info:
93 :return:
94 """
95 converted_gl_list = []
Ankush Menat494bd9e2022-03-28 18:52:46 +053096 presentation_currency = currency_info["presentation_currency"]
97 company_currency = currency_info["company_currency"]
tundebabzyc8978252018-02-12 10:34:50 +010098
Ankush Menat494bd9e2022-03-28 18:52:46 +053099 account_currencies = list(set(entry["account_currency"] for entry in gl_entries))
Nabin Hait111183d2020-08-22 12:31:06 +0530100
tundebabzyc8978252018-02-12 10:34:50 +0100101 for entry in gl_entries:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530102 debit = flt(entry["debit"])
103 credit = flt(entry["credit"])
104 debit_in_account_currency = flt(entry["debit_in_account_currency"])
105 credit_in_account_currency = flt(entry["credit_in_account_currency"])
106 account_currency = entry["account_currency"]
tundebabzyc8978252018-02-12 10:34:50 +0100107
Afshan4d61fa22021-05-25 19:16:02 +0530108 if len(account_currencies) == 1 and account_currency == presentation_currency:
ruthra kumar914b2302023-01-02 14:33:14 +0530109 entry["debit"] = debit_in_account_currency
110 entry["credit"] = credit_in_account_currency
Afshan4d61fa22021-05-25 19:16:02 +0530111 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530112 date = currency_info["report_date"]
Deepesh Gargceaa8042021-09-05 17:21:29 +0530113 converted_debit_value = convert(debit, presentation_currency, company_currency, date)
114 converted_credit_value = convert(credit, presentation_currency, company_currency, date)
tundebabzyc8978252018-02-12 10:34:50 +0100115
Ankush Menat494bd9e2022-03-28 18:52:46 +0530116 if entry.get("debit"):
117 entry["debit"] = converted_debit_value
Rohit Waghchaure376db4f2019-04-18 22:01:33 +0530118
Ankush Menat494bd9e2022-03-28 18:52:46 +0530119 if entry.get("credit"):
120 entry["credit"] = converted_credit_value
tundebabzyc8978252018-02-12 10:34:50 +0100121
tundebabzyc8978252018-02-12 10:34:50 +0100122 converted_gl_list.append(entry)
123
124 return converted_gl_list
125
126
127def get_appropriate_company(filters):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530128 if filters.get("company"):
129 company = filters["company"]
tundebabzyc8978252018-02-12 10:34:50 +0100130 else:
131 company = get_default_company()
132
133 return company
Rohit Waghchaure1d6f2c32019-04-23 18:33:01 +0530134
Ankush Menat494bd9e2022-03-28 18:52:46 +0530135
Rohit Waghchaure1d6f2c32019-04-23 18:33:01 +0530136@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530137def get_invoiced_item_gross_margin(
138 sales_invoice=None, item_code=None, company=None, with_item_data=False
139):
Rohit Waghchaure1d6f2c32019-04-23 18:33:01 +0530140 from erpnext.accounts.report.gross_profit.gross_profit import GrossProfitGenerator
141
Ankush Menat494bd9e2022-03-28 18:52:46 +0530142 sales_invoice = sales_invoice or frappe.form_dict.get("sales_invoice")
143 item_code = item_code or frappe.form_dict.get("item_code")
144 company = company or frappe.get_cached_value("Sales Invoice", sales_invoice, "company")
Rohit Waghchaure1d6f2c32019-04-23 18:33:01 +0530145
146 filters = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530147 "sales_invoice": sales_invoice,
148 "item_code": item_code,
149 "company": company,
150 "group_by": "Invoice",
Rohit Waghchaure1d6f2c32019-04-23 18:33:01 +0530151 }
152
153 gross_profit_data = GrossProfitGenerator(filters)
Rohit Waghchaure7bee5022019-05-08 15:31:29 +0530154 result = gross_profit_data.grouped_data
155 if not with_item_data:
Ankush Menat98917802021-06-11 18:40:22 +0530156 result = sum(d.gross_profit for d in result)
Rohit Waghchaure1d6f2c32019-04-23 18:33:01 +0530157
Rohit Waghchaure7bee5022019-05-08 15:31:29 +0530158 return result
Gursheen Anandcbef6c32023-07-10 18:39:35 +0530159
160
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530161def get_query_columns(report_columns):
162 if not report_columns:
163 return ""
164
165 columns = []
166 for column in report_columns:
167 fieldname = column["fieldname"]
168
169 if doctype := column.get("_doctype"):
170 columns.append(f"`{get_table_name(doctype)}`.`{fieldname}`")
171 else:
172 columns.append(fieldname)
173
174 return ", " + ", ".join(columns)
175
176
177def get_values_for_columns(report_columns, report_row):
178 values = {}
179
180 if not report_columns:
181 return values
182
183 for column in report_columns:
184 fieldname = column["fieldname"]
185 values[fieldname] = report_row.get(fieldname)
186
187 return values
188
189
Gursheen Anandcbef6c32023-07-10 18:39:35 +0530190def get_party_details(party_type, party_list):
191 party_details = {}
192 party = frappe.qb.DocType(party_type)
193 query = frappe.qb.from_(party).select(party.name, party.tax_id).where(party.name.isin(party_list))
194 if party_type == "Supplier":
195 query = query.select(party.supplier_group)
196 else:
197 query = query.select(party.customer_group, party.territory)
198
199 party_detail_list = query.run(as_dict=True)
200 for party_dict in party_detail_list:
201 party_details[party_dict.name] = party_dict
202 return party_details
203
204
205def get_taxes_query(invoice_list, doctype, parenttype):
206 taxes = frappe.qb.DocType(doctype)
207
208 query = (
209 frappe.qb.from_(taxes)
210 .select(taxes.account_head)
211 .distinct()
212 .where(
213 (taxes.parenttype == parenttype)
214 & (taxes.docstatus == 1)
215 & (taxes.account_head.isnotnull())
216 & (taxes.parent.isin([inv.name for inv in invoice_list]))
217 )
218 .orderby(taxes.account_head)
219 )
220
221 if doctype == "Purchase Taxes and Charges":
222 return query.where(taxes.category.isin(["Total", "Valuation and Total"]))
223 elif doctype == "Sales Taxes and Charges":
Gursheen Anandf5027fd2023-07-12 16:42:58 +0530224 return query
Gursheen Anandcbef6c32023-07-10 18:39:35 +0530225 return query.where(taxes.charge_type.isin(["On Paid Amount", "Actual"]))
Gursheen Anandd5aa0e32023-07-11 14:47:23 +0530226
227
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530228def get_journal_entries(filters, accounting_dimensions, args):
229 je = frappe.qb.DocType("Journal Entry")
230 journal_account = frappe.qb.DocType("Journal Entry Account")
231 query = (
232 frappe.qb.from_(je)
233 .inner_join(journal_account)
234 .on(je.name == journal_account.parent)
235 .select(
236 je.voucher_type.as_("doctype"),
237 je.name,
238 je.posting_date,
239 journal_account.account.as_(args.account),
240 journal_account.party.as_(args.party),
241 journal_account.party.as_(args.party_name),
242 je.bill_no,
243 je.bill_date,
244 je.remark.as_("remarks"),
245 je.total_amount.as_("base_net_total"),
246 je.total_amount.as_("base_grand_total"),
247 je.mode_of_payment,
248 journal_account.project,
249 )
250 .where((je.voucher_type == "Journal Entry") & (journal_account.party == filters.get(args.party)))
251 .orderby(je.posting_date, je.name, order=Order.desc)
Gursheen Anandd5aa0e32023-07-11 14:47:23 +0530252 )
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530253 query = get_conditions(filters, query, [je], accounting_dimensions, payments=True)
Gursheen Anandf5027fd2023-07-12 16:42:58 +0530254 journal_entries = query.run(as_dict=True)
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530255 return journal_entries
Gursheen Anandd5aa0e32023-07-11 14:47:23 +0530256
257
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530258def get_payment_entries(filters, accounting_dimensions, args):
259 pe = frappe.qb.DocType("Payment Entry")
260 query = (
261 frappe.qb.from_(pe)
262 .select(
263 ConstantColumn("Payment Entry").as_("doctype"),
264 pe.name,
265 pe.posting_date,
266 pe.paid_to.as_(args.account),
267 pe.party.as_(args.party),
268 pe.party_name.as_(args.party_name),
269 pe.remarks,
270 pe.paid_amount.as_("base_net_total"),
271 pe.paid_amount_after_tax.as_("base_grand_total"),
272 pe.mode_of_payment,
273 pe.project,
274 pe.cost_center,
275 )
276 .where((pe.party == filters.get(args.party)))
277 .orderby(pe.posting_date, pe.name, order=Order.desc)
Gursheen Anandd5aa0e32023-07-11 14:47:23 +0530278 )
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530279 query = get_conditions(filters, query, [pe], accounting_dimensions, payments=True)
Gursheen Anandf5027fd2023-07-12 16:42:58 +0530280 payment_entries = query.run(as_dict=True)
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530281 return payment_entries
Gursheen Kaur Anand10943192023-07-12 11:00:35 +0530282
283
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530284def get_conditions(filters, query, docs, accounting_dimensions, payments=False):
285 parent_doc = docs[0]
286 if not payments:
287 child_doc = docs[1]
Sagar Vora30e40522023-07-04 17:41:30 +0530288
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530289 if parent_doc.get_table_name() == "tabSales Invoice":
290 if filters.get("owner"):
291 query = query.where(parent_doc.owner == filters.owner)
292 if filters.get("mode_of_payment"):
293 payment_doc = docs[2]
294 query = query.where(payment_doc.mode_of_payment == filters.mode_of_payment)
295 if not payments:
296 if filters.get("brand"):
297 query = query.where(child_doc.brand == filters.brand)
298 else:
299 if filters.get("mode_of_payment"):
300 query = query.where(parent_doc.mode_of_payment == filters.mode_of_payment)
Sagar Vora30e40522023-07-04 17:41:30 +0530301
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530302 if filters.get("company"):
303 query = query.where(parent_doc.company == filters.company)
304 if filters.get("from_date"):
305 query = query.where(parent_doc.posting_date >= filters.from_date)
306 if filters.get("to_date"):
307 query = query.where(parent_doc.posting_date <= filters.to_date)
Sagar Vora30e40522023-07-04 17:41:30 +0530308
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530309 if payments:
310 if filters.get("cost_center"):
311 query = query.where(parent_doc.cost_center == filters.cost_center)
312 else:
313 if filters.get("cost_center"):
314 query = query.where(child_doc.cost_center == filters.cost_center)
315 if filters.get("warehouse"):
316 query = query.where(child_doc.warehouse == filters.warehouse)
317 if filters.get("item_group"):
318 query = query.where(child_doc.item_group == filters.item_group)
Sagar Vora30e40522023-07-04 17:41:30 +0530319
Gursheen Anand6c11ca12023-07-12 14:43:18 +0530320 if accounting_dimensions:
321 for dimension in accounting_dimensions:
322 if filters.get(dimension.fieldname):
323 if frappe.get_cached_value("DocType", dimension.document_type, "is_tree"):
324 filters[dimension.fieldname] = get_dimension_with_children(
325 dimension.document_type, filters.get(dimension.fieldname)
326 )
327 fieldname = dimension.fieldname
328 query = query.where(parent_doc.fieldname.isin(filters.fieldname))
329 return query
Gursheen Anandf5027fd2023-07-12 16:42:58 +0530330
331
332def get_advance_taxes_and_charges(invoice_list):
333 adv_taxes = frappe.qb.DocType("Advance Taxes and Charges")
334 return (
335 frappe.qb.from_(adv_taxes)
336 .select(
337 adv_taxes.parent,
338 adv_taxes.account_head,
339 (
340 frappe.qb.terms.Case()
341 .when(adv_taxes.add_deduct_tax == "Add", Sum(adv_taxes.base_tax_amount))
342 .else_(Sum(adv_taxes.base_tax_amount) * -1)
343 ).as_("tax_amount"),
344 )
345 .where(
346 (adv_taxes.parent.isin([inv.name for inv in invoice_list]))
347 & (adv_taxes.charge_type.isin(["On Paid Amount", "Actual"]))
348 & (adv_taxes.base_tax_amount != 0)
349 )
350 .groupby(adv_taxes.parent, adv_taxes.account_head, adv_taxes.add_deduct_tax)
351 ).run(as_dict=True, debug=True)