Add basic functions for keeping track of Deepl account usage

This commit is contained in:
Thelonius Kort
2023-03-15 11:35:26 +01:00
parent 2eba3bc500
commit 5dfbf7011e

View File

@ -48,6 +48,19 @@ defmodule Outlook.Translators do
|> Repo.update_all([inc: [our_character_count: billed_characters]])
end
def get_uptodate_deepl_counts(user) do
deepl_counts = Deepl.get_usage_counts(get_deepl_auth_key(user))
our_character_count = deepl_account_for_user(user)
|> select([:our_character_count])
|> Repo.one()
|> Map.get(:our_character_count)
most_accurate = max(our_character_count, deepl_counts.character_count)
%{character_limit: deepl_counts.character_limit,
character_count: deepl_counts.character_count,
our_character_count: our_character_count,
percent_used: most_accurate * 100 / deepl_counts.character_limit}
end
def translate(translation, current_user) do
%{language: target_lang,
article: %{content: article_tree, language: source_lang}
@ -71,6 +84,14 @@ defmodule Outlook.Translators do
process_translation(result.translation, tunit_ids)
end
def update_deepl_counts(user, counts) do
deepl_account_for_user(user)
|> Repo.update_all([set: [
character_limit: counts.character_limit,
character_count: counts.character_count
]])
end
defp deepl_account_for_user(user) when is_struct(user), do: deepl_account_for_user(user.id)
defp deepl_account_for_user(user_id) do
DeeplAccount |> where(user_id: ^user_id)