mirror of
https://git.victorphan.net/basketballcantho/ten-project.git
synced 2026-08-05 12:03:12 +07:00
Hoàn thành bước 3.3. Interactive Workbook (The Core Viewer)
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..dependencies import get_current_user
|
||||
from ..models import Annotation, PDF, User
|
||||
from ..schemas import AnnotationIn, AnnotationOut
|
||||
|
||||
router = APIRouter(prefix="/annotations", tags=["annotations"])
|
||||
|
||||
|
||||
def _verify_pdf_ownership(db: Session, pdf_id: int, user_id: int) -> PDF:
|
||||
pdf = db.get(PDF, pdf_id)
|
||||
if not pdf or pdf.user_id != user_id:
|
||||
raise HTTPException(status_code=404, detail="PDF not found.")
|
||||
return pdf
|
||||
|
||||
|
||||
# ── GET /api/annotations/{pdf_id}/{page_number} ───────────────────────────────
|
||||
|
||||
@router.get("/{pdf_id}/{page_number}", response_model=AnnotationOut)
|
||||
def get_annotation(
|
||||
pdf_id: int,
|
||||
page_number: int,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
_verify_pdf_ownership(db, pdf_id, current_user.id)
|
||||
|
||||
ann = (
|
||||
db.query(Annotation)
|
||||
.filter(
|
||||
Annotation.pdf_id == pdf_id,
|
||||
Annotation.user_id == current_user.id,
|
||||
Annotation.page_number == page_number,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
# Return empty canvas if no annotation exists yet — not an error
|
||||
if ann is None:
|
||||
return AnnotationOut(
|
||||
id=0,
|
||||
pdf_id=pdf_id,
|
||||
page_number=page_number,
|
||||
canvas_data={},
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
return ann
|
||||
|
||||
|
||||
# ── PUT /api/annotations/{pdf_id}/{page_number} ───────────────────────────────
|
||||
|
||||
@router.put("/{pdf_id}/{page_number}", response_model=AnnotationOut)
|
||||
def upsert_annotation(
|
||||
pdf_id: int,
|
||||
page_number: int,
|
||||
body: AnnotationIn,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
_verify_pdf_ownership(db, pdf_id, current_user.id)
|
||||
|
||||
ann = (
|
||||
db.query(Annotation)
|
||||
.filter(
|
||||
Annotation.pdf_id == pdf_id,
|
||||
Annotation.user_id == current_user.id,
|
||||
Annotation.page_number == page_number,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
if ann is None:
|
||||
ann = Annotation(
|
||||
pdf_id=pdf_id,
|
||||
user_id=current_user.id,
|
||||
page_number=page_number,
|
||||
canvas_data=body.canvas_data,
|
||||
)
|
||||
db.add(ann)
|
||||
else:
|
||||
ann.canvas_data = body.canvas_data
|
||||
ann.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
db.commit()
|
||||
db.refresh(ann)
|
||||
return ann
|
||||
Reference in New Issue
Block a user