docbot/src/core/utils.py
2025-12-21 01:15:13 +04:00

87 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import uuid
import hashlib
import base64
import re
import pytz
from datetime import datetime
from decimal import Decimal
from urllib.parse import urlparse
from urllib.parse import urlencode
def UUID_code_generator(code_length: int) -> str:
"""
Генерирует уникальный код в формате UUID.
Возвращает строку с кодом.
"""
return str(uuid.uuid4().hex[:code_length].upper())
def generate_session_code(telegram_id: int, phone: str, consultation_date_time: str) -> str:
"""Генерация 8-символьного уникального кода на основе 3 параметров."""
combined = f"{telegram_id}|{phone}|{consultation_date_time}"
hash_digest = hashlib.sha256(combined.encode()).digest()
b64 = base64.urlsafe_b64encode(hash_digest).decode()
return b64[:8].upper()
def date_time_formatter(date_time: str) -> datetime:
"""
Форматирует дату и время в строку формата ДД.ММ.ГГГГ ЧЧ:ММ.
:param date_time: Дата и время в формате ISO 8601.
:return: Строка с отформатированной датой и временем.
"""
dt = datetime.strptime(date_time, '%d.%m.%y %H:%M')
return dt
def is_phone_correct(phone: str) -> bool:
normalized = re.sub(r"[()\s-]", "", phone)
regex = r"^(?:\+7|8|7)\d{10}$"
return re.match(regex, normalized)
def get_timezones():
return_value = {}
for tz in pytz.common_timezones:
c = tz.split("/")
if len(c) > 1:
if c[0] not in return_value.keys():
return_value[c[0]] = []
return_value[c[0]].append(c[1])
for i in ["GMT"]:
if i in return_value.keys():
return_value.pop(i)
return return_value
def is_valid_url(text: str) -> bool:
try:
result = urlparse(text)
return all([result.scheme in ["http", "https"], result.netloc])
except Exception:
return False
def make_a_payment_link(base_link: str, code: str, phone: str, amount: Decimal, *, service_name: str) -> str | None:
if not all([base_link, code, phone]) or amount is None:
return None
currency = "RUB"
quantity = "1"
params = [
("order_id", code),
("customer_phone", phone),
("products[0][name]", service_name),
("products[0][price]", f"{amount:.2f}"),
("products[0][quantity]", quantity),
("products[0][currency]", currency),
("do", "pay"),
]
return f"{base_link}?{urlencode(params, doseq=True)}"