Add configuration rules, refactor settings management, and enhance import functionality

- Introduced a new configuration file `.cursorrules` to define coding standards, error handling, testing requirements, and project-specific guidelines.
- Refactored `config.py` to implement a `Settings` dataclass for better management of environment variables, improving testability and maintainability.
- Updated the import duty schedule handler to utilize session management with `session_scope`, ensuring proper database session handling.
- Enhanced the import service to streamline the duty schedule import process, improving code organization and readability.
- Added new service layer functions to encapsulate business logic related to group duty pinning and duty schedule imports.
- Updated README documentation to reflect the new configuration structure and improved import functionality.
This commit is contained in:
2026-02-18 12:35:11 +03:00
parent 8697b9e30b
commit 5331fac334
25 changed files with 1032 additions and 397 deletions

View File

@@ -6,8 +6,9 @@ import config
from telegram import Update
from telegram.ext import CommandHandler, ContextTypes
from db.session import get_session
from db.session import session_scope
from db.repository import get_or_create_user, set_user_phone
from utils.user import build_full_name
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
@@ -16,18 +17,14 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user = update.effective_user
if not user:
return
full_name = (
" ".join(filter(None, [user.first_name or "", user.last_name or ""])).strip()
or "User"
)
full_name = build_full_name(user.first_name, user.last_name)
telegram_user_id = user.id
username = user.username
first_name = user.first_name
last_name = user.last_name
def do_get_or_create() -> None:
session = get_session(config.DATABASE_URL)
try:
with session_scope(config.DATABASE_URL) as session:
get_or_create_user(
session,
telegram_user_id=telegram_user_id,
@@ -36,8 +33,6 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
first_name=first_name,
last_name=last_name,
)
finally:
session.close()
await asyncio.get_running_loop().run_in_executor(None, do_get_or_create)
@@ -53,24 +48,14 @@ async def set_phone(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Команда /set_phone доступна только в личке.")
return
# Optional: restrict to allowed usernames; plan says "or without restrictions"
args = (context.args or [])
args = context.args or []
phone = " ".join(args).strip() if args else None
telegram_user_id = update.effective_user.id
def do_set_phone() -> str:
session = get_session(config.DATABASE_URL)
try:
full_name = (
" ".join(
filter(
None,
[
update.effective_user.first_name or "",
update.effective_user.last_name or "",
],
)
).strip()
or "User"
with session_scope(config.DATABASE_URL) as session:
full_name = build_full_name(
update.effective_user.first_name, update.effective_user.last_name
)
get_or_create_user(
session,
@@ -86,8 +71,6 @@ async def set_phone(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if phone:
return f"Телефон сохранён: {phone}"
return "Телефон очищен."
finally:
session.close()
result = await asyncio.get_running_loop().run_in_executor(None, do_set_phone)
await update.message.reply_text(result)

View File

@@ -3,7 +3,6 @@
import asyncio
import logging
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
import config
from telegram import Update
@@ -11,14 +10,14 @@ from telegram.constants import ChatMemberStatus
from telegram.error import BadRequest, Forbidden
from telegram.ext import ChatMemberHandler, CommandHandler, ContextTypes
from db.session import get_session
from db.repository import (
get_current_duty,
get_next_shift_end,
get_group_duty_pin,
save_group_duty_pin,
delete_group_duty_pin,
get_all_group_duty_pin_chat_ids,
from db.session import session_scope
from services.group_duty_pin_service import (
get_duty_message_text,
get_next_shift_end_utc,
save_pin,
delete_pin,
get_message_id,
get_all_pin_chat_ids,
)
logger = logging.getLogger(__name__)
@@ -27,83 +26,31 @@ JOB_NAME_PREFIX = "duty_pin_"
RETRY_WHEN_NO_DUTY_MINUTES = 15
def _format_duty_message(duty, user, tz_name: str) -> str:
"""Build the text for the pinned message. duty, user may be None."""
if duty is None or user is None:
return "Сейчас дежурства нет."
try:
tz = ZoneInfo(tz_name)
except Exception:
tz = ZoneInfo("Europe/Moscow")
tz_name = "Europe/Moscow"
start_dt = datetime.fromisoformat(duty.start_at.replace("Z", "+00:00"))
end_dt = datetime.fromisoformat(duty.end_at.replace("Z", "+00:00"))
start_local = start_dt.astimezone(tz)
end_local = end_dt.astimezone(tz)
# Показать смещение (UTC+3) чтобы было понятно, в каком поясе время
offset_sec = start_local.utcoffset().total_seconds() if start_local.utcoffset() else 0
sign = "+" if offset_sec >= 0 else "-"
h, r = divmod(abs(int(offset_sec)), 3600)
m = r // 60
tz_hint = f"UTC{sign}{h:d}:{m:02d}, {tz_name}"
time_range = f"{start_local.strftime('%d.%m.%Y %H:%M')}{end_local.strftime('%d.%m.%Y %H:%M')} ({tz_hint})"
lines = [
f"🕐 Дежурство: {time_range}",
f"👤 {user.full_name}",
]
if user.phone:
lines.append(f"📞 {user.phone}")
if user.username:
lines.append(f"@{user.username}")
return "\n".join(lines)
def _get_duty_message_text_sync() -> str:
"""Get current duty message (sync, for run_in_executor)."""
with session_scope(config.DATABASE_URL) as session:
return get_duty_message_text(session, config.DUTY_DISPLAY_TZ)
def _get_duty_message_text() -> str:
"""Get current duty from DB and return formatted message (sync, for run_in_executor)."""
session = get_session(config.DATABASE_URL)
try:
now = datetime.now(timezone.utc)
result = get_current_duty(session, now)
if result is None:
return "Сейчас дежурства нет."
duty, user = result
return _format_duty_message(duty, user, config.DUTY_DISPLAY_TZ)
finally:
session.close()
def _get_next_shift_end_utc():
"""Return next shift end as naive UTC datetime for job scheduling (sync)."""
session = get_session(config.DATABASE_URL)
try:
return get_next_shift_end(session, datetime.now(timezone.utc))
finally:
session.close()
def _get_next_shift_end_sync():
"""Return next shift end as naive UTC (sync, for run_in_executor)."""
with session_scope(config.DATABASE_URL) as session:
return get_next_shift_end_utc(session)
def _sync_save_pin(chat_id: int, message_id: int) -> None:
session = get_session(config.DATABASE_URL)
try:
save_group_duty_pin(session, chat_id, message_id)
finally:
session.close()
with session_scope(config.DATABASE_URL) as session:
save_pin(session, chat_id, message_id)
def _sync_delete_pin(chat_id: int) -> None:
session = get_session(config.DATABASE_URL)
try:
delete_group_duty_pin(session, chat_id)
finally:
session.close()
with session_scope(config.DATABASE_URL) as session:
delete_pin(session, chat_id)
def _sync_get_message_id(chat_id: int) -> int | None:
session = get_session(config.DATABASE_URL)
try:
pin = get_group_duty_pin(session, chat_id)
return pin.message_id if pin else None
finally:
session.close()
with session_scope(config.DATABASE_URL) as session:
return get_message_id(session, chat_id)
async def _schedule_next_update(
@@ -131,6 +78,7 @@ async def _schedule_next_update(
logger.info("Scheduled pin update for chat_id=%s at %s", chat_id, when_utc)
else:
from datetime import timedelta
job_queue.run_once(
update_group_pin,
when=timedelta(minutes=RETRY_WHEN_NO_DUTY_MINUTES),
@@ -154,7 +102,7 @@ async def update_group_pin(context: ContextTypes.DEFAULT_TYPE) -> None:
if message_id is None:
logger.info("No pin record for chat_id=%s, skipping update", chat_id)
return
text = await loop.run_in_executor(None, _get_duty_message_text)
text = await loop.run_in_executor(None, _get_duty_message_text_sync)
try:
await context.bot.edit_message_text(
chat_id=chat_id,
@@ -163,11 +111,13 @@ async def update_group_pin(context: ContextTypes.DEFAULT_TYPE) -> None:
)
except (BadRequest, Forbidden) as e:
logger.warning("Failed to edit pinned message chat_id=%s: %s", chat_id, e)
next_end = await loop.run_in_executor(None, _get_next_shift_end_utc)
next_end = await loop.run_in_executor(None, _get_next_shift_end_sync)
await _schedule_next_update(context.application, chat_id, next_end)
async def my_chat_member_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
async def my_chat_member_handler(
update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
"""On bot added to group: send, pin, save, schedule. On removed: delete pin, cancel job."""
if not update.my_chat_member or not update.effective_user:
return
@@ -181,12 +131,15 @@ async def my_chat_member_handler(update: Update, context: ContextTypes.DEFAULT_T
chat_id = chat.id
# Bot added to group
if new.status in (ChatMemberStatus.MEMBER, ChatMemberStatus.ADMINISTRATOR) and old.status in (
if new.status in (
ChatMemberStatus.MEMBER,
ChatMemberStatus.ADMINISTRATOR,
) and old.status in (
ChatMemberStatus.LEFT,
ChatMemberStatus.BANNED,
):
loop = asyncio.get_running_loop()
text = await loop.run_in_executor(None, _get_duty_message_text)
text = await loop.run_in_executor(None, _get_duty_message_text_sync)
try:
msg = await context.bot.send_message(chat_id=chat_id, text=text)
except (BadRequest, Forbidden) as e:
@@ -214,13 +167,15 @@ async def my_chat_member_handler(update: Update, context: ContextTypes.DEFAULT_T
)
except (BadRequest, Forbidden):
pass
next_end = await loop.run_in_executor(None, _get_next_shift_end_utc)
next_end = await loop.run_in_executor(None, _get_next_shift_end_sync)
await _schedule_next_update(context.application, chat_id, next_end)
return
# Bot removed from group
if new.status in (ChatMemberStatus.LEFT, ChatMemberStatus.BANNED):
await asyncio.get_running_loop().run_in_executor(None, _sync_delete_pin, chat_id)
await asyncio.get_running_loop().run_in_executor(
None, _sync_delete_pin, chat_id
)
name = f"{JOB_NAME_PREFIX}{chat_id}"
if context.application.job_queue:
for job in context.application.job_queue.get_jobs_by_name(name):
@@ -229,11 +184,8 @@ async def my_chat_member_handler(update: Update, context: ContextTypes.DEFAULT_T
def _get_all_pin_chat_ids_sync() -> list[int]:
session = get_session(config.DATABASE_URL)
try:
return get_all_group_duty_pin_chat_ids(session)
finally:
session.close()
with session_scope(config.DATABASE_URL) as session:
return get_all_pin_chat_ids(session)
async def restore_group_pin_jobs(application) -> None:
@@ -241,7 +193,7 @@ async def restore_group_pin_jobs(application) -> None:
loop = asyncio.get_running_loop()
chat_ids = await loop.run_in_executor(None, _get_all_pin_chat_ids_sync)
for chat_id in chat_ids:
next_end = await loop.run_in_executor(None, _get_next_shift_end_utc)
next_end = await loop.run_in_executor(None, _get_next_shift_end_sync)
await _schedule_next_update(application, chat_id, next_end)
logger.info("Restored %s group pin jobs", len(chat_ids))
@@ -258,7 +210,9 @@ async def pin_duty_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
loop = asyncio.get_running_loop()
message_id = await loop.run_in_executor(None, _sync_get_message_id, chat_id)
if message_id is None:
await update.message.reply_text("В этом чате ещё нет сообщения о дежурстве. Добавьте бота в группу — оно создастся автоматически.")
await update.message.reply_text(
"В этом чате ещё нет сообщения о дежурстве. Добавьте бота в группу — оно создастся автоматически."
)
return
try:
await context.bot.pin_chat_message(

View File

@@ -1,93 +1,20 @@
"""Import duty-schedule: /import_duty_schedule (admin only). Two steps: handover time -> JSON file."""
import asyncio
import re
from datetime import date, datetime, timedelta, timezone
import config
from telegram import Update
from telegram.ext import CommandHandler, ContextTypes, MessageHandler, filters
from db.session import get_session
from db.repository import (
get_or_create_user_by_full_name,
delete_duties_in_range,
insert_duty,
)
from importers.duty_schedule import (
DutyScheduleParseError,
DutyScheduleResult,
parse_duty_schedule,
)
# HH:MM or HH:MM:SS, optional space + timezone (IANA or "UTC")
HANDOVER_TIME_RE = re.compile(
r"^\s*(\d{1,2}):(\d{2})(?::(\d{2}))?\s*(?:\s+(\S+))?\s*$", re.IGNORECASE
)
from db.session import session_scope
from importers.duty_schedule import DutyScheduleParseError, parse_duty_schedule
from services.import_service import run_import
from utils.handover import parse_handover_time
def _parse_handover_time(text: str) -> tuple[int, int] | None:
"""Parse handover time string to (hour_utc, minute_utc). Returns None on failure."""
m = HANDOVER_TIME_RE.match(text)
if not m:
return None
hour = int(m.group(1))
minute = int(m.group(2))
# second = m.group(3) ignored
tz_str = (m.group(4) or "").strip()
if not tz_str or tz_str.upper() == "UTC":
return (hour % 24, minute)
try:
from zoneinfo import ZoneInfo
except ImportError:
try:
from backports.zoneinfo import ZoneInfo # type: ignore
except ImportError:
return None
try:
tz = ZoneInfo(tz_str)
except Exception:
return None
# Build datetime in that tz and convert to UTC
dt = datetime(2000, 1, 1, hour, minute, 0, tzinfo=tz)
utc = dt.astimezone(timezone.utc)
return (utc.hour, utc.minute)
def _duty_to_iso(d: date, hour_utc: int, minute_utc: int) -> str:
"""ISO 8601 with Z for start of duty on date d at given UTC time."""
dt = datetime(d.year, d.month, d.day, hour_utc, minute_utc, 0, tzinfo=timezone.utc)
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
def _day_start_iso(d: date) -> str:
"""ISO 8601 start of calendar day UTC: YYYY-MM-DDT00:00:00Z."""
return d.isoformat() + "T00:00:00Z"
def _day_end_iso(d: date) -> str:
"""ISO 8601 end of calendar day UTC: YYYY-MM-DDT23:59:59Z."""
return d.isoformat() + "T23:59:59Z"
def _consecutive_date_ranges(dates: list[date]) -> list[tuple[date, date]]:
"""Sort dates and merge consecutive ones into (first, last) ranges. Empty list -> []."""
if not dates:
return []
sorted_dates = sorted(set(dates))
ranges: list[tuple[date, date]] = []
start_d = end_d = sorted_dates[0]
for d in sorted_dates[1:]:
if (d - end_d).days == 1:
end_d = d
else:
ranges.append((start_d, end_d))
start_d = end_d = d
ranges.append((start_d, end_d))
return ranges
async def import_duty_schedule_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
async def import_duty_schedule_cmd(
update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
if not update.message or not update.effective_user:
return
if not config.is_admin(update.effective_user.username or ""):
@@ -100,7 +27,9 @@ async def import_duty_schedule_cmd(update: Update, context: ContextTypes.DEFAULT
)
async def handle_handover_time_text(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
async def handle_handover_time_text(
update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
if not update.message or not update.effective_user or not update.message.text:
return
if not context.user_data.get("awaiting_handover_time"):
@@ -108,7 +37,7 @@ async def handle_handover_time_text(update: Update, context: ContextTypes.DEFAUL
if not config.is_admin(update.effective_user.username or ""):
return
text = update.message.text.strip()
parsed = _parse_handover_time(text)
parsed = parse_handover_time(text)
if parsed is None:
await update.message.reply_text(
"Не удалось разобрать время. Укажите, например: 09:00 Europe/Moscow"
@@ -118,56 +47,12 @@ async def handle_handover_time_text(update: Update, context: ContextTypes.DEFAUL
context.user_data["handover_utc_time"] = (hour_utc, minute_utc)
context.user_data["awaiting_handover_time"] = False
context.user_data["awaiting_duty_schedule_file"] = True
await update.message.reply_text(
"Отправьте файл в формате duty-schedule (JSON)."
)
await update.message.reply_text("Отправьте файл в формате duty-schedule (JSON).")
def _run_import(
database_url: str,
result: DutyScheduleResult,
hour_utc: int,
minute_utc: int,
) -> tuple[int, int, int, int]:
"""Returns (num_users, num_duty, num_unavailable, num_vacation)."""
session = get_session(database_url)
try:
from_date_str = result.start_date.isoformat()
to_date_str = result.end_date.isoformat()
num_duty = num_unavailable = num_vacation = 0
for entry in result.entries:
user = get_or_create_user_by_full_name(session, entry.full_name)
delete_duties_in_range(session, user.id, from_date_str, to_date_str)
for d in entry.duty_dates:
start_at = _duty_to_iso(d, hour_utc, minute_utc)
d_next = d + timedelta(days=1)
end_at = _duty_to_iso(d_next, hour_utc, minute_utc)
insert_duty(session, user.id, start_at, end_at, event_type="duty")
num_duty += 1
for d in entry.unavailable_dates:
insert_duty(
session,
user.id,
_day_start_iso(d),
_day_end_iso(d),
event_type="unavailable",
)
num_unavailable += 1
for start_d, end_d in _consecutive_date_ranges(entry.vacation_dates):
insert_duty(
session,
user.id,
_day_start_iso(start_d),
_day_end_iso(end_d),
event_type="vacation",
)
num_vacation += 1
return (len(result.entries), num_duty, num_unavailable, num_vacation)
finally:
session.close()
async def handle_duty_schedule_document(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
async def handle_duty_schedule_document(
update: Update, context: ContextTypes.DEFAULT_TYPE
) -> None:
if not update.message or not update.message.document or not update.effective_user:
return
if not context.user_data.get("awaiting_duty_schedule_file"):
@@ -193,11 +78,14 @@ async def handle_duty_schedule_document(update: Update, context: ContextTypes.DE
await update.message.reply_text(f"Ошибка разбора файла: {e}")
return
def run_import_with_scope():
with session_scope(config.DATABASE_URL) as session:
return run_import(session, result, hour_utc, minute_utc)
loop = asyncio.get_running_loop()
try:
num_users, num_duty, num_unavailable, num_vacation = await loop.run_in_executor(
None,
lambda: _run_import(config.DATABASE_URL, result, hour_utc, minute_utc),
None, run_import_with_scope
)
except Exception as e:
await update.message.reply_text(f"Ошибка импорта: {e}")
@@ -216,7 +104,9 @@ async def handle_duty_schedule_document(update: Update, context: ContextTypes.DE
context.user_data.pop("handover_utc_time", None)
import_duty_schedule_handler = CommandHandler("import_duty_schedule", import_duty_schedule_cmd)
import_duty_schedule_handler = CommandHandler(
"import_duty_schedule", import_duty_schedule_cmd
)
handover_time_handler = MessageHandler(
filters.TEXT & ~filters.COMMAND,
handle_handover_time_text,