redisign and bug fix

This commit is contained in:
vrubelroman 2026-03-22 12:48:20 +03:00
parent a18b5ad1ce
commit 8542ce8e01
10 changed files with 1622 additions and 1169 deletions

View file

@ -1,19 +1,13 @@
from fastapi import APIRouter, Depends, HTTPException, Body
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_
from datetime import datetime, timedelta from datetime import datetime, timedelta
import pytz
from typing import List, Union
from backend.database import get_db, Task, Event, WeeklyTaskException import pytz
from backend.models import ( from fastapi import APIRouter, Depends, HTTPException, Body
TaskCreate, EventCreate, ScheduleResponse, ScheduleItem, from sqlalchemy import and_, select
TaskResponse, EventResponse, UpdateRequest from sqlalchemy.ext.asyncio import AsyncSession
)
from backend.utils import ( from backend.database import get_db, Task, Event, WeeklyTaskException, EventException
get_week_range, check_event_overlap, get_weekday_from_date, from backend.models import TaskCreate, EventCreate, ScheduleResponse, ScheduleItem, UpdateRequest
materialize_weekly_tasks, format_date_russian from backend.utils import check_event_overlap, get_weekday_from_date, materialize_weekly_tasks, materialize_events
)
router = APIRouter() router = APIRouter()
@ -26,16 +20,18 @@ async def get_schedule(
to_date: str, to_date: str,
db: AsyncSession = Depends(get_db) db: AsyncSession = Depends(get_db)
): ):
"""Получить расписание в диапазоне дат""" """Получить расписание в диапазоне дат."""
try: try:
from_dt = datetime.strptime(from_date, "%Y-%m-%d").date() from_dt = datetime.strptime(from_date, "%Y-%m-%d").date()
to_dt = datetime.strptime(to_date, "%Y-%m-%d").date() to_dt = datetime.strptime(to_date, "%Y-%m-%d").date()
except ValueError: except ValueError:
raise HTTPException(status_code=400, detail="Invalid date format. Use YYYY-MM-DD") raise HTTPException(status_code=400, detail="Invalid date format. Use YYYY-MM-DD")
if to_dt < from_dt:
raise HTTPException(status_code=400, detail="to_date must be greater than or equal to from_date")
items = [] items = []
# Получаем разовые tasks
result = await db.execute( result = await db.execute(
select(Task).where( select(Task).where(
and_( and_(
@ -51,34 +47,14 @@ async def get_schedule(
kind="task", kind="task",
id=task.id, id=task.id,
date=task.date, date=task.date,
source_date=task.date,
title=task.title, title=task.title,
repeat_weekly=False repeat_weekly=False
)) ))
# Получаем events items.extend(await materialize_weekly_tasks(db, from_date, to_date))
result = await db.execute( items.extend(await materialize_events(db, from_date, to_date))
select(Event).where(
and_(
Event.date >= from_date,
Event.date <= to_date
)
)
)
events = result.scalars().all()
for event in events:
items.append(ScheduleItem(
kind="event",
id=event.id,
date=event.date,
title=event.title,
start_time=event.start_time,
duration_min=event.duration_min
))
# Материализуем weekly tasks
weekly_tasks = await materialize_weekly_tasks(db, from_date, to_date)
items.extend(weekly_tasks)
return ScheduleResponse(items=items) return ScheduleResponse(items=items)
@ -88,74 +64,69 @@ async def create_item(
data: dict = Body(...), data: dict = Body(...),
db: AsyncSession = Depends(get_db) db: AsyncSession = Depends(get_db)
): ):
"""Создать task или event""" """Создать task или event."""
if kind == "task": if kind == "task":
try: try:
task = TaskCreate(**data) task = TaskCreate(**data)
except Exception as e: except Exception as exc:
raise HTTPException(status_code=400, detail=f"Invalid task data: {e}") raise HTTPException(status_code=400, detail=f"Invalid task data: {exc}")
# Создаём основную task
new_task = Task( new_task = Task(
date=task.date, date=task.date,
title=task.title, title=task.title,
repeat_weekly=task.repeat_weekly repeat_weekly=task.repeat_weekly
) )
if task.repeat_weekly: if task.repeat_weekly:
weekday = get_weekday_from_date(task.date) new_task.weekday = get_weekday_from_date(task.date)
new_task.weekday = weekday
db.add(new_task) db.add(new_task)
await db.commit() await db.commit()
await db.refresh(new_task) await db.refresh(new_task)
# Копирование на другие дни недели
if task.copy_to_weekdays and not task.repeat_weekly: if task.copy_to_weekdays and not task.repeat_weekly:
base_date = datetime.strptime(task.date, "%Y-%m-%d").date() base_date = datetime.strptime(task.date, "%Y-%m-%d").date()
base_weekday = base_date.weekday() base_weekday = base_date.weekday()
for target_weekday in task.copy_to_weekdays: for target_weekday in task.copy_to_weekdays:
# Вычисляем дату целевого дня недели в той же неделе days_diff = target_weekday - base_weekday
days_diff = (target_weekday - base_weekday) % 7 if days_diff <= 0:
if days_diff > 0: # только будущие дни continue
target_date = base_date + timedelta(days=days_diff) target_date = base_date + timedelta(days=days_diff)
copy_task = Task( db.add(Task(
date=target_date.strftime("%Y-%m-%d"), date=target_date.strftime("%Y-%m-%d"),
title=task.title, title=task.title,
repeat_weekly=False repeat_weekly=False
) ))
db.add(copy_task)
await db.commit() await db.commit()
return {"id": new_task.id, "kind": "task"} return {"id": new_task.id, "kind": "task"}
elif kind == "event": if kind == "event":
try: try:
event = EventCreate(**data) event = EventCreate(**data)
except Exception as e: except Exception as exc:
raise HTTPException(status_code=400, detail=f"Invalid event data: {e}") raise HTTPException(status_code=400, detail=f"Invalid event data: {exc}")
# Проверка пересечений overlap = await check_event_overlap(db, event.date, event.start_time, event.duration_min, None)
overlap = await check_event_overlap(
db, event.date, event.start_time, event.duration_min, None
)
if overlap: if overlap:
raise HTTPException(status_code=400, detail="Нельзя добавить: пересечение по времени") raise HTTPException(status_code=400, detail="Нельзя добавить: пересечение по времени")
new_event = Event( new_event = Event(
date=event.date, date=event.date,
start_time=event.start_time, start_time=event.start_time,
duration_min=event.duration_min, duration_min=event.duration_min,
title=event.title title=event.title,
repeat_weekly=event.repeat_weekly
) )
if event.repeat_weekly:
new_event.weekday = get_weekday_from_date(event.date)
db.add(new_event) db.add(new_event)
await db.commit() await db.commit()
await db.refresh(new_event) await db.refresh(new_event)
return {"id": new_event.id, "kind": "event"} return {"id": new_event.id, "kind": "event"}
else: raise HTTPException(status_code=400, detail="Invalid kind. Use 'task' or 'event'")
raise HTTPException(status_code=400, detail="Invalid kind. Use 'task' or 'event'")
@router.put("/events/{item_id}") @router.put("/events/{item_id}")
@ -164,130 +135,200 @@ async def update_item(
update: UpdateRequest, update: UpdateRequest,
db: AsyncSession = Depends(get_db) db: AsyncSession = Depends(get_db)
): ):
"""Обновить task или event""" """Обновить task или event."""
# Пробуем найти как task
result = await db.execute(select(Task).where(Task.id == item_id)) result = await db.execute(select(Task).where(Task.id == item_id))
task = result.scalar_one_or_none() task = result.scalar_one_or_none()
if task: if task:
if task.repeat_weekly and update.scope == "one_date": if task.repeat_weekly and update.scope == "one_date":
# Создаём исключение для конкретной даты occurrence_date = update.occurrence_date or task.date
weekday = get_weekday_from_date(task.date) result = await db.execute(
select(WeeklyTaskException).where(
and_(
WeeklyTaskException.task_id == task.id,
WeeklyTaskException.date == occurrence_date
)
)
)
for existing_exception in result.scalars().all():
await db.delete(existing_exception)
exception = WeeklyTaskException( exception = WeeklyTaskException(
weekday=weekday, task_id=task.id,
date=task.date, weekday=get_weekday_from_date(occurrence_date),
action="replace" if update.title else "delete", date=occurrence_date,
replacement_title=update.title action="replace",
replacement_title=update.title or task.title,
replacement_date=update.date or occurrence_date
) )
db.add(exception) db.add(exception)
await db.commit() await db.commit()
return {"success": True, "action": "exception_created"} return {"success": True, "action": "exception_created"}
if update.title: if update.title:
if task.repeat_weekly and update.scope == "series": task.title = update.title
# Обновляем все weekly tasks с этим weekday if update.date:
await db.execute( task.date = update.date
Task.__table__.update() if task.repeat_weekly:
.where(Task.weekday == task.weekday) task.weekday = get_weekday_from_date(update.date)
.values(title=update.title)
)
else:
task.title = update.title
await db.commit() await db.commit()
return {"success": True} return {"success": True}
# Пробуем найти как event
result = await db.execute(select(Event).where(Event.id == item_id)) result = await db.execute(select(Event).where(Event.id == item_id))
event = result.scalar_one_or_none() event = result.scalar_one_or_none()
if not event:
if event: raise HTTPException(status_code=404, detail="Item not found")
new_date = update.date or event.date
new_start_time = update.start_time or event.start_time if event.repeat_weekly and update.scope == "one_date":
new_duration = update.duration_min or event.duration_min occurrence_date = update.occurrence_date or event.date
replacement_date = update.date or occurrence_date
# Проверка пересечений replacement_start_time = update.start_time or event.start_time
replacement_duration = update.duration_min or event.duration_min
overlap = await check_event_overlap( overlap = await check_event_overlap(
db, new_date, new_start_time, new_duration, item_id db,
replacement_date,
replacement_start_time,
replacement_duration,
item_id,
occurrence_date=occurrence_date
) )
if overlap: if overlap:
raise HTTPException(status_code=400, detail="Нельзя изменить: пересечение по времени") raise HTTPException(status_code=400, detail="Нельзя изменить: пересечение по времени")
if update.title: result = await db.execute(
event.title = update.title select(EventException).where(
if update.date: and_(
event.date = update.date EventException.event_id == event.id,
if update.start_time: EventException.date == occurrence_date
event.start_time = update.start_time )
if update.duration_min: )
event.duration_min = update.duration_min )
for existing_exception in result.scalars().all():
await db.delete(existing_exception)
db.add(EventException(
event_id=event.id,
date=occurrence_date,
action="replace",
replacement_title=update.title or event.title,
replacement_date=replacement_date,
replacement_start_time=replacement_start_time,
replacement_duration_min=replacement_duration
))
await db.commit() await db.commit()
return {"success": True} return {"success": True, "action": "exception_created"}
raise HTTPException(status_code=404, detail="Item not found") new_date = update.date or event.date
new_start_time = update.start_time or event.start_time
new_duration = update.duration_min or event.duration_min
overlap = await check_event_overlap(db, new_date, new_start_time, new_duration, item_id)
if overlap:
raise HTTPException(status_code=400, detail="Нельзя изменить: пересечение по времени")
if update.title:
event.title = update.title
if update.date:
event.date = update.date
if event.repeat_weekly:
event.weekday = get_weekday_from_date(update.date)
if update.start_time:
event.start_time = update.start_time
if update.duration_min:
event.duration_min = update.duration_min
await db.commit()
return {"success": True}
@router.delete("/events/{item_id}") @router.delete("/events/{item_id}")
async def delete_item( async def delete_item(
item_id: int, item_id: int,
scope: str = None, scope: str = None,
occurrence_date: str = None,
db: AsyncSession = Depends(get_db) db: AsyncSession = Depends(get_db)
): ):
"""Удалить task или event""" """Удалить task или event."""
# Пробуем найти как task
result = await db.execute(select(Task).where(Task.id == item_id)) result = await db.execute(select(Task).where(Task.id == item_id))
task = result.scalar_one_or_none() task = result.scalar_one_or_none()
if task: if task:
if task.repeat_weekly: if task.repeat_weekly and scope == "one_date":
if scope == "one_date": delete_date = occurrence_date or task.date
# Создаём исключение на удаление result = await db.execute(
weekday = get_weekday_from_date(task.date) select(WeeklyTaskException).where(
exception = WeeklyTaskException( and_(
weekday=weekday, WeeklyTaskException.task_id == task.id,
date=task.date, WeeklyTaskException.date == delete_date
action="delete" )
) )
db.add(exception) )
await db.commit() for existing_exception in result.scalars().all():
return {"success": True, "action": "exception_created"} await db.delete(existing_exception)
elif scope == "series": db.add(WeeklyTaskException(
# Удаляем все weekly tasks с этим weekday task_id=task.id,
await db.execute( weekday=get_weekday_from_date(delete_date),
Task.__table__.delete().where(Task.weekday == task.weekday) date=delete_date,
) action="delete"
await db.commit() ))
return {"success": True} await db.commit()
return {"success": True, "action": "exception_created"}
if task.repeat_weekly and scope == "series":
result = await db.execute(select(WeeklyTaskException).where(WeeklyTaskException.task_id == task.id))
for exception in result.scalars().all():
await db.delete(exception)
await db.delete(task) await db.delete(task)
await db.commit() await db.commit()
return {"success": True} return {"success": True}
# Пробуем найти как event
result = await db.execute(select(Event).where(Event.id == item_id)) result = await db.execute(select(Event).where(Event.id == item_id))
event = result.scalar_one_or_none() event = result.scalar_one_or_none()
if not event:
if event: raise HTTPException(status_code=404, detail="Item not found")
await db.delete(event)
if event.repeat_weekly and scope == "one_date":
delete_date = occurrence_date or event.date
result = await db.execute(
select(EventException).where(
and_(
EventException.event_id == event.id,
EventException.date == delete_date
)
)
)
for existing_exception in result.scalars().all():
await db.delete(existing_exception)
db.add(EventException(
event_id=event.id,
date=delete_date,
action="delete"
))
await db.commit() await db.commit()
return {"success": True} return {"success": True, "action": "exception_created"}
raise HTTPException(status_code=404, detail="Item not found") if event.repeat_weekly and scope == "series":
result = await db.execute(select(EventException).where(EventException.event_id == event.id))
for exception in result.scalars().all():
await db.delete(exception)
await db.delete(event)
await db.commit()
return {"success": True}
@router.get("/backup") @router.get("/backup")
async def backup_database(): async def backup_database():
"""Создать backup базы данных""" """Создать backup базы данных."""
import shutil
import os import os
from datetime import datetime import shutil
db_path = os.getenv("DATABASE_PATH", "data/schedule.db") db_path = os.getenv("DATABASE_PATH", "data/schedule.db")
backup_path = f"{db_path}.backup.{datetime.now().strftime('%Y%m%d_%H%M%S')}" backup_path = f"{db_path}.backup.{datetime.now().strftime('%Y%m%d_%H%M%S')}"
if os.path.exists(db_path): if os.path.exists(db_path):
shutil.copy2(db_path, backup_path) shutil.copy2(db_path, backup_path)
return {"success": True, "backup_path": backup_path} return {"success": True, "backup_path": backup_path}
return {"success": False, "error": "Database not found"} return {"success": False, "error": "Database not found"}

