from djmoney.money import Money from decimal import Decimal from apps.tasrif.models import CurrencyRate def convert_currency_pure(from_rate, to_rate, amount): converted_amount = (amount / from_rate.rate) * to_rate.rate if to_rate.code == "IRR": converted_amount = round(converted_amount) one_unit_conversion = to_rate.rate / from_rate.rate return converted_amount, one_unit_conversion def convert_currency(amount, from_currency_code, to_currency_code): try: from_currency_rate = CurrencyRate.objects.get(code=from_currency_code) to_currency_rate = CurrencyRate.objects.get(code=to_currency_code) # مطمئن شدن از نوع داده Decimal برای نرخ‌ها from_rate = Decimal(to_currency_rate.rate) to_rate = Decimal(from_currency_rate.rate) # محاسبه نرخ تبدیل conversion_rate = from_rate / to_rate # تبدیل مبلغ converted_amount = Decimal(amount) * conversion_rate # ایجاد نمونه Money converted_money = Money(converted_amount, to_currency_code) print(f'>>>>>>>>> {converted_amount} /// {converted_money}') return converted_money except CurrencyRate.DoesNotExist: return None # یا می‌توانید خطا را مدیریت کنید def convert_currency2(from_currency_code, to_currency_code, amount): try: # Fetch the currencies from the database from_currency = CurrencyRate.objects.get(code=from_currency_code) to_currency = CurrencyRate.objects.get(code=to_currency_code) # Convert the amount to USD first, then to the target currency amount_in_usd = amount / from_currency.rate converted_amount = amount_in_usd * to_currency.rate # Ensure IRR values are integer if converting to IRR if to_currency_code == 'IRR': converted_amount = round(converted_amount) return converted_amount except CurrencyRate.DoesNotExist: raise ValueError("One or both of the specified currencies are not available in the database.") def formater_convert_currency(to_currency, converted_amount, rate_per_unit): if to_currency == 'IRR': # Format without decimals for IRR formatted_converted_amount = f"{converted_amount:,.0f}" # No decimal places formatted_rate_per_unit = f"{rate_per_unit:,.0f}" else: # Format with two decimal places for other currencies formatted_converted_amount = f"{converted_amount:,.2f}" # Two decimal places formatted_rate_per_unit = f"{rate_per_unit:,.2f}" return formatted_converted_amount, formatted_rate_per_unit