coderound-task-backend / app /api /routes /candidates.py
AnishDev's picture
initial code and logic pushed
ff7b177
Raw History Blame Contribute Delete
3.44 kB
import uuid
import json
import logging
from datetime import datetime, timezone
from dataclasses import asdict
from fastapi import APIRouter, UploadFile, File, HTTPException
from app.services import storage, file_parser
from app.models.schemas import CandidateBatchResponse, BatchListItem
router = APIRouter(prefix="/api/v1/candidates", tags=["candidates"])
logger = logging.getLogger(__name__)
def _candidate_to_dict(c) -> dict:
"""Serialize CandidateData to JSON-safe dict."""
return {
"id": c.id,
"name": c.name,
"current_position": c.current_position,
"current_title": c.current_title,
"years_of_experience": c.years_of_experience,
"engineer_type": c.engineer_type,
"gen_ai_experience": c.gen_ai_experience,
"parsed_skills": c.parsed_skills,
"parsed_summary": c.parsed_summary,
"parsed_work_experience_raw": c.parsed_work_experience_raw,
"parsed_work_experience_text": c.parsed_work_experience_text,
"work_experiences": [
{
"company": we.company,
"role": we.role,
"duration": we.duration,
"description": we.description,
}
for we in c.work_experiences
],
"most_recent_company": c.most_recent_company,
"notice_period": c.notice_period,
"is_actively_looking": c.is_actively_looking,
"flags": c.flags,
"penalties": c.penalties,
}
@router.post("/upload", response_model=CandidateBatchResponse)
async def upload_candidates(file: UploadFile = File(...)):
if not file.filename or not file.filename.lower().endswith(".xlsx"):
raise HTTPException(400, "Only XLSX files accepted for candidates")
content = await file.read()
if len(content) > 50 * 1024 * 1024:
raise HTTPException(413, "File too large (max 50 MB)")
try:
candidates, dist = file_parser.parse_xlsx(content)
except ValueError as e:
raise HTTPException(400, str(e))
if not candidates:
raise HTTPException(400, "No valid candidates found in file")
batch_id = str(uuid.uuid4())[:8]
now = datetime.now(timezone.utc).isoformat()
metadata = {
"batch_id": batch_id,
"total_count": len(candidates),
"engineer_type_distribution": json.dumps(dist),
"uploaded_at": now,
"filename": file.filename,
}
candidates_json = json.dumps([_candidate_to_dict(c) for c in candidates])
storage.save_batch(batch_id, metadata, candidates_json)
logger.info(f"Batch uploaded: {batch_id}, {len(candidates)} candidates, dist={dist}")
return CandidateBatchResponse(
batch_id=batch_id,
total_count=len(candidates),
engineer_type_distribution=dist,
uploaded_at=now,
)
@router.get("/", response_model=list[BatchListItem])
def list_batches():
items = storage.list_batches()
result = []
for d in items:
dist = d.get("engineer_type_distribution", {})
if isinstance(dist, str):
try:
dist = json.loads(dist)
except Exception:
dist = {}
result.append(BatchListItem(
batch_id=d.get("batch_id", ""),
total_count=int(d.get("total_count", 0)),
engineer_type_distribution=dist,
uploaded_at=d.get("uploaded_at", ""),
))
return result