View file

@ -1,6 +1,6 @@
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text from sqlalchemy import Column, Integer, String, Boolean, text
import os import os
Base = declarative_base() Base = declarative_base()
@ -31,16 +31,33 @@ class Event(Base):
start_time = Column(String) # HH:MM start_time = Column(String) # HH:MM
duration_min = Column(Integer, nullable=False) duration_min = Column(Integer, nullable=False)
title = Column(String, nullable=False) title = Column(String, nullable=False)
repeat_weekly = Column(Boolean, default=False)
weekday = Column(Integer) # 0=Monday, 6=Sunday, только для weekly events
class WeeklyTaskException(Base): class WeeklyTaskException(Base):
__tablename__ = "weekly_task_exceptions" __tablename__ = "weekly_task_exceptions"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
task_id = Column(Integer, index=True)
weekday = Column(Integer, nullable=False) # 0=Monday, 6=Sunday weekday = Column(Integer, nullable=False) # 0=Monday, 6=Sunday
date = Column(String, nullable=False) # YYYY-MM-DD date = Column(String, nullable=False) # YYYY-MM-DD
action = Column(String, nullable=False) # "delete" или "replace" action = Column(String, nullable=False) # "delete" или "replace"
replacement_title = Column(String) # для action="replace" replacement_title = Column(String) # для action="replace"
replacement_date = Column(String) # для переноса/замены одного вхождения
class EventException(Base):
__tablename__ = "event_exceptions"
id = Column(Integer, primary_key=True, index=True)
event_id = Column(Integer, index=True, nullable=False)
date = Column(String, nullable=False)
action = Column(String, nullable=False) # "delete" или "replace"
replacement_title = Column(String)
replacement_date = Column(String)
replacement_start_time = Column(String)
replacement_duration_min = Column(Integer)
class TelegramUser(Base): class TelegramUser(Base):
@ -53,6 +70,37 @@ class TelegramUser(Base):
async def init_db(): async def init_db():
async with engine.begin() as conn: async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all) await conn.run_sync(Base.metadata.create_all)
await _run_migrations(conn)
async def _run_migrations(conn):
table_columns = await _get_table_columns(conn)
task_columns = table_columns.get("tasks", set())
if "weekday" not in task_columns:
await conn.execute(text("ALTER TABLE tasks ADD COLUMN weekday INTEGER"))
event_columns = table_columns.get("events", set())
if "repeat_weekly" not in event_columns:
await conn.execute(text("ALTER TABLE events ADD COLUMN repeat_weekly BOOLEAN DEFAULT 0"))
if "weekday" not in event_columns:
await conn.execute(text("ALTER TABLE events ADD COLUMN weekday INTEGER"))
exception_columns = table_columns.get("weekly_task_exceptions", set())
if "task_id" not in exception_columns:
await conn.execute(text("ALTER TABLE weekly_task_exceptions ADD COLUMN task_id INTEGER"))
if "replacement_date" not in exception_columns:
await conn.execute(text("ALTER TABLE weekly_task_exceptions ADD COLUMN replacement_date TEXT"))
async def _get_table_columns(conn):
table_names = ["tasks", "events", "weekly_task_exceptions", "event_exceptions"]
columns = {}
for table_name in table_names:
result = await conn.exec_driver_sql(f"PRAGMA table_info({table_name})")
rows = result.fetchall()
columns[table_name] = {row[1] for row in rows}
return columns
async def get_db(): async def get_db():
@ -61,4 +109,3 @@ async def get_db():
yield session yield session
finally: finally:
await session.close() await session.close()

