File size: 2,174 Bytes
507973e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""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)