42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
"""رندر قالب متن پیامک با placeholderهای امن."""
|
|
from persiantools.jdatetime import JalaliDate, JalaliDateTime
|
|
|
|
|
|
class _SafeDict(dict):
|
|
"""دیکشنری که برای کلیدهای ناشناخته رشته خالی برمیگرداند (بدون خطا)."""
|
|
|
|
def __missing__(self, key):
|
|
return ""
|
|
|
|
|
|
def format_amount(value):
|
|
try:
|
|
return f"{int(value):,}"
|
|
except (TypeError, ValueError):
|
|
return str(value or "")
|
|
|
|
|
|
def format_jalali(value):
|
|
"""تبدیل datetime/date به تاریخ جلالی ``YYYY/MM/DD``."""
|
|
if not value:
|
|
return ""
|
|
try:
|
|
if hasattr(value, "date") and callable(getattr(value, "date")):
|
|
value = value.date()
|
|
return JalaliDate(value).strftime("%Y/%m/%d")
|
|
except Exception:
|
|
try:
|
|
return JalaliDateTime(value).strftime("%Y/%m/%d")
|
|
except Exception:
|
|
return str(value)
|
|
|
|
|
|
def render_template(text, context=None):
|
|
ctx = dict(context or {})
|
|
if "amount" in ctx:
|
|
ctx.setdefault("amount_sep", format_amount(ctx["amount"]))
|
|
if "date" in ctx:
|
|
ctx.setdefault("date_raw", ctx["date"])
|
|
ctx["date"] = format_jalali(ctx["date"])
|
|
return (text or "").format_map(_SafeDict(ctx))
|