View file

@ -1,7 +1,5 @@
from pydantic import BaseModel from pydantic import BaseModel
from typing import Optional, Literal from typing import Optional, Literal
from datetime import date
class TaskCreate(BaseModel): class TaskCreate(BaseModel):
date: str # YYYY-MM-DD date: str # YYYY-MM-DD
title: str title: str
@ -13,6 +11,7 @@ class EventCreate(BaseModel):
start_time: str # HH:MM start_time: str # HH:MM
duration_min: int duration_min: int
title: str title: str
repeat_weekly: bool = False
class TaskResponse(BaseModel): class TaskResponse(BaseModel):
id: int id: int
@ -28,11 +27,13 @@ class EventResponse(BaseModel):
duration_min: int duration_min: int
title: str title: str
kind: Literal["event"] = "event" kind: Literal["event"] = "event"
repeat_weekly: bool = False
class ScheduleItem(BaseModel): class ScheduleItem(BaseModel):
kind: Literal["task", "event"] kind: Literal["task", "event"]
id: int id: int
date: str date: str
source_date: Optional[str] = None
title: str title: str
start_time: Optional[str] = None start_time: Optional[str] = None
duration_min: Optional[int] = None duration_min: Optional[int] = None
@ -46,5 +47,5 @@ class UpdateRequest(BaseModel):
date: Optional[str] = None date: Optional[str] = None
start_time: Optional[str] = None start_time: Optional[str] = None
duration_min: Optional[int] = None duration_min: Optional[int] = None
occurrence_date: Optional[str] = None
scope: Optional[Literal["one_date", "series"]] = None # для weekly tasks scope: Optional[Literal["one_date", "series"]] = None # для weekly tasks

View file

