You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

165 lines
4.8 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # License: GNU General Public License v3. See license.txt
  3. import frappe
  4. from frappe import _
  5. from frappe.utils import add_days, flt, get_datetime_str, nowdate
  6. from frappe.utils.data import now_datetime
  7. from frappe.utils.nestedset import get_ancestors_of, get_root_of # noqa
  8. from erpnext import get_default_company
  9. def before_tests():
  10. frappe.clear_cache()
  11. # complete setup if missing
  12. from frappe.desk.page.setup_wizard.setup_wizard import setup_complete
  13. if not frappe.db.a_row_exists("Company"):
  14. current_year = now_datetime().year
  15. setup_complete(
  16. {
  17. "currency": "USD",
  18. "full_name": "Test User",
  19. "company_name": "Wind Power LLC",
  20. "timezone": "America/New_York",
  21. "company_abbr": "WP",
  22. "industry": "Manufacturing",
  23. "country": "United States",
  24. "fy_start_date": f"{current_year}-01-01",
  25. "fy_end_date": f"{current_year}-12-31",
  26. "language": "english",
  27. "company_tagline": "Testing",
  28. "email": "test@erpnext.com",
  29. "password": "test",
  30. "chart_of_accounts": "Standard",
  31. }
  32. )
  33. frappe.db.sql("delete from `tabItem Price`")
  34. _enable_all_roles_for_admin()
  35. set_defaults_for_tests()
  36. frappe.db.commit()
  37. @frappe.whitelist()
  38. def get_exchange_rate(from_currency, to_currency, transaction_date=None, args=None):
  39. if not (from_currency and to_currency):
  40. # manqala 19/09/2016: Should this be an empty return or should it throw and exception?
  41. return
  42. if from_currency == to_currency:
  43. return 1
  44. if not transaction_date:
  45. transaction_date = nowdate()
  46. currency_settings = frappe.get_doc("Accounts Settings").as_dict()
  47. allow_stale_rates = currency_settings.get("allow_stale")
  48. filters = [
  49. ["date", "<=", get_datetime_str(transaction_date)],
  50. ["from_currency", "=", from_currency],
  51. ["to_currency", "=", to_currency],
  52. ]
  53. if args == "for_buying":
  54. filters.append(["for_buying", "=", "1"])
  55. elif args == "for_selling":
  56. filters.append(["for_selling", "=", "1"])
  57. if not allow_stale_rates:
  58. stale_days = currency_settings.get("stale_days")
  59. checkpoint_date = add_days(transaction_date, -stale_days)
  60. filters.append(["date", ">", get_datetime_str(checkpoint_date)])
  61. # cksgb 19/09/2016: get last entry in Currency Exchange with from_currency and to_currency.
  62. entries = frappe.get_all(
  63. "Currency Exchange", fields=["exchange_rate"], filters=filters, order_by="date desc", limit=1
  64. )
  65. if entries:
  66. return flt(entries[0].exchange_rate)
  67. try:
  68. cache = frappe.cache()
  69. key = "currency_exchange_rate_{0}:{1}:{2}".format(transaction_date, from_currency, to_currency)
  70. value = cache.get(key)
  71. if not value:
  72. import requests
  73. settings = frappe.get_cached_doc("Currency Exchange Settings")
  74. req_params = {
  75. "transaction_date": transaction_date,
  76. "from_currency": from_currency,
  77. "to_currency": to_currency,
  78. }
  79. params = {}
  80. for row in settings.req_params:
  81. params[row.key] = format_ces_api(row.value, req_params)
  82. response = requests.get(format_ces_api(settings.api_endpoint, req_params), params=params)
  83. # expire in 6 hours
  84. response.raise_for_status()
  85. value = response.json()
  86. for res_key in settings.result_key:
  87. value = value[format_ces_api(str(res_key.key), req_params)]
  88. cache.setex(name=key, time=21600, value=flt(value))
  89. return flt(value)
  90. except Exception:
  91. frappe.log_error("Unable to fetch exchange rate")
  92. frappe.msgprint(
  93. _(
  94. "Unable to find exchange rate for {0} to {1} for key date {2}. Please create a Currency Exchange record manually"
  95. ).format(from_currency, to_currency, transaction_date)
  96. )
  97. return 0.0
  98. def format_ces_api(data, param):
  99. return data.format(
  100. transaction_date=param.get("transaction_date"),
  101. to_currency=param.get("to_currency"),
  102. from_currency=param.get("from_currency"),
  103. )
  104. def enable_all_roles_and_domains():
  105. """enable all roles and domain for testing"""
  106. _enable_all_roles_for_admin()
  107. def _enable_all_roles_for_admin():
  108. from frappe.desk.page.setup_wizard.setup_wizard import add_all_roles_to
  109. all_roles = set(frappe.db.get_values("Role", pluck="name"))
  110. admin_roles = set(
  111. frappe.db.get_values("Has Role", {"parent": "Administrator"}, fieldname="role", pluck="role")
  112. )
  113. if all_roles.difference(admin_roles):
  114. add_all_roles_to("Administrator")
  115. def set_defaults_for_tests():
  116. defaults = {
  117. "customer_group": get_root_of("Customer Group"),
  118. "territory": get_root_of("Territory"),
  119. }
  120. frappe.db.set_single_value("Selling Settings", defaults)
  121. for key, value in defaults.items():
  122. frappe.db.set_default(key, value)
  123. frappe.db.set_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing", 0)
  124. def insert_record(records):
  125. from frappe.desk.page.setup_wizard.setup_wizard import make_records
  126. make_records(records)
  127. def welcome_email():
  128. site_name = get_default_company() or "ERPNext"
  129. title = _("Welcome to {0}").format(site_name)
  130. return title