All checks were successful
CI / lint-and-test (push) Successful in 21s
- Introduced a new `normalize_lang` function to standardize language codes across the application, ensuring consistent handling of user language preferences. - Refactored date handling utilities by adding `parse_utc_iso` and `parse_utc_iso_naive` functions for better parsing of ISO 8601 date strings, enhancing timezone awareness. - Updated various modules to utilize the new language normalization and date parsing functions, improving code clarity and maintainability. - Enhanced error handling in date validation to raise specific `DateRangeValidationError` exceptions, providing clearer feedback on validation issues. - Improved test coverage for date range validation and language normalization functionalities, ensuring robustness and reliability.
38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
"""get_lang and t(): language from Telegram user, translate by key with fallback to en."""
|
|
|
|
from typing import TYPE_CHECKING
|
|
|
|
import duty_teller.config as config
|
|
from duty_teller.i18n.lang import normalize_lang
|
|
from duty_teller.i18n.messages import MESSAGES
|
|
|
|
if TYPE_CHECKING:
|
|
from telegram import User
|
|
|
|
|
|
def get_lang(user: "User | None") -> str:
|
|
"""
|
|
Normalize Telegram user language to 'ru' or 'en'.
|
|
Uses normalize_lang for user.language_code; when user is None or has no
|
|
language_code, returns config.DEFAULT_LANGUAGE.
|
|
"""
|
|
if user is None or not getattr(user, "language_code", None):
|
|
return config.DEFAULT_LANGUAGE
|
|
return normalize_lang(user.language_code)
|
|
|
|
|
|
def t(lang: str, key: str, **kwargs: str) -> str:
|
|
"""
|
|
Return translated string for lang and key; substitute kwargs into placeholders like {phone}.
|
|
Fallback to 'en' if key missing for lang.
|
|
"""
|
|
lang = "ru" if lang == "ru" else "en"
|
|
messages = MESSAGES.get(lang) or MESSAGES["en"]
|
|
template = messages.get(key)
|
|
if template is None:
|
|
template = MESSAGES["en"].get(key, key)
|
|
try:
|
|
return template.format(**kwargs)
|
|
except KeyError:
|
|
return template
|