@ -3,97 +3,182 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_ from sqlalchemy import select, and_
import pytz import pytz
from backend.database import Task, Event, WeeklyTaskException from backend.database import Task, Event, WeeklyTaskException, EventException
from backend.models import ScheduleItem from backend.models import ScheduleItem
TZ = pytz.timezone("Europe/Moscow") TZ = pytz.timezone("Europe/Moscow")
def get_weekday_from_date(date_str: str) -> int: def get_weekday_from_date(date_str: str) -> int:
"""Получить день недели (0=Monday, 6=Sunday) из даты""" """Получить день недели (0=Monday, 6=Sunday) из даты."""
dt = datetime.strptime(date_str, "%Y-%m-%d") dt = datetime.strptime(date_str, "%Y-%m-%d")
return dt.weekday() return dt.weekday()
def get_week_range(date_str: str = None): def get_week_range(date_str: str = None):
"""Получить диапазон дат недели (понедельник-воскресенье)""" """Получить диапазон дат недели (понедельник-воскресенье)."""
if date_str: if date_str:
base_date = datetime.strptime(date_str, "%Y-%m-%d").date() base_date = datetime.strptime(date_str, "%Y-%m-%d").date()
else: else:
base_date = datetime.now(TZ).date() base_date = datetime.now(TZ).date()
# Находим понедельник
days_since_monday = base_date.weekday() days_since_monday = base_date.weekday()
monday = base_date - timedelta(days=days_since_monday) monday = base_date - timedelta(days=days_since_monday)
sunday = monday + timedelta(days=6) sunday = monday + timedelta(days=6)
return monday.strftime("%Y-%m-%d"), sunday.strftime("%Y-%m-%d") return monday.strftime("%Y-%m-%d"), sunday.strftime("%Y-%m-%d")
def format_date_russian(date_str: str) -> str: def format_date_russian(date_str: str) -> str:
"""Форматировать дату в русском формате: 'Вторник, 2 декабря'""" """Форматировать дату в русском формате: 'Вторник, 2 декабря'."""
dt = datetime.strptime(date_str, "%Y-%m-%d") dt = datetime.strptime(date_str, "%Y-%m-%d")
weekdays = ["Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"] weekdays = ["Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"]
months = [ months = [
"января", "февраля", "марта", "апреля", "мая", "июня", "января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря" "июля", "августа", "сентября", "октября", "ноября", "декабря"
] ]
weekday = weekdays[dt.weekday()] weekday = weekdays[dt.weekday()]
month = months[dt.month - 1] month = months[dt.month - 1]
return f"{weekday}, {dt.day} {month}" return f"{weekday}, {dt.day} {month}"
def _time_to_minutes(value: str) -> int:
hour, minute = map(int, value.split(":"))
return hour * 60 + minute
async def check_event_overlap( async def check_event_overlap(
db: AsyncSession, db: AsyncSession,
date: str, date: str,
start_time: str, start_time: str,
duration_min: int, duration_min: int,
exclude_id: int = None exclude_id: int = None,
occurrence_date: str = None
) -> bool: ) -> bool:
"""Проверить пересечение по времени с другими events""" """Проверить пересечение по времени с разовыми и weekly events."""
# Парсим время начала start_minutes = _time_to_minutes(start_time)
start_hour, start_min = map(int, start_time.split(":"))
start_minutes = start_hour * 60 + start_min
end_minutes = start_minutes + duration_min end_minutes = start_minutes + duration_min
# Получаем все events на эту дату events = await materialize_events(db, date, date)
query = select(Event).where(Event.date == date)
if exclude_id:
query = query.where(Event.id != exclude_id)
result = await db.execute(query)
events = result.scalars().all()
for event in events: for event in events:
ev_start_hour, ev_start_min = map(int, event.start_time.split(":")) if exclude_id and event.id == exclude_id and (occurrence_date is None or event.date == occurrence_date):
ev_start_minutes = ev_start_hour * 60 + ev_start_min continue
ev_end_minutes = ev_start_minutes + event.duration_min
ev_start_minutes = _time_to_minutes(event.start_time)
# Проверка пересечения интервалов ev_end_minutes = ev_start_minutes + (event.duration_min or 0)
if not (end_minutes <= ev_start_minutes or start_minutes >= ev_end_minutes): if not (end_minutes <= ev_start_minutes or start_minutes >= ev_end_minutes):
return True return True
return False return False
async def materialize_events(
db: AsyncSession,
from_date: str,
to_date: str
) -> list[ScheduleItem]:
items = []
result = await db.execute(
select(Event).where(
and_(
Event.date >= from_date,
Event.date <= to_date,
Event.repeat_weekly == False
)
)
)
one_off_events = result.scalars().all()
for event in one_off_events:
items.append(ScheduleItem(
kind="event",
id=event.id,
date=event.date,
source_date=event.date,
title=event.title,
start_time=event.start_time,
duration_min=event.duration_min,
repeat_weekly=False
))
result = await db.execute(select(Event).where(Event.repeat_weekly == True))
weekly_events = result.scalars().all()
if not weekly_events:
return items
result = await db.execute(
select(EventException).where(
and_(
EventException.date >= from_date,
EventException.date <= to_date
)
)
)
exceptions = result.scalars().all()
exception_dict = {(ex.event_id, ex.date): ex for ex in exceptions}
from_dt = datetime.strptime(from_date, "%Y-%m-%d").date()
to_dt = datetime.strptime(to_date, "%Y-%m-%d").date()
current_date = from_dt
while current_date <= to_dt:
date_str = current_date.strftime("%Y-%m-%d")
weekday = current_date.weekday()
for event in weekly_events:
base_date = datetime.strptime(event.date, "%Y-%m-%d").date()
if current_date < base_date or event.weekday != weekday:
continue
exception = exception_dict.get((event.id, date_str))
if exception:
if exception.action == "delete":
continue
items.append(ScheduleItem(
kind="event",
id=event.id,
date=exception.replacement_date or date_str,
source_date=date_str,
title=exception.replacement_title or event.title,
start_time=exception.replacement_start_time or event.start_time,
duration_min=exception.replacement_duration_min or event.duration_min,
repeat_weekly=True
))
continue
items.append(ScheduleItem(
kind="event",
id=event.id,
date=date_str,
source_date=date_str,
title=event.title,
start_time=event.start_time,
duration_min=event.duration_min,
repeat_weekly=True
))
current_date += timedelta(days=1)
return items
async def materialize_weekly_tasks( async def materialize_weekly_tasks(
db: AsyncSession, db: AsyncSession,
from_date: str, from_date: str,
to_date: str to_date: str
) -> list[ScheduleItem]: ) -> list[ScheduleItem]:
"""Материализовать weekly tasks в диапазоне дат""" """Материализовать weekly tasks в диапазоне дат."""
from backend.database import Task, WeeklyTaskException
items = [] items = []
# Получаем все weekly tasks
result = await db.execute(select(Task).where(Task.repeat_weekly == True)) result = await db.execute(select(Task).where(Task.repeat_weekly == True))
weekly_tasks = result.scalars().all() weekly_tasks = result.scalars().all()
if not weekly_tasks:
# Получаем все исключения return items
result = await db.execute( result = await db.execute(
select(WeeklyTaskException).where( select(WeeklyTaskException).where(
and_( and_(
@ -103,44 +188,52 @@ async def materialize_weekly_tasks(
) )
) )
exceptions = result.scalars().all() exceptions = result.scalars().all()
exception_dict = {(ex.date, ex.weekday): ex for ex in exceptions} exception_dict = {}
for ex in exceptions:
if ex.task_id is not None:
exception_dict[(ex.task_id, ex.date)] = ex
else:
exception_dict[(None, ex.date, ex.weekday)] = ex
from_dt = datetime.strptime(from_date, "%Y-%m-%d").date() from_dt = datetime.strptime(from_date, "%Y-%m-%d").date()
to_dt = datetime.strptime(to_date, "%Y-%m-%d").date() to_dt = datetime.strptime(to_date, "%Y-%m-%d").date()
current_date = from_dt current_date = from_dt
while current_date <= to_dt: while current_date <= to_dt:
date_str = current_date.strftime("%Y-%m-%d") date_str = current_date.strftime("%Y-%m-%d")
weekday = current_date.weekday() weekday = current_date.weekday()
for task in weekly_tasks: for task in weekly_tasks:
if task.weekday == weekday: base_date = datetime.strptime(task.date, "%Y-%m-%d").date()
# Проверяем исключения if current_date < base_date or task.weekday != weekday:
ex_key = (date_str, weekday) continue
if ex_key in exception_dict:
exception = exception_dict[ex_key] exception = exception_dict.get((task.id, date_str))
if exception.action == "delete": if not exception:
continue # Пропускаем эту дату exception = exception_dict.get((None, date_str, weekday))
elif exception.action == "replace":
items.append(ScheduleItem( if exception:
kind="task", if exception.action == "delete":
id=task.id, continue
date=date_str,
title=exception.replacement_title,
repeat_weekly=True
))
continue
# Обычная weekly task
items.append(ScheduleItem( items.append(ScheduleItem(
kind="task", kind="task",
id=task.id, id=task.id,
date=date_str, date=exception.replacement_date or date_str,
title=task.title, source_date=date_str,
title=exception.replacement_title or task.title,
repeat_weekly=True repeat_weekly=True
)) ))
continue
current_date += timedelta(days=1)
return items
items.append(ScheduleItem(
kind="task",
id=task.id,
date=date_str,
source_date=date_str,
title=task.title,
repeat_weekly=True
))
current_date += timedelta(days=1)
return items

View file

@ -3,37 +3,58 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Админка - Расписание</title> <title>Админка расписания</title>
<link rel="stylesheet" href="/admin/static/style.css"> <link rel="stylesheet" href="/admin/static/style.css?v=3">
</head> </head>
<body> <body>
<div class="container"> <div class="app-shell">
<header> <header class="hero">
<h1>Админка расписания</h1> <div>
<div class="week-navigation"> <p class="eyebrow">Schedule Studio</p>
<button id="prev-week">← Предыдущая неделя</button> <h1>Редактор расписания</h1>
<span id="week-range"></span> <p class="hero-copy">Планируйте задачи и занятия на несколько недель вперед, меняйте серии целиком и переносите встречи прямо мышкой по сетке времени.</p>
<button id="next-week">Следующая неделя →</button> </div>
<div class="hero-actions">
<button id="today-btn" class="btn btn-secondary">Текущая неделя</button>
<button id="add-task-btn" class="btn btn-secondary">Новая задача</button>
<button id="add-event-btn" class="btn btn-primary">Новое занятие</button>
</div> </div>
</header> </header>
<div class="actions"> <section class="toolbar">
<button id="add-task-btn" class="btn btn-primary"> Добавить задачу</button> <div class="week-navigation">
<button id="add-event-btn" class="btn btn-primary"> Добавить занятие</button> <button id="prev-week" class="nav-btn">← Назад</button>
<div>
<div class="toolbar-label">Видимый диапазон</div>
<div id="week-range" class="range-title"></div>
</div>
<button id="next-week" class="nav-btn">Вперед →</button>
</div>
<div class="legend">
<span class="legend-chip task-chip">Задачи</span>
<span class="legend-chip event-chip">Занятия</span>
<span class="legend-chip recurring-chip">Цикличные</span>
</div>
</section>
<section class="hint-panel">
<span>Клик по дню добавляет занятие.</span>
<span>`Ctrl/Cmd + клик` открывает создание задачи.</span>
<span>Перетаскивайте карточки занятий на новое время или другой день.</span>
</section>
<div class="schedule-scroll">
<main id="schedule-grid" class="schedule-grid"></main>
</div> </div>
<div id="schedule-grid" class="schedule-grid"></div>
</div> </div>
<!-- Модальное окно для добавления/редактирования -->
<div id="modal" class="modal"> <div id="modal" class="modal">
<div class="modal-content"> <div class="modal-content">
<span class="close">&times;</span> <button class="close" type="button" aria-label="Закрыть">×</button>
<div id="modal-body"></div> <div id="modal-body"></div>
</div> </div>
</div> </div>
<script src="/admin/static/script.js"></script> <script src="/admin/static/script.js?v=3"></script>
</body> </body>
</html> </html>

File diff suppressed because it is too large Load diff

View file

@ -1,264 +1,513 @@
:root {
--bg: #f6efe5;
--paper: rgba(255, 252, 248, 0.88);
--paper-strong: #fffaf2;
--text: #1f2937;
--muted: #6b7280;
--line: rgba(123, 92, 62, 0.18);
--brand: #d97706;
--brand-deep: #9a3412;
--task: #15803d;
--event: #0f766e;
--accent: #f59e0b;
--shadow: 0 20px 55px rgba(101, 67, 33, 0.12);
}
* { * {
box-sizing: border-box;
margin: 0; margin: 0;
padding: 0; padding: 0;
box-sizing: border-box;
} }
body { body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; min-height: 100vh;
background: #f5f5f5; font-family: Georgia, "Times New Roman", serif;
padding: 20px; color: var(--text);
background:
radial-gradient(circle at top left, rgba(217, 119, 6, 0.18), transparent 28%),
radial-gradient(circle at bottom right, rgba(15, 118, 110, 0.14), transparent 22%),
linear-gradient(180deg, #f9f4ec 0%, #efe5d5 100%);
padding: 18px;
} }
.container { .app-shell {
max-width: 1400px; max-width: 100%;
margin: 0 auto; margin: 0 auto;
} }
header { .hero,
background: white; .toolbar,
padding: 20px; .hint-panel,
border-radius: 8px; .day-card,
margin-bottom: 20px; .modal-content {
box-shadow: 0 2px 4px rgba(0,0,0,0.1); backdrop-filter: blur(14px);
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.55);
box-shadow: var(--shadow);
} }
header h1 { .hero {
margin-bottom: 15px; border-radius: 30px;
color: #333; padding: 32px;
}
.week-navigation {
display: flex; display: flex;
align-items: center; justify-content: space-between;
gap: 20px; gap: 24px;
} align-items: flex-start;
.week-navigation button {
padding: 8px 16px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
.week-navigation button:hover {
background: #45a049;
}
#week-range {
font-weight: 600;
color: #555;
}
.actions {
margin-bottom: 20px; margin-bottom: 20px;
display: flex;
gap: 10px;
} }
.btn { .eyebrow {
padding: 10px 20px; text-transform: uppercase;
letter-spacing: 0.2em;
font-size: 12px;
color: var(--brand-deep);
margin-bottom: 10px;
}
.hero h1 {
font-size: clamp(34px, 4vw, 56px);
line-height: 0.95;
margin-bottom: 14px;
}
.hero-copy {
max-width: 760px;
font-size: 18px;
line-height: 1.5;
color: var(--muted);
}
.hero-actions,
.week-navigation,
.legend,
.hint-panel,
.task-list,
.item-actions,
.scope-row,
.form-row {
display: flex;
gap: 12px;
}
.hero-actions {
flex-wrap: wrap;
justify-content: flex-end;
}
.btn,
.nav-btn {
border: none; border: none;
border-radius: 4px; border-radius: 999px;
cursor: pointer; padding: 12px 18px;
font-size: 14px; font-size: 14px;
cursor: pointer;
transition: transform 0.18s ease, opacity 0.18s ease, background 0.18s ease;
}
.btn:hover,
.nav-btn:hover {
transform: translateY(-1px);
} }
.btn-primary { .btn-primary {
background: #2196F3; background: linear-gradient(135deg, var(--brand) 0%, var(--brand-deep) 100%);
color: white; color: white;
} }
.btn-primary:hover { .btn-secondary,
background: #0b7dda; .nav-btn {
background: rgba(255, 248, 236, 0.95);
color: var(--text);
border: 1px solid rgba(123, 92, 62, 0.16);
}
.toolbar {
border-radius: 24px;
padding: 18px 22px;
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
margin-bottom: 16px;
}
.toolbar-label {
color: var(--muted);
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.15em;
margin-bottom: 4px;
}
.range-title {
font-size: 20px;
font-weight: 700;
}
.legend {
flex-wrap: wrap;
}
.legend-chip {
padding: 8px 12px;
border-radius: 999px;
font-size: 13px;
border: 1px solid transparent;
}
.task-chip {
background: rgba(21, 128, 61, 0.12);
color: var(--task);
}
.event-chip {
background: rgba(15, 118, 110, 0.12);
color: var(--event);
}
.recurring-chip {
background: rgba(245, 158, 11, 0.16);
color: var(--brand-deep);
}
.hint-panel {
border-radius: 20px;
padding: 14px 18px;
margin-bottom: 22px;
flex-wrap: wrap;
color: var(--muted);
font-size: 14px;
} }
.schedule-grid { .schedule-grid {
display: grid; display: grid;
grid-template-columns: repeat(7, 1fr); grid-template-columns: repeat(7, minmax(220px, 1fr));
gap: 15px; gap: 14px;
padding-bottom: 8px;
min-width: 1624px;
} }
.day-column { .schedule-scroll {
background: white; overflow-x: auto;
border-radius: 8px; overflow-y: visible;
padding: 15px; padding-bottom: 10px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1); scrollbar-width: thin;
}
.day-card {
border-radius: 26px;
padding: 16px;
min-height: 820px;
position: relative;
}
.day-card.is-today {
outline: 2px solid rgba(217, 119, 6, 0.28);
} }
.day-header { .day-header {
font-weight: 600; display: flex;
font-size: 16px; justify-content: space-between;
margin-bottom: 15px; align-items: flex-start;
padding-bottom: 10px; margin-bottom: 16px;
border-bottom: 2px solid #4CAF50; gap: 12px;
color: #333;
} }
.day-items { .day-title {
min-height: 200px; font-size: 22px;
line-height: 1.1;
} }
.item { .day-subtitle {
background: #f9f9f9; color: var(--muted);
padding: 10px; margin-top: 6px;
margin-bottom: 8px; font-size: 13px;
border-radius: 4px;
border-left: 3px solid #4CAF50;
cursor: pointer;
transition: background 0.2s;
} }
.item:hover { .day-badge {
background: #f0f0f0; border-radius: 999px;
} background: rgba(217, 119, 6, 0.12);
color: var(--brand-deep);
.item.task { padding: 8px 10px;
border-left-color: #FF9800;
}
.item.event {
border-left-color: #2196F3;
}
.item-title {
font-weight: 500;
margin-bottom: 4px;
}
.item-time {
font-size: 12px; font-size: 12px;
color: #666; white-space: nowrap;
}
.task-section {
margin-bottom: 18px;
}
.section-label {
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.15em;
color: var(--muted);
margin-bottom: 10px;
}
.task-list {
flex-direction: column;
}
.task-item,
.empty-state {
border-radius: 18px;
padding: 12px 14px;
}
.task-item {
background: rgba(21, 128, 61, 0.08);
border: 1px solid rgba(21, 128, 61, 0.16);
}
.task-title,
.event-title {
font-size: 15px;
font-weight: 700;
line-height: 1.3;
}
.meta-text {
color: var(--muted);
font-size: 12px;
margin-top: 6px;
} }
.item-actions { .item-actions {
margin-top: 8px; margin-top: 10px;
display: flex; flex-wrap: wrap;
gap: 5px; display: none;
} }
.item-actions button { .task-item.is-active .item-actions,
padding: 4px 8px; .event-block.is-active .item-actions {
font-size: 11px; display: flex;
}
.item-action {
border: none; border: none;
border-radius: 3px; border-radius: 999px;
padding: 6px 10px;
font-size: 12px;
cursor: pointer; cursor: pointer;
} }
.btn-edit { .item-action.edit {
background: #FFC107; background: rgba(15, 118, 110, 0.12);
color: #333; color: var(--event);
} }
.btn-delete { .item-action.delete {
background: #f44336; background: rgba(154, 52, 18, 0.12);
color: var(--brand-deep);
}
.timeline {
position: relative;
height: 576px;
border-radius: 22px;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.9) 0%, rgba(252, 246, 238, 0.95) 100%);
border: 1px solid var(--line);
overflow: hidden;
}
.timeline-dropzone {
position: absolute;
inset: 0;
}
.timeline-hour {
position: absolute;
left: 0;
right: 0;
height: 48px;
border-top: 1px solid rgba(123, 92, 62, 0.12);
}
.timeline-hour-label {
position: absolute;
top: -8px;
left: 10px;
font-size: 11px;
color: var(--muted);
background: rgba(255, 250, 242, 0.9);
padding: 0 4px;
}
.event-block {
position: absolute;
left: 14px;
right: 14px;
border-radius: 18px;
padding: 12px 14px;
background: linear-gradient(160deg, rgba(15, 118, 110, 0.92), rgba(17, 94, 89, 0.84));
color: white; color: white;
box-shadow: 0 12px 24px rgba(15, 118, 110, 0.22);
cursor: grab;
user-select: none;
transition: transform 0.18s ease, box-shadow 0.18s ease, opacity 0.18s ease;
}
.event-block.recurring {
outline: 2px solid rgba(245, 158, 11, 0.55);
}
.event-block.is-active {
transform: scale(1.01);
box-shadow: 0 18px 32px rgba(15, 118, 110, 0.28);
}
.event-block.dragging {
opacity: 0.5;
}
.event-time {
font-size: 12px;
opacity: 0.82;
margin-bottom: 6px;
}
.empty-state {
color: var(--muted);
border: 1px dashed rgba(123, 92, 62, 0.2);
background: rgba(255, 255, 255, 0.35);
} }
/* Модальное окно */
.modal { .modal {
display: none; display: none;
position: fixed; position: fixed;
inset: 0;
background: rgba(41, 28, 16, 0.38);
z-index: 1000; z-index: 1000;
left: 0; padding: 24px;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
} }
.modal-content { .modal-content {
background-color: white; width: min(720px, 100%);
margin: 5% auto; max-height: calc(100vh - 48px);
padding: 30px; overflow-y: auto;
border-radius: 8px; margin: 0 auto;
width: 90%; border-radius: 28px;
max-width: 500px; padding: 28px;
position: relative; position: relative;
} }
.close { .close {
position: absolute; position: absolute;
right: 20px; top: 18px;
top: 15px; right: 18px;
font-size: 28px; width: 40px;
font-weight: bold; height: 40px;
color: #aaa; border-radius: 999px;
border: none;
background: rgba(123, 92, 62, 0.08);
cursor: pointer; cursor: pointer;
font-size: 24px;
} }
.close:hover { .modal-title {
color: #000; font-size: 30px;
margin-bottom: 8px;
}
.modal-subtitle {
color: var(--muted);
margin-bottom: 22px;
line-height: 1.5;
}
.form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
} }
.form-group { .form-group {
margin-bottom: 15px; margin-bottom: 14px;
}
.form-group.full {
grid-column: 1 / -1;
} }
.form-group label { .form-group label {
display: block; display: block;
margin-bottom: 5px; margin-bottom: 6px;
font-weight: 500; font-size: 13px;
color: #333; color: var(--muted);
} }
.form-group input, .form-group input,
.form-group select, .form-group textarea,
.form-group textarea { .form-group select {
width: 100%; width: 100%;
padding: 8px; padding: 12px 14px;
border: 1px solid #ddd; border-radius: 16px;
border-radius: 4px; border: 1px solid rgba(123, 92, 62, 0.18);
font-size: 14px; background: rgba(255, 255, 255, 0.85);
font-size: 15px;
font-family: inherit;
} }
.form-group textarea { .form-group textarea {
min-height: 80px; min-height: 108px;
resize: vertical; resize: vertical;
} }
.checkbox-group { .checkbox-card,
display: flex; .scope-card {
align-items: center; border-radius: 18px;
gap: 8px; border: 1px solid rgba(123, 92, 62, 0.14);
background: rgba(255, 250, 242, 0.8);
padding: 14px;
} }
.checkbox-group input[type="checkbox"] { .checkbox-card input,
.scope-card input {
width: auto; width: auto;
} }
.weekdays-select { .scope-row {
display: flex; flex-direction: column;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
} }
.weekdays-select label { .scope-card {
display: flex; display: flex;
align-items: center; gap: 10px;
gap: 5px; align-items: flex-start;
font-weight: normal; }
.actions-row {
display: flex;
gap: 10px;
margin-top: 18px;
flex-wrap: wrap;
} }
@media (max-width: 1200px) { @media (max-width: 1200px) {
.schedule-grid { .schedule-grid {
grid-template-columns: repeat(4, 1fr); min-width: 1624px;
} }
} }
@media (max-width: 768px) { @media (max-width: 860px) {
.schedule-grid { body {
grid-template-columns: repeat(2, 1fr); padding: 16px;
} }
}
@media (max-width: 480px) { .hero,
.schedule-grid { .toolbar {
flex-direction: column;
align-items: stretch;
}
.form-grid {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
} }
@media (max-width: 560px) {
.timeline {
height: 520px;
}
}

View file

@ -4,22 +4,33 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Расписание</title> <title>Расписание</title>
<link rel="stylesheet" href="/static/style.css"> <link rel="stylesheet" href="/static/style.css?v=3">
</head> </head>
<body> <body>
<div class="container"> <main class="board">
<div id="today-section" class="day-section"> <section class="board-hero">
<h1 class="day-title" id="today-title">Сегодня</h1> <p class="board-label">Сегодня и завтра</p>
<div id="today-content"></div> <h1>Расписание на ближайшие дни</h1>
</div> <p class="board-copy">Задачи отображаются сверху, занятия ниже по времени. Данные обновляются автоматически каждые пять минут.</p>
</section>
<div id="tomorrow-section" class="day-section">
<h1 class="day-title" id="tomorrow-title">Завтра</h1> <section class="days-grid">
<div id="tomorrow-content"></div> <article id="today-section" class="day-panel">
</div> <div class="panel-head">
</div> <h2 class="day-title" id="today-title">Сегодня</h2>
</div>
<script src="/static/script.js?v=2"></script> <div id="today-content"></div>
</article>
<article id="tomorrow-section" class="day-panel">
<div class="panel-head">
<h2 class="day-title" id="tomorrow-title">Завтра</h2>
</div>
<div id="tomorrow-content"></div>
</article>
</section>
</main>
<script src="/static/script.js?v=3"></script>
</body> </body>
</html> </html>

View file

@ -1,88 +1,35 @@
const TZ = 'Europe/Moscow'; const MOSCOW_TIMEZONE = 'Europe/Moscow';
const WEEKDAYS = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'];
const MONTHS = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];
function formatDate(dateStr) { function getMoscowDateString() {
const date = new Date(dateStr + 'T00:00:00');
// getDay() возвращает 0=воскресенье, 1=понедельник, ..., 6=суббота
// Конвертируем в формат где 0=понедельник
const jsDay = date.getDay();
const weekdayIndex = jsDay === 0 ? 6 : jsDay - 1; // 0=пн, 6=вс
const weekdays = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'];
const months = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];
const weekday = weekdays[weekdayIndex];
const day = date.getDate();
const month = months[date.getMonth()];
return `${weekday}, ${day} ${month}`;
}
function getTodayInMoscow() {
// Получаем текущую дату в таймзоне Moscow
const now = new Date();
const formatter = new Intl.DateTimeFormat('en-CA', { const formatter = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Europe/Moscow', timeZone: MOSCOW_TIMEZONE,
year: 'numeric', year: 'numeric',
month: '2-digit', month: '2-digit',
day: '2-digit' day: '2-digit'
}); });
return formatter.format(now); return formatter.format(new Date());
} }
function getTomorrowInLondon() { function parseISODate(value) {
const today = getTodayInMoscow(); const [year, month, day] = value.split('-').map(Number);
const date = new Date(today); return new Date(year, month - 1, day);
date.setDate(date.getDate() + 1);
return date.toISOString().split('T')[0];
} }
function renderDay(container, titleEl, dateStr, items, isToday = false, isTomorrow = false) { function formatISODate(date) {
let titleText = formatDate(dateStr); return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
if (isToday) { }
// Преобразуем "Вторник, 30 декабря" в "Сегодня вторник, 30 декабря"
const parts = titleText.split(', '); function addDays(dateStr, days) {
if (parts.length === 2) { const date = parseISODate(dateStr);
titleText = `Сегодня ${parts[0].toLowerCase()}, ${parts[1]}`; date.setDate(date.getDate() + days);
} return formatISODate(date);
} else if (isTomorrow) { }
// Преобразуем "Среда, 31 декабря" в "Завтра среда, 31 декабря"
const parts = titleText.split(', '); function formatDate(dateStr) {
if (parts.length === 2) { const date = parseISODate(dateStr);
titleText = `Завтра ${parts[0].toLowerCase()}, ${parts[1]}`; return `${WEEKDAYS[(date.getDay() + 6) % 7]}, ${date.getDate()} ${MONTHS[date.getMonth()]}`;
}
}
titleEl.textContent = titleText;
const tasks = items.filter(item => item.kind === 'task');
const events = items.filter(item => item.kind === 'event');
let html = '';
if (tasks.length > 0) {
html += '<div class="tasks-list">';
tasks.forEach(task => {
html += `<div class="task-item">• ${task.title}</div>`;
});
html += '</div>';
}
if (events.length > 0) {
html += '<div class="events-list">';
events.sort((a, b) => a.start_time.localeCompare(b.start_time)).forEach(event => {
const endTime = calculateEndTime(event.start_time, event.duration_min);
html += `<div class="event-item">
<span class="event-time">${event.start_time}-${endTime}</span>
<span class="event-title">${event.title}</span>
</div>`;
});
html += '</div>';
}
if (tasks.length === 0 && events.length === 0) {
html = '<div class="empty-message">На этот день расписания нет.</div>';
}
container.innerHTML = html;
} }
function calculateEndTime(startTime, durationMin) { function calculateEndTime(startTime, durationMin) {
@ -93,49 +40,79 @@ function calculateEndTime(startTime, durationMin) {
return `${String(endHour).padStart(2, '0')}:${String(endMinute).padStart(2, '0')}`; return `${String(endHour).padStart(2, '0')}:${String(endMinute).padStart(2, '0')}`;
} }
async function loadSchedule() { function renderDay(container, titleEl, dateStr, items, options = {}) {
const today = getTodayInMoscow(); let titleText = formatDate(dateStr);
const tomorrow = getTomorrowInLondon(); if (options.today) {
titleText = `Сегодня, ${titleText.toLowerCase()}`;
console.log('Loading schedule from', today, 'to', tomorrow); } else if (options.tomorrow) {
titleText = `Завтра, ${titleText.toLowerCase()}`;
try {
const response = await fetch(`/api/schedule?from_date=${today}&to_date=${tomorrow}`);
const data = await response.json();
console.log('Received items:', data.items);
const todayItems = data.items.filter(item => item.date === today);
const tomorrowItems = data.items.filter(item => item.date === tomorrow);
console.log('Today items:', todayItems);
console.log('Tomorrow items:', tomorrowItems);
renderDay(
document.getElementById('today-content'),
document.getElementById('today-title'),
today,
todayItems,
true, // isToday
false
);
renderDay(
document.getElementById('tomorrow-content'),
document.getElementById('tomorrow-title'),
tomorrow,
tomorrowItems,
false,
true // isTomorrow
);
} catch (error) {
console.error('Error loading schedule:', error);
} }
titleEl.textContent = titleText;
const tasks = items.filter((item) => item.kind === 'task');
const events = items
.filter((item) => item.kind === 'event')
.sort((a, b) => a.start_time.localeCompare(b.start_time));
if (!tasks.length && !events.length) {
container.innerHTML = '<div class="empty-message">На этот день расписания нет.</div>';
return;
}
const tasksHtml = tasks.length ? `
<div class="tasks-list">
${tasks.map((task) => `<div class="task-item">${task.repeat_weekly ? 'Каждую неделю: ' : ''}${escapeHtml(task.title)}</div>`).join('')}
</div>
` : '';
const eventsHtml = events.length ? `
<div class="events-list">
${events.map((event) => `
<div class="event-item">
<span class="event-time">${event.start_time}-${calculateEndTime(event.start_time, event.duration_min)}</span>
<span class="event-title">${escapeHtml(event.title)}</span>
</div>
`).join('')}
</div>
` : '';
container.innerHTML = `${tasksHtml}${eventsHtml}`;
} }
// Загружаем расписание при загрузке страницы function escapeHtml(value) {
loadSchedule(); return String(value)
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
// Автообновление каждые 5 минут async function loadSchedule() {
setInterval(loadSchedule, 5 * 60 * 1000); const today = getMoscowDateString();
const tomorrow = addDays(today, 1);
const response = await fetch(`/api/schedule?from_date=${today}&to_date=${tomorrow}`);
if (!response.ok) {
throw new Error('Не удалось загрузить расписание');
}
const data = await response.json();
renderDay(
document.getElementById('today-content'),
document.getElementById('today-title'),
today,
data.items.filter((item) => item.date === today),
{ today: true }
);
renderDay(
document.getElementById('tomorrow-content'),
document.getElementById('tomorrow-title'),
tomorrow,
data.items.filter((item) => item.date === tomorrow),
{ tomorrow: true }
);
}
loadSchedule().catch((error) => console.error(error));
setInterval(() => loadSchedule().catch((error) => console.error(error)), 5 * 60 * 1000);

