tasklert-api / src /services /recurring_service.py
hashir-qt's picture
initial deploy
507973e
Raw History Blame Contribute Delete
2.17 kB
"""Phase V: Recurring task service — auto-create next occurrence on completion."""
import logging
from datetime import datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from ..models.todo import Todo
logger = logging.getLogger(__name__)
def _next_due_date(current: datetime, recurrence: str) -> datetime:
if recurrence == "daily":
return current + timedelta(days=1)
elif recurrence == "weekly":
return current + timedelta(weeks=1)
elif recurrence == "monthly":
# Simple month increment (handles end-of-month edge cases minimally)
month = current.month + 1
year = current.year + (month - 1) // 12
month = ((month - 1) % 12) + 1
try:
return current.replace(year=year, month=month)
except ValueError:
# Day doesn't exist in next month — use last day
import calendar
last_day = calendar.monthrange(year, month)[1]
return current.replace(year=year, month=month, day=last_day)
return current
async def maybe_create_next(session: AsyncSession, task_data: dict) -> None:
"""If the completed task has a recurrence pattern, create the next instance."""
recurrence = task_data.get("recurrence", "none")
if recurrence == "none" or not recurrence:
return
task_id = task_data.get("id")
if not task_id:
return
# Get the original task to copy its fields
from sqlmodel import select
result = await session.execute(select(Todo).where(Todo.id == task_id))
original = result.scalar_one_or_none()
if not original:
return
base_date = original.due_date or datetime.utcnow()
next_due = _next_due_date(base_date, recurrence)
next_todo = Todo(
title=original.title,
description=original.description,
user_id=original.user_id,
priority=original.priority,
tags=original.tags,
due_date=next_due,
recurrence=recurrence,
parent_id=original.id,
)
session.add(next_todo)
await session.commit()
logger.info("Created recurring instance: parent=%d next_due=%s", task_id, next_due)