Phase 2: 백엔드 데이터모델·시드·REST API·Ollama 추상화
- models.py: 11개 SQLModel 테이블(person/folder/project/task/task_comment/ inbox_item/inbox_classification/event/approval/goal/briefing), FK·enum·무한중첩 자기참조 - schemas.py: 전 I/O 스키마(types.ts 1:1, snake_case, 재귀 ProjectNode/TaskNode) - seed.py: 지우의 한 주(REF 4파일 그대로) — 5인/2폴더/14프로젝트/45작업/4인박스/대시보드 - Alembic: init schema 마이그레이션(+sqlmodel import), base↔head 왕복 검증 - 라우터 6종: people/tree(폴더·프로젝트 CRUD·pin)/tasks(CRUD·댓글·scaffold·risks)/ inbox(capture·reclassify·confirm 연합·dismiss)/dashboard(집계)/llm - services: risk.py(지연/쏠림/의존, TODAY=8), scaffold.py(정규식 4템플릿), classification.py - LLM 추상화: provider/ollama(format=json, think=false→수초 응답, 모델 비종속)/heuristic 폴백/prompts - inbox confirm = federation(task 실체화 + materialized_task_id) 검증: pytest 38 passed, ruff clean, 마이그레이션 왕복 OK, 시드 카운트 일치, 골든 분류 4케이스 통과(heuristic), 라이브: Ollama 분류 동작(model:ollama:qwen3.6, 13s) + 폴백 동작, 전 엔드포인트 정상 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>main
parent
59e836bba0
commit
1cd1d10243
@ -1,21 +1,30 @@
|
||||
# backend/app/config.py
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env", env_file_encoding="utf-8", extra="ignore"
|
||||
)
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
# ── DB ──
|
||||
database_url: str = "sqlite:///./ari.db"
|
||||
|
||||
# ── CORS ──
|
||||
# LLM — 절대 특정 모델을 하드코딩하지 않는다. 설치된 모델을 env로 주입.
|
||||
ollama_host: str = "http://localhost:11434"
|
||||
ollama_model: str = "llama3.1" # 기본 placeholder. 실제 운영은 .env 로 덮어쓴다.
|
||||
llm_provider: str = "auto" # auto | ollama | heuristic
|
||||
llm_timeout: float = 20.0 # 초
|
||||
|
||||
# 리스크 계산 기준일 — CONTRACT: TODAY=8 (6/8). 시드가 '6/7~6/12 한 주' 가정.
|
||||
risk_today: int = 8
|
||||
|
||||
# CORS 허용 출처(콤마구분). 단일 환경변수 규약: FRONTEND_ORIGIN.
|
||||
frontend_origin: str = "http://localhost:3000"
|
||||
|
||||
# ── Ollama (모델 비종속: 모델명은 환경변수로 주입) ──
|
||||
ollama_host: str = "http://localhost:11434"
|
||||
ollama_model: str = "llama3.1" # 예시 기본값 — 강제 아님, 설치된 모델로 덮어쓰기
|
||||
# 테스트 리셋 게이트 (테스트 환경에서만 시드 리셋 허용)
|
||||
ari_allow_test_reset: bool = False
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
||||
@ -1,18 +1,20 @@
|
||||
# backend/app/db.py
|
||||
from collections.abc import Generator
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from sqlmodel import Session, create_engine
|
||||
from .config import get_settings
|
||||
|
||||
from app.config import settings
|
||||
|
||||
# SQLite + 단일 프로세스 dev: check_same_thread=False 필요
|
||||
engine = create_engine(
|
||||
settings.database_url,
|
||||
echo=False,
|
||||
connect_args={"check_same_thread": False},
|
||||
settings = get_settings()
|
||||
# SQLite + FastAPI: check_same_thread=False 필요
|
||||
connect_args = (
|
||||
{"check_same_thread": False} if settings.database_url.startswith("sqlite") else {}
|
||||
)
|
||||
engine = create_engine(settings.database_url, echo=False, connect_args=connect_args)
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
|
||||
def get_session() -> Generator[Session, None, None]:
|
||||
def get_session():
|
||||
with Session(engine) as session:
|
||||
yield session
|
||||
|
||||
@ -1,33 +1,92 @@
|
||||
# backend/app/llm/ollama.py
|
||||
import json
|
||||
|
||||
import httpx
|
||||
|
||||
from app.config import settings
|
||||
from ..config import get_settings
|
||||
from .heuristic import HeuristicProvider
|
||||
from .prompts import CLASSIFY_SYSTEM, build_classify_prompt
|
||||
from .provider import Classification, LLMProvider
|
||||
|
||||
|
||||
class OllamaProvider(LLMProvider):
|
||||
name = "ollama"
|
||||
|
||||
def __init__(self):
|
||||
st = get_settings()
|
||||
self.host = st.ollama_host
|
||||
self.model = st.ollama_model # 비종속: env 주입값 그대로 사용
|
||||
self.timeout = st.llm_timeout
|
||||
|
||||
async def check_ollama() -> dict:
|
||||
"""Ollama 데몬 reachability + 설치 모델 목록을 비차단으로 점검.
|
||||
Ollama 가 꺼져 있어도 예외를 삼키고 reachable=False 로 반환한다(서버는 죽지 않음).
|
||||
"""
|
||||
url = f"{settings.ollama_host}/api/tags"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=2.0) as client:
|
||||
res = await client.get(url)
|
||||
res.raise_for_status()
|
||||
data = res.json()
|
||||
models = [m.get("name") for m in data.get("models", [])]
|
||||
def health(self) -> dict:
|
||||
try:
|
||||
r = httpx.get(f"{self.host}/api/tags", timeout=3.0)
|
||||
ok = r.status_code == 200
|
||||
tags = [m.get("name") for m in r.json().get("models", [])] if ok else []
|
||||
return {
|
||||
"reachable": ok, "provider": "ollama", "model": self.model,
|
||||
"host": self.host, "detail": f"models={tags}",
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
"reachable": True,
|
||||
"host": settings.ollama_host,
|
||||
"model": settings.ollama_model,
|
||||
"model_installed": settings.ollama_model in models,
|
||||
"available_models": models,
|
||||
"reachable": False, "provider": "ollama", "model": self.model,
|
||||
"host": self.host, "detail": str(e),
|
||||
}
|
||||
except Exception as exc: # 연결 거부/타임아웃/JSON 오류 모두 포함
|
||||
return {
|
||||
"reachable": False,
|
||||
"host": settings.ollama_host,
|
||||
"model": settings.ollama_model,
|
||||
"model_installed": False,
|
||||
"available_models": [],
|
||||
"error": type(exc).__name__,
|
||||
|
||||
def generate_json(self, prompt: str, schema: dict | None = None) -> dict:
|
||||
# Ollama 구조화 출력: format="json" (모델 비종속). chat API 사용.
|
||||
# think=False: 추론형 모델의 사고 단계를 끈다(분류는 즉답이 더 적합·빠름).
|
||||
# 미지원 모델은 무시되거나, 거부 시 except 에서 폴백 처리.
|
||||
payload = {
|
||||
"model": self.model,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"stream": False,
|
||||
"format": "json",
|
||||
"think": False,
|
||||
"options": {"temperature": 0.2},
|
||||
}
|
||||
r = httpx.post(f"{self.host}/api/chat", json=payload, timeout=self.timeout)
|
||||
r.raise_for_status()
|
||||
content = r.json()["message"]["content"]
|
||||
return json.loads(content)
|
||||
|
||||
def classify_capture(self, raw: str, context: dict) -> Classification:
|
||||
prompt = build_classify_prompt(raw, context)
|
||||
try:
|
||||
payload = {
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{"role": "system", "content": CLASSIFY_SYSTEM},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
"stream": False,
|
||||
"format": "json",
|
||||
"think": False, # 추론 단계 off → 분류 즉답(수초). 미지원 시 except 폴백.
|
||||
"options": {"temperature": 0.2},
|
||||
}
|
||||
r = httpx.post(f"{self.host}/api/chat", json=payload, timeout=self.timeout)
|
||||
r.raise_for_status()
|
||||
data = json.loads(r.json()["message"]["content"])
|
||||
return _coerce(data, raw, context, model=f"ollama:{self.model}")
|
||||
except Exception:
|
||||
# 모델 미가용/파싱 실패 → 규칙 폴백 (오프라인에서도 동작)
|
||||
return HeuristicProvider().classify_capture(raw, context)
|
||||
|
||||
|
||||
def _coerce(data: dict, raw: str, context: dict, model: str) -> Classification:
|
||||
"""LLM JSON을 Classification으로. 누락 필드는 휴리스틱/기본값 보강."""
|
||||
h = HeuristicProvider().classify_capture(raw, context) # 폴백 베이스
|
||||
t = data.get("type") if data.get("type") in ("task", "event", "idea") else h.type
|
||||
sp = data.get("sphere") if data.get("sphere") in ("work", "life") else h.sphere
|
||||
return Classification(
|
||||
type=t, sphere=sp,
|
||||
project_id=data.get("project_id") or h.project_id,
|
||||
proj_label=data.get("proj_label") or h.proj_label,
|
||||
tone=data.get("tone") or h.tone,
|
||||
due_text=data.get("due_text", h.due_text),
|
||||
when_text=data.get("when_text", h.when_text),
|
||||
extra=data.get("extra", h.extra),
|
||||
reason=data.get("reason") or h.reason,
|
||||
confidence=float(data.get("confidence", 0.85)),
|
||||
model=model,
|
||||
)
|
||||
|
||||
@ -0,0 +1,61 @@
|
||||
# backend/app/llm/provider.py
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
|
||||
from ..config import get_settings
|
||||
|
||||
|
||||
@dataclass
|
||||
class Classification:
|
||||
type: str # task | event | idea
|
||||
sphere: str # work | life
|
||||
project_id: str | None = None
|
||||
proj_label: str = ""
|
||||
tone: str = "ink"
|
||||
due_text: str = ""
|
||||
when_text: str = ""
|
||||
extra: str = ""
|
||||
reason: str = "" # 한국어
|
||||
confidence: float = 0.0
|
||||
model: str = ""
|
||||
|
||||
|
||||
class LLMProvider(ABC):
|
||||
name: str = "base"
|
||||
|
||||
@abstractmethod
|
||||
def health(self) -> dict: ...
|
||||
|
||||
@abstractmethod
|
||||
def generate_json(self, prompt: str, schema: dict | None = None) -> dict: ...
|
||||
|
||||
@abstractmethod
|
||||
def classify_capture(self, raw: str, context: dict) -> Classification: ...
|
||||
|
||||
|
||||
_cached: LLMProvider | None = None
|
||||
|
||||
|
||||
def get_provider(force: str | None = None) -> LLMProvider:
|
||||
"""LLM_PROVIDER=auto|ollama|heuristic. auto면 ollama health 확인 후 폴백."""
|
||||
global _cached
|
||||
from .heuristic import HeuristicProvider
|
||||
from .ollama import OllamaProvider
|
||||
|
||||
mode = force or get_settings().llm_provider
|
||||
if mode == "heuristic":
|
||||
return HeuristicProvider()
|
||||
if mode == "ollama":
|
||||
return OllamaProvider()
|
||||
# auto
|
||||
ollama = OllamaProvider()
|
||||
if ollama.health().get("reachable"):
|
||||
return ollama
|
||||
return HeuristicProvider()
|
||||
|
||||
|
||||
def reset_provider_cache():
|
||||
global _cached
|
||||
_cached = None
|
||||
@ -1,22 +1,44 @@
|
||||
# backend/app/main.py
|
||||
from fastapi import FastAPI
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import APIRouter, FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.config import settings
|
||||
from app.routers import health, llm
|
||||
from .config import get_settings
|
||||
from .db import init_db
|
||||
from .routers import dashboard, inbox, llm, people, tasks, tree
|
||||
|
||||
settings = get_settings()
|
||||
health_router = APIRouter() # 내부 prefix 없음. /health → /api/health
|
||||
|
||||
|
||||
app = FastAPI(title="아리 — AI LIFE OS API", version="0.1.0")
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_db() # 개발 편의(운영은 alembic). 테이블 보장.
|
||||
yield
|
||||
|
||||
# CORS: 프론트 origin 허용
|
||||
|
||||
app = FastAPI(title="아리 Ari API", lifespan=lifespan)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[settings.frontend_origin],
|
||||
allow_credentials=True,
|
||||
allow_origins=[o.strip() for o in settings.frontend_origin.split(",")],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
allow_credentials=True,
|
||||
)
|
||||
|
||||
# 모든 API 는 /api 프리픽스 (CONTRACT)
|
||||
# 라우터는 내부 prefix 없이 경로를 정의하고, /api 프리픽스는 여기서만 붙인다
|
||||
app.include_router(health.router, prefix="/api", tags=["health"])
|
||||
|
||||
# health: 라우터 내부 prefix 없이 "/health" 로 정의 → prefix="/api" 등록 시 /api/health.
|
||||
@health_router.get("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# 모든 라우터를 prefix="/api" 로 등록(라우터 내부 prefix 없음).
|
||||
app.include_router(health_router, prefix="/api", tags=["health"])
|
||||
app.include_router(people.router, prefix="/api", tags=["people"])
|
||||
app.include_router(tree.router, prefix="/api", tags=["tree"])
|
||||
app.include_router(tasks.router, prefix="/api", tags=["tasks"])
|
||||
app.include_router(inbox.router, prefix="/api", tags=["inbox"])
|
||||
app.include_router(dashboard.router, prefix="/api", tags=["dashboard"])
|
||||
app.include_router(llm.router, prefix="/api", tags=["llm"])
|
||||
|
||||
@ -0,0 +1,99 @@
|
||||
# backend/app/routers/dashboard.py
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..db import get_session
|
||||
from ..models import Approval, Briefing, Event, Goal, InboxItem, Person, Project, Task
|
||||
from ..routers.inbox import latest_cls
|
||||
from ..schemas import (
|
||||
ApprovalSummaryOut,
|
||||
BadgesOut,
|
||||
BriefingOut,
|
||||
DashboardOut,
|
||||
EventOut,
|
||||
GoalOut,
|
||||
InboxRecentOut,
|
||||
TaskSummaryItem,
|
||||
TaskSummaryOut,
|
||||
UserOut,
|
||||
WeatherOut,
|
||||
)
|
||||
|
||||
router = APIRouter() # prefix 없음. main.py 에서 prefix="/api" 등록.
|
||||
|
||||
# 날씨 아이콘 저장값 → 표시값 매핑(cloudSun 저장 → sun 표시)
|
||||
WEATHER_ICON_MAP = {"cloudSun": "sun"}
|
||||
|
||||
|
||||
@router.get("/dashboard", response_model=DashboardOut)
|
||||
def dashboard(s: Session = Depends(get_session)):
|
||||
me = s.exec(select(Person).where(Person.is_me == True)).first() # noqa: E712
|
||||
user = UserOut(name=me.name, initial=me.initial) if me else UserOut(name="", initial="")
|
||||
|
||||
br = s.exec(select(Briefing)).first()
|
||||
if br:
|
||||
weather = WeatherOut(
|
||||
temp=br.weather_temp, cond=br.weather_cond,
|
||||
icon=WEATHER_ICON_MAP.get(br.weather_icon, br.weather_icon),
|
||||
)
|
||||
briefing = BriefingOut(
|
||||
today=br.today, weather=weather, commute=br.commute, sleep=br.sleep, note=br.note
|
||||
)
|
||||
saved_today, today_routed = br.saved_today, br.today_routed
|
||||
else:
|
||||
briefing = BriefingOut(
|
||||
today="", weather=WeatherOut(temp=0, cond="", icon="sun"),
|
||||
commute="", sleep="", note="",
|
||||
)
|
||||
saved_today, today_routed = "", 0
|
||||
|
||||
schedule = [
|
||||
EventOut(time=e.time, title=e.title, tag=e.tag, dur=e.dur, tone=e.tone, soon=e.soon)
|
||||
for e in s.exec(select(Event).order_by(Event.sort_order)).all()
|
||||
]
|
||||
|
||||
tasks = s.exec(select(Task)).all()
|
||||
proj_name = {p.id: p.name for p in s.exec(select(Project)).all()}
|
||||
open_tasks = [t for t in tasks if t.status.value != "done"]
|
||||
items = [
|
||||
TaskSummaryItem(
|
||||
id=t.id, title=t.title, prio=t.prio.value, project=proj_name.get(t.project_id, "")
|
||||
)
|
||||
for t in open_tasks
|
||||
]
|
||||
task_summary = TaskSummaryOut(open_count=len(open_tasks), items=items)
|
||||
|
||||
goals = [
|
||||
GoalOut(id=g.id, title=g.title, pct=g.pct, sub=g.sub, tone=g.tone)
|
||||
for g in s.exec(select(Goal).order_by(Goal.sort_order)).all()
|
||||
]
|
||||
|
||||
apprs = s.exec(select(Approval).order_by(Approval.sort_order)).all()
|
||||
high = [a for a in apprs if a.risk == "high"]
|
||||
approvals_summary = [
|
||||
ApprovalSummaryOut(id=a.id, icon=a.icon, tone=a.tone, title=a.title, time=a.time)
|
||||
for a in high[:3]
|
||||
] # high-risk 만, 최대 3건
|
||||
|
||||
recent = s.exec(select(InboxItem).order_by(InboxItem.created_at.desc()).limit(3)).all()
|
||||
# 평탄화: 각 항목의 최신 classification 에서 type/proj_label/tone 을 끌어와 채운다.
|
||||
inbox_recent = []
|
||||
for it in recent:
|
||||
c = latest_cls(s, it.id)
|
||||
inbox_recent.append(
|
||||
InboxRecentOut(
|
||||
id=it.id,
|
||||
kind=it.kind.value if hasattr(it.kind, "value") else it.kind,
|
||||
raw=it.raw,
|
||||
type=(c.type.value if c and hasattr(c.type, "value") else (c.type if c else "")),
|
||||
proj_label=c.proj_label if c else "",
|
||||
tone=c.tone if c else "ink",
|
||||
)
|
||||
)
|
||||
|
||||
badges = BadgesOut(appr=len(high), task=len(open_tasks), noti=6)
|
||||
return DashboardOut(
|
||||
user=user, briefing=briefing, saved_today=saved_today, today_routed=today_routed,
|
||||
schedule=schedule, task_summary=task_summary, goals=goals,
|
||||
approvals_summary=approvals_summary, inbox_recent=inbox_recent, badges=badges,
|
||||
)
|
||||
@ -1,9 +0,0 @@
|
||||
# backend/app/routers/health.py
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health() -> dict:
|
||||
return {"status": "ok"}
|
||||
@ -0,0 +1,141 @@
|
||||
# backend/app/routers/inbox.py
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..db import get_session
|
||||
from ..llm.provider import LLMProvider, get_provider
|
||||
from ..models import InboxClassification, InboxItem, InboxStatus, Prio, Project, Task, TaskStatus
|
||||
from ..routers.tasks import to_node
|
||||
from ..schemas import (
|
||||
CaptureRequest,
|
||||
CaptureResponse,
|
||||
ClassificationOut,
|
||||
ConfirmResponse,
|
||||
InboxItemOut,
|
||||
ReclassifyRequest,
|
||||
)
|
||||
from ..services.classification import classify, persist_classification
|
||||
|
||||
router = APIRouter() # prefix 없음. main.py 에서 prefix="/api" 등록.
|
||||
|
||||
|
||||
def latest_cls(s: Session, item_id: str) -> InboxClassification | None:
|
||||
# id 가 TEXT PK(UUID)라 정렬 키로 부적합 → created_at 기준 최신.
|
||||
rows = s.exec(
|
||||
select(InboxClassification)
|
||||
.where(InboxClassification.inbox_item_id == item_id)
|
||||
.order_by(InboxClassification.created_at.desc())
|
||||
).all()
|
||||
return rows[0] if rows else None
|
||||
|
||||
|
||||
def item_out(s: Session, item: InboxItem) -> InboxItemOut:
|
||||
c = latest_cls(s, item.id)
|
||||
cls = ClassificationOut.model_validate(c, from_attributes=True) if c else None
|
||||
return InboxItemOut(
|
||||
id=item.id, kind=item.kind, raw=item.raw, status=item.status,
|
||||
created_at=item.created_at, materialized_task_id=item.materialized_task_id,
|
||||
classification=cls,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/inbox", response_model=list[InboxItemOut])
|
||||
def list_inbox(s: Session = Depends(get_session)):
|
||||
items = s.exec(select(InboxItem).order_by(InboxItem.created_at.desc())).all()
|
||||
return [item_out(s, it) for it in items]
|
||||
|
||||
|
||||
@router.post("/inbox/capture", response_model=CaptureResponse)
|
||||
def capture(
|
||||
body: CaptureRequest,
|
||||
s: Session = Depends(get_session),
|
||||
provider: LLMProvider = Depends(get_provider),
|
||||
):
|
||||
iid = "s-" + uuid.uuid4().hex[:8]
|
||||
item = InboxItem(id=iid, kind=body.kind, raw=body.raw, status=InboxStatus.new)
|
||||
s.add(item)
|
||||
s.commit()
|
||||
s.refresh(item)
|
||||
c = classify(s, body.raw, provider) # 동기 분류 (LLM or 폴백)
|
||||
row = persist_classification(s, iid, c)
|
||||
item.status = InboxStatus.classified
|
||||
s.add(item)
|
||||
s.commit()
|
||||
return CaptureResponse(
|
||||
item=item_out(s, item),
|
||||
classification=ClassificationOut.model_validate(row, from_attributes=True),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/inbox/{iid}/reclassify", response_model=ClassificationOut)
|
||||
def reclassify(
|
||||
iid: str,
|
||||
body: ReclassifyRequest,
|
||||
s: Session = Depends(get_session),
|
||||
provider: LLMProvider = Depends(get_provider),
|
||||
):
|
||||
item = s.get(InboxItem, iid)
|
||||
if not item:
|
||||
raise HTTPException(404, "inbox item not found")
|
||||
c = classify(s, item.raw, provider, force_type=body.type.value if body.type else None)
|
||||
row = persist_classification(s, iid, c) # 새 row → latest 가 최신
|
||||
item.status = InboxStatus.classified
|
||||
s.add(item)
|
||||
s.commit()
|
||||
return ClassificationOut.model_validate(row, from_attributes=True)
|
||||
|
||||
|
||||
@router.post("/inbox/{iid}/confirm", response_model=ConfirmResponse)
|
||||
def confirm(iid: str, s: Session = Depends(get_session)):
|
||||
item = s.get(InboxItem, iid)
|
||||
if not item:
|
||||
raise HTTPException(404, "inbox item not found")
|
||||
c = latest_cls(s, iid)
|
||||
if not c:
|
||||
raise HTTPException(400, "no classification to confirm")
|
||||
|
||||
created: Task | None = None
|
||||
ctype = c.type.value if hasattr(c.type, "value") else c.type
|
||||
csphere = c.sphere.value if hasattr(c.sphere, "value") else c.sphere
|
||||
if ctype == "task":
|
||||
# 프로젝트 결정: classification.project_id 있으면 그대로, 없으면 sphere 기본
|
||||
pid = c.project_id
|
||||
if not pid or not s.get(Project, pid):
|
||||
pid = "me" if csphere == "life" else _fallback_work_project(s)
|
||||
# confirm task 필드 정본(R10)
|
||||
notes = "스마트 인박스에서 실체화된 작업이에요."
|
||||
if c.extra:
|
||||
notes += " " + c.extra # 예: 비행기 티켓 → "가격 추적 알림 켜둠"
|
||||
tid = "t-" + uuid.uuid4().hex[:8]
|
||||
created = Task(
|
||||
id=tid, title=item.raw, project_id=pid, status=TaskStatus.todo,
|
||||
assignee_id="jiwoo", prio=Prio.normal, due=None, notes=notes,
|
||||
)
|
||||
s.add(created)
|
||||
s.commit()
|
||||
s.refresh(created)
|
||||
item.materialized_task_id = tid
|
||||
|
||||
item.status = InboxStatus.confirmed
|
||||
s.add(item)
|
||||
s.commit()
|
||||
node = to_node(s, created, s.exec(select(Task)).all()) if created else None
|
||||
return ConfirmResponse(item=item_out(s, item), task=node)
|
||||
|
||||
|
||||
@router.post("/inbox/{iid}/dismiss", response_model=InboxItemOut)
|
||||
def dismiss(iid: str, s: Session = Depends(get_session)):
|
||||
item = s.get(InboxItem, iid)
|
||||
if not item:
|
||||
raise HTTPException(404, "inbox item not found")
|
||||
item.status = InboxStatus.dismissed
|
||||
s.add(item)
|
||||
s.commit()
|
||||
return item_out(s, item)
|
||||
|
||||
|
||||
def _fallback_work_project(s: Session) -> str:
|
||||
p = s.exec(select(Project).where(Project.folder_id == "work")).first()
|
||||
return p.id if p else "me"
|
||||
@ -1,11 +1,19 @@
|
||||
# backend/app/routers/llm.py
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.llm.ollama import check_ollama
|
||||
from ..llm.provider import LLMProvider, get_provider
|
||||
from ..schemas import LLMHealth
|
||||
|
||||
router = APIRouter()
|
||||
router = APIRouter() # prefix 없음. main.py 에서 prefix="/api" 등록.
|
||||
|
||||
|
||||
@router.get("/llm/health")
|
||||
async def llm_health() -> dict:
|
||||
return await check_ollama()
|
||||
@router.get("/llm/health", response_model=LLMHealth)
|
||||
def llm_health(provider: LLMProvider = Depends(get_provider)):
|
||||
h = provider.health()
|
||||
return LLMHealth(
|
||||
reachable=h.get("reachable", False),
|
||||
provider=h.get("provider", ""),
|
||||
model=h.get("model", ""),
|
||||
host=h.get("host"),
|
||||
detail=h.get("detail", ""),
|
||||
)
|
||||
|
||||
@ -0,0 +1,14 @@
|
||||
# backend/app/routers/people.py
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..db import get_session
|
||||
from ..models import Person
|
||||
from ..schemas import PersonOut
|
||||
|
||||
router = APIRouter() # prefix 없음. main.py 에서 prefix="/api" 등록.
|
||||
|
||||
|
||||
@router.get("/people", response_model=list[PersonOut])
|
||||
def list_people(s: Session = Depends(get_session)):
|
||||
return s.exec(select(Person)).all()
|
||||
@ -0,0 +1,189 @@
|
||||
# backend/app/routers/tasks.py
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..db import get_session
|
||||
from ..models import Project, Task, TaskComment, TaskStatus
|
||||
from ..schemas import (
|
||||
CommentCreate,
|
||||
CommentOut,
|
||||
RiskOut,
|
||||
ScaffoldOut,
|
||||
ScaffoldRequest,
|
||||
TaskCreate,
|
||||
TaskNode,
|
||||
TaskPatch,
|
||||
)
|
||||
from ..services.risk import compute_risks
|
||||
from ..services.scaffold import pick_scaffold, scaffold_create
|
||||
|
||||
router = APIRouter() # prefix 없음. main.py 에서 prefix="/api" 등록.
|
||||
|
||||
|
||||
def _tid() -> str:
|
||||
return "t-" + uuid.uuid4().hex[:8]
|
||||
|
||||
|
||||
def folder_of_project(s: Session, project_id: str) -> str | None:
|
||||
p = s.get(Project, project_id)
|
||||
return p.folder_id if p else None
|
||||
|
||||
|
||||
def project_subtree_ids(s: Session, root_id: str) -> set[str]:
|
||||
"""root_id 와 그 모든 하위 프로젝트 id 집합."""
|
||||
all_projects = s.exec(select(Project)).all()
|
||||
by_parent: dict[str | None, list[Project]] = {}
|
||||
for p in all_projects:
|
||||
by_parent.setdefault(p.parent_id, []).append(p)
|
||||
ids: set[str] = set()
|
||||
|
||||
def walk(pid: str):
|
||||
ids.add(pid)
|
||||
for ch in by_parent.get(pid, []):
|
||||
walk(ch.id)
|
||||
|
||||
walk(root_id)
|
||||
return ids
|
||||
|
||||
|
||||
def to_node(s: Session, t: Task, all_tasks: list[Task]) -> TaskNode:
|
||||
kids = sorted([x for x in all_tasks if x.parent_id == t.id], key=lambda x: x.sort_order)
|
||||
comments = s.exec(
|
||||
select(TaskComment)
|
||||
.where(TaskComment.task_id == t.id)
|
||||
.order_by(TaskComment.created_at, TaskComment.id)
|
||||
).all()
|
||||
return TaskNode(
|
||||
id=t.id, project_id=t.project_id, parent_id=t.parent_id, title=t.title,
|
||||
status=t.status, assignee_id=t.assignee_id, due=t.due, prio=t.prio,
|
||||
notes=t.notes, est=t.est, delegated=t.delegated, sort_order=t.sort_order,
|
||||
created_at=t.created_at, updated_at=t.updated_at,
|
||||
comments=[CommentOut.model_validate(c, from_attributes=True) for c in comments],
|
||||
children=[to_node(s, k, all_tasks) for k in kids],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/tasks", response_model=list[TaskNode])
|
||||
def list_tasks(
|
||||
area: str | None = None,
|
||||
project_id: str | None = None,
|
||||
status: TaskStatus | None = None,
|
||||
assignee: str | None = None,
|
||||
s: Session = Depends(get_session),
|
||||
):
|
||||
all_tasks = s.exec(select(Task)).all()
|
||||
roots = [t for t in all_tasks if t.parent_id is None]
|
||||
# 필터 우선순위: project_id(+하위 프로젝트) > area > 전체. status/assignee 는 추가 필터.
|
||||
if project_id:
|
||||
scope = project_subtree_ids(s, project_id)
|
||||
roots = [t for t in roots if t.project_id in scope]
|
||||
elif area:
|
||||
roots = [t for t in roots if folder_of_project(s, t.project_id) == area]
|
||||
if status:
|
||||
roots = [t for t in roots if t.status == status]
|
||||
if assignee:
|
||||
roots = [t for t in roots if t.assignee_id == assignee]
|
||||
roots.sort(key=lambda t: t.sort_order)
|
||||
return [to_node(s, t, all_tasks) for t in roots]
|
||||
|
||||
|
||||
@router.get("/tasks/{tid}", response_model=TaskNode)
|
||||
def get_task(tid: str, s: Session = Depends(get_session)):
|
||||
t = s.get(Task, tid)
|
||||
if not t:
|
||||
raise HTTPException(404, "task not found")
|
||||
return to_node(s, t, s.exec(select(Task)).all())
|
||||
|
||||
|
||||
@router.post("/tasks", response_model=TaskNode)
|
||||
def create_task(body: TaskCreate, s: Session = Depends(get_session)):
|
||||
if not s.get(Project, body.project_id):
|
||||
raise HTTPException(404, "project not found")
|
||||
if body.parent_id and not s.get(Task, body.parent_id):
|
||||
raise HTTPException(404, "parent task not found")
|
||||
siblings = s.exec(
|
||||
select(Task).where(Task.parent_id == body.parent_id, Task.project_id == body.project_id)
|
||||
).all()
|
||||
order = max([x.sort_order for x in siblings] + [-1]) + 1
|
||||
t = Task(
|
||||
id=_tid(), title=body.title, project_id=body.project_id, parent_id=body.parent_id,
|
||||
status=body.status or TaskStatus.todo, assignee_id=body.assignee_id,
|
||||
due=body.due, prio=body.prio, notes=body.notes or "", est=body.est or "",
|
||||
sort_order=order,
|
||||
)
|
||||
s.add(t)
|
||||
s.commit()
|
||||
return to_node(s, t, s.exec(select(Task)).all())
|
||||
|
||||
|
||||
@router.patch("/tasks/{tid}", response_model=TaskNode)
|
||||
def patch_task(tid: str, body: TaskPatch, s: Session = Depends(get_session)):
|
||||
t = s.get(Task, tid)
|
||||
if not t:
|
||||
raise HTTPException(404, "task not found")
|
||||
for k, v in body.model_dump(exclude_none=True).items():
|
||||
setattr(t, k, v)
|
||||
t.updated_at = datetime.now(UTC)
|
||||
s.add(t)
|
||||
s.commit()
|
||||
return to_node(s, t, s.exec(select(Task)).all())
|
||||
|
||||
|
||||
@router.delete("/tasks/{tid}")
|
||||
def delete_task(tid: str, s: Session = Depends(get_session)):
|
||||
t = s.get(Task, tid)
|
||||
if not t:
|
||||
raise HTTPException(404, "task not found")
|
||||
# 하위작업 재귀 삭제
|
||||
all_tasks = s.exec(select(Task)).all()
|
||||
|
||||
def collect(pid):
|
||||
ids = [pid]
|
||||
for c in [x for x in all_tasks if x.parent_id == pid]:
|
||||
ids += collect(c.id)
|
||||
return ids
|
||||
|
||||
for did in collect(tid):
|
||||
for c in s.exec(select(TaskComment).where(TaskComment.task_id == did)).all():
|
||||
s.delete(c)
|
||||
d = s.get(Task, did)
|
||||
s.delete(d)
|
||||
s.commit()
|
||||
return {"deleted": tid}
|
||||
|
||||
|
||||
@router.post("/tasks/{tid}/comments", response_model=CommentOut)
|
||||
def add_comment(tid: str, body: CommentCreate, s: Session = Depends(get_session)):
|
||||
if not s.get(Task, tid):
|
||||
raise HTTPException(404, "task not found")
|
||||
c = TaskComment(
|
||||
id="c-" + uuid.uuid4().hex[:8], task_id=tid, person_id=body.person_id, text=body.text
|
||||
)
|
||||
s.add(c)
|
||||
s.commit()
|
||||
s.refresh(c)
|
||||
return CommentOut.model_validate(c, from_attributes=True)
|
||||
|
||||
|
||||
@router.post("/tasks/{tid}/scaffold", response_model=ScaffoldOut)
|
||||
def scaffold(tid: str, body: ScaffoldRequest, s: Session = Depends(get_session)):
|
||||
t = s.get(Task, tid)
|
||||
if not t:
|
||||
raise HTTPException(404, "task not found")
|
||||
tpl = pick_scaffold(t.title, use_llm=body.use_llm)
|
||||
if body.create:
|
||||
ids = scaffold_create(s, t, tpl)
|
||||
return ScaffoldOut(
|
||||
kind=tpl["kind"], icon=tpl["icon"], items=tpl["items"],
|
||||
created=True, created_task_ids=ids,
|
||||
)
|
||||
return ScaffoldOut(kind=tpl["kind"], icon=tpl["icon"], items=tpl["items"], created=False)
|
||||
|
||||
|
||||
@router.get("/risks", response_model=list[RiskOut])
|
||||
def risks(area: str = "work", s: Session = Depends(get_session)):
|
||||
# area 기본값 work. 주어진 area 로 리스크 계산.
|
||||
return compute_risks(s, area=area)
|
||||
@ -0,0 +1,192 @@
|
||||
# backend/app/routers/tree.py
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..db import get_session
|
||||
from ..models import Folder, Project, Task
|
||||
from ..schemas import (
|
||||
FolderCreate,
|
||||
FolderOut,
|
||||
FolderPatch,
|
||||
ProjectCreate,
|
||||
ProjectNode,
|
||||
ProjectPatch,
|
||||
)
|
||||
|
||||
router = APIRouter() # prefix 없음. main.py 에서 prefix="/api" 등록.
|
||||
|
||||
|
||||
def _slug() -> str:
|
||||
return "p-" + uuid.uuid4().hex[:8]
|
||||
|
||||
|
||||
def build_tree(s: Session) -> list[FolderOut]:
|
||||
folders = s.exec(select(Folder).order_by(Folder.sort_order)).all()
|
||||
projects = s.exec(select(Project).order_by(Project.sort_order)).all()
|
||||
# 작업 수: project_id 별 직접 작업 수
|
||||
direct: dict[str, int] = {}
|
||||
for t in s.exec(select(Task)).all():
|
||||
direct[t.project_id] = direct.get(t.project_id, 0) + 1
|
||||
by_parent: dict[str | None, list[Project]] = {}
|
||||
for p in projects:
|
||||
by_parent.setdefault(p.parent_id, []).append(p)
|
||||
|
||||
def count_recursive(pid: str) -> int:
|
||||
total = direct.get(pid, 0)
|
||||
for ch in by_parent.get(pid, []):
|
||||
total += count_recursive(ch.id)
|
||||
return total
|
||||
|
||||
def node(p: Project) -> ProjectNode:
|
||||
kids = [node(c) for c in by_parent.get(p.id, [])]
|
||||
return ProjectNode(
|
||||
id=p.id, folder_id=p.folder_id, parent_id=p.parent_id, name=p.name,
|
||||
tone=p.tone, sort_order=p.sort_order, pinned=p.pinned,
|
||||
task_count=count_recursive(p.id), children=kids,
|
||||
)
|
||||
|
||||
out = []
|
||||
for f in folders:
|
||||
roots = [node(p) for p in by_parent.get(None, []) if p.folder_id == f.id]
|
||||
out.append(
|
||||
FolderOut(
|
||||
id=f.id, name=f.name, tone=f.tone, icon=f.icon,
|
||||
sort_order=f.sort_order, is_system=f.is_system, projects=roots,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/tree", response_model=list[FolderOut])
|
||||
def get_tree(s: Session = Depends(get_session)):
|
||||
return build_tree(s)
|
||||
|
||||
|
||||
@router.post("/folders", response_model=FolderOut)
|
||||
def create_folder(body: FolderCreate, s: Session = Depends(get_session)):
|
||||
fid = _slug()
|
||||
mx = max([f.sort_order for f in s.exec(select(Folder)).all()] + [-1]) + 1
|
||||
f = Folder(
|
||||
id=fid, name=body.name, tone=body.tone or "ink",
|
||||
icon=body.icon or "folder", sort_order=mx, is_system=False,
|
||||
)
|
||||
s.add(f)
|
||||
s.commit()
|
||||
return [x for x in build_tree(s) if x.id == fid][0]
|
||||
|
||||
|
||||
@router.patch("/folders/{fid}", response_model=FolderOut)
|
||||
def patch_folder(fid: str, body: FolderPatch, s: Session = Depends(get_session)):
|
||||
f = s.get(Folder, fid)
|
||||
if not f:
|
||||
raise HTTPException(404, "folder not found")
|
||||
for k, v in body.model_dump(exclude_none=True).items():
|
||||
setattr(f, k, v)
|
||||
s.add(f)
|
||||
s.commit()
|
||||
return [x for x in build_tree(s) if x.id == fid][0]
|
||||
|
||||
|
||||
@router.delete("/folders/{fid}")
|
||||
def delete_folder(fid: str, s: Session = Depends(get_session)):
|
||||
f = s.get(Folder, fid)
|
||||
if not f:
|
||||
raise HTTPException(404, "folder not found")
|
||||
if f.is_system:
|
||||
raise HTTPException(400, "system folder cannot be deleted")
|
||||
if s.exec(select(Project).where(Project.folder_id == fid)).first():
|
||||
raise HTTPException(400, "folder has projects")
|
||||
s.delete(f)
|
||||
s.commit()
|
||||
return {"deleted": fid}
|
||||
|
||||
|
||||
@router.post("/projects", response_model=ProjectNode)
|
||||
def create_project(body: ProjectCreate, s: Session = Depends(get_session)):
|
||||
if not s.get(Folder, body.folder_id):
|
||||
raise HTTPException(404, "folder not found")
|
||||
if body.parent_id and not s.get(Project, body.parent_id):
|
||||
raise HTTPException(404, "parent project not found")
|
||||
pid = _slug()
|
||||
siblings = s.exec(
|
||||
select(Project).where(
|
||||
Project.parent_id == body.parent_id, Project.folder_id == body.folder_id
|
||||
)
|
||||
).all()
|
||||
order = max([p.sort_order for p in siblings] + [-1]) + 1
|
||||
p = Project(
|
||||
id=pid, folder_id=body.folder_id, parent_id=body.parent_id,
|
||||
name=body.name, tone=body.tone or "ink", sort_order=order,
|
||||
)
|
||||
s.add(p)
|
||||
s.commit()
|
||||
s.refresh(p)
|
||||
return ProjectNode(
|
||||
id=p.id, folder_id=p.folder_id, parent_id=p.parent_id, name=p.name,
|
||||
tone=p.tone, sort_order=p.sort_order, pinned=p.pinned, task_count=0, children=[],
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/projects/{pid}", response_model=ProjectNode)
|
||||
def patch_project(pid: str, body: ProjectPatch, s: Session = Depends(get_session)):
|
||||
p = s.get(Project, pid)
|
||||
if not p:
|
||||
raise HTTPException(404, "project not found")
|
||||
data = body.model_dump(exclude_none=True)
|
||||
# parent_id 이동 시 순환(자기 자신/후손으로 이동) 금지
|
||||
if "parent_id" in data and data["parent_id"]:
|
||||
cur = s.get(Project, data["parent_id"])
|
||||
while cur:
|
||||
if cur.id == pid:
|
||||
raise HTTPException(400, "cannot move into own descendant")
|
||||
cur = s.get(Project, cur.parent_id) if cur.parent_id else None
|
||||
for k, v in data.items():
|
||||
setattr(p, k, v)
|
||||
s.add(p)
|
||||
s.commit()
|
||||
s.refresh(p)
|
||||
|
||||
def find(nodes):
|
||||
for n in nodes:
|
||||
if n.id == pid:
|
||||
return n
|
||||
r = find(n.children)
|
||||
if r:
|
||||
return r
|
||||
|
||||
for f in build_tree(s):
|
||||
r = find(f.projects)
|
||||
if r:
|
||||
return r
|
||||
raise HTTPException(500, "rebuild failed")
|
||||
|
||||
|
||||
@router.delete("/projects/{pid}")
|
||||
def delete_project(pid: str, s: Session = Depends(get_session)):
|
||||
p = s.get(Project, pid)
|
||||
if not p:
|
||||
raise HTTPException(404, "project not found")
|
||||
if s.exec(select(Project).where(Project.parent_id == pid)).first():
|
||||
raise HTTPException(400, "project has sub-projects")
|
||||
if s.exec(select(Task).where(Task.project_id == pid)).first():
|
||||
raise HTTPException(400, "project has tasks")
|
||||
s.delete(p)
|
||||
s.commit()
|
||||
return {"deleted": pid}
|
||||
|
||||
|
||||
@router.post("/projects/{pid}/pin", response_model=ProjectNode)
|
||||
def pin_project(pid: str, s: Session = Depends(get_session)):
|
||||
p = s.get(Project, pid)
|
||||
if not p:
|
||||
raise HTTPException(404, "project not found")
|
||||
p.pinned = not p.pinned
|
||||
s.add(p)
|
||||
s.commit()
|
||||
s.refresh(p)
|
||||
return ProjectNode(
|
||||
id=p.id, folder_id=p.folder_id, parent_id=p.parent_id, name=p.name,
|
||||
tone=p.tone, sort_order=p.sort_order, pinned=p.pinned, task_count=0, children=[],
|
||||
)
|
||||
@ -0,0 +1,304 @@
|
||||
# backend/app/schemas.py
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .models import ClsType, InboxKind, InboxStatus, Prio, Sphere, TaskStatus
|
||||
|
||||
|
||||
# ---------- people ----------
|
||||
class PersonOut(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
initial: str
|
||||
color: str
|
||||
is_me: bool
|
||||
|
||||
|
||||
# ---------- tree ----------
|
||||
class ProjectNode(BaseModel):
|
||||
id: str
|
||||
folder_id: str
|
||||
parent_id: Optional[str] = None
|
||||
name: str
|
||||
tone: str
|
||||
sort_order: int
|
||||
pinned: bool
|
||||
task_count: int = 0 # 자신+하위 프로젝트의 작업 수 합
|
||||
children: list[ProjectNode] = []
|
||||
|
||||
|
||||
class FolderOut(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
tone: str
|
||||
icon: str
|
||||
sort_order: int
|
||||
is_system: bool
|
||||
projects: list[ProjectNode] = [] # 최상위 프로젝트(중첩 children 포함)
|
||||
|
||||
|
||||
class FolderCreate(BaseModel):
|
||||
name: str
|
||||
tone: Optional[str] = "ink"
|
||||
icon: Optional[str] = "folder"
|
||||
|
||||
|
||||
class FolderPatch(BaseModel):
|
||||
name: Optional[str] = None
|
||||
tone: Optional[str] = None
|
||||
icon: Optional[str] = None
|
||||
sort_order: Optional[int] = None
|
||||
|
||||
|
||||
class ProjectCreate(BaseModel):
|
||||
folder_id: str
|
||||
parent_id: Optional[str] = None
|
||||
name: str
|
||||
tone: Optional[str] = "ink"
|
||||
|
||||
|
||||
class ProjectPatch(BaseModel):
|
||||
name: Optional[str] = None
|
||||
tone: Optional[str] = None
|
||||
parent_id: Optional[str] = None
|
||||
sort_order: Optional[int] = None
|
||||
|
||||
|
||||
# ---------- tasks ----------
|
||||
class CommentOut(BaseModel):
|
||||
id: str
|
||||
task_id: str
|
||||
person_id: str
|
||||
text: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class TaskNode(BaseModel):
|
||||
id: str
|
||||
project_id: str
|
||||
parent_id: Optional[str] = None
|
||||
title: str
|
||||
status: TaskStatus
|
||||
assignee_id: Optional[str] = None
|
||||
due: Optional[date] = None
|
||||
prio: Prio
|
||||
notes: str
|
||||
est: str
|
||||
delegated: bool
|
||||
sort_order: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
comments: list[CommentOut] = []
|
||||
children: list[TaskNode] = []
|
||||
|
||||
|
||||
class TaskCreate(BaseModel):
|
||||
title: str
|
||||
project_id: str
|
||||
parent_id: Optional[str] = None
|
||||
status: Optional[TaskStatus] = TaskStatus.todo
|
||||
assignee_id: Optional[str] = None
|
||||
due: Optional[date] = None
|
||||
prio: Optional[Prio] = Prio.normal
|
||||
notes: Optional[str] = ""
|
||||
est: Optional[str] = ""
|
||||
|
||||
|
||||
class TaskPatch(BaseModel):
|
||||
title: Optional[str] = None
|
||||
project_id: Optional[str] = None
|
||||
parent_id: Optional[str] = None
|
||||
status: Optional[TaskStatus] = None
|
||||
assignee_id: Optional[str] = None
|
||||
due: Optional[date] = None
|
||||
prio: Optional[Prio] = None
|
||||
notes: Optional[str] = None
|
||||
est: Optional[str] = None
|
||||
delegated: Optional[bool] = None
|
||||
sort_order: Optional[int] = None
|
||||
|
||||
|
||||
class CommentCreate(BaseModel):
|
||||
person_id: str
|
||||
text: str
|
||||
|
||||
|
||||
# ---------- scaffold ----------
|
||||
class ScaffoldItem(BaseModel):
|
||||
title: str
|
||||
est: str = ""
|
||||
|
||||
|
||||
class ScaffoldOut(BaseModel):
|
||||
kind: str # "연구 · 논문 작성" 등
|
||||
icon: str # "brain"|"branch"|"file"|"list"
|
||||
items: list[ScaffoldItem]
|
||||
created: bool = False # True면 실제 생성됨, False면 미리보기
|
||||
created_task_ids: list[str] = []
|
||||
|
||||
|
||||
class ScaffoldRequest(BaseModel):
|
||||
create: bool = False # True면 하위작업 실제 생성, False면 미리보기
|
||||
use_llm: bool = False # LLM 보강 사용 여부
|
||||
|
||||
|
||||
# ---------- risks ----------
|
||||
class RiskOut(BaseModel):
|
||||
kind: str # "지연 위험" | "업무 쏠림" | "의존성"
|
||||
icon: str # "clock" | "scale" | "link"
|
||||
tone: str # "coral" | "amber" | "violet"
|
||||
task_id: Optional[str] = None # 관련 task id (cta 대상)
|
||||
text: str # 한국어. 강조어를 ** ** 마크다운으로 감싼다
|
||||
cta: Optional[str] = None # "작업 열기" | "후속 작업 보기"
|
||||
|
||||
|
||||
# ---------- inbox ----------
|
||||
class ClassificationOut(BaseModel):
|
||||
id: Optional[str] = None
|
||||
inbox_item_id: str
|
||||
type: ClsType
|
||||
sphere: Sphere
|
||||
project_id: Optional[str] = None
|
||||
proj_label: str
|
||||
tone: str
|
||||
due_text: str
|
||||
when_text: str
|
||||
extra: str
|
||||
reason: str
|
||||
confidence: float
|
||||
model: str
|
||||
created_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class InboxItemOut(BaseModel):
|
||||
id: str
|
||||
kind: InboxKind
|
||||
raw: str
|
||||
status: InboxStatus
|
||||
created_at: datetime
|
||||
materialized_task_id: Optional[str] = None
|
||||
classification: Optional[ClassificationOut] = None # 최신 1건
|
||||
|
||||
|
||||
class CaptureRequest(BaseModel):
|
||||
kind: InboxKind = InboxKind.text
|
||||
raw: str
|
||||
|
||||
|
||||
class CaptureResponse(BaseModel):
|
||||
item: InboxItemOut
|
||||
classification: ClassificationOut
|
||||
|
||||
|
||||
class ReclassifyRequest(BaseModel):
|
||||
type: Optional[ClsType] = None # 사용자가 타입 강제 가능
|
||||
|
||||
|
||||
class ConfirmResponse(BaseModel):
|
||||
item: InboxItemOut
|
||||
task: Optional[TaskNode] = None # type=task 면 생성된 작업
|
||||
|
||||
|
||||
# ---------- llm ----------
|
||||
class LLMHealth(BaseModel):
|
||||
reachable: bool
|
||||
provider: str # "ollama" | "heuristic"
|
||||
model: str
|
||||
host: Optional[str] = None
|
||||
detail: str = ""
|
||||
|
||||
|
||||
# ---------- dashboard ----------
|
||||
class UserOut(BaseModel):
|
||||
name: str # 예: "지우"
|
||||
initial: str # 예: "지"
|
||||
|
||||
|
||||
class WeatherOut(BaseModel):
|
||||
temp: int # 현재 기온 (예: 24)
|
||||
cond: str # "맑음 · 한낮 28°"
|
||||
icon: str # 'cloudSun' 저장 → 표시용 'sun' 으로 매핑
|
||||
|
||||
|
||||
class BriefingOut(BaseModel):
|
||||
today: str # 히어로 날짜 라벨 (예: "6월 7일 일요일")
|
||||
weather: WeatherOut
|
||||
commute: str
|
||||
sleep: str
|
||||
note: str # HTML 허용
|
||||
|
||||
|
||||
class EventOut(BaseModel):
|
||||
time: str
|
||||
title: str
|
||||
tag: str
|
||||
dur: str
|
||||
tone: str
|
||||
soon: bool
|
||||
|
||||
|
||||
class ApprovalSummaryOut(BaseModel):
|
||||
id: str
|
||||
icon: str
|
||||
tone: str
|
||||
title: str
|
||||
time: str
|
||||
# risk=="high" 만 포함, 최대 3건. detail/cta/alt/undo_label 미포함.
|
||||
|
||||
|
||||
class GoalOut(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
pct: int
|
||||
sub: str
|
||||
tone: str # tone=키('blue' 등)
|
||||
|
||||
|
||||
class InboxRecentOut(BaseModel):
|
||||
id: str
|
||||
kind: str
|
||||
raw: str
|
||||
type: str
|
||||
proj_label: str
|
||||
tone: str
|
||||
# 평탄화 형태: 최신 classification 에서 type/proj_label/tone 을 끌어와 채운다.
|
||||
|
||||
|
||||
class TaskSummaryItem(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
prio: str
|
||||
project: str
|
||||
|
||||
|
||||
class TaskSummaryOut(BaseModel):
|
||||
open_count: int # 미완료 작업 수
|
||||
items: list[TaskSummaryItem]
|
||||
|
||||
|
||||
class BadgesOut(BaseModel):
|
||||
appr: int # 결재함 대기(=high risk 건수)
|
||||
task: int # 미완료 작업 수(상단 작업 배지)
|
||||
noti: int # 알림 배지 (시드 상수 6)
|
||||
|
||||
|
||||
class DashboardOut(BaseModel):
|
||||
user: UserOut
|
||||
briefing: BriefingOut
|
||||
saved_today: str # "47분"
|
||||
today_routed: int # 7
|
||||
schedule: list[EventOut]
|
||||
task_summary: TaskSummaryOut
|
||||
goals: list[GoalOut]
|
||||
approvals_summary: list[ApprovalSummaryOut] # high-risk 만, 최대 3건
|
||||
inbox_recent: list[InboxRecentOut] # 최근 3 (평탄화 형태)
|
||||
badges: BadgesOut
|
||||
|
||||
|
||||
# 재귀 모델 전방참조 해소
|
||||
ProjectNode.model_rebuild()
|
||||
TaskNode.model_rebuild()
|
||||
@ -0,0 +1,43 @@
|
||||
# backend/app/services/classification.py
|
||||
import uuid
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..llm.provider import Classification, LLMProvider
|
||||
from ..models import InboxClassification, Project
|
||||
|
||||
|
||||
def _context(s: Session) -> dict:
|
||||
projects = s.exec(select(Project)).all()
|
||||
return {
|
||||
"projects": [
|
||||
{"id": p.id, "name": p.name, "folder_id": p.folder_id} for p in projects
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def classify(
|
||||
s: Session, raw: str, provider: LLMProvider, force_type: str | None = None
|
||||
) -> Classification:
|
||||
# provider 는 라우터에서 Depends(get_provider) 로 주입받아 전달한다(auto: ollama→heuristic).
|
||||
c = provider.classify_capture(raw, _context(s))
|
||||
if force_type and force_type in ("task", "event", "idea"):
|
||||
c.type = force_type # 사용자 강제 타입
|
||||
c.reason = f"사용자가 '{force_type}'(으)로 지정했어요. " + c.reason
|
||||
return c
|
||||
|
||||
|
||||
def persist_classification(
|
||||
s: Session, inbox_item_id: str, c: Classification
|
||||
) -> InboxClassification:
|
||||
row = InboxClassification(
|
||||
id="cls-" + uuid.uuid4().hex[:8], # TEXT PK
|
||||
inbox_item_id=inbox_item_id, type=c.type, sphere=c.sphere,
|
||||
project_id=c.project_id, proj_label=c.proj_label, tone=c.tone,
|
||||
due_text=c.due_text, when_text=c.when_text, extra=c.extra,
|
||||
reason=c.reason, confidence=c.confidence, model=c.model,
|
||||
)
|
||||
s.add(row)
|
||||
s.commit()
|
||||
s.refresh(row)
|
||||
return row
|
||||
@ -0,0 +1,101 @@
|
||||
# backend/app/services/risk.py
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..config import get_settings
|
||||
from ..models import Person, Project, Task
|
||||
from ..schemas import RiskOut
|
||||
|
||||
STATUS_LABEL = {"todo": "시작 전", "doing": "진행 중", "waiting": "대기 중", "review": "검토 중"}
|
||||
DEPS = [
|
||||
{"blocker": "예산 섹션 작성", "blocked": "경영진 검토 요청 메일"},
|
||||
{"blocker": "데이터 전처리 파이프라인", "blocked": "사용자 인터뷰 5건 정리"},
|
||||
]
|
||||
|
||||
|
||||
def _due_day(t: Task) -> int:
|
||||
return t.due.day if t.due else 99
|
||||
|
||||
|
||||
def _due_txt(t: Task) -> str:
|
||||
return f"6/{t.due.day}" if t.due else ""
|
||||
|
||||
|
||||
def _status_value(t: Task) -> str:
|
||||
return t.status.value if hasattr(t.status, "value") else t.status
|
||||
|
||||
|
||||
def compute_risks(s: Session, area: str = "work") -> list[RiskOut]:
|
||||
today = get_settings().risk_today # 8
|
||||
all_tasks = s.exec(select(Task)).all()
|
||||
people = {p.id: p for p in s.exec(select(Person)).all()}
|
||||
|
||||
# area 필터: 작업이 속한 project 의 folder 로 판정
|
||||
proj_folder = {p.id: p.folder_id for p in s.exec(select(Project)).all()}
|
||||
|
||||
def in_area(t: Task) -> bool:
|
||||
return proj_folder.get(t.project_id) == area
|
||||
|
||||
scoped = [t for t in all_tasks if in_area(t)]
|
||||
roots = [t for t in scoped if t.parent_id is None]
|
||||
|
||||
risks: list[RiskOut] = []
|
||||
|
||||
# ① 지연 위험 (최상위 작업, 첫 1건)
|
||||
late = [
|
||||
t for t in sorted(roots, key=lambda x: x.sort_order)
|
||||
if _status_value(t) != "done" and t.due and _due_day(t) <= today
|
||||
]
|
||||
if late:
|
||||
t = late[0]
|
||||
risks.append(
|
||||
RiskOut(
|
||||
kind="지연 위험", icon="clock", tone="coral", task_id=t.id, cta="작업 열기",
|
||||
text=f"**{t.title}** — 오늘({_due_txt(t)}) 마감인데 아직 {STATUS_LABEL.get(_status_value(t), '')}이에요", # noqa: E501
|
||||
)
|
||||
)
|
||||
|
||||
# ② 업무 쏠림 (전체 노드 카운트)
|
||||
counts: dict[str, int] = {}
|
||||
for n in scoped:
|
||||
if _status_value(n) != "done" and n.assignee_id:
|
||||
counts[n.assignee_id] = counts.get(n.assignee_id, 0) + 1
|
||||
entries = [(w, c) for w, c in counts.items() if w in people]
|
||||
if len(entries) > 1:
|
||||
entries.sort(key=lambda x: -x[1])
|
||||
top_who, top_n = entries[0]
|
||||
avg = sum(c for _, c in entries) / len(entries)
|
||||
if top_n >= avg * 1.5 and top_n >= 4:
|
||||
mult = round(top_n / avg, 1)
|
||||
p = people[top_who]
|
||||
if p.is_me:
|
||||
text = (
|
||||
f"미완료 작업 **{top_n}건**이 내게 몰려 있어요 — 팀 평균의 **{mult}배**. "
|
||||
f"벅찬 작업은 위임 & 추적으로 넘겨보세요"
|
||||
)
|
||||
else:
|
||||
text = (
|
||||
f"**{p.name}님**에게 미완료 작업 **{top_n}건**이 몰려 있어요 — "
|
||||
f"평균의 **{mult}배**, 일부 재배분을 추천드려요"
|
||||
)
|
||||
risks.append(RiskOut(kind="업무 쏠림", icon="scale", tone="amber", text=text))
|
||||
|
||||
# ③ 의존성 (가장 임박한 1건)
|
||||
def find_by_title(title: str) -> Task | None:
|
||||
for n in scoped:
|
||||
if n.title == title:
|
||||
return n
|
||||
return None
|
||||
|
||||
for d in DEPS:
|
||||
a, b = find_by_title(d["blocker"]), find_by_title(d["blocked"])
|
||||
if a and b and _status_value(a) != "done" and _status_value(b) != "done":
|
||||
suffix = f"({_due_txt(b)})" if b.due else ""
|
||||
risks.append(
|
||||
RiskOut(
|
||||
kind="의존성", icon="link", tone="violet", task_id=b.id, cta="후속 작업 보기",
|
||||
text=f"**{d['blocker']}**이(가) 늦어지면 **{d['blocked']}**{suffix}까지 함께 밀려요", # noqa: E501
|
||||
)
|
||||
)
|
||||
break
|
||||
|
||||
return risks[:3]
|
||||
@ -0,0 +1,117 @@
|
||||
# backend/app/services/scaffold.py
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..models import Task, TaskStatus
|
||||
|
||||
SCAFFOLDS = {
|
||||
"research": {
|
||||
"kind": "연구 · 논문 작성",
|
||||
"icon": "brain",
|
||||
"items": [
|
||||
{"title": "선행 연구 조사", "est": "1일"},
|
||||
{"title": "실험 데이터 취합", "est": "1일"},
|
||||
{"title": "아키텍처 다이어그램 작성", "est": "반나절"},
|
||||
{"title": "서론 초안", "est": "반나절"},
|
||||
{"title": "결론 작성", "est": "반나절"},
|
||||
],
|
||||
},
|
||||
"dev": {
|
||||
"kind": "개발 업무",
|
||||
"icon": "branch",
|
||||
"items": [
|
||||
{"title": "API 엔드포인트 설계", "est": "2시간"},
|
||||
{"title": "UI 폼 컴포넌트 개발", "est": "3시간"},
|
||||
{"title": "토큰 저장소 세팅", "est": "1.5시간"},
|
||||
{"title": "테스트 코드 작성", "est": "2시간"},
|
||||
],
|
||||
},
|
||||
"doc": {
|
||||
"kind": "문서 · 리포트",
|
||||
"icon": "file",
|
||||
"items": [
|
||||
{"title": "목차 & 범위 정의", "est": "30분"},
|
||||
{"title": "핵심 데이터 수집", "est": "2시간"},
|
||||
{"title": "섹션별 초안 작성", "est": "3시간"},
|
||||
{"title": "리뷰 & 수정", "est": "1시간"},
|
||||
{"title": "최종 정리 & 공유", "est": "30분"},
|
||||
],
|
||||
},
|
||||
"generic": {
|
||||
"kind": "일반 업무",
|
||||
"icon": "list",
|
||||
"items": [
|
||||
{"title": "범위 정의 & 자료 수집", "est": "1시간"},
|
||||
{"title": "초안 작성", "est": "2시간"},
|
||||
{"title": "리뷰 & 피드백 반영", "est": "1시간"},
|
||||
{"title": "최종 정리 & 공유", "est": "30분"},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
# 원본 pickScaffold 정규식 (순서 중요: research > dev > doc > generic)
|
||||
RE_RESEARCH = re.compile(r"(논문|연구|리서치|실험|학회|발표|조사|인터뷰)")
|
||||
RE_DEV = re.compile(r"(구현|개발|API|로직|컴포넌트|버그|배포|인증|앱)")
|
||||
RE_DOC = re.compile(r"(리포트|문서|보고|자료|작성|초안|회고|정산)")
|
||||
|
||||
|
||||
def pick_scaffold(title: str, use_llm: bool = False) -> dict:
|
||||
t = title or ""
|
||||
if RE_RESEARCH.search(t):
|
||||
base = SCAFFOLDS["research"]
|
||||
elif RE_DEV.search(t):
|
||||
base = SCAFFOLDS["dev"]
|
||||
elif RE_DOC.search(t):
|
||||
base = SCAFFOLDS["doc"]
|
||||
else:
|
||||
base = SCAFFOLDS["generic"]
|
||||
|
||||
if use_llm:
|
||||
try:
|
||||
from ..llm.provider import get_provider
|
||||
|
||||
enriched = get_provider().generate_json(
|
||||
_scaffold_prompt(title, base), schema={"items": "list"}
|
||||
)
|
||||
items = enriched.get("items")
|
||||
if isinstance(items, list) and items:
|
||||
norm = [
|
||||
{"title": str(i.get("title", "")).strip(), "est": str(i.get("est", "")).strip()}
|
||||
for i in items
|
||||
if i.get("title")
|
||||
]
|
||||
if norm:
|
||||
return {"kind": base["kind"], "icon": base["icon"], "items": norm}
|
||||
except Exception:
|
||||
pass # 폴백: 정규식 템플릿 그대로
|
||||
return base
|
||||
|
||||
|
||||
def scaffold_create(s: Session, parent: Task, tpl: dict) -> list[str]:
|
||||
existing = s.exec(select(Task).where(Task.parent_id == parent.id)).all()
|
||||
order = max([x.sort_order for x in existing] + [-1]) + 1
|
||||
ids = []
|
||||
for i, it in enumerate(tpl["items"]):
|
||||
tid = "t-" + uuid.uuid4().hex[:8]
|
||||
s.add(
|
||||
Task(
|
||||
id=tid, title=it["title"], project_id=parent.project_id, parent_id=parent.id,
|
||||
status=TaskStatus.todo, assignee_id=parent.assignee_id, prio=parent.prio,
|
||||
est=it.get("est", ""), sort_order=order + i,
|
||||
)
|
||||
)
|
||||
ids.append(tid)
|
||||
s.commit()
|
||||
return ids
|
||||
|
||||
|
||||
def _scaffold_prompt(title: str, base: dict) -> str:
|
||||
return (
|
||||
"다음 작업을 실행 가능한 하위작업으로 4~6개 쪼개세요. "
|
||||
"각 항목은 {title, est(예상 소요)} 형태의 JSON. 한국어.\n"
|
||||
f"작업: {title}\n"
|
||||
f"참고 템플릿({base['kind']}): {[i['title'] for i in base['items']]}\n"
|
||||
'반드시 {"items":[{"title":"...","est":"..."}]} 형식 JSON만 출력.'
|
||||
)
|
||||
@ -0,0 +1,177 @@
|
||||
"""init schema
|
||||
|
||||
Revision ID: 3e46d0f29340
|
||||
Revises:
|
||||
Create Date: 2026-06-13 18:54:35.709820
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import sqlmodel # SQLModel AutoString 등 컬럼 타입 참조
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '3e46d0f29340'
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('approval',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('icon', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('tone', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('risk', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('time', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('detail', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('cta', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('alt', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('undo_label', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('briefing',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('today', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('weather_temp', sa.Integer(), nullable=False),
|
||||
sa.Column('weather_cond', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('weather_icon', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('commute', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('sleep', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('note', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('saved_today', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('today_routed', sa.Integer(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('event',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('time', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('tag', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('dur', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('tone', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('soon', sa.Boolean(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('folder',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('tone', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('icon', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.Column('is_system', sa.Boolean(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('goal',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('pct', sa.Integer(), nullable=False),
|
||||
sa.Column('sub', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('tone', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('person',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('initial', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('color', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('is_me', sa.Boolean(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('project',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('folder_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('parent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
|
||||
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('tone', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.Column('pinned', sa.Boolean(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['folder_id'], ['folder.id'], ),
|
||||
sa.ForeignKeyConstraint(['parent_id'], ['project.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('task',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('project_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('parent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
|
||||
sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('status', sa.Enum('todo', 'doing', 'waiting', 'review', 'done', name='taskstatus'), nullable=False),
|
||||
sa.Column('assignee_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
|
||||
sa.Column('due', sa.Date(), nullable=True),
|
||||
sa.Column('prio', sa.Enum('high', 'normal', 'low', name='prio'), nullable=False),
|
||||
sa.Column('notes', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('est', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('delegated', sa.Boolean(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['assignee_id'], ['person.id'], ),
|
||||
sa.ForeignKeyConstraint(['parent_id'], ['task.id'], ),
|
||||
sa.ForeignKeyConstraint(['project_id'], ['project.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('inbox_item',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('kind', sa.Enum('text', 'voice', 'image', name='inboxkind'), nullable=False),
|
||||
sa.Column('raw', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('status', sa.Enum('new', 'classified', 'confirmed', 'dismissed', name='inboxstatus'), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('materialized_task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['materialized_task_id'], ['task.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('task_comment',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('person_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('text', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['person_id'], ['person.id'], ),
|
||||
sa.ForeignKeyConstraint(['task_id'], ['task.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('inbox_classification',
|
||||
sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('inbox_item_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('type', sa.Enum('task', 'event', 'idea', name='clstype'), nullable=False),
|
||||
sa.Column('sphere', sa.Enum('work', 'life', name='sphere'), nullable=False),
|
||||
sa.Column('project_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
|
||||
sa.Column('proj_label', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('tone', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('due_text', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('when_text', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('extra', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('reason', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('confidence', sa.Float(), nullable=False),
|
||||
sa.Column('model', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['inbox_item_id'], ['inbox_item.id'], ),
|
||||
sa.ForeignKeyConstraint(['project_id'], ['project.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('inbox_classification')
|
||||
op.drop_table('task_comment')
|
||||
op.drop_table('inbox_item')
|
||||
op.drop_table('task')
|
||||
op.drop_table('project')
|
||||
op.drop_table('person')
|
||||
op.drop_table('goal')
|
||||
op.drop_table('folder')
|
||||
op.drop_table('event')
|
||||
op.drop_table('briefing')
|
||||
op.drop_table('approval')
|
||||
# ### end Alembic commands ###
|
||||
@ -1,9 +1,39 @@
|
||||
# backend/tests/conftest.py
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
from sqlmodel.pool import StaticPool
|
||||
|
||||
from app import seed as seed_mod
|
||||
from app.db import get_session
|
||||
from app.llm.heuristic import HeuristicProvider
|
||||
from app.llm.provider import get_provider
|
||||
from app.main import app
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
def session():
|
||||
engine = create_engine(
|
||||
"sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
with Session(engine) as s:
|
||||
yield s, engine
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(session):
|
||||
s, engine = session
|
||||
# 테스트 세션을 주입해 시드(정본 시그니처: run_seed(session=..., reset=True)).
|
||||
with Session(engine) as seed_s:
|
||||
seed_mod.run_seed(session=seed_s, reset=True)
|
||||
|
||||
def _get_session():
|
||||
with Session(engine) as ss:
|
||||
yield ss
|
||||
|
||||
app.dependency_overrides[get_session] = _get_session
|
||||
# LLM은 기본적으로 heuristic 강제(테스트 결정성).
|
||||
app.dependency_overrides[get_provider] = lambda: HeuristicProvider()
|
||||
yield TestClient(app)
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
@ -0,0 +1,15 @@
|
||||
def test_dashboard(client):
|
||||
d = client.get("/api/dashboard").json()
|
||||
assert d["user"]["name"] == "지우" and d["user"]["initial"] == "지"
|
||||
assert d["briefing"]["today"] == "6월 7일 일요일" # 히어로 날짜 라벨
|
||||
assert d["briefing"]["weather"]["temp"] == 24
|
||||
assert d["briefing"]["weather"]["icon"] == "sun" # cloudSun 저장 → sun 표시
|
||||
assert d["saved_today"] == "47분" and d["today_routed"] == 7
|
||||
assert any(e["soon"] for e in d["schedule"]) # 14:00 분기 전략 미팅 soon
|
||||
assert d["badges"]["appr"] == 3 # high risk 3건
|
||||
assert d["badges"]["noti"] == 6
|
||||
assert d["task_summary"]["open_count"] > 0
|
||||
assert len(d["approvals_summary"]) <= 3 # high-risk 만, 최대 3건
|
||||
assert d["goals"][0]["tone"] == "blue" # tone 키('var(--blue)' 아님)
|
||||
# inbox_recent 는 평탄화 형태 {id,kind,raw,type,proj_label,tone}
|
||||
assert set(d["inbox_recent"][0]) == {"id", "kind", "raw", "type", "proj_label", "tone"}
|
||||
@ -0,0 +1,48 @@
|
||||
def test_capture_confirm_federation(client):
|
||||
cap = client.post(
|
||||
"/api/inbox/capture",
|
||||
json={"kind": "text", "raw": "다음 주에 한국 놀러가는 비행기 티켓 사기"},
|
||||
).json()
|
||||
iid = cap["item"]["id"]
|
||||
assert cap["classification"]["type"] == "task"
|
||||
conf = client.post(f"/api/inbox/{iid}/confirm").json()
|
||||
assert conf["item"]["status"] == "confirmed"
|
||||
assert conf["item"]["materialized_task_id"]
|
||||
assert conf["task"]["title"].startswith("다음 주에 한국")
|
||||
# extra(가격 추적 알림)가 notes 에 포함
|
||||
assert "가격 추적" in conf["task"]["notes"]
|
||||
|
||||
|
||||
def test_reclassify_force(client):
|
||||
cap = client.post(
|
||||
"/api/inbox/capture", json={"kind": "text", "raw": "엄마 생신 선물 알아보기"}
|
||||
).json()
|
||||
iid = cap["item"]["id"]
|
||||
re = client.post(f"/api/inbox/{iid}/reclassify", json={"type": "idea"}).json()
|
||||
assert re["type"] == "idea"
|
||||
|
||||
|
||||
def test_dismiss(client):
|
||||
cap = client.post("/api/inbox/capture", json={"kind": "text", "raw": "잡담"}).json()
|
||||
iid = cap["item"]["id"]
|
||||
assert client.post(f"/api/inbox/{iid}/dismiss").json()["status"] == "dismissed"
|
||||
|
||||
|
||||
def test_capture_model_is_heuristic(client):
|
||||
# 테스트는 휴리스틱 강제 → model 표기 heuristic
|
||||
cap = client.post(
|
||||
"/api/inbox/capture", json={"kind": "text", "raw": "수요일 11시 자전거 수리"}
|
||||
).json()
|
||||
assert cap["classification"]["model"] == "heuristic"
|
||||
|
||||
|
||||
def test_confirm_event_no_task(client):
|
||||
# event 는 confirm 시 task 미생성, 상태만 confirmed
|
||||
cap = client.post(
|
||||
"/api/inbox/capture", json={"kind": "text", "raw": "수요일 11시 자전거 수리 맡기기"}
|
||||
).json()
|
||||
iid = cap["item"]["id"]
|
||||
conf = client.post(f"/api/inbox/{iid}/confirm").json()
|
||||
assert conf["item"]["status"] == "confirmed"
|
||||
assert conf["item"]["materialized_task_id"] is None
|
||||
assert conf["task"] is None
|
||||
@ -0,0 +1,33 @@
|
||||
def test_tasks_nested_and_filter(client):
|
||||
work = client.get("/api/tasks?area=work").json()
|
||||
k1 = next(t for t in work if t["id"] == "k1")
|
||||
assert k1["children"], "k1 has subtasks"
|
||||
assert len(k1["comments"]) == 2
|
||||
life = client.get("/api/tasks?area=life").json()
|
||||
assert {t["id"] for t in life} >= {"k4", "k20", "k21"}
|
||||
|
||||
|
||||
def test_task_status_move(client):
|
||||
r = client.patch("/api/tasks/k1", json={"status": "review"}).json()
|
||||
assert r["status"] == "review"
|
||||
|
||||
|
||||
def test_task_comment(client):
|
||||
c = client.post("/api/tasks/k1/comments", json={"person_id": "minseo", "text": "확인했습니다"}).json()
|
||||
assert c["text"] == "확인했습니다"
|
||||
|
||||
|
||||
def test_task_filter_project_subtree(client):
|
||||
# biz 프로젝트(+하위)의 작업: k1(biz-report), k6(biz-okr) 등 포함
|
||||
r = client.get("/api/tasks?project_id=biz").json()
|
||||
ids = {t["id"] for t in r}
|
||||
assert "k1" in ids and "k6" in ids
|
||||
|
||||
|
||||
def test_task_create_and_delete(client):
|
||||
created = client.post(
|
||||
"/api/tasks", json={"title": "신규 작업", "project_id": "me"}
|
||||
).json()
|
||||
tid = created["id"]
|
||||
assert created["status"] == "todo"
|
||||
assert client.delete(f"/api/tasks/{tid}").json()["deleted"] == tid
|
||||
@ -0,0 +1,27 @@
|
||||
def test_tree_shape(client):
|
||||
tree = client.get("/api/tree").json()
|
||||
assert [f["name"] for f in tree] == ["업무", "개인"]
|
||||
work = tree[0]
|
||||
biz = next(p for p in work["projects"] if p["id"] == "biz")
|
||||
assert {c["id"] for c in biz["children"]} == {"biz-okr", "biz-report", "biz-budget"}
|
||||
assert biz["task_count"] >= biz["children"][0]["task_count"] # 재귀 합
|
||||
|
||||
|
||||
def test_project_crud(client):
|
||||
created = client.post("/api/projects", json={"folder_id": "work", "name": "새 프로젝트"}).json()
|
||||
pid = created["id"]
|
||||
client.patch(f"/api/projects/{pid}", json={"name": "이름변경"})
|
||||
assert client.post(f"/api/projects/{pid}/pin").json()["pinned"] is True
|
||||
assert client.delete(f"/api/projects/{pid}").json()["deleted"] == pid
|
||||
|
||||
|
||||
def test_folder_system_protected(client):
|
||||
# system 폴더(work)는 삭제 불가
|
||||
r = client.delete("/api/folders/work")
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_project_cycle_move_blocked(client):
|
||||
# biz 를 자기 자식(biz-okr) 아래로 이동 시도 → 400
|
||||
r = client.patch("/api/projects/biz", json={"parent_id": "biz-okr"})
|
||||
assert r.status_code == 400
|
||||
@ -0,0 +1,30 @@
|
||||
import pytest
|
||||
|
||||
from app.llm.heuristic import HeuristicProvider
|
||||
|
||||
CTX = {
|
||||
"projects": [
|
||||
{"id": "life-trip", "name": "여행 — 한국", "folder_id": "life"},
|
||||
{"id": "life-fam", "name": "가족", "folder_id": "life"},
|
||||
{"id": "onb", "name": "온보딩 리디자인", "folder_id": "work"},
|
||||
]
|
||||
}
|
||||
|
||||
GOLDEN = [
|
||||
# (raw, type, sphere, proj_label 포함어, extra 포함어)
|
||||
("다음 주에 한국 놀러가는 비행기 티켓 사기", "task", "life", "여행", "가격"),
|
||||
("수요일 11시 자전거 수리 맡기기", "event", "life", "캘린더", ""),
|
||||
("엄마 생신 선물 미리 알아보기", "task", "life", "가족", ""),
|
||||
("온보딩 환영 화면에 짧은 애니메이션 넣으면 어떨까", "idea", "work", "온보딩", ""),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw,typ,sphere,proj_kw,extra_kw", GOLDEN)
|
||||
def test_golden(raw, typ, sphere, proj_kw, extra_kw):
|
||||
c = HeuristicProvider().classify_capture(raw, CTX)
|
||||
assert c.type == typ, f"{raw} → type {c.type}"
|
||||
assert c.sphere == sphere, f"{raw} → sphere {c.sphere}"
|
||||
assert proj_kw in c.proj_label, f"{raw} → proj_label {c.proj_label}"
|
||||
if extra_kw:
|
||||
assert extra_kw in c.extra
|
||||
assert c.reason # 한국어 reason 비어있지 않음
|
||||
@ -0,0 +1,24 @@
|
||||
import pytest
|
||||
|
||||
from app.llm.heuristic import HeuristicProvider
|
||||
|
||||
CTX = {
|
||||
"projects": [
|
||||
{"id": "life-trip", "name": "여행 — 한국", "folder_id": "life"},
|
||||
{"id": "life-fam", "name": "가족", "folder_id": "life"},
|
||||
{"id": "onb", "name": "온보딩 리디자인", "folder_id": "work"},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw,ctype",
|
||||
[
|
||||
("수요일 11시 자전거 수리 맡기기", "event"), # 시각 명시
|
||||
("다음 주에 비행기 티켓 사기", "task"), # 행동+기한
|
||||
("온보딩에 애니메이션 넣으면 어떨까", "idea"), # 막연
|
||||
],
|
||||
)
|
||||
def test_heuristic_type(raw, ctype):
|
||||
c = HeuristicProvider().classify_capture(raw, CTX)
|
||||
assert c.type == ctype
|
||||
@ -0,0 +1,26 @@
|
||||
def test_risk_delay_present(client):
|
||||
r = client.get("/api/risks?area=work").json()
|
||||
kinds = [x["kind"] for x in r]
|
||||
assert "지연 위험" in kinds
|
||||
delay = next(x for x in r if x["kind"] == "지연 위험")
|
||||
assert "마감인데" in delay["text"] and delay["icon"] == "clock"
|
||||
|
||||
|
||||
def test_risk_dependency(client):
|
||||
r = client.get("/api/risks?area=work").json()
|
||||
dep = [x for x in r if x["kind"] == "의존성"]
|
||||
assert dep, "예산 섹션 작성→경영진 검토 요청 메일 의존성 1건"
|
||||
assert "함께 밀려요" in dep[0]["text"]
|
||||
|
||||
|
||||
def test_risk_max_three(client):
|
||||
r = client.get("/api/risks?area=work").json()
|
||||
assert len(r) <= 3
|
||||
|
||||
|
||||
def test_risk_overload_threshold(client):
|
||||
# 시드 기준 업무 쏠림이 topN>=avg*1.5 && topN>=4 를 만족하면 포함
|
||||
r = client.get("/api/risks?area=work").json()
|
||||
over = [x for x in r if x["kind"] == "업무 쏠림"]
|
||||
for o in over:
|
||||
assert o["icon"] == "scale" and o["tone"] == "amber"
|
||||
@ -0,0 +1,26 @@
|
||||
import pytest
|
||||
|
||||
from app.services.scaffold import pick_scaffold
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"title,kind",
|
||||
[
|
||||
("선행 연구 인터뷰 진행", "연구 · 논문 작성"), # research
|
||||
("결제 API 개발", "개발 업무"), # dev
|
||||
("OKR 중간 점검 자료 준비", "문서 · 리포트"), # doc (자료/작성)
|
||||
("분기 리포트 초안 마무리", "문서 · 리포트"), # doc (리포트/초안)
|
||||
("화분 물 주기", "일반 업무"), # generic
|
||||
],
|
||||
)
|
||||
def test_pick_scaffold(title, kind):
|
||||
assert pick_scaffold(title)["kind"] == kind
|
||||
|
||||
|
||||
def test_scaffold_create_via_api(client):
|
||||
r = client.post("/api/tasks/k6/scaffold", json={"create": True}).json()
|
||||
assert r["created"] is True and len(r["created_task_ids"]) == len(r["items"])
|
||||
# 생성 후 트리에 하위작업 반영
|
||||
t = client.get("/api/tasks/k6").json()
|
||||
titles = [c["title"] for c in t["children"]]
|
||||
assert "목차 & 범위 정의" in titles
|
||||
Loading…
Reference in New Issue