View file

@ -1,100 +1,153 @@
:root {
--bg: #f4efe8;
--panel: rgba(255, 251, 246, 0.9);
--text: #1f2937;
--muted: #6b7280;
--task: #166534;
--event: #0f766e;
--line: rgba(123, 92, 62, 0.18);
}
* { * {
box-sizing: border-box;
margin: 0; margin: 0;
padding: 0; padding: 0;
box-sizing: border-box;
} }
body { body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; min-height: 100vh;
background: #f5f5f5; font-family: Georgia, "Times New Roman", serif;
padding: 20px; color: var(--text);
font-size: 24px; background:
line-height: 1.6; radial-gradient(circle at top left, rgba(245, 158, 11, 0.16), transparent 28%),
radial-gradient(circle at bottom right, rgba(15, 118, 110, 0.14), transparent 22%),
linear-gradient(180deg, #faf4eb 0%, #efe4d2 100%);
padding: 24px;
} }
.container { .board {
max-width: 1200px; max-width: 1440px;
margin: 0 auto; margin: 0 auto;
} }
.day-section { .board-hero,
background: white; .day-panel {
border-radius: 12px; background: var(--panel);
padding: 30px; border: 1px solid rgba(255, 255, 255, 0.6);
margin-bottom: 30px; box-shadow: 0 18px 45px rgba(101, 67, 33, 0.12);
box-shadow: 0 2px 8px rgba(0,0,0,0.1); backdrop-filter: blur(14px);
}
.board-hero {
border-radius: 28px;
padding: 28px;
margin-bottom: 20px;
}
.board-label {
text-transform: uppercase;
letter-spacing: 0.18em;
font-size: 12px;
color: #92400e;
margin-bottom: 10px;
}
.board-hero h1 {
font-size: clamp(34px, 5vw, 62px);
line-height: 0.95;
margin-bottom: 12px;
}
.board-copy {
max-width: 780px;
color: var(--muted);
font-size: 22px;
line-height: 1.4;
}
.days-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20px;
}
.day-panel {
border-radius: 28px;
padding: 28px;
}
.panel-head {
border-bottom: 1px solid var(--line);
padding-bottom: 16px;
margin-bottom: 18px;
} }
.day-title { .day-title {
font-size: 36px; font-size: 36px;
font-weight: 600; line-height: 1.1;
color: #333; }
margin-bottom: 20px;
padding-bottom: 15px; .tasks-list,
border-bottom: 3px solid #4CAF50; .events-list {
display: flex;
flex-direction: column;
gap: 12px;
} }
.tasks-list { .tasks-list {
margin-bottom: 30px; margin-bottom: 18px;
}
.task-item,
.event-item,
.empty-message {
border-radius: 18px;
padding: 16px 18px;
} }
.task-item { .task-item {
background: rgba(22, 101, 52, 0.08);
border: 1px solid rgba(22, 101, 52, 0.14);
font-size: 28px; font-size: 28px;
padding: 15px 0;
color: #555;
border-bottom: 1px solid #eee;
}
.task-item:last-child {
border-bottom: none;
}
.events-list {
margin-top: 20px;
} }
.event-item { .event-item {
display: grid;
grid-template-columns: 160px 1fr;
gap: 14px;
background: rgba(15, 118, 110, 0.08);
border: 1px solid rgba(15, 118, 110, 0.14);
font-size: 28px; font-size: 28px;
padding: 15px 0; align-items: start;
color: #333;
border-bottom: 1px solid #eee;
display: flex;
align-items: center;
gap: 15px;
}
.event-item:last-child {
border-bottom: none;
} }
.event-time { .event-time {
font-weight: 600; color: var(--event);
color: #4CAF50; font-weight: 700;
min-width: 120px;
}
.event-title {
flex: 1;
} }
.empty-message { .empty-message {
color: #999; color: var(--muted);
font-style: italic; border: 1px dashed var(--line);
padding: 20px 0; font-size: 24px;
} }
@media (max-width: 768px) { @media (max-width: 900px) {
body { .days-grid {
font-size: 20px; grid-template-columns: 1fr;
padding: 15px;
} }
.day-title { .day-title {
font-size: 28px; font-size: 28px;
} }
.task-item, .event-item { .board-copy,
font-size: 22px; .task-item,
.event-item {
font-size: 20px;
}
.event-item {
grid-template-columns: 1fr;
} }
} }