Spaces:
Sleeping
Sleeping
feat: sync briga-backend — 2026 fallback chain (Gemini->OpenRouter :free->Groq), per-agent tier override, supabase JWT auth, agents router, retry columns
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- app/api/academy.py +94 -94
- app/api/admin.py +92 -92
- app/api/agents.py +273 -0
- app/api/career.py +141 -141
- app/api/debug_admin.py +29 -29
- app/api/interview.py +174 -174
- app/api/job.py +219 -219
- app/api/legacy_compat.py +720 -718
- app/api/talent.py +876 -876
- app/api/telegram.py +39 -39
- app/api/whatsapp.py +106 -106
- app/config/settings.py +4 -0
- app/config/vetting_rules.py +322 -0
- app/main.py +506 -715
- app/middleware/ab_assign.py +30 -30
- app/middleware/auth.py +155 -155
- app/middleware/token_tracker.py +32 -32
- app/models/ab.py +29 -29
- app/models/career.py +134 -134
- app/models/community.py +102 -102
- app/models/content.py +92 -87
- app/models/employer.py +64 -64
- app/models/finance.py +47 -47
- app/models/job.py +120 -120
- app/models/lpk.py +130 -130
- app/models/security.py +56 -56
- app/models/skkni.py +161 -161
- app/models/system.py +208 -208
- app/models/talent.py +70 -70
- app/schemas/career.py +170 -170
- app/schemas/interview.py +117 -117
- app/schemas/job.py +156 -156
- app/services/academy_email_service.py +170 -169
- app/services/agent_activity_service.py +116 -0
- app/services/agent_memory_service.py +102 -0
- app/services/agent_service.py +764 -0
- app/services/ai_service.py +0 -0
- app/services/antigravity.py +460 -460
- app/services/audit_service.py +134 -134
- app/services/auth_service.py +379 -379
- app/services/autonomous_dev_service.py +150 -0
- app/services/career_service.py +169 -169
- app/services/chat_service.py +526 -526
- app/services/content_scheduler_service.py +122 -0
- app/services/deploy_service.py +58 -0
- app/services/email_service.py +47 -47
- app/services/google_workspace_service.py +210 -210
- app/services/interview_service.py +558 -558
- app/services/job_service.py +288 -288
- app/services/kms_service.py +82 -82
app/api/academy.py
CHANGED
|
@@ -1,94 +1,94 @@
|
|
| 1 |
-
"""Academy API Routes."""
|
| 2 |
-
from fastapi import APIRouter, Depends, Request
|
| 3 |
-
from pydantic import BaseModel
|
| 4 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 5 |
-
from app.database import get_db
|
| 6 |
-
from app.services.academy_email_service import AcademyEmailService
|
| 7 |
-
router = APIRouter(prefix="/v1/academy", tags=["Academy"])
|
| 8 |
-
_service = None
|
| 9 |
-
def get_svc():
|
| 10 |
-
global _service
|
| 11 |
-
if _service is None:
|
| 12 |
-
_service = AcademyEmailService()
|
| 13 |
-
return _service
|
| 14 |
-
class FeedbackReq(BaseModel):
|
| 15 |
-
email: str | None = None # Optional: if admin wants to trigger for specific talent
|
| 16 |
-
@router.post("/feedback")
|
| 17 |
-
async def trigger_feedback(req: Request, body: FeedbackReq, db: AsyncSession = Depends(get_db)):
|
| 18 |
-
target = body.email or getattr(req.state, "user_email", None)
|
| 19 |
-
if not target:
|
| 20 |
-
return {"success": False, "error": "Email atau autentikasi diperlukan"}
|
| 21 |
-
return await get_svc().process_academy_feedback(db=db, email=target)
|
| 22 |
-
@router.post("/feedback/bulk")
|
| 23 |
-
async def trigger_bulk_feedback(req: Request, db: AsyncSession = Depends(get_db)):
|
| 24 |
-
email = getattr(req.state, "user_email", None)
|
| 25 |
-
role = getattr(req.state, "user_role", None)
|
| 26 |
-
if not email or role != "admin":
|
| 27 |
-
return {"success": False, "error": "Admin access required"}
|
| 28 |
-
return await get_svc().process_bulk_academy_feedback(db=db, limit=50)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
@router.get("/leads")
|
| 32 |
-
async def get_academy_leads(db: AsyncSession = Depends(get_db)):
|
| 33 |
-
"""
|
| 34 |
-
Fetch all scraped LPK partnership leads (Admin only).
|
| 35 |
-
"""
|
| 36 |
-
from sqlalchemy import text
|
| 37 |
-
query = text("SELECT id, name, course_title, syllabus_text, matched_skills, similarity_score, contact_email, status, created_at FROM academy_leads ORDER BY similarity_score DESC")
|
| 38 |
-
res = await db.execute(query)
|
| 39 |
-
rows = res.fetchall()
|
| 40 |
-
|
| 41 |
-
leads = []
|
| 42 |
-
for row in rows:
|
| 43 |
-
leads.append({
|
| 44 |
-
"id": str(row.id),
|
| 45 |
-
"name": row.name,
|
| 46 |
-
"course_title": row.course_title,
|
| 47 |
-
"syllabus_text": row.syllabus_text,
|
| 48 |
-
"matched_skills": row.matched_skills,
|
| 49 |
-
"similarity_score": row.similarity_score,
|
| 50 |
-
"contact_email": row.contact_email,
|
| 51 |
-
"status": row.status,
|
| 52 |
-
"created_at": row.created_at.isoformat() if row.created_at else None
|
| 53 |
-
})
|
| 54 |
-
return {"success": True, "data": leads}
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
class ContactLeadRequest(BaseModel):
|
| 58 |
-
subject: str
|
| 59 |
-
body: str
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
@router.post("/leads/{lead_id}/contact")
|
| 63 |
-
async def contact_academy_lead(lead_id: str, body: ContactLeadRequest, db: AsyncSession = Depends(get_db)):
|
| 64 |
-
"""
|
| 65 |
-
Send an outreach email proposal to the LPK partner and set status to 'contacted'.
|
| 66 |
-
"""
|
| 67 |
-
from sqlalchemy import text
|
| 68 |
-
query = text("SELECT id, name, contact_email, status FROM academy_leads WHERE id = :id")
|
| 69 |
-
res = await db.execute(query, {"id": lead_id})
|
| 70 |
-
lead = res.fetchone()
|
| 71 |
-
if not lead:
|
| 72 |
-
return {"success": False, "error": "Lead tidak ditemukan"}
|
| 73 |
-
|
| 74 |
-
if lead.status == "contacted":
|
| 75 |
-
return {"success": False, "error": "Outreach proposal sudah dikirim sebelumnya"}
|
| 76 |
-
|
| 77 |
-
from app.services.email_service import email_service
|
| 78 |
-
import asyncio
|
| 79 |
-
|
| 80 |
-
success = await asyncio.to_thread(
|
| 81 |
-
email_service.send_html_email,
|
| 82 |
-
lead.contact_email,
|
| 83 |
-
body.subject,
|
| 84 |
-
body.body
|
| 85 |
-
)
|
| 86 |
-
|
| 87 |
-
if success:
|
| 88 |
-
update_query = text("UPDATE academy_leads SET status = 'contacted', updated_at = now() WHERE id = :id")
|
| 89 |
-
await db.execute(update_query, {"id": lead_id})
|
| 90 |
-
await db.commit()
|
| 91 |
-
return {"success": True, "message": "Email outreach berhasil dikirim"}
|
| 92 |
-
|
| 93 |
-
return {"success": False, "error": "Gagal mengirim email via SMTP"}
|
| 94 |
-
|
|
|
|
| 1 |
+
"""Academy API Routes."""
|
| 2 |
+
from fastapi import APIRouter, Depends, Request
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 5 |
+
from app.database import get_db
|
| 6 |
+
from app.services.academy_email_service import AcademyEmailService
|
| 7 |
+
router = APIRouter(prefix="/v1/academy", tags=["Academy"])
|
| 8 |
+
_service = None
|
| 9 |
+
def get_svc():
|
| 10 |
+
global _service
|
| 11 |
+
if _service is None:
|
| 12 |
+
_service = AcademyEmailService()
|
| 13 |
+
return _service
|
| 14 |
+
class FeedbackReq(BaseModel):
|
| 15 |
+
email: str | None = None # Optional: if admin wants to trigger for specific talent
|
| 16 |
+
@router.post("/feedback")
|
| 17 |
+
async def trigger_feedback(req: Request, body: FeedbackReq, db: AsyncSession = Depends(get_db)):
|
| 18 |
+
target = body.email or getattr(req.state, "user_email", None)
|
| 19 |
+
if not target:
|
| 20 |
+
return {"success": False, "error": "Email atau autentikasi diperlukan"}
|
| 21 |
+
return await get_svc().process_academy_feedback(db=db, email=target)
|
| 22 |
+
@router.post("/feedback/bulk")
|
| 23 |
+
async def trigger_bulk_feedback(req: Request, db: AsyncSession = Depends(get_db)):
|
| 24 |
+
email = getattr(req.state, "user_email", None)
|
| 25 |
+
role = getattr(req.state, "user_role", None)
|
| 26 |
+
if not email or role != "admin":
|
| 27 |
+
return {"success": False, "error": "Admin access required"}
|
| 28 |
+
return await get_svc().process_bulk_academy_feedback(db=db, limit=50)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@router.get("/leads")
|
| 32 |
+
async def get_academy_leads(db: AsyncSession = Depends(get_db)):
|
| 33 |
+
"""
|
| 34 |
+
Fetch all scraped LPK partnership leads (Admin only).
|
| 35 |
+
"""
|
| 36 |
+
from sqlalchemy import text
|
| 37 |
+
query = text("SELECT id, name, course_title, syllabus_text, matched_skills, similarity_score, contact_email, status, created_at FROM academy_leads ORDER BY similarity_score DESC")
|
| 38 |
+
res = await db.execute(query)
|
| 39 |
+
rows = res.fetchall()
|
| 40 |
+
|
| 41 |
+
leads = []
|
| 42 |
+
for row in rows:
|
| 43 |
+
leads.append({
|
| 44 |
+
"id": str(row.id),
|
| 45 |
+
"name": row.name,
|
| 46 |
+
"course_title": row.course_title,
|
| 47 |
+
"syllabus_text": row.syllabus_text,
|
| 48 |
+
"matched_skills": row.matched_skills,
|
| 49 |
+
"similarity_score": row.similarity_score,
|
| 50 |
+
"contact_email": row.contact_email,
|
| 51 |
+
"status": row.status,
|
| 52 |
+
"created_at": row.created_at.isoformat() if row.created_at else None
|
| 53 |
+
})
|
| 54 |
+
return {"success": True, "data": leads}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class ContactLeadRequest(BaseModel):
|
| 58 |
+
subject: str
|
| 59 |
+
body: str
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@router.post("/leads/{lead_id}/contact")
|
| 63 |
+
async def contact_academy_lead(lead_id: str, body: ContactLeadRequest, db: AsyncSession = Depends(get_db)):
|
| 64 |
+
"""
|
| 65 |
+
Send an outreach email proposal to the LPK partner and set status to 'contacted'.
|
| 66 |
+
"""
|
| 67 |
+
from sqlalchemy import text
|
| 68 |
+
query = text("SELECT id, name, contact_email, status FROM academy_leads WHERE id = :id")
|
| 69 |
+
res = await db.execute(query, {"id": lead_id})
|
| 70 |
+
lead = res.fetchone()
|
| 71 |
+
if not lead:
|
| 72 |
+
return {"success": False, "error": "Lead tidak ditemukan"}
|
| 73 |
+
|
| 74 |
+
if lead.status == "contacted":
|
| 75 |
+
return {"success": False, "error": "Outreach proposal sudah dikirim sebelumnya"}
|
| 76 |
+
|
| 77 |
+
from app.services.email_service import email_service
|
| 78 |
+
import asyncio
|
| 79 |
+
|
| 80 |
+
success = await asyncio.to_thread(
|
| 81 |
+
email_service.send_html_email,
|
| 82 |
+
lead.contact_email,
|
| 83 |
+
body.subject,
|
| 84 |
+
body.body
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
if success:
|
| 88 |
+
update_query = text("UPDATE academy_leads SET status = 'contacted', updated_at = now() WHERE id = :id")
|
| 89 |
+
await db.execute(update_query, {"id": lead_id})
|
| 90 |
+
await db.commit()
|
| 91 |
+
return {"success": True, "message": "Email outreach berhasil dikirim"}
|
| 92 |
+
|
| 93 |
+
return {"success": False, "error": "Gagal mengirim email via SMTP"}
|
| 94 |
+
|
app/api/admin.py
CHANGED
|
@@ -1,92 +1,92 @@
|
|
| 1 |
-
from fastapi import APIRouter, Depends, Request, HTTPException
|
| 2 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
-
from sqlalchemy import select, update
|
| 4 |
-
from datetime import datetime, timezone
|
| 5 |
-
from loguru import logger
|
| 6 |
-
|
| 7 |
-
from app.database import get_db
|
| 8 |
-
from app.models.system import WorkflowConfig, ActivityLog
|
| 9 |
-
|
| 10 |
-
router = APIRouter(prefix="/v1/admin", tags=["Admin"])
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
def _ensure_admin(request: Request):
|
| 14 |
-
"""Enforce admin role requirement."""
|
| 15 |
-
role = getattr(request.state, "user_role", None)
|
| 16 |
-
if role not in ("admin", "ADMIN"):
|
| 17 |
-
raise HTTPException(status_code=403, detail="Admin role required")
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
async def _get_workflow_or_404(workflow_name: str, db: AsyncSession) -> WorkflowConfig:
|
| 21 |
-
"""Fetch a workflow by name or raise 404."""
|
| 22 |
-
result = await db.execute(
|
| 23 |
-
select(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name)
|
| 24 |
-
)
|
| 25 |
-
row = result.scalar_one_or_none()
|
| 26 |
-
if row is None:
|
| 27 |
-
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_name}' not found")
|
| 28 |
-
return row
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
async def _log_activity(db: AsyncSession, request: Request, action: str, metadata: str):
|
| 32 |
-
"""Record an activity log entry. Errors are logged but do not fail the request."""
|
| 33 |
-
try:
|
| 34 |
-
log = ActivityLog(
|
| 35 |
-
actor=getattr(request.state, 'user_email', None) or 'system',
|
| 36 |
-
action=action,
|
| 37 |
-
log_metadata=metadata,
|
| 38 |
-
)
|
| 39 |
-
db.add(log)
|
| 40 |
-
await db.commit()
|
| 41 |
-
except Exception as e:
|
| 42 |
-
logger.warning(f"Failed to log activity '{action}': {e}")
|
| 43 |
-
try:
|
| 44 |
-
await db.rollback()
|
| 45 |
-
except Exception:
|
| 46 |
-
pass
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
@router.get("/workflows")
|
| 50 |
-
async def list_workflows(request: Request, db: AsyncSession = Depends(get_db)):
|
| 51 |
-
_ensure_admin(request)
|
| 52 |
-
result = await db.execute(select(WorkflowConfig))
|
| 53 |
-
rows = result.scalars().all()
|
| 54 |
-
return [
|
| 55 |
-
{
|
| 56 |
-
"workflow_name": r.workflow_name,
|
| 57 |
-
"is_active": r.is_active,
|
| 58 |
-
"schedule_cron": r.schedule_cron,
|
| 59 |
-
"last_run": r.last_run,
|
| 60 |
-
"updated_at": r.updated_at,
|
| 61 |
-
}
|
| 62 |
-
for r in rows
|
| 63 |
-
]
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
@router.patch("/workflows/{workflow_name}")
|
| 67 |
-
async def update_workflow(workflow_name: str, payload: dict, request: Request, db: AsyncSession = Depends(get_db)):
|
| 68 |
-
_ensure_admin(request)
|
| 69 |
-
await _get_workflow_or_404(workflow_name, db)
|
| 70 |
-
# Only allow specific fields
|
| 71 |
-
allowed = {"is_active", "schedule_cron"}
|
| 72 |
-
update_values = {k: v for k, v in payload.items() if k in allowed}
|
| 73 |
-
if not update_values:
|
| 74 |
-
raise HTTPException(status_code=400, detail="No valid fields to update. Allowed: is_active, schedule_cron")
|
| 75 |
-
update_values["updated_at"] = datetime.now(timezone.utc)
|
| 76 |
-
stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values(**update_values)
|
| 77 |
-
await db.execute(stmt)
|
| 78 |
-
await db.commit()
|
| 79 |
-
await _log_activity(db, request, f"workflow_update:{workflow_name}", str(update_values))
|
| 80 |
-
return {"success": True, "updated": update_values}
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
@router.post("/workflows/{workflow_name}/run")
|
| 84 |
-
async def run_workflow(workflow_name: str, request: Request, db: AsyncSession = Depends(get_db)):
|
| 85 |
-
_ensure_admin(request)
|
| 86 |
-
await _get_workflow_or_404(workflow_name, db)
|
| 87 |
-
# Manual trigger stub: update last_run and return accepted. Actual orchestrator should listen to this event.
|
| 88 |
-
stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values({"last_run": datetime.now(timezone.utc), "updated_at": datetime.now(timezone.utc)})
|
| 89 |
-
await db.execute(stmt)
|
| 90 |
-
await db.commit()
|
| 91 |
-
await _log_activity(db, request, f"workflow_manual_trigger:{workflow_name}", "Manual trigger via admin panel")
|
| 92 |
-
return {"success": True, "message": "Workflow run recorded (manual trigger)."}
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, Request, HTTPException
|
| 2 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
+
from sqlalchemy import select, update
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
from loguru import logger
|
| 6 |
+
|
| 7 |
+
from app.database import get_db
|
| 8 |
+
from app.models.system import WorkflowConfig, ActivityLog
|
| 9 |
+
|
| 10 |
+
router = APIRouter(prefix="/v1/admin", tags=["Admin"])
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _ensure_admin(request: Request):
|
| 14 |
+
"""Enforce admin role requirement."""
|
| 15 |
+
role = getattr(request.state, "user_role", None)
|
| 16 |
+
if role not in ("admin", "ADMIN"):
|
| 17 |
+
raise HTTPException(status_code=403, detail="Admin role required")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
async def _get_workflow_or_404(workflow_name: str, db: AsyncSession) -> WorkflowConfig:
|
| 21 |
+
"""Fetch a workflow by name or raise 404."""
|
| 22 |
+
result = await db.execute(
|
| 23 |
+
select(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name)
|
| 24 |
+
)
|
| 25 |
+
row = result.scalar_one_or_none()
|
| 26 |
+
if row is None:
|
| 27 |
+
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_name}' not found")
|
| 28 |
+
return row
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
async def _log_activity(db: AsyncSession, request: Request, action: str, metadata: str):
|
| 32 |
+
"""Record an activity log entry. Errors are logged but do not fail the request."""
|
| 33 |
+
try:
|
| 34 |
+
log = ActivityLog(
|
| 35 |
+
actor=getattr(request.state, 'user_email', None) or 'system',
|
| 36 |
+
action=action,
|
| 37 |
+
log_metadata=metadata,
|
| 38 |
+
)
|
| 39 |
+
db.add(log)
|
| 40 |
+
await db.commit()
|
| 41 |
+
except Exception as e:
|
| 42 |
+
logger.warning(f"Failed to log activity '{action}': {e}")
|
| 43 |
+
try:
|
| 44 |
+
await db.rollback()
|
| 45 |
+
except Exception:
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@router.get("/workflows")
|
| 50 |
+
async def list_workflows(request: Request, db: AsyncSession = Depends(get_db)):
|
| 51 |
+
_ensure_admin(request)
|
| 52 |
+
result = await db.execute(select(WorkflowConfig))
|
| 53 |
+
rows = result.scalars().all()
|
| 54 |
+
return [
|
| 55 |
+
{
|
| 56 |
+
"workflow_name": r.workflow_name,
|
| 57 |
+
"is_active": r.is_active,
|
| 58 |
+
"schedule_cron": r.schedule_cron,
|
| 59 |
+
"last_run": r.last_run,
|
| 60 |
+
"updated_at": r.updated_at,
|
| 61 |
+
}
|
| 62 |
+
for r in rows
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@router.patch("/workflows/{workflow_name}")
|
| 67 |
+
async def update_workflow(workflow_name: str, payload: dict, request: Request, db: AsyncSession = Depends(get_db)):
|
| 68 |
+
_ensure_admin(request)
|
| 69 |
+
await _get_workflow_or_404(workflow_name, db)
|
| 70 |
+
# Only allow specific fields
|
| 71 |
+
allowed = {"is_active", "schedule_cron"}
|
| 72 |
+
update_values = {k: v for k, v in payload.items() if k in allowed}
|
| 73 |
+
if not update_values:
|
| 74 |
+
raise HTTPException(status_code=400, detail="No valid fields to update. Allowed: is_active, schedule_cron")
|
| 75 |
+
update_values["updated_at"] = datetime.now(timezone.utc)
|
| 76 |
+
stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values(**update_values)
|
| 77 |
+
await db.execute(stmt)
|
| 78 |
+
await db.commit()
|
| 79 |
+
await _log_activity(db, request, f"workflow_update:{workflow_name}", str(update_values))
|
| 80 |
+
return {"success": True, "updated": update_values}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@router.post("/workflows/{workflow_name}/run")
|
| 84 |
+
async def run_workflow(workflow_name: str, request: Request, db: AsyncSession = Depends(get_db)):
|
| 85 |
+
_ensure_admin(request)
|
| 86 |
+
await _get_workflow_or_404(workflow_name, db)
|
| 87 |
+
# Manual trigger stub: update last_run and return accepted. Actual orchestrator should listen to this event.
|
| 88 |
+
stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values({"last_run": datetime.now(timezone.utc), "updated_at": datetime.now(timezone.utc)})
|
| 89 |
+
await db.execute(stmt)
|
| 90 |
+
await db.commit()
|
| 91 |
+
await _log_activity(db, request, f"workflow_manual_trigger:{workflow_name}", "Manual trigger via admin panel")
|
| 92 |
+
return {"success": True, "message": "Workflow run recorded (manual trigger)."}
|
app/api/agents.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AI Agents API — Antigravity Gateway."""
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict, Optional, List
|
| 4 |
+
from fastapi import APIRouter, Depends, HTTPException, Security, Request
|
| 5 |
+
from fastapi.security.api_key import APIKeyHeader
|
| 6 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
|
| 9 |
+
from app.database import get_db
|
| 10 |
+
from app.services.antigravity import AntigravityOrchestrator
|
| 11 |
+
from app.services.orchestrator_service import Orchestrator
|
| 12 |
+
from app.services.deploy_service import DeployService
|
| 13 |
+
from app.config.settings import settings
|
| 14 |
+
from sqlalchemy import text
|
| 15 |
+
|
| 16 |
+
router = APIRouter(prefix="/v1/agents", tags=["AI Agents"])
|
| 17 |
+
|
| 18 |
+
# Boardroom Security setup
|
| 19 |
+
API_KEY_NAME = "Authorization"
|
| 20 |
+
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
|
| 21 |
+
|
| 22 |
+
async def verify_boardroom_token(api_key_header: str = Security(api_key_header)):
|
| 23 |
+
if not api_key_header:
|
| 24 |
+
raise HTTPException(status_code=401, detail="Missing Authorization Header")
|
| 25 |
+
|
| 26 |
+
# Extract token (remove 'Bearer ' if present)
|
| 27 |
+
token = api_key_header.replace("Bearer ", "").strip()
|
| 28 |
+
|
| 29 |
+
# Check against the secure token in .env
|
| 30 |
+
expected_token = settings.security_webhook_token
|
| 31 |
+
if not expected_token or token != expected_token:
|
| 32 |
+
raise HTTPException(status_code=403, detail="Invalid Super Admin Token")
|
| 33 |
+
|
| 34 |
+
return token
|
| 35 |
+
|
| 36 |
+
class AgentTaskRequest(BaseModel):
|
| 37 |
+
agent_name: str
|
| 38 |
+
task_name: str
|
| 39 |
+
payload: Dict[str, Any]
|
| 40 |
+
priority: int = 0
|
| 41 |
+
user_email: Optional[str] = None
|
| 42 |
+
|
| 43 |
+
class BoardDirectiveRequest(BaseModel):
|
| 44 |
+
directive: str
|
| 45 |
+
|
| 46 |
+
@router.get("/boardroom/activities")
|
| 47 |
+
async def get_agent_activities(
|
| 48 |
+
db: AsyncSession = Depends(get_db),
|
| 49 |
+
_: str = Depends(verify_boardroom_token)
|
| 50 |
+
):
|
| 51 |
+
"""Fetch the latest agent activities for the Boardroom Kanban (Admin Only)."""
|
| 52 |
+
|
| 53 |
+
query = text("""
|
| 54 |
+
SELECT id, agent_id, task_description, status, next_action, requires_intervention, created_at, updated_at
|
| 55 |
+
FROM agent_activities
|
| 56 |
+
ORDER BY created_at DESC
|
| 57 |
+
LIMIT 50
|
| 58 |
+
""")
|
| 59 |
+
res = await db.execute(query)
|
| 60 |
+
rows = res.fetchall()
|
| 61 |
+
|
| 62 |
+
activities = []
|
| 63 |
+
for row in rows:
|
| 64 |
+
activities.append({
|
| 65 |
+
"id": row.id,
|
| 66 |
+
"agent_id": row.agent_id,
|
| 67 |
+
"task_description": row.task_description,
|
| 68 |
+
"status": row.status,
|
| 69 |
+
"next_action": row.next_action,
|
| 70 |
+
"requires_intervention": row.requires_intervention,
|
| 71 |
+
"created_at": row.created_at.isoformat(),
|
| 72 |
+
"updated_at": row.updated_at.isoformat()
|
| 73 |
+
})
|
| 74 |
+
return {"success": True, "data": activities}
|
| 75 |
+
|
| 76 |
+
@router.post("/boardroom/directive")
|
| 77 |
+
async def process_board_directive(
|
| 78 |
+
request: BoardDirectiveRequest
|
| 79 |
+
):
|
| 80 |
+
"""Send a high-level directive to the AI Organization Boardroom (CEO Orchestrated)."""
|
| 81 |
+
result = await Orchestrator.process_board_directive(request.directive)
|
| 82 |
+
return result
|
| 83 |
+
|
| 84 |
+
@router.post("/execute")
|
| 85 |
+
async def execute_agent_task(
|
| 86 |
+
request: AgentTaskRequest,
|
| 87 |
+
db: AsyncSession = Depends(get_db)
|
| 88 |
+
):
|
| 89 |
+
"""Execute an autonomous AI task through the Antigravity gateway."""
|
| 90 |
+
orchestrator = AntigravityOrchestrator(db)
|
| 91 |
+
|
| 92 |
+
result = await orchestrator.execute_task(
|
| 93 |
+
agent_name=request.agent_name,
|
| 94 |
+
task_name=request.task_name,
|
| 95 |
+
payload=request.payload,
|
| 96 |
+
priority=request.priority,
|
| 97 |
+
user_email=request.user_email
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if result.get("status") == "error":
|
| 101 |
+
raise HTTPException(status_code=503, detail=result.get("message"))
|
| 102 |
+
|
| 103 |
+
return result
|
| 104 |
+
|
| 105 |
+
@router.get("/stats")
|
| 106 |
+
async def get_agent_stats(
|
| 107 |
+
db: AsyncSession = Depends(get_db)
|
| 108 |
+
):
|
| 109 |
+
"""Exposes Antigravity Command Center data for the Admin Dashboard."""
|
| 110 |
+
orchestrator = AntigravityOrchestrator(db)
|
| 111 |
+
stats = await orchestrator.get_command_center_stats()
|
| 112 |
+
return stats
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@router.post('/deploy/preview')
|
| 116 |
+
async def trigger_preview(request: Request):
|
| 117 |
+
body = await request.json()
|
| 118 |
+
project = body.get('project', 'main-frontend-native')
|
| 119 |
+
# Trigger CF preview and notify CEO
|
| 120 |
+
deploy_resp = DeployService.trigger_cloudflare_preview(project)
|
| 121 |
+
if not deploy_resp.get('success'):
|
| 122 |
+
return {'success': False, 'error': deploy_resp.get('error')}
|
| 123 |
+
preview_url = deploy_resp.get('preview_url')
|
| 124 |
+
deploy_id = deploy_resp.get('raw', {}).get('result', {}).get('id', 'unknown')
|
| 125 |
+
DeployService.notify_ceo_preview(preview_url, deploy_id)
|
| 126 |
+
return {'success': True, 'preview_url': preview_url, 'deploy_id': deploy_id}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class HealApprovalRequest(BaseModel):
|
| 130 |
+
task_id: str
|
| 131 |
+
approved: bool
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@router.post("/heal/approve")
|
| 135 |
+
async def approve_heal_task(
|
| 136 |
+
request: HealApprovalRequest,
|
| 137 |
+
req: Request,
|
| 138 |
+
db: AsyncSession = Depends(get_db)
|
| 139 |
+
):
|
| 140 |
+
"""
|
| 141 |
+
Receives authorization to apply code patch and deploy sync for a failed task.
|
| 142 |
+
Enforces header verification (X-Webhook-Token).
|
| 143 |
+
"""
|
| 144 |
+
import os
|
| 145 |
+
import json
|
| 146 |
+
import shutil
|
| 147 |
+
import subprocess
|
| 148 |
+
from datetime import datetime
|
| 149 |
+
from loguru import logger
|
| 150 |
+
from app.models.content import KnowledgeQueue
|
| 151 |
+
|
| 152 |
+
# 1. Verification of incoming token
|
| 153 |
+
received_token = req.headers.get("X-Security-Token") or req.headers.get("X-Webhook-Token")
|
| 154 |
+
expected_token = settings.webhook_secret or os.getenv("WEBHOOK_SECRET", "briga_secret_webhook_123_xyz")
|
| 155 |
+
if not received_token or received_token != expected_token:
|
| 156 |
+
logger.warning("[CTOAgent Webhook] Unauthorized approval attempt.")
|
| 157 |
+
raise HTTPException(status_code=403, detail="Unauthorized webhook token")
|
| 158 |
+
|
| 159 |
+
if not request.approved:
|
| 160 |
+
return {"success": False, "message": "Approval rejected by client"}
|
| 161 |
+
|
| 162 |
+
# 2. Fetch the task from knowledge_queue
|
| 163 |
+
from sqlalchemy import select
|
| 164 |
+
stmt = select(KnowledgeQueue).where(KnowledgeQueue.id == request.task_id)
|
| 165 |
+
res = await db.execute(stmt)
|
| 166 |
+
task = res.scalar_one_or_none()
|
| 167 |
+
if not task:
|
| 168 |
+
raise HTTPException(status_code=404, detail="Task not found in queue")
|
| 169 |
+
|
| 170 |
+
# Parse fact JSON
|
| 171 |
+
try:
|
| 172 |
+
fact_data = json.loads(task.fact) if isinstance(task.fact, str) else task.fact
|
| 173 |
+
if not isinstance(fact_data, dict):
|
| 174 |
+
fact_data = {}
|
| 175 |
+
except Exception:
|
| 176 |
+
fact_data = {}
|
| 177 |
+
|
| 178 |
+
target_file = fact_data.get("target_file")
|
| 179 |
+
target_code = fact_data.get("target_code_to_replace")
|
| 180 |
+
replacement_code = fact_data.get("replacement_code")
|
| 181 |
+
|
| 182 |
+
if not target_file or not target_code:
|
| 183 |
+
raise HTTPException(status_code=400, detail="Missing patch parameters in task fact data")
|
| 184 |
+
|
| 185 |
+
# 3. Resolve file paths
|
| 186 |
+
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 187 |
+
if not os.path.isabs(target_file):
|
| 188 |
+
abs_path = os.path.join(base_dir, target_file)
|
| 189 |
+
else:
|
| 190 |
+
abs_path = target_file
|
| 191 |
+
|
| 192 |
+
if not os.path.exists(abs_path):
|
| 193 |
+
# Fallback to direct path check
|
| 194 |
+
abs_path = target_file
|
| 195 |
+
if not os.path.exists(abs_path):
|
| 196 |
+
raise HTTPException(status_code=404, detail=f"Target file {target_file} not found in workspace")
|
| 197 |
+
|
| 198 |
+
# Create Safety Backup (.bak)
|
| 199 |
+
try:
|
| 200 |
+
backup_path = abs_path + ".bak"
|
| 201 |
+
shutil.copy2(abs_path, backup_path)
|
| 202 |
+
logger.info(f"[CTOAgent Webhook] Created safety backup at {backup_path}")
|
| 203 |
+
except Exception as e:
|
| 204 |
+
logger.error(f"[CTOAgent Webhook] Backup failed: {e}")
|
| 205 |
+
raise HTTPException(status_code=500, detail=f"Failed to create file backup: {str(e)}")
|
| 206 |
+
|
| 207 |
+
# Replace content and compile-check
|
| 208 |
+
try:
|
| 209 |
+
with open(abs_path, "r", encoding="utf-8") as f:
|
| 210 |
+
content = f.read()
|
| 211 |
+
|
| 212 |
+
if target_code not in content:
|
| 213 |
+
raise HTTPException(status_code=400, detail="Target code block not found in file content")
|
| 214 |
+
|
| 215 |
+
new_content = content.replace(target_code, replacement_code)
|
| 216 |
+
|
| 217 |
+
# Dry-run compile check (if Python)
|
| 218 |
+
if abs_path.endswith(".py"):
|
| 219 |
+
try:
|
| 220 |
+
compile(new_content, abs_path, "exec")
|
| 221 |
+
logger.info("[CTOAgent Webhook] Patch dry-run compile validation passed.")
|
| 222 |
+
except Exception as ce:
|
| 223 |
+
logger.error(f"[CTOAgent Webhook] Compilation error: {ce}")
|
| 224 |
+
raise HTTPException(status_code=422, detail=f"Patch compilation check failed: {str(ce)}")
|
| 225 |
+
|
| 226 |
+
# Write verified patch
|
| 227 |
+
with open(abs_path, "w", encoding="utf-8") as f:
|
| 228 |
+
f.write(new_content)
|
| 229 |
+
logger.info(f"[CTOAgent Webhook] Patch applied successfully to {abs_path}")
|
| 230 |
+
except HTTPException:
|
| 231 |
+
raise
|
| 232 |
+
except Exception as e:
|
| 233 |
+
logger.error(f"[CTOAgent Webhook] Error writing patch: {e}")
|
| 234 |
+
raise HTTPException(status_code=500, detail=f"Failed to write patch: {str(e)}")
|
| 235 |
+
|
| 236 |
+
# 4. RUN DEPLOYMENT PIPELINE
|
| 237 |
+
deploy_output = []
|
| 238 |
+
try:
|
| 239 |
+
workspace_root = os.path.dirname(base_dir)
|
| 240 |
+
git_root = os.path.join(workspace_root, "brigawan")
|
| 241 |
+
|
| 242 |
+
# Git operations (best-effort)
|
| 243 |
+
if os.path.exists(git_root):
|
| 244 |
+
subprocess.run(["git", "add", "-A"], cwd=git_root, capture_output=True, text=True)
|
| 245 |
+
commit_res = subprocess.run(["git", "commit", "-m", f"auto-heal: patch {os.path.basename(target_file)} via CTO Agent"], cwd=git_root, capture_output=True, text=True)
|
| 246 |
+
push_res = subprocess.run(["git", "push", "origin", "master"], cwd=git_root, capture_output=True, text=True)
|
| 247 |
+
deploy_output.append(f"Git commit/push exit code: {push_res.returncode}")
|
| 248 |
+
|
| 249 |
+
# Run split_monolith.py
|
| 250 |
+
split_script = os.path.join(workspace_root, "split_monolith.py")
|
| 251 |
+
if os.path.exists(split_script):
|
| 252 |
+
split_res = subprocess.run(["python", "split_monolith.py"], cwd=workspace_root, capture_output=True, text=True)
|
| 253 |
+
deploy_output.append(f"split_monolith exit code: {split_res.returncode}")
|
| 254 |
+
|
| 255 |
+
# Run hf upload
|
| 256 |
+
hf_res = subprocess.run([
|
| 257 |
+
"hf", "upload", "yabeskn/briga-agent-worker",
|
| 258 |
+
"./spaces/briga-agent-worker/", ".", "--repo-type", "space"
|
| 259 |
+
], cwd=workspace_root, capture_output=True, text=True)
|
| 260 |
+
deploy_output.append(f"hf upload exit code: {hf_res.returncode}")
|
| 261 |
+
|
| 262 |
+
except Exception as de:
|
| 263 |
+
logger.error(f"[CTOAgent Webhook] Deploy sync error: {de}")
|
| 264 |
+
deploy_output.append(f"Deploy sync failed: {str(de)}")
|
| 265 |
+
|
| 266 |
+
# 5. Update Task Status
|
| 267 |
+
task.status = "Healed"
|
| 268 |
+
task.timestamp = datetime.now()
|
| 269 |
+
fact_data["healing_logs"] = deploy_output
|
| 270 |
+
task.fact = json.dumps(fact_data)
|
| 271 |
+
await db.commit()
|
| 272 |
+
|
| 273 |
+
return {"success": True, "message": f"Patch applied to {target_file}", "logs": deploy_output}
|
app/api/career.py
CHANGED
|
@@ -1,141 +1,141 @@
|
|
| 1 |
-
"""Career history API router.
|
| 2 |
-
|
| 3 |
-
Provides endpoints for managing secure experiences and credentials.
|
| 4 |
-
Enforces PDP compliance and cryptographic integrity checks.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
from typing import List, Optional
|
| 8 |
-
from uuid import UUID
|
| 9 |
-
|
| 10 |
-
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
| 11 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
-
|
| 13 |
-
from app.database import get_db
|
| 14 |
-
from app.schemas.career import (
|
| 15 |
-
ExperienceCreate, ExperienceRead, ExperiencePublicRead,
|
| 16 |
-
CredentialCreate, CredentialRead, CredentialPublicRead,
|
| 17 |
-
ProfileRead, ProfilePublicRead, OrganizationRead
|
| 18 |
-
)
|
| 19 |
-
from app.services.career_service import career_service
|
| 20 |
-
from app.services.audit_service import audit_service
|
| 21 |
-
from app.utils.errors import error_response, ErrorCode
|
| 22 |
-
|
| 23 |
-
router = APIRouter(prefix="/v1/career", tags=["Career History"])
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def get_current_user_id(request: Request) -> UUID:
|
| 27 |
-
"""Extract user UUID from request state (set by AuthMiddleware)."""
|
| 28 |
-
user = getattr(request.state, "user", None)
|
| 29 |
-
if not user or "sub" not in user:
|
| 30 |
-
raise HTTPException(
|
| 31 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 32 |
-
detail="Authentication required"
|
| 33 |
-
)
|
| 34 |
-
return UUID(user["sub"])
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
# ─── Experience ─────────────────────────────────────────────────────────────
|
| 38 |
-
|
| 39 |
-
@router.post("/experience", response_model=ExperienceRead)
|
| 40 |
-
async def add_experience(
|
| 41 |
-
data: ExperienceCreate,
|
| 42 |
-
db: AsyncSession = Depends(get_db),
|
| 43 |
-
user_id: UUID = Depends(get_current_user_id)
|
| 44 |
-
):
|
| 45 |
-
"""Add a new employment record. Payload is AES-256 encrypted before storage."""
|
| 46 |
-
try:
|
| 47 |
-
return await career_service.add_experience(db, user_id, data)
|
| 48 |
-
except Exception as e:
|
| 49 |
-
raise HTTPException(
|
| 50 |
-
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 51 |
-
detail=f"Failed to save experience: {str(e)}"
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
@router.get("/experience", response_model=List[ExperienceRead])
|
| 56 |
-
async def list_experiences(
|
| 57 |
-
db: AsyncSession = Depends(get_db),
|
| 58 |
-
user_id: UUID = Depends(get_current_user_id)
|
| 59 |
-
):
|
| 60 |
-
"""Retrieve all personal experience records (decrypted)."""
|
| 61 |
-
return await career_service.list_experiences(db, user_id)
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
# ─── Credential ─────────────────────────────────────────────────────────────
|
| 65 |
-
|
| 66 |
-
@router.post("/credential", response_model=CredentialRead)
|
| 67 |
-
async def add_credential(
|
| 68 |
-
data: CredentialCreate,
|
| 69 |
-
issuer_signature: str,
|
| 70 |
-
db: AsyncSession = Depends(get_db),
|
| 71 |
-
user_id: UUID = Depends(get_current_user_id)
|
| 72 |
-
):
|
| 73 |
-
"""Add a new certification. Requires a valid issuer signature."""
|
| 74 |
-
try:
|
| 75 |
-
return await career_service.add_credential(db, user_id, data, issuer_signature)
|
| 76 |
-
except Exception as e:
|
| 77 |
-
raise HTTPException(
|
| 78 |
-
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 79 |
-
detail=f"Failed to save credential: {str(e)}"
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
@router.get("/credential", response_model=List[CredentialRead])
|
| 84 |
-
async def list_credentials(
|
| 85 |
-
db: AsyncSession = Depends(get_db),
|
| 86 |
-
user_id: UUID = Depends(get_current_user_id)
|
| 87 |
-
):
|
| 88 |
-
"""Retrieve all personal credentials (decrypted)."""
|
| 89 |
-
return await career_service.list_credentials(db, user_id)
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
# ─── Public Profile ─────────────────────────────────────────────────────────
|
| 93 |
-
|
| 94 |
-
@router.get("/profile/{profile_id}", response_model=ProfilePublicRead)
|
| 95 |
-
async def get_public_profile(
|
| 96 |
-
profile_id: UUID,
|
| 97 |
-
db: AsyncSession = Depends(get_db)
|
| 98 |
-
):
|
| 99 |
-
"""Fetch public profile data with masked email and verified counts."""
|
| 100 |
-
profile = await career_service.get_profile(db, profile_id)
|
| 101 |
-
if not profile:
|
| 102 |
-
raise HTTPException(status_code=404, detail="Profile not found")
|
| 103 |
-
|
| 104 |
-
# In a real implementation, this would query the public view or
|
| 105 |
-
# use a specific public schema/mapper.
|
| 106 |
-
return ProfilePublicRead(
|
| 107 |
-
id=profile.id,
|
| 108 |
-
full_name=profile.full_name,
|
| 109 |
-
industry=profile.industry,
|
| 110 |
-
general_skills=profile.general_skills or [],
|
| 111 |
-
masked_email="***@***.***", # Masking logic should be here or in model
|
| 112 |
-
verified_credential_count=0, # Placeholder
|
| 113 |
-
created_at=profile.created_at
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
# ─── System / Admin Operations ──────────────────────────────────────────────
|
| 118 |
-
|
| 119 |
-
@router.get("/system/verify-audit")
|
| 120 |
-
async def verify_audit_trail(
|
| 121 |
-
db: AsyncSession = Depends(get_db),
|
| 122 |
-
user_role: str = Depends(lambda r: getattr(r.state, "user_role", "talent"))
|
| 123 |
-
):
|
| 124 |
-
"""Verify the integrity of the cryptographic audit trail (Admin only)."""
|
| 125 |
-
if user_role != "admin":
|
| 126 |
-
raise HTTPException(status_code=403, detail="Admin access required")
|
| 127 |
-
|
| 128 |
-
return await audit_service.verify_integrity(db)
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
@router.post("/system/archive-logs")
|
| 132 |
-
async def run_audit_archiving(
|
| 133 |
-
days: int = 365,
|
| 134 |
-
db: AsyncSession = Depends(get_db),
|
| 135 |
-
user_role: str = Depends(lambda r: getattr(r.state, "user_role", "talent"))
|
| 136 |
-
):
|
| 137 |
-
"""Archive old audit logs to cold storage (Admin only)."""
|
| 138 |
-
if user_role != "admin":
|
| 139 |
-
raise HTTPException(status_code=403, detail="Admin access required")
|
| 140 |
-
|
| 141 |
-
return await audit_service.run_archiving(db, days_threshold=days)
|
|
|
|
| 1 |
+
"""Career history API router.
|
| 2 |
+
|
| 3 |
+
Provides endpoints for managing secure experiences and credentials.
|
| 4 |
+
Enforces PDP compliance and cryptographic integrity checks.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import List, Optional
|
| 8 |
+
from uuid import UUID
|
| 9 |
+
|
| 10 |
+
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
| 11 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
+
|
| 13 |
+
from app.database import get_db
|
| 14 |
+
from app.schemas.career import (
|
| 15 |
+
ExperienceCreate, ExperienceRead, ExperiencePublicRead,
|
| 16 |
+
CredentialCreate, CredentialRead, CredentialPublicRead,
|
| 17 |
+
ProfileRead, ProfilePublicRead, OrganizationRead
|
| 18 |
+
)
|
| 19 |
+
from app.services.career_service import career_service
|
| 20 |
+
from app.services.audit_service import audit_service
|
| 21 |
+
from app.utils.errors import error_response, ErrorCode
|
| 22 |
+
|
| 23 |
+
router = APIRouter(prefix="/v1/career", tags=["Career History"])
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_current_user_id(request: Request) -> UUID:
|
| 27 |
+
"""Extract user UUID from request state (set by AuthMiddleware)."""
|
| 28 |
+
user = getattr(request.state, "user", None)
|
| 29 |
+
if not user or "sub" not in user:
|
| 30 |
+
raise HTTPException(
|
| 31 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 32 |
+
detail="Authentication required"
|
| 33 |
+
)
|
| 34 |
+
return UUID(user["sub"])
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# ─── Experience ─────────────────────────────────────────────────────────────
|
| 38 |
+
|
| 39 |
+
@router.post("/experience", response_model=ExperienceRead)
|
| 40 |
+
async def add_experience(
|
| 41 |
+
data: ExperienceCreate,
|
| 42 |
+
db: AsyncSession = Depends(get_db),
|
| 43 |
+
user_id: UUID = Depends(get_current_user_id)
|
| 44 |
+
):
|
| 45 |
+
"""Add a new employment record. Payload is AES-256 encrypted before storage."""
|
| 46 |
+
try:
|
| 47 |
+
return await career_service.add_experience(db, user_id, data)
|
| 48 |
+
except Exception as e:
|
| 49 |
+
raise HTTPException(
|
| 50 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 51 |
+
detail=f"Failed to save experience: {str(e)}"
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@router.get("/experience", response_model=List[ExperienceRead])
|
| 56 |
+
async def list_experiences(
|
| 57 |
+
db: AsyncSession = Depends(get_db),
|
| 58 |
+
user_id: UUID = Depends(get_current_user_id)
|
| 59 |
+
):
|
| 60 |
+
"""Retrieve all personal experience records (decrypted)."""
|
| 61 |
+
return await career_service.list_experiences(db, user_id)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# ─── Credential ─────────────────────────────────────────────────────────────
|
| 65 |
+
|
| 66 |
+
@router.post("/credential", response_model=CredentialRead)
|
| 67 |
+
async def add_credential(
|
| 68 |
+
data: CredentialCreate,
|
| 69 |
+
issuer_signature: str,
|
| 70 |
+
db: AsyncSession = Depends(get_db),
|
| 71 |
+
user_id: UUID = Depends(get_current_user_id)
|
| 72 |
+
):
|
| 73 |
+
"""Add a new certification. Requires a valid issuer signature."""
|
| 74 |
+
try:
|
| 75 |
+
return await career_service.add_credential(db, user_id, data, issuer_signature)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
raise HTTPException(
|
| 78 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 79 |
+
detail=f"Failed to save credential: {str(e)}"
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@router.get("/credential", response_model=List[CredentialRead])
|
| 84 |
+
async def list_credentials(
|
| 85 |
+
db: AsyncSession = Depends(get_db),
|
| 86 |
+
user_id: UUID = Depends(get_current_user_id)
|
| 87 |
+
):
|
| 88 |
+
"""Retrieve all personal credentials (decrypted)."""
|
| 89 |
+
return await career_service.list_credentials(db, user_id)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# ─── Public Profile ─────────────────────────────────────────────────────────
|
| 93 |
+
|
| 94 |
+
@router.get("/profile/{profile_id}", response_model=ProfilePublicRead)
|
| 95 |
+
async def get_public_profile(
|
| 96 |
+
profile_id: UUID,
|
| 97 |
+
db: AsyncSession = Depends(get_db)
|
| 98 |
+
):
|
| 99 |
+
"""Fetch public profile data with masked email and verified counts."""
|
| 100 |
+
profile = await career_service.get_profile(db, profile_id)
|
| 101 |
+
if not profile:
|
| 102 |
+
raise HTTPException(status_code=404, detail="Profile not found")
|
| 103 |
+
|
| 104 |
+
# In a real implementation, this would query the public view or
|
| 105 |
+
# use a specific public schema/mapper.
|
| 106 |
+
return ProfilePublicRead(
|
| 107 |
+
id=profile.id,
|
| 108 |
+
full_name=profile.full_name,
|
| 109 |
+
industry=profile.industry,
|
| 110 |
+
general_skills=profile.general_skills or [],
|
| 111 |
+
masked_email="***@***.***", # Masking logic should be here or in model
|
| 112 |
+
verified_credential_count=0, # Placeholder
|
| 113 |
+
created_at=profile.created_at
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# ─── System / Admin Operations ──────────────────────────────────────────────
|
| 118 |
+
|
| 119 |
+
@router.get("/system/verify-audit")
|
| 120 |
+
async def verify_audit_trail(
|
| 121 |
+
db: AsyncSession = Depends(get_db),
|
| 122 |
+
user_role: str = Depends(lambda r: getattr(r.state, "user_role", "talent"))
|
| 123 |
+
):
|
| 124 |
+
"""Verify the integrity of the cryptographic audit trail (Admin only)."""
|
| 125 |
+
if user_role != "admin":
|
| 126 |
+
raise HTTPException(status_code=403, detail="Admin access required")
|
| 127 |
+
|
| 128 |
+
return await audit_service.verify_integrity(db)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@router.post("/system/archive-logs")
|
| 132 |
+
async def run_audit_archiving(
|
| 133 |
+
days: int = 365,
|
| 134 |
+
db: AsyncSession = Depends(get_db),
|
| 135 |
+
user_role: str = Depends(lambda r: getattr(r.state, "user_role", "talent"))
|
| 136 |
+
):
|
| 137 |
+
"""Archive old audit logs to cold storage (Admin only)."""
|
| 138 |
+
if user_role != "admin":
|
| 139 |
+
raise HTTPException(status_code=403, detail="Admin access required")
|
| 140 |
+
|
| 141 |
+
return await audit_service.run_archiving(db, days_threshold=days)
|
app/api/debug_admin.py
CHANGED
|
@@ -1,29 +1,29 @@
|
|
| 1 |
-
from fastapi import APIRouter, Depends, Request, HTTPException
|
| 2 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
-
from sqlalchemy import select
|
| 4 |
-
|
| 5 |
-
from app.database import get_db
|
| 6 |
-
from app.models.system import WorkflowConfig
|
| 7 |
-
|
| 8 |
-
router = APIRouter(prefix="/v1/debug", tags=["Debug"])
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
@router.get("/workflows")
|
| 12 |
-
async def debug_list_workflows(request: Request, db: AsyncSession = Depends(get_db)):
|
| 13 |
-
"""Debug endpoint: admin-only workflow listing."""
|
| 14 |
-
role = getattr(request.state, "user_role", None)
|
| 15 |
-
if role not in ("admin", "ADMIN"):
|
| 16 |
-
raise HTTPException(status_code=403, detail="Admin role required")
|
| 17 |
-
|
| 18 |
-
result = await db.execute(select(WorkflowConfig))
|
| 19 |
-
rows = result.scalars().all()
|
| 20 |
-
return {"success": True, "workflows": [
|
| 21 |
-
{
|
| 22 |
-
"workflow_name": r.workflow_name,
|
| 23 |
-
"is_active": r.is_active,
|
| 24 |
-
"schedule_cron": r.schedule_cron,
|
| 25 |
-
"last_run": r.last_run,
|
| 26 |
-
"updated_at": r.updated_at,
|
| 27 |
-
}
|
| 28 |
-
for r in rows
|
| 29 |
-
]}
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, Request, HTTPException
|
| 2 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
+
from sqlalchemy import select
|
| 4 |
+
|
| 5 |
+
from app.database import get_db
|
| 6 |
+
from app.models.system import WorkflowConfig
|
| 7 |
+
|
| 8 |
+
router = APIRouter(prefix="/v1/debug", tags=["Debug"])
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@router.get("/workflows")
|
| 12 |
+
async def debug_list_workflows(request: Request, db: AsyncSession = Depends(get_db)):
|
| 13 |
+
"""Debug endpoint: admin-only workflow listing."""
|
| 14 |
+
role = getattr(request.state, "user_role", None)
|
| 15 |
+
if role not in ("admin", "ADMIN"):
|
| 16 |
+
raise HTTPException(status_code=403, detail="Admin role required")
|
| 17 |
+
|
| 18 |
+
result = await db.execute(select(WorkflowConfig))
|
| 19 |
+
rows = result.scalars().all()
|
| 20 |
+
return {"success": True, "workflows": [
|
| 21 |
+
{
|
| 22 |
+
"workflow_name": r.workflow_name,
|
| 23 |
+
"is_active": r.is_active,
|
| 24 |
+
"schedule_cron": r.schedule_cron,
|
| 25 |
+
"last_run": r.last_run,
|
| 26 |
+
"updated_at": r.updated_at,
|
| 27 |
+
}
|
| 28 |
+
for r in rows
|
| 29 |
+
]}
|
app/api/interview.py
CHANGED
|
@@ -1,174 +1,174 @@
|
|
| 1 |
-
"""Interview & AI Notulen API Routes.
|
| 2 |
-
|
| 3 |
-
Endpoints:
|
| 4 |
-
POST /v1/interviews/schedule — Schedule interview (costs 5 coins)
|
| 5 |
-
POST /v1/interviews/{id}/transcript — Save transcript
|
| 6 |
-
POST /v1/interviews/{id}/notulen — Generate AI Notulen (meeting summary)
|
| 7 |
-
POST /v1/interviews/{id}/competency — Analyze competency
|
| 8 |
-
POST /v1/interviews/compare — Multi-candidate comparison
|
| 9 |
-
GET /v1/interviews — List interviews for employer
|
| 10 |
-
GET /v1/interviews/{id} — Get interview detail
|
| 11 |
-
|
| 12 |
-
All endpoints require employer authentication.
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
-
from fastapi import APIRouter, Depends, Query, Request
|
| 16 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 17 |
-
|
| 18 |
-
from app.database import get_db
|
| 19 |
-
from app.schemas.interview import (
|
| 20 |
-
ComparisonRequest,
|
| 21 |
-
ComparisonResponse,
|
| 22 |
-
CompetencyAnalysisResponse,
|
| 23 |
-
InterviewDetailResponse,
|
| 24 |
-
InterviewListResponse,
|
| 25 |
-
NotulenResponse,
|
| 26 |
-
SaveTranscriptRequest,
|
| 27 |
-
SaveTranscriptResponse,
|
| 28 |
-
ScheduleInterviewRequest,
|
| 29 |
-
ScheduleInterviewResponse,
|
| 30 |
-
)
|
| 31 |
-
from app.services.interview_service import (
|
| 32 |
-
analyze_competency,
|
| 33 |
-
compare_candidates,
|
| 34 |
-
generate_ai_notulen,
|
| 35 |
-
get_interview_detail,
|
| 36 |
-
list_interviews,
|
| 37 |
-
save_transcript,
|
| 38 |
-
schedule_interview,
|
| 39 |
-
)
|
| 40 |
-
from app.utils.errors import ErrorCode, raise_error
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
router = APIRouter(prefix="/v1/interviews", tags=["Interviews & AI Notulen"])
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
@router.post("/schedule", response_model=ScheduleInterviewResponse)
|
| 47 |
-
async def api_schedule_interview(
|
| 48 |
-
req: Request,
|
| 49 |
-
body: ScheduleInterviewRequest,
|
| 50 |
-
db: AsyncSession = Depends(get_db),
|
| 51 |
-
):
|
| 52 |
-
"""Schedule an interview with a candidate.
|
| 53 |
-
Costs 5 coins (except Enterprise tier — free).
|
| 54 |
-
"""
|
| 55 |
-
email = getattr(req.state, "user_email", None)
|
| 56 |
-
if not email:
|
| 57 |
-
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 58 |
-
|
| 59 |
-
return await schedule_interview(
|
| 60 |
-
db=db,
|
| 61 |
-
recruiter_email=email,
|
| 62 |
-
candidate_id=body.candidate_id,
|
| 63 |
-
scheduled_time=body.scheduled_time,
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
@router.post("/{interview_id}/transcript", response_model=SaveTranscriptResponse)
|
| 68 |
-
async def api_save_transcript(
|
| 69 |
-
req: Request,
|
| 70 |
-
interview_id: str,
|
| 71 |
-
body: SaveTranscriptRequest,
|
| 72 |
-
db: AsyncSession = Depends(get_db),
|
| 73 |
-
):
|
| 74 |
-
"""Save interview transcript after completion.
|
| 75 |
-
Sets status to "Completed".
|
| 76 |
-
"""
|
| 77 |
-
email = getattr(req.state, "user_email", None)
|
| 78 |
-
if not email:
|
| 79 |
-
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 80 |
-
|
| 81 |
-
return await save_transcript(
|
| 82 |
-
db=db,
|
| 83 |
-
interview_id=interview_id,
|
| 84 |
-
transcript_text=body.transcript_text,
|
| 85 |
-
)
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
@router.post("/{interview_id}/notulen", response_model=NotulenResponse)
|
| 89 |
-
async def api_generate_notulen(
|
| 90 |
-
req: Request,
|
| 91 |
-
interview_id: str,
|
| 92 |
-
db: AsyncSession = Depends(get_db),
|
| 93 |
-
):
|
| 94 |
-
"""Generate AI Notulen (meeting summary) from interview transcript.
|
| 95 |
-
Uses Gemini MEDIUM tier (3.5 Flash).
|
| 96 |
-
"""
|
| 97 |
-
email = getattr(req.state, "user_email", None)
|
| 98 |
-
if not email:
|
| 99 |
-
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 100 |
-
|
| 101 |
-
return await generate_ai_notulen(
|
| 102 |
-
db=db,
|
| 103 |
-
interview_id=interview_id,
|
| 104 |
-
)
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
@router.post("/{interview_id}/competency", response_model=CompetencyAnalysisResponse)
|
| 108 |
-
async def api_analyze_competency(
|
| 109 |
-
req: Request,
|
| 110 |
-
interview_id: str,
|
| 111 |
-
db: AsyncSession = Depends(get_db),
|
| 112 |
-
):
|
| 113 |
-
"""Analyze candidate competency from interview transcript.
|
| 114 |
-
Uses Gemini MEDIUM tier for structured scoring.
|
| 115 |
-
"""
|
| 116 |
-
email = getattr(req.state, "user_email", None)
|
| 117 |
-
if not email:
|
| 118 |
-
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 119 |
-
|
| 120 |
-
return await analyze_competency(
|
| 121 |
-
db=db,
|
| 122 |
-
interview_id=interview_id,
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
@router.post("/compare", response_model=ComparisonResponse)
|
| 127 |
-
async def api_compare_candidates(
|
| 128 |
-
req: Request,
|
| 129 |
-
body: ComparisonRequest,
|
| 130 |
-
db: AsyncSession = Depends(get_db),
|
| 131 |
-
):
|
| 132 |
-
"""Compare multiple candidates from their interviews.
|
| 133 |
-
Uses Gemini HIGH tier (3.1 Pro) for intelligent comparison.
|
| 134 |
-
Min 2 candidates, max 10.
|
| 135 |
-
"""
|
| 136 |
-
email = getattr(req.state, "user_email", None)
|
| 137 |
-
if not email:
|
| 138 |
-
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 139 |
-
|
| 140 |
-
return await compare_candidates(
|
| 141 |
-
db=db,
|
| 142 |
-
interview_ids=body.interview_ids,
|
| 143 |
-
)
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
@router.get("", response_model=InterviewListResponse)
|
| 147 |
-
async def api_list_interviews(
|
| 148 |
-
req: Request,
|
| 149 |
-
status: str = Query(None, description="Filter by status: Scheduled, Completed, Cancelled"),
|
| 150 |
-
db: AsyncSession = Depends(get_db),
|
| 151 |
-
):
|
| 152 |
-
"""List all interviews for the authenticated employer."""
|
| 153 |
-
email = getattr(req.state, "user_email", None)
|
| 154 |
-
if not email:
|
| 155 |
-
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 156 |
-
|
| 157 |
-
return await list_interviews(db=db, email=email, status=status)
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
@router.get("/{interview_id}", response_model=InterviewDetailResponse)
|
| 161 |
-
async def api_get_interview_detail(
|
| 162 |
-
req: Request,
|
| 163 |
-
interview_id: str,
|
| 164 |
-
db: AsyncSession = Depends(get_db),
|
| 165 |
-
):
|
| 166 |
-
"""Get full interview detail with transcript, AI summary, and competency analysis."""
|
| 167 |
-
email = getattr(req.state, "user_email", None)
|
| 168 |
-
if not email:
|
| 169 |
-
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 170 |
-
|
| 171 |
-
return await get_interview_detail(
|
| 172 |
-
db=db,
|
| 173 |
-
interview_id=interview_id,
|
| 174 |
-
)
|
|
|
|
| 1 |
+
"""Interview & AI Notulen API Routes.
|
| 2 |
+
|
| 3 |
+
Endpoints:
|
| 4 |
+
POST /v1/interviews/schedule — Schedule interview (costs 5 coins)
|
| 5 |
+
POST /v1/interviews/{id}/transcript — Save transcript
|
| 6 |
+
POST /v1/interviews/{id}/notulen — Generate AI Notulen (meeting summary)
|
| 7 |
+
POST /v1/interviews/{id}/competency — Analyze competency
|
| 8 |
+
POST /v1/interviews/compare — Multi-candidate comparison
|
| 9 |
+
GET /v1/interviews — List interviews for employer
|
| 10 |
+
GET /v1/interviews/{id} — Get interview detail
|
| 11 |
+
|
| 12 |
+
All endpoints require employer authentication.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from fastapi import APIRouter, Depends, Query, Request
|
| 16 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 17 |
+
|
| 18 |
+
from app.database import get_db
|
| 19 |
+
from app.schemas.interview import (
|
| 20 |
+
ComparisonRequest,
|
| 21 |
+
ComparisonResponse,
|
| 22 |
+
CompetencyAnalysisResponse,
|
| 23 |
+
InterviewDetailResponse,
|
| 24 |
+
InterviewListResponse,
|
| 25 |
+
NotulenResponse,
|
| 26 |
+
SaveTranscriptRequest,
|
| 27 |
+
SaveTranscriptResponse,
|
| 28 |
+
ScheduleInterviewRequest,
|
| 29 |
+
ScheduleInterviewResponse,
|
| 30 |
+
)
|
| 31 |
+
from app.services.interview_service import (
|
| 32 |
+
analyze_competency,
|
| 33 |
+
compare_candidates,
|
| 34 |
+
generate_ai_notulen,
|
| 35 |
+
get_interview_detail,
|
| 36 |
+
list_interviews,
|
| 37 |
+
save_transcript,
|
| 38 |
+
schedule_interview,
|
| 39 |
+
)
|
| 40 |
+
from app.utils.errors import ErrorCode, raise_error
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
router = APIRouter(prefix="/v1/interviews", tags=["Interviews & AI Notulen"])
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@router.post("/schedule", response_model=ScheduleInterviewResponse)
|
| 47 |
+
async def api_schedule_interview(
|
| 48 |
+
req: Request,
|
| 49 |
+
body: ScheduleInterviewRequest,
|
| 50 |
+
db: AsyncSession = Depends(get_db),
|
| 51 |
+
):
|
| 52 |
+
"""Schedule an interview with a candidate.
|
| 53 |
+
Costs 5 coins (except Enterprise tier — free).
|
| 54 |
+
"""
|
| 55 |
+
email = getattr(req.state, "user_email", None)
|
| 56 |
+
if not email:
|
| 57 |
+
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 58 |
+
|
| 59 |
+
return await schedule_interview(
|
| 60 |
+
db=db,
|
| 61 |
+
recruiter_email=email,
|
| 62 |
+
candidate_id=body.candidate_id,
|
| 63 |
+
scheduled_time=body.scheduled_time,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@router.post("/{interview_id}/transcript", response_model=SaveTranscriptResponse)
|
| 68 |
+
async def api_save_transcript(
|
| 69 |
+
req: Request,
|
| 70 |
+
interview_id: str,
|
| 71 |
+
body: SaveTranscriptRequest,
|
| 72 |
+
db: AsyncSession = Depends(get_db),
|
| 73 |
+
):
|
| 74 |
+
"""Save interview transcript after completion.
|
| 75 |
+
Sets status to "Completed".
|
| 76 |
+
"""
|
| 77 |
+
email = getattr(req.state, "user_email", None)
|
| 78 |
+
if not email:
|
| 79 |
+
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 80 |
+
|
| 81 |
+
return await save_transcript(
|
| 82 |
+
db=db,
|
| 83 |
+
interview_id=interview_id,
|
| 84 |
+
transcript_text=body.transcript_text,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@router.post("/{interview_id}/notulen", response_model=NotulenResponse)
|
| 89 |
+
async def api_generate_notulen(
|
| 90 |
+
req: Request,
|
| 91 |
+
interview_id: str,
|
| 92 |
+
db: AsyncSession = Depends(get_db),
|
| 93 |
+
):
|
| 94 |
+
"""Generate AI Notulen (meeting summary) from interview transcript.
|
| 95 |
+
Uses Gemini MEDIUM tier (3.5 Flash).
|
| 96 |
+
"""
|
| 97 |
+
email = getattr(req.state, "user_email", None)
|
| 98 |
+
if not email:
|
| 99 |
+
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 100 |
+
|
| 101 |
+
return await generate_ai_notulen(
|
| 102 |
+
db=db,
|
| 103 |
+
interview_id=interview_id,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@router.post("/{interview_id}/competency", response_model=CompetencyAnalysisResponse)
|
| 108 |
+
async def api_analyze_competency(
|
| 109 |
+
req: Request,
|
| 110 |
+
interview_id: str,
|
| 111 |
+
db: AsyncSession = Depends(get_db),
|
| 112 |
+
):
|
| 113 |
+
"""Analyze candidate competency from interview transcript.
|
| 114 |
+
Uses Gemini MEDIUM tier for structured scoring.
|
| 115 |
+
"""
|
| 116 |
+
email = getattr(req.state, "user_email", None)
|
| 117 |
+
if not email:
|
| 118 |
+
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 119 |
+
|
| 120 |
+
return await analyze_competency(
|
| 121 |
+
db=db,
|
| 122 |
+
interview_id=interview_id,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@router.post("/compare", response_model=ComparisonResponse)
|
| 127 |
+
async def api_compare_candidates(
|
| 128 |
+
req: Request,
|
| 129 |
+
body: ComparisonRequest,
|
| 130 |
+
db: AsyncSession = Depends(get_db),
|
| 131 |
+
):
|
| 132 |
+
"""Compare multiple candidates from their interviews.
|
| 133 |
+
Uses Gemini HIGH tier (3.1 Pro) for intelligent comparison.
|
| 134 |
+
Min 2 candidates, max 10.
|
| 135 |
+
"""
|
| 136 |
+
email = getattr(req.state, "user_email", None)
|
| 137 |
+
if not email:
|
| 138 |
+
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 139 |
+
|
| 140 |
+
return await compare_candidates(
|
| 141 |
+
db=db,
|
| 142 |
+
interview_ids=body.interview_ids,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@router.get("", response_model=InterviewListResponse)
|
| 147 |
+
async def api_list_interviews(
|
| 148 |
+
req: Request,
|
| 149 |
+
status: str = Query(None, description="Filter by status: Scheduled, Completed, Cancelled"),
|
| 150 |
+
db: AsyncSession = Depends(get_db),
|
| 151 |
+
):
|
| 152 |
+
"""List all interviews for the authenticated employer."""
|
| 153 |
+
email = getattr(req.state, "user_email", None)
|
| 154 |
+
if not email:
|
| 155 |
+
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 156 |
+
|
| 157 |
+
return await list_interviews(db=db, email=email, status=status)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@router.get("/{interview_id}", response_model=InterviewDetailResponse)
|
| 161 |
+
async def api_get_interview_detail(
|
| 162 |
+
req: Request,
|
| 163 |
+
interview_id: str,
|
| 164 |
+
db: AsyncSession = Depends(get_db),
|
| 165 |
+
):
|
| 166 |
+
"""Get full interview detail with transcript, AI summary, and competency analysis."""
|
| 167 |
+
email = getattr(req.state, "user_email", None)
|
| 168 |
+
if not email:
|
| 169 |
+
raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
|
| 170 |
+
|
| 171 |
+
return await get_interview_detail(
|
| 172 |
+
db=db,
|
| 173 |
+
interview_id=interview_id,
|
| 174 |
+
)
|
app/api/job.py
CHANGED
|
@@ -1,219 +1,219 @@
|
|
| 1 |
-
"""Job API Routes - Posting CRUD, Outreach, Compatibility, Vouchers, Limits."""
|
| 2 |
-
|
| 3 |
-
from typing import Optional
|
| 4 |
-
|
| 5 |
-
from fastapi import APIRouter, Depends, Query, Request
|
| 6 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
-
|
| 8 |
-
from app.database import get_db
|
| 9 |
-
from app.schemas.job import (
|
| 10 |
-
AnalyzeCompatibilityRequest, AnalyzeCompatibilityResponse,
|
| 11 |
-
CheckJobLimitResponse, CreateJobRequest, JobListResponse,
|
| 12 |
-
JobPostingResponse, OutreachRecordResponse, SendOutreachRequest,
|
| 13 |
-
SendOutreachResponse, UpdateJobStatusRequest,
|
| 14 |
-
VoucherGenerateRequest, VoucherGenerateResponse,
|
| 15 |
-
VoucherListResponse, VoucherRedeemRequest, VoucherRedeemResponse,
|
| 16 |
-
)
|
| 17 |
-
from app.services.job_service import (
|
| 18 |
-
analyze_job_compatibility, check_active_job_posting_limit,
|
| 19 |
-
create_job_posting, generate_vouchers, get_job_posting,
|
| 20 |
-
get_job_postings, get_lpk_vouchers, list_outreach_history,
|
| 21 |
-
record_pending_outreach, redeem_voucher, send_instant_outreach,
|
| 22 |
-
update_job_status,
|
| 23 |
-
)
|
| 24 |
-
|
| 25 |
-
router = APIRouter(prefix="/v1/jobs", tags=["Jobs"])
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def _check_auth(req: Request) -> Optional[str]:
|
| 29 |
-
return getattr(req.state, "user_email", None)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
@router.get("", response_model=JobListResponse)
|
| 33 |
-
async def api_get_jobs(
|
| 34 |
-
page: int = Query(1, ge=1),
|
| 35 |
-
limit: int = Query(10, ge=1, le=50),
|
| 36 |
-
db: AsyncSession = Depends(get_db),
|
| 37 |
-
):
|
| 38 |
-
result = await get_job_postings(db, page, limit)
|
| 39 |
-
return JobListResponse(
|
| 40 |
-
success=result.get("success", False),
|
| 41 |
-
page=result.get("page", page),
|
| 42 |
-
limit=result.get("limit", limit),
|
| 43 |
-
total=result.get("total", 0),
|
| 44 |
-
data=result.get("data", []),
|
| 45 |
-
error=result.get("error"),
|
| 46 |
-
)
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
@router.get("/{job_id}", response_model=JobPostingResponse)
|
| 50 |
-
async def api_get_job(
|
| 51 |
-
job_id: str,
|
| 52 |
-
db: AsyncSession = Depends(get_db),
|
| 53 |
-
):
|
| 54 |
-
result = await get_job_posting(db, job_id)
|
| 55 |
-
if not result.get("success"):
|
| 56 |
-
return JobPostingResponse(job_id=job_id, error=result.get("error", "Not found"))
|
| 57 |
-
data = result.get("data", {})
|
| 58 |
-
return JobPostingResponse(**data)
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
@router.post("", response_model=dict)
|
| 62 |
-
async def api_create_job(
|
| 63 |
-
req: Request,
|
| 64 |
-
body: CreateJobRequest,
|
| 65 |
-
db: AsyncSession = Depends(get_db),
|
| 66 |
-
):
|
| 67 |
-
email = _check_auth(req)
|
| 68 |
-
if not email:
|
| 69 |
-
return {"success": False, "error": "Authentication required."}
|
| 70 |
-
return await create_job_posting(db, email, body.model_dump())
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
@router.put("/status", response_model=dict)
|
| 74 |
-
async def api_update_job_status(
|
| 75 |
-
req: Request,
|
| 76 |
-
body: UpdateJobStatusRequest,
|
| 77 |
-
db: AsyncSession = Depends(get_db),
|
| 78 |
-
):
|
| 79 |
-
email = _check_auth(req)
|
| 80 |
-
if not email:
|
| 81 |
-
return {"success": False, "error": "Authentication required."}
|
| 82 |
-
return await update_job_status(db, body.job_id, body.status)
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
@router.get("/limit/check", response_model=CheckJobLimitResponse)
|
| 86 |
-
async def api_check_job_limit(
|
| 87 |
-
req: Request,
|
| 88 |
-
db: AsyncSession = Depends(get_db),
|
| 89 |
-
):
|
| 90 |
-
email = _check_auth(req)
|
| 91 |
-
if not email:
|
| 92 |
-
return CheckJobLimitResponse(allowed=False, error="Authentication required.")
|
| 93 |
-
result = await check_active_job_posting_limit(db, email)
|
| 94 |
-
return CheckJobLimitResponse(
|
| 95 |
-
allowed=result.get("allowed", False),
|
| 96 |
-
tier=result.get("tier", "free"),
|
| 97 |
-
active_count=result.get("active_count", 0),
|
| 98 |
-
limit=result.get("limit", 1),
|
| 99 |
-
error=result.get("error"),
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
@router.post("/analyze-compatibility", response_model=AnalyzeCompatibilityResponse)
|
| 104 |
-
async def api_analyze_compatibility(
|
| 105 |
-
req: Request,
|
| 106 |
-
body: AnalyzeCompatibilityRequest,
|
| 107 |
-
db: AsyncSession = Depends(get_db),
|
| 108 |
-
):
|
| 109 |
-
email = _check_auth(req)
|
| 110 |
-
if not email:
|
| 111 |
-
return AnalyzeCompatibilityResponse(success=False, error="Authentication required.")
|
| 112 |
-
result = await analyze_job_compatibility(db, email, body.job_id)
|
| 113 |
-
return AnalyzeCompatibilityResponse(
|
| 114 |
-
success=result.get("success", False),
|
| 115 |
-
data=result.get("data"),
|
| 116 |
-
error=result.get("error"),
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
@router.post("/outreach/record", response_model=OutreachRecordResponse)
|
| 121 |
-
async def api_record_outreach(
|
| 122 |
-
req: Request,
|
| 123 |
-
body: SendOutreachRequest,
|
| 124 |
-
db: AsyncSession = Depends(get_db),
|
| 125 |
-
):
|
| 126 |
-
email = _check_auth(req)
|
| 127 |
-
if not email:
|
| 128 |
-
return OutreachRecordResponse(success=False, error="Authentication required.")
|
| 129 |
-
result = await record_pending_outreach(
|
| 130 |
-
db, body.job_id, body.talent_email, body.match_score,
|
| 131 |
-
email, body.method, body.subject, body.body)
|
| 132 |
-
return OutreachRecordResponse(
|
| 133 |
-
success=result.get("success", False),
|
| 134 |
-
outreach_id=result.get("outreach_id", ""),
|
| 135 |
-
error=result.get("error"),
|
| 136 |
-
)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
@router.post("/outreach/send", response_model=SendOutreachResponse)
|
| 140 |
-
async def api_send_instant_outreach(
|
| 141 |
-
req: Request,
|
| 142 |
-
body: SendOutreachRequest,
|
| 143 |
-
db: AsyncSession = Depends(get_db),
|
| 144 |
-
):
|
| 145 |
-
email = _check_auth(req)
|
| 146 |
-
if not email:
|
| 147 |
-
return SendOutreachResponse(success=False, error="Authentication required.")
|
| 148 |
-
result = await send_instant_outreach(
|
| 149 |
-
db, email, body.job_id, body.talent_email, body.match_score,
|
| 150 |
-
body.method, body.subject, body.body)
|
| 151 |
-
return SendOutreachResponse(
|
| 152 |
-
success=result.get("success", False),
|
| 153 |
-
outreach_id=result.get("outreach_id", ""),
|
| 154 |
-
remaining=result.get("remaining", 0),
|
| 155 |
-
error=result.get("error"),
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
@router.get("/outreach/history", response_model=dict)
|
| 160 |
-
async def api_outreach_history(
|
| 161 |
-
req: Request,
|
| 162 |
-
db: AsyncSession = Depends(get_db),
|
| 163 |
-
):
|
| 164 |
-
email = _check_auth(req)
|
| 165 |
-
if not email:
|
| 166 |
-
return {"success": False, "error": "Authentication required."}
|
| 167 |
-
return await list_outreach_history(db, email)
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
@router.post("/vouchers/generate", response_model=VoucherGenerateResponse)
|
| 171 |
-
async def api_generate_vouchers(
|
| 172 |
-
req: Request,
|
| 173 |
-
body: VoucherGenerateRequest,
|
| 174 |
-
db: AsyncSession = Depends(get_db),
|
| 175 |
-
):
|
| 176 |
-
email = _check_auth(req)
|
| 177 |
-
if not email:
|
| 178 |
-
return VoucherGenerateResponse(success=False, error="Authentication required.")
|
| 179 |
-
result = await generate_vouchers(db, body.lpk_id, body.quantity)
|
| 180 |
-
return VoucherGenerateResponse(
|
| 181 |
-
success=result.get("success", False),
|
| 182 |
-
message=result.get("message", ""),
|
| 183 |
-
vouchers=result.get("vouchers", []),
|
| 184 |
-
count=result.get("count", 0),
|
| 185 |
-
error=result.get("error"),
|
| 186 |
-
)
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
@router.post("/vouchers/redeem", response_model=VoucherRedeemResponse)
|
| 190 |
-
async def api_redeem_voucher(
|
| 191 |
-
req: Request,
|
| 192 |
-
body: VoucherRedeemRequest,
|
| 193 |
-
db: AsyncSession = Depends(get_db),
|
| 194 |
-
):
|
| 195 |
-
email = _check_auth(req)
|
| 196 |
-
if not email:
|
| 197 |
-
return VoucherRedeemResponse(success=False, error="Authentication required.")
|
| 198 |
-
result = await redeem_voucher(db, email, email, body.voucher_code)
|
| 199 |
-
return VoucherRedeemResponse(
|
| 200 |
-
success=result.get("success", False),
|
| 201 |
-
message=result.get("message", ""),
|
| 202 |
-
lpk_id=result.get("lpk_id", ""),
|
| 203 |
-
voucher_code=result.get("voucher_code", ""),
|
| 204 |
-
error=result.get("error"),
|
| 205 |
-
)
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
@router.get("/vouchers/{lpk_id}", response_model=VoucherListResponse)
|
| 209 |
-
async def api_get_lpk_vouchers(
|
| 210 |
-
lpk_id: str,
|
| 211 |
-
db: AsyncSession = Depends(get_db),
|
| 212 |
-
):
|
| 213 |
-
result = await get_lpk_vouchers(db, lpk_id)
|
| 214 |
-
return VoucherListResponse(
|
| 215 |
-
success=result.get("success", False),
|
| 216 |
-
vouchers=result.get("vouchers", []),
|
| 217 |
-
counts=result.get("counts", {"Available":0,"Used":0,"Total":0}),
|
| 218 |
-
error=result.get("error"),
|
| 219 |
-
)
|
|
|
|
| 1 |
+
"""Job API Routes - Posting CRUD, Outreach, Compatibility, Vouchers, Limits."""
|
| 2 |
+
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from fastapi import APIRouter, Depends, Query, Request
|
| 6 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
+
|
| 8 |
+
from app.database import get_db
|
| 9 |
+
from app.schemas.job import (
|
| 10 |
+
AnalyzeCompatibilityRequest, AnalyzeCompatibilityResponse,
|
| 11 |
+
CheckJobLimitResponse, CreateJobRequest, JobListResponse,
|
| 12 |
+
JobPostingResponse, OutreachRecordResponse, SendOutreachRequest,
|
| 13 |
+
SendOutreachResponse, UpdateJobStatusRequest,
|
| 14 |
+
VoucherGenerateRequest, VoucherGenerateResponse,
|
| 15 |
+
VoucherListResponse, VoucherRedeemRequest, VoucherRedeemResponse,
|
| 16 |
+
)
|
| 17 |
+
from app.services.job_service import (
|
| 18 |
+
analyze_job_compatibility, check_active_job_posting_limit,
|
| 19 |
+
create_job_posting, generate_vouchers, get_job_posting,
|
| 20 |
+
get_job_postings, get_lpk_vouchers, list_outreach_history,
|
| 21 |
+
record_pending_outreach, redeem_voucher, send_instant_outreach,
|
| 22 |
+
update_job_status,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
router = APIRouter(prefix="/v1/jobs", tags=["Jobs"])
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _check_auth(req: Request) -> Optional[str]:
|
| 29 |
+
return getattr(req.state, "user_email", None)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@router.get("", response_model=JobListResponse)
|
| 33 |
+
async def api_get_jobs(
|
| 34 |
+
page: int = Query(1, ge=1),
|
| 35 |
+
limit: int = Query(10, ge=1, le=50),
|
| 36 |
+
db: AsyncSession = Depends(get_db),
|
| 37 |
+
):
|
| 38 |
+
result = await get_job_postings(db, page, limit)
|
| 39 |
+
return JobListResponse(
|
| 40 |
+
success=result.get("success", False),
|
| 41 |
+
page=result.get("page", page),
|
| 42 |
+
limit=result.get("limit", limit),
|
| 43 |
+
total=result.get("total", 0),
|
| 44 |
+
data=result.get("data", []),
|
| 45 |
+
error=result.get("error"),
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@router.get("/{job_id}", response_model=JobPostingResponse)
|
| 50 |
+
async def api_get_job(
|
| 51 |
+
job_id: str,
|
| 52 |
+
db: AsyncSession = Depends(get_db),
|
| 53 |
+
):
|
| 54 |
+
result = await get_job_posting(db, job_id)
|
| 55 |
+
if not result.get("success"):
|
| 56 |
+
return JobPostingResponse(job_id=job_id, error=result.get("error", "Not found"))
|
| 57 |
+
data = result.get("data", {})
|
| 58 |
+
return JobPostingResponse(**data)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@router.post("", response_model=dict)
|
| 62 |
+
async def api_create_job(
|
| 63 |
+
req: Request,
|
| 64 |
+
body: CreateJobRequest,
|
| 65 |
+
db: AsyncSession = Depends(get_db),
|
| 66 |
+
):
|
| 67 |
+
email = _check_auth(req)
|
| 68 |
+
if not email:
|
| 69 |
+
return {"success": False, "error": "Authentication required."}
|
| 70 |
+
return await create_job_posting(db, email, body.model_dump())
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@router.put("/status", response_model=dict)
|
| 74 |
+
async def api_update_job_status(
|
| 75 |
+
req: Request,
|
| 76 |
+
body: UpdateJobStatusRequest,
|
| 77 |
+
db: AsyncSession = Depends(get_db),
|
| 78 |
+
):
|
| 79 |
+
email = _check_auth(req)
|
| 80 |
+
if not email:
|
| 81 |
+
return {"success": False, "error": "Authentication required."}
|
| 82 |
+
return await update_job_status(db, body.job_id, body.status)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@router.get("/limit/check", response_model=CheckJobLimitResponse)
|
| 86 |
+
async def api_check_job_limit(
|
| 87 |
+
req: Request,
|
| 88 |
+
db: AsyncSession = Depends(get_db),
|
| 89 |
+
):
|
| 90 |
+
email = _check_auth(req)
|
| 91 |
+
if not email:
|
| 92 |
+
return CheckJobLimitResponse(allowed=False, error="Authentication required.")
|
| 93 |
+
result = await check_active_job_posting_limit(db, email)
|
| 94 |
+
return CheckJobLimitResponse(
|
| 95 |
+
allowed=result.get("allowed", False),
|
| 96 |
+
tier=result.get("tier", "free"),
|
| 97 |
+
active_count=result.get("active_count", 0),
|
| 98 |
+
limit=result.get("limit", 1),
|
| 99 |
+
error=result.get("error"),
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@router.post("/analyze-compatibility", response_model=AnalyzeCompatibilityResponse)
|
| 104 |
+
async def api_analyze_compatibility(
|
| 105 |
+
req: Request,
|
| 106 |
+
body: AnalyzeCompatibilityRequest,
|
| 107 |
+
db: AsyncSession = Depends(get_db),
|
| 108 |
+
):
|
| 109 |
+
email = _check_auth(req)
|
| 110 |
+
if not email:
|
| 111 |
+
return AnalyzeCompatibilityResponse(success=False, error="Authentication required.")
|
| 112 |
+
result = await analyze_job_compatibility(db, email, body.job_id)
|
| 113 |
+
return AnalyzeCompatibilityResponse(
|
| 114 |
+
success=result.get("success", False),
|
| 115 |
+
data=result.get("data"),
|
| 116 |
+
error=result.get("error"),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@router.post("/outreach/record", response_model=OutreachRecordResponse)
|
| 121 |
+
async def api_record_outreach(
|
| 122 |
+
req: Request,
|
| 123 |
+
body: SendOutreachRequest,
|
| 124 |
+
db: AsyncSession = Depends(get_db),
|
| 125 |
+
):
|
| 126 |
+
email = _check_auth(req)
|
| 127 |
+
if not email:
|
| 128 |
+
return OutreachRecordResponse(success=False, error="Authentication required.")
|
| 129 |
+
result = await record_pending_outreach(
|
| 130 |
+
db, body.job_id, body.talent_email, body.match_score,
|
| 131 |
+
email, body.method, body.subject, body.body)
|
| 132 |
+
return OutreachRecordResponse(
|
| 133 |
+
success=result.get("success", False),
|
| 134 |
+
outreach_id=result.get("outreach_id", ""),
|
| 135 |
+
error=result.get("error"),
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@router.post("/outreach/send", response_model=SendOutreachResponse)
|
| 140 |
+
async def api_send_instant_outreach(
|
| 141 |
+
req: Request,
|
| 142 |
+
body: SendOutreachRequest,
|
| 143 |
+
db: AsyncSession = Depends(get_db),
|
| 144 |
+
):
|
| 145 |
+
email = _check_auth(req)
|
| 146 |
+
if not email:
|
| 147 |
+
return SendOutreachResponse(success=False, error="Authentication required.")
|
| 148 |
+
result = await send_instant_outreach(
|
| 149 |
+
db, email, body.job_id, body.talent_email, body.match_score,
|
| 150 |
+
body.method, body.subject, body.body)
|
| 151 |
+
return SendOutreachResponse(
|
| 152 |
+
success=result.get("success", False),
|
| 153 |
+
outreach_id=result.get("outreach_id", ""),
|
| 154 |
+
remaining=result.get("remaining", 0),
|
| 155 |
+
error=result.get("error"),
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@router.get("/outreach/history", response_model=dict)
|
| 160 |
+
async def api_outreach_history(
|
| 161 |
+
req: Request,
|
| 162 |
+
db: AsyncSession = Depends(get_db),
|
| 163 |
+
):
|
| 164 |
+
email = _check_auth(req)
|
| 165 |
+
if not email:
|
| 166 |
+
return {"success": False, "error": "Authentication required."}
|
| 167 |
+
return await list_outreach_history(db, email)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@router.post("/vouchers/generate", response_model=VoucherGenerateResponse)
|
| 171 |
+
async def api_generate_vouchers(
|
| 172 |
+
req: Request,
|
| 173 |
+
body: VoucherGenerateRequest,
|
| 174 |
+
db: AsyncSession = Depends(get_db),
|
| 175 |
+
):
|
| 176 |
+
email = _check_auth(req)
|
| 177 |
+
if not email:
|
| 178 |
+
return VoucherGenerateResponse(success=False, error="Authentication required.")
|
| 179 |
+
result = await generate_vouchers(db, body.lpk_id, body.quantity)
|
| 180 |
+
return VoucherGenerateResponse(
|
| 181 |
+
success=result.get("success", False),
|
| 182 |
+
message=result.get("message", ""),
|
| 183 |
+
vouchers=result.get("vouchers", []),
|
| 184 |
+
count=result.get("count", 0),
|
| 185 |
+
error=result.get("error"),
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@router.post("/vouchers/redeem", response_model=VoucherRedeemResponse)
|
| 190 |
+
async def api_redeem_voucher(
|
| 191 |
+
req: Request,
|
| 192 |
+
body: VoucherRedeemRequest,
|
| 193 |
+
db: AsyncSession = Depends(get_db),
|
| 194 |
+
):
|
| 195 |
+
email = _check_auth(req)
|
| 196 |
+
if not email:
|
| 197 |
+
return VoucherRedeemResponse(success=False, error="Authentication required.")
|
| 198 |
+
result = await redeem_voucher(db, email, email, body.voucher_code)
|
| 199 |
+
return VoucherRedeemResponse(
|
| 200 |
+
success=result.get("success", False),
|
| 201 |
+
message=result.get("message", ""),
|
| 202 |
+
lpk_id=result.get("lpk_id", ""),
|
| 203 |
+
voucher_code=result.get("voucher_code", ""),
|
| 204 |
+
error=result.get("error"),
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@router.get("/vouchers/{lpk_id}", response_model=VoucherListResponse)
|
| 209 |
+
async def api_get_lpk_vouchers(
|
| 210 |
+
lpk_id: str,
|
| 211 |
+
db: AsyncSession = Depends(get_db),
|
| 212 |
+
):
|
| 213 |
+
result = await get_lpk_vouchers(db, lpk_id)
|
| 214 |
+
return VoucherListResponse(
|
| 215 |
+
success=result.get("success", False),
|
| 216 |
+
vouchers=result.get("vouchers", []),
|
| 217 |
+
counts=result.get("counts", {"Available":0,"Used":0,"Total":0}),
|
| 218 |
+
error=result.get("error"),
|
| 219 |
+
)
|
app/api/legacy_compat.py
CHANGED
|
@@ -1,718 +1,720 @@
|
|
| 1 |
-
"""Legacy GAS Compatibility Endpoint — Emulates legacy Google Apps Script webhooks.
|
| 2 |
-
|
| 3 |
-
Ensures GEO-security by applying 'X-Robots-Tag: noindex, nofollow, noai' on all responses.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import secrets
|
| 7 |
-
import re
|
| 8 |
-
import asyncio
|
| 9 |
-
from datetime import datetime, timedelta, timezone
|
| 10 |
-
from typing import Any, Dict, List, Optional
|
| 11 |
-
from pydantic import BaseModel
|
| 12 |
-
|
| 13 |
-
from fastapi import APIRouter, Depends, Request, Response
|
| 14 |
-
from sqlalchemy import select, func, update
|
| 15 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 16 |
-
from loguru import logger
|
| 17 |
-
|
| 18 |
-
from app.database import get_db
|
| 19 |
-
from app.config.settings import settings, FINANCE_CONFIG
|
| 20 |
-
from app.utils.security import decode_access_token, hash_password
|
| 21 |
-
from app.models.talent import Talent
|
| 22 |
-
from app.models.employer import ClientAccount, Company, PendingEmployer
|
| 23 |
-
from app.models.finance import ProfileUnlock, Transaction, Interview
|
| 24 |
-
from app.models.system import ActivityLog, AnalyticsTraffic
|
| 25 |
-
from app.models.skkni import LPKRegistrationLead
|
| 26 |
-
from app.services.employer_service import deduct_coins
|
| 27 |
-
from app.services.google_workspace_service import spark_agent
|
| 28 |
-
from app.services.email_service import email_service
|
| 29 |
-
|
| 30 |
-
router = APIRouter(prefix="/v1", tags=["Legacy Compatibility"])
|
| 31 |
-
|
| 32 |
-
class LegacyPayload(BaseModel):
|
| 33 |
-
action: str
|
| 34 |
-
params: List[Any] = []
|
| 35 |
-
|
| 36 |
-
def calculate_exp_tier(text: str) -> str:
|
| 37 |
-
"""Calculates experience tier based on years matching.
|
| 38 |
-
|
| 39 |
-
Under 3 years: Junior
|
| 40 |
-
3 to 7 years: Mid
|
| 41 |
-
8+ years: Senior
|
| 42 |
-
"""
|
| 43 |
-
if not text:
|
| 44 |
-
return "Junior"
|
| 45 |
-
match = re.search(r'\d+', str(text))
|
| 46 |
-
if not match:
|
| 47 |
-
return "Junior"
|
| 48 |
-
y = int(match.group())
|
| 49 |
-
if y >= 8:
|
| 50 |
-
return "Senior"
|
| 51 |
-
elif y >= 3:
|
| 52 |
-
return "Mid"
|
| 53 |
-
else:
|
| 54 |
-
return "Junior"
|
| 55 |
-
|
| 56 |
-
async def local_verify_session(db: AsyncSession, email: str, token: str) -> bool:
|
| 57 |
-
"""Helper to verify a session token (JWT or auth_key)."""
|
| 58 |
-
if not email or not token:
|
| 59 |
-
return False
|
| 60 |
-
|
| 61 |
-
email_clean = email.lower().strip()
|
| 62 |
-
|
| 63 |
-
# 1. Mock token override
|
| 64 |
-
if token in ("mock_session_token_123", "mock_session_token"):
|
| 65 |
-
return True
|
| 66 |
-
|
| 67 |
-
# 2. Try JWT Decode first
|
| 68 |
-
payload = decode_access_token(token)
|
| 69 |
-
if payload:
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
response.headers["X-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
"
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
"
|
| 213 |
-
"
|
| 214 |
-
"
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
"
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
"
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
"
|
| 303 |
-
"
|
| 304 |
-
"
|
| 305 |
-
"
|
| 306 |
-
"
|
| 307 |
-
"
|
| 308 |
-
"
|
| 309 |
-
"
|
| 310 |
-
"
|
| 311 |
-
"
|
| 312 |
-
"
|
| 313 |
-
"
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
"
|
| 329 |
-
"
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
"
|
| 340 |
-
"
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
.
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
.
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
"
|
| 377 |
-
"
|
| 378 |
-
"
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
if status in ["
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
"
|
| 409 |
-
"
|
| 410 |
-
"
|
| 411 |
-
"
|
| 412 |
-
"
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
"
|
| 424 |
-
"
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
"
|
| 518 |
-
"
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
"
|
| 539 |
-
"
|
| 540 |
-
"
|
| 541 |
-
"
|
| 542 |
-
"
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
"
|
| 562 |
-
"
|
| 563 |
-
"
|
| 564 |
-
"
|
| 565 |
-
"
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
"
|
| 586 |
-
"
|
| 587 |
-
"
|
| 588 |
-
"
|
| 589 |
-
"
|
| 590 |
-
"
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
<
|
| 618 |
-
<
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
<li><strong>
|
| 622 |
-
<li><strong>
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
{
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
"
|
| 646 |
-
"
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
"
|
| 666 |
-
"
|
| 667 |
-
"
|
| 668 |
-
"
|
| 669 |
-
"
|
| 670 |
-
"
|
| 671 |
-
"
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
<
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
"
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
"
|
| 692 |
-
"
|
| 693 |
-
"
|
| 694 |
-
"
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
"
|
| 700 |
-
"
|
| 701 |
-
"
|
| 702 |
-
"
|
| 703 |
-
"
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Legacy GAS Compatibility Endpoint — Emulates legacy Google Apps Script webhooks.
|
| 2 |
+
|
| 3 |
+
Ensures GEO-security by applying 'X-Robots-Tag: noindex, nofollow, noai' on all responses.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import secrets
|
| 7 |
+
import re
|
| 8 |
+
import asyncio
|
| 9 |
+
from datetime import datetime, timedelta, timezone
|
| 10 |
+
from typing import Any, Dict, List, Optional
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
|
| 13 |
+
from fastapi import APIRouter, Depends, Request, Response
|
| 14 |
+
from sqlalchemy import select, func, update
|
| 15 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 16 |
+
from loguru import logger
|
| 17 |
+
|
| 18 |
+
from app.database import get_db
|
| 19 |
+
from app.config.settings import settings, FINANCE_CONFIG
|
| 20 |
+
from app.utils.security import decode_access_token, hash_password, verify_supabase_token
|
| 21 |
+
from app.models.talent import Talent
|
| 22 |
+
from app.models.employer import ClientAccount, Company, PendingEmployer
|
| 23 |
+
from app.models.finance import ProfileUnlock, Transaction, Interview
|
| 24 |
+
from app.models.system import ActivityLog, AnalyticsTraffic
|
| 25 |
+
from app.models.skkni import LPKRegistrationLead
|
| 26 |
+
from app.services.employer_service import deduct_coins
|
| 27 |
+
from app.services.google_workspace_service import spark_agent
|
| 28 |
+
from app.services.email_service import email_service
|
| 29 |
+
|
| 30 |
+
router = APIRouter(prefix="/v1", tags=["Legacy Compatibility"])
|
| 31 |
+
|
| 32 |
+
class LegacyPayload(BaseModel):
|
| 33 |
+
action: str
|
| 34 |
+
params: List[Any] = []
|
| 35 |
+
|
| 36 |
+
def calculate_exp_tier(text: str) -> str:
|
| 37 |
+
"""Calculates experience tier based on years matching.
|
| 38 |
+
|
| 39 |
+
Under 3 years: Junior
|
| 40 |
+
3 to 7 years: Mid
|
| 41 |
+
8+ years: Senior
|
| 42 |
+
"""
|
| 43 |
+
if not text:
|
| 44 |
+
return "Junior"
|
| 45 |
+
match = re.search(r'\d+', str(text))
|
| 46 |
+
if not match:
|
| 47 |
+
return "Junior"
|
| 48 |
+
y = int(match.group())
|
| 49 |
+
if y >= 8:
|
| 50 |
+
return "Senior"
|
| 51 |
+
elif y >= 3:
|
| 52 |
+
return "Mid"
|
| 53 |
+
else:
|
| 54 |
+
return "Junior"
|
| 55 |
+
|
| 56 |
+
async def local_verify_session(db: AsyncSession, email: str, token: str) -> bool:
|
| 57 |
+
"""Helper to verify a session token (JWT or auth_key)."""
|
| 58 |
+
if not email or not token:
|
| 59 |
+
return False
|
| 60 |
+
|
| 61 |
+
email_clean = email.lower().strip()
|
| 62 |
+
|
| 63 |
+
# 1. Mock token override
|
| 64 |
+
if token in ("mock_session_token_123", "mock_session_token"):
|
| 65 |
+
return True
|
| 66 |
+
|
| 67 |
+
# 2. Try JWT Decode first
|
| 68 |
+
payload = decode_access_token(token)
|
| 69 |
+
if not payload:
|
| 70 |
+
payload = await verify_supabase_token(token)
|
| 71 |
+
if payload:
|
| 72 |
+
if payload.get("email", "").lower().strip() == email_clean:
|
| 73 |
+
return True
|
| 74 |
+
|
| 75 |
+
# 3. Check Admin Role
|
| 76 |
+
if email_clean == "admin@briga.id":
|
| 77 |
+
if token == settings.admin_password:
|
| 78 |
+
return True
|
| 79 |
+
|
| 80 |
+
# 4. Check ClientAccount auth_key in DB
|
| 81 |
+
stmt_client = select(ClientAccount).where(ClientAccount.email == email_clean)
|
| 82 |
+
res_client = await db.execute(stmt_client)
|
| 83 |
+
client = res_client.scalar_one_or_none()
|
| 84 |
+
if client and client.auth_key == token:
|
| 85 |
+
return True
|
| 86 |
+
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
@router.post("/legacy-gas-compat")
|
| 90 |
+
async def legacy_gas_compat(
|
| 91 |
+
payload: LegacyPayload,
|
| 92 |
+
response: Response,
|
| 93 |
+
db: AsyncSession = Depends(get_db)
|
| 94 |
+
):
|
| 95 |
+
# Enforce GEO-Security headers as mandated by Brigawan rules
|
| 96 |
+
response.headers["X-Robots-Tag"] = "noindex, nofollow, noai"
|
| 97 |
+
response.headers["X-Content-Type-Options"] = "nosniff"
|
| 98 |
+
response.headers["X-Frame-Options"] = "DENY"
|
| 99 |
+
|
| 100 |
+
action = payload.action
|
| 101 |
+
params = payload.params
|
| 102 |
+
|
| 103 |
+
logger.info(f"[LegacyGASCompat] Action: {action}, Params: {params}")
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
if action == "verifySession":
|
| 107 |
+
if len(params) < 2:
|
| 108 |
+
return {"success": False, "error": "Parameter email dan token diperlukan."}
|
| 109 |
+
email, token = params[0], params[1]
|
| 110 |
+
success = await local_verify_session(db, email, token)
|
| 111 |
+
if success:
|
| 112 |
+
return {"success": True}
|
| 113 |
+
return {"success": False, "error": "Sesi tidak valid atau telah berakhir."}
|
| 114 |
+
|
| 115 |
+
elif action == "deductEmployerToken":
|
| 116 |
+
if len(params) < 3:
|
| 117 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 118 |
+
email, token, amount = params[0], params[1], int(params[2])
|
| 119 |
+
|
| 120 |
+
if not await local_verify_session(db, email, token):
|
| 121 |
+
return {"success": False, "error": "Sesi tidak valid."}
|
| 122 |
+
|
| 123 |
+
res = await deduct_coins(db, email, amount, tx_type="Deduction", description="Employer Token Deduction")
|
| 124 |
+
return {"success": True, "remaining": res["remaining"]}
|
| 125 |
+
|
| 126 |
+
elif action == "deductCoinsForAIReport":
|
| 127 |
+
if len(params) < 3:
|
| 128 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 129 |
+
email, token, reason = params[0], params[1], params[2]
|
| 130 |
+
|
| 131 |
+
if not await local_verify_session(db, email, token):
|
| 132 |
+
return {"success": False, "error": "Sesi tidak valid."}
|
| 133 |
+
|
| 134 |
+
cost = FINANCE_CONFIG["DEDUCTION"]["AI_MATCH_REPORT"]
|
| 135 |
+
res = await deduct_coins(db, email, cost, tx_type="AIReport", description=f"AI Match Report: {reason}")
|
| 136 |
+
return {"success": True, "remaining": res["remaining"]}
|
| 137 |
+
|
| 138 |
+
elif action == "deductCoinsForOutreach":
|
| 139 |
+
if len(params) < 3:
|
| 140 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 141 |
+
email, token, candidate_email = params[0], params[1], params[2]
|
| 142 |
+
|
| 143 |
+
if not await local_verify_session(db, email, token):
|
| 144 |
+
return {"success": False, "error": "Sesi tidak valid."}
|
| 145 |
+
|
| 146 |
+
cost = FINANCE_CONFIG["DEDUCTION"]["DIRECT_OUTREACH"]
|
| 147 |
+
res = await deduct_coins(db, email, cost, tx_type="Outreach", description=f"Direct Outreach to: {candidate_email}")
|
| 148 |
+
return {"success": True, "remaining": res["remaining"]}
|
| 149 |
+
|
| 150 |
+
elif action == "unlockCandidate":
|
| 151 |
+
if len(params) < 3:
|
| 152 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 153 |
+
email, token, candidate_id = params[0], params[1], params[2]
|
| 154 |
+
query = params[3] if len(params) > 3 else "-"
|
| 155 |
+
|
| 156 |
+
if not await local_verify_session(db, email, token):
|
| 157 |
+
return {"success": False, "error": "Sesi tidak valid."}
|
| 158 |
+
|
| 159 |
+
stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
|
| 160 |
+
client_res = await db.execute(stmt_client)
|
| 161 |
+
client = client_res.scalar_one_or_none()
|
| 162 |
+
if not client or not client.company_id:
|
| 163 |
+
return {"success": False, "error": "Akun Employer tidak ditemukan."}
|
| 164 |
+
|
| 165 |
+
stmt_unlock = select(ProfileUnlock).where(
|
| 166 |
+
ProfileUnlock.company_id == client.company_id,
|
| 167 |
+
ProfileUnlock.candidate_id == candidate_id
|
| 168 |
+
)
|
| 169 |
+
unlock_res = await db.execute(stmt_unlock)
|
| 170 |
+
if unlock_res.scalar_one_or_none():
|
| 171 |
+
return {"success": True, "message": "Already unlocked.", "cvUrl": f"https://briga.id/ats/cv/{candidate_id}"}
|
| 172 |
+
|
| 173 |
+
stmt_talent = select(Talent).where(Talent.talent_id == candidate_id)
|
| 174 |
+
talent_res = await db.execute(stmt_talent)
|
| 175 |
+
talent = talent_res.scalar_one_or_none()
|
| 176 |
+
if not talent:
|
| 177 |
+
return {"success": False, "error": "Talenta tidak ditemukan."}
|
| 178 |
+
|
| 179 |
+
exp_tier = calculate_exp_tier(talent.experience)
|
| 180 |
+
costs = {
|
| 181 |
+
"Senior": FINANCE_CONFIG["DEDUCTION"]["UNLOCK_SENIOR"],
|
| 182 |
+
"Mid": FINANCE_CONFIG["DEDUCTION"]["UNLOCK_MID"],
|
| 183 |
+
"Junior": FINANCE_CONFIG["DEDUCTION"]["UNLOCK_JUNIOR"]
|
| 184 |
+
}
|
| 185 |
+
cost = costs.get(exp_tier, FINANCE_CONFIG["DEDUCTION"]["UNLOCK_JUNIOR"])
|
| 186 |
+
|
| 187 |
+
res = await deduct_coins(db, email, cost, tx_type="Unlock", description=f"Unlock Profile: {candidate_id}")
|
| 188 |
+
|
| 189 |
+
new_unlock = ProfileUnlock(
|
| 190 |
+
company_id=client.company_id,
|
| 191 |
+
candidate_id=candidate_id,
|
| 192 |
+
is_masked_only=False
|
| 193 |
+
)
|
| 194 |
+
db.add(new_unlock)
|
| 195 |
+
await db.commit()
|
| 196 |
+
|
| 197 |
+
if settings.google_sheets_spreadsheet_id:
|
| 198 |
+
row_values = [
|
| 199 |
+
f"UNL-{secrets.token_hex(4).upper()}",
|
| 200 |
+
email,
|
| 201 |
+
candidate_id,
|
| 202 |
+
datetime.now(timezone.utc).isoformat(),
|
| 203 |
+
query
|
| 204 |
+
]
|
| 205 |
+
await spark_agent.append_row_to_sheet(
|
| 206 |
+
settings.google_sheets_spreadsheet_id,
|
| 207 |
+
"Unlocks!A1",
|
| 208 |
+
row_values
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
return {
|
| 212 |
+
"success": True,
|
| 213 |
+
"message": "Unlocked successfully.",
|
| 214 |
+
"deducted": cost,
|
| 215 |
+
"remaining": res["remaining"],
|
| 216 |
+
"cvUrl": f"https://briga.id/ats/cv/{candidate_id}"
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
elif action == "getUnlockHistory":
|
| 220 |
+
if len(params) < 2:
|
| 221 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 222 |
+
email, token = params[0], params[1]
|
| 223 |
+
|
| 224 |
+
if not await local_verify_session(db, email, token):
|
| 225 |
+
return {"success": False, "error": "Sesi tidak valid."}
|
| 226 |
+
|
| 227 |
+
stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
|
| 228 |
+
client_res = await db.execute(stmt_client)
|
| 229 |
+
client = client_res.scalar_one_or_none()
|
| 230 |
+
if not client or not client.company_id:
|
| 231 |
+
return {"success": True, "data": []}
|
| 232 |
+
|
| 233 |
+
stmt_unlocks = select(ProfileUnlock).where(ProfileUnlock.company_id == client.company_id)
|
| 234 |
+
unlocks_res = await db.execute(stmt_unlocks)
|
| 235 |
+
unlocks = unlocks_res.scalars().all()
|
| 236 |
+
|
| 237 |
+
history = []
|
| 238 |
+
for u in unlocks:
|
| 239 |
+
history.append({
|
| 240 |
+
"id": u.candidate_id,
|
| 241 |
+
"date": int(u.created_at.timestamp() * 1000) if u.created_at else int(datetime.now(timezone.utc).timestamp() * 1000),
|
| 242 |
+
"query": "Sustainability Role"
|
| 243 |
+
})
|
| 244 |
+
history.sort(key=lambda x: x["date"], reverse=True)
|
| 245 |
+
return {"success": True, "data": history}
|
| 246 |
+
|
| 247 |
+
elif action == "getEmployerProfile":
|
| 248 |
+
if len(params) < 1:
|
| 249 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 250 |
+
email = params[0]
|
| 251 |
+
|
| 252 |
+
stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
|
| 253 |
+
client_res = await db.execute(stmt_client)
|
| 254 |
+
client = client_res.scalar_one_or_none()
|
| 255 |
+
if not client or not client.company_id:
|
| 256 |
+
return {"success": False, "error": "Employer profile not found."}
|
| 257 |
+
|
| 258 |
+
stmt_company = select(Company).where(Company.id == client.company_id)
|
| 259 |
+
comp_res = await db.execute(stmt_company)
|
| 260 |
+
company = comp_res.scalar_one_or_none()
|
| 261 |
+
if not company:
|
| 262 |
+
return {"success": False, "error": "Company not found."}
|
| 263 |
+
|
| 264 |
+
return {
|
| 265 |
+
"success": True,
|
| 266 |
+
"name": client.name,
|
| 267 |
+
"tokens": company.credit_balance or 0
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
elif action == "getEmployerTokens":
|
| 271 |
+
if len(params) < 1:
|
| 272 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 273 |
+
email = params[0]
|
| 274 |
+
|
| 275 |
+
stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
|
| 276 |
+
client_res = await db.execute(stmt_client)
|
| 277 |
+
client = client_res.scalar_one_or_none()
|
| 278 |
+
if not client or not client.company_id:
|
| 279 |
+
return 0
|
| 280 |
+
|
| 281 |
+
stmt_company = select(Company).where(Company.id == client.company_id)
|
| 282 |
+
comp_res = await db.execute(stmt_company)
|
| 283 |
+
company = comp_res.scalar_one_or_none()
|
| 284 |
+
if not company:
|
| 285 |
+
return 0
|
| 286 |
+
|
| 287 |
+
return company.credit_balance or 0
|
| 288 |
+
|
| 289 |
+
elif action == "checkTalentVerificationStatus":
|
| 290 |
+
if len(params) < 1:
|
| 291 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 292 |
+
email = params[0]
|
| 293 |
+
is_admin = params[1] if len(params) > 1 else False
|
| 294 |
+
|
| 295 |
+
stmt = select(Talent).where(Talent.email == email.lower().strip())
|
| 296 |
+
res = await db.execute(stmt)
|
| 297 |
+
t = res.scalar_one_or_none()
|
| 298 |
+
if not t:
|
| 299 |
+
return {"success": False, "found": False, "error": "Data talenta tidak ditemukan."}
|
| 300 |
+
|
| 301 |
+
return {
|
| 302 |
+
"success": True,
|
| 303 |
+
"found": True,
|
| 304 |
+
"nama": t.name,
|
| 305 |
+
"email": t.email,
|
| 306 |
+
"talentId": t.talent_id if is_admin else "****",
|
| 307 |
+
"pddikti_status": t.verification_status or "Verifikasi Otomatis",
|
| 308 |
+
"ai_readiness_score": t.score or 70,
|
| 309 |
+
"kategori": t.category or "Semi-Skilled",
|
| 310 |
+
"ai_pathway": t.advisory_snippet or "Peta jalan Karir...",
|
| 311 |
+
"ai_pathway_full": t.advisory_full or "-",
|
| 312 |
+
"ai_skills": t.skill_tags or "-",
|
| 313 |
+
"badges": t.badges or [],
|
| 314 |
+
"isUnlocked": t.is_unlocked or is_admin,
|
| 315 |
+
"sessionToken": None
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
elif action == "getAdminDashboardData":
|
| 319 |
+
talents_count = (await db.execute(select(func.count(Talent.id)))).scalar() or 0
|
| 320 |
+
companies_count = (await db.execute(select(func.count(Company.id)))).scalar() or 0
|
| 321 |
+
pending_count = (await db.execute(select(func.count(PendingEmployer.id)).where(PendingEmployer.status == "PENDING"))).scalar() or 0
|
| 322 |
+
|
| 323 |
+
recent_logs = []
|
| 324 |
+
try:
|
| 325 |
+
stmt_logs = select(ActivityLog).order_by(ActivityLog.timestamp.desc()).limit(5)
|
| 326 |
+
logs_res = await db.execute(stmt_logs)
|
| 327 |
+
recent_logs = [{
|
| 328 |
+
"timestamp": l.timestamp.isoformat() if l.timestamp else None,
|
| 329 |
+
"actor": l.actor,
|
| 330 |
+
"action": l.action,
|
| 331 |
+
"metadata": l.log_metadata
|
| 332 |
+
} for l in logs_res.scalars().all()]
|
| 333 |
+
except Exception:
|
| 334 |
+
pass
|
| 335 |
+
|
| 336 |
+
return {
|
| 337 |
+
"success": True,
|
| 338 |
+
"stats": {
|
| 339 |
+
"talents": talents_count,
|
| 340 |
+
"employers": companies_count,
|
| 341 |
+
"pending": pending_count,
|
| 342 |
+
"tokens": 1000
|
| 343 |
+
},
|
| 344 |
+
"recentLogs": recent_logs
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
elif action == "fetchAnalyticsOverview":
|
| 348 |
+
now = datetime.now(timezone.utc)
|
| 349 |
+
total_hits = (await db.execute(select(func.count(AnalyticsTraffic.id)))).scalar() or 0
|
| 350 |
+
|
| 351 |
+
stmt_pages = select(AnalyticsTraffic.page, func.count(AnalyticsTraffic.id))\
|
| 352 |
+
.group_by(AnalyticsTraffic.page)\
|
| 353 |
+
.order_by(func.count(AnalyticsTraffic.id).desc())\
|
| 354 |
+
.limit(5)
|
| 355 |
+
top_pages_res = await db.execute(stmt_pages)
|
| 356 |
+
top_pages = [{"page": r[0] or "Unknown", "count": r[1]} for r in top_pages_res.all()]
|
| 357 |
+
|
| 358 |
+
stmt_geo = select(AnalyticsTraffic.geo, func.count(AnalyticsTraffic.id))\
|
| 359 |
+
.group_by(AnalyticsTraffic.geo)\
|
| 360 |
+
.order_by(func.count(AnalyticsTraffic.id).desc())\
|
| 361 |
+
.limit(5)
|
| 362 |
+
top_geo_res = await db.execute(stmt_geo)
|
| 363 |
+
top_geo = [{"geo": r[0] or "Unknown", "count": r[1]} for r in top_geo_res.all()]
|
| 364 |
+
|
| 365 |
+
daily_trend = []
|
| 366 |
+
for i in range(6, -1, -1):
|
| 367 |
+
day = now - timedelta(days=i)
|
| 368 |
+
day_start = day.replace(hour=0, minute=0, second=0, microsecond=0)
|
| 369 |
+
day_end = day.replace(hour=23, minute=59, second=59, microsecond=999999)
|
| 370 |
+
stmt_trend = select(func.count(AnalyticsTraffic.id))\
|
| 371 |
+
.where(AnalyticsTraffic.timestamp.between(day_start, day_end))
|
| 372 |
+
count = (await db.execute(stmt_trend)).scalar() or 0
|
| 373 |
+
daily_trend.append({"date": day_start.date().isoformat(), "count": count})
|
| 374 |
+
|
| 375 |
+
return {
|
| 376 |
+
"success": True,
|
| 377 |
+
"totalHits": total_hits,
|
| 378 |
+
"topPages": top_pages,
|
| 379 |
+
"topGeo": top_geo,
|
| 380 |
+
"dailyTrend": daily_trend
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
elif action == "getLPKDashboardDataServer":
|
| 384 |
+
stmt_leads = select(LPKRegistrationLead)
|
| 385 |
+
leads_res = await db.execute(stmt_leads)
|
| 386 |
+
lead_records = leads_res.scalars().all()
|
| 387 |
+
|
| 388 |
+
stmt_talents = select(Talent.email, Talent.name, Talent.phone)
|
| 389 |
+
talents_res = await db.execute(stmt_talents)
|
| 390 |
+
talent_lookup = {r[0].lower().strip(): {"name": r[1], "phone": r[2]} for r in talents_res.all() if r[0]}
|
| 391 |
+
|
| 392 |
+
leads = []
|
| 393 |
+
completed_leads = 0
|
| 394 |
+
outreach_leads = 0
|
| 395 |
+
|
| 396 |
+
for record in reversed(lead_records):
|
| 397 |
+
email = record.email.lower().strip() if record.email else ""
|
| 398 |
+
status = record.status or "Pending LPK Outreach"
|
| 399 |
+
|
| 400 |
+
if status in ["Onsite Certified", "Certified"]:
|
| 401 |
+
completed_leads += 1
|
| 402 |
+
if status in ["Ongoing Outreach", "LPK Outreach"]:
|
| 403 |
+
outreach_leads += 1
|
| 404 |
+
|
| 405 |
+
t_info = talent_lookup.get(email, {"name": "Talenta Brigawan", "phone": record.talent_phone or "-"})
|
| 406 |
+
|
| 407 |
+
leads.append({
|
| 408 |
+
"timestamp": record.timestamp.isoformat() if record.timestamp else None,
|
| 409 |
+
"email": record.email,
|
| 410 |
+
"moduleId": record.module_id,
|
| 411 |
+
"branch": record.lpk_branch,
|
| 412 |
+
"status": status,
|
| 413 |
+
"phone": t_info["phone"] or record.talent_phone or "-",
|
| 414 |
+
"name": t_info["name"]
|
| 415 |
+
})
|
| 416 |
+
|
| 417 |
+
commission_flat_rate = 150000
|
| 418 |
+
total_commission = completed_leads * commission_flat_rate
|
| 419 |
+
|
| 420 |
+
return {
|
| 421 |
+
"success": True,
|
| 422 |
+
"stats": {
|
| 423 |
+
"total": len(lead_records),
|
| 424 |
+
"completed": completed_leads,
|
| 425 |
+
"outreach": outreach_leads,
|
| 426 |
+
"commission": total_commission
|
| 427 |
+
},
|
| 428 |
+
"leads": leads
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
elif action == "updateLPKLeadStatusServer":
|
| 432 |
+
if len(params) < 5:
|
| 433 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 434 |
+
admin_email, admin_token, target_email, module_id, next_status = params[0], params[1], params[2], params[3], params[4]
|
| 435 |
+
|
| 436 |
+
if not await local_verify_session(db, admin_email, admin_token):
|
| 437 |
+
return {"success": False, "error": "Sesi admin tidak valid."}
|
| 438 |
+
|
| 439 |
+
stmt = select(LPKRegistrationLead).where(
|
| 440 |
+
LPKRegistrationLead.email == target_email.lower().strip(),
|
| 441 |
+
LPKRegistrationLead.module_id == module_id
|
| 442 |
+
)
|
| 443 |
+
lead_res = await db.execute(stmt)
|
| 444 |
+
lead = lead_res.scalar_one_or_none()
|
| 445 |
+
if lead:
|
| 446 |
+
lead.status = next_status
|
| 447 |
+
else:
|
| 448 |
+
new_lead = LPKRegistrationLead(
|
| 449 |
+
email=target_email.lower().strip(),
|
| 450 |
+
module_id=module_id,
|
| 451 |
+
lpk_branch="Regional Hub",
|
| 452 |
+
status=next_status
|
| 453 |
+
)
|
| 454 |
+
db.add(new_lead)
|
| 455 |
+
|
| 456 |
+
if next_status == "Onsite Certified":
|
| 457 |
+
stmt_t = select(Talent).where(Talent.email == target_email.lower().strip())
|
| 458 |
+
t_res = await db.execute(stmt_t)
|
| 459 |
+
t = t_res.scalar_one_or_none()
|
| 460 |
+
if t:
|
| 461 |
+
t.green_score = (t.green_score or 0) + 100
|
| 462 |
+
db.add(t)
|
| 463 |
+
|
| 464 |
+
db.add(ActivityLog(
|
| 465 |
+
actor=admin_email,
|
| 466 |
+
action="Update LPK Lead Status",
|
| 467 |
+
log_metadata=f"Email: {target_email}, Module: {module_id}, Status: {next_status}"
|
| 468 |
+
))
|
| 469 |
+
await db.commit()
|
| 470 |
+
return {"success": True, "message": "Status lead berhasil diperbarui!"}
|
| 471 |
+
|
| 472 |
+
elif action == "updateCRMRecordServer":
|
| 473 |
+
if len(params) < 3:
|
| 474 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 475 |
+
admin_email, admin_token, crm_data = params[0], params[1], params[2]
|
| 476 |
+
|
| 477 |
+
if not await local_verify_session(db, admin_email, admin_token):
|
| 478 |
+
return {"success": False, "error": "Sesi admin tidak valid."}
|
| 479 |
+
|
| 480 |
+
crm_type = crm_data.get("type")
|
| 481 |
+
crm_id = crm_data.get("id")
|
| 482 |
+
crm_status = crm_data.get("status")
|
| 483 |
+
|
| 484 |
+
if crm_type == "talent":
|
| 485 |
+
stmt = select(Talent).where(Talent.talent_id == crm_id)
|
| 486 |
+
t_res = await db.execute(stmt)
|
| 487 |
+
t = t_res.scalar_one_or_none()
|
| 488 |
+
if t:
|
| 489 |
+
t.verification_status = crm_status
|
| 490 |
+
db.add(t)
|
| 491 |
+
|
| 492 |
+
db.add(ActivityLog(
|
| 493 |
+
actor=admin_email,
|
| 494 |
+
action="Update CRM",
|
| 495 |
+
log_metadata=f"Type: {crm_type}, ID: {crm_id}, Status: {crm_status}"
|
| 496 |
+
))
|
| 497 |
+
await db.commit()
|
| 498 |
+
return {"success": True}
|
| 499 |
+
|
| 500 |
+
elif action == "getCRMDataServer":
|
| 501 |
+
return {"success": True, "data": {}}
|
| 502 |
+
|
| 503 |
+
elif action == "getAdminUsersServer":
|
| 504 |
+
if len(params) < 2:
|
| 505 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 506 |
+
admin_email, admin_token = params[0], params[1]
|
| 507 |
+
if not await local_verify_session(db, admin_email, admin_token):
|
| 508 |
+
return {"success": False, "error": "Sesi admin tidak valid."}
|
| 509 |
+
|
| 510 |
+
stmt = select(ClientAccount).where(ClientAccount.role == "Admin")
|
| 511 |
+
admin_res = await db.execute(stmt)
|
| 512 |
+
admins = admin_res.scalars().all()
|
| 513 |
+
|
| 514 |
+
users = []
|
| 515 |
+
for i, a in enumerate(admins):
|
| 516 |
+
users.append({
|
| 517 |
+
"name": a.name,
|
| 518 |
+
"email": a.email,
|
| 519 |
+
"role": a.role,
|
| 520 |
+
"index": i
|
| 521 |
+
})
|
| 522 |
+
return {"success": True, "data": users}
|
| 523 |
+
|
| 524 |
+
elif action == "getAdminTalentsServer":
|
| 525 |
+
if len(params) < 2:
|
| 526 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 527 |
+
admin_email, admin_token = params[0], params[1]
|
| 528 |
+
if not await local_verify_session(db, admin_email, admin_token):
|
| 529 |
+
return {"success": False, "error": "Sesi admin tidak valid."}
|
| 530 |
+
|
| 531 |
+
stmt = select(Talent).order_by(Talent.created_at.desc())
|
| 532 |
+
talents_res = await db.execute(stmt)
|
| 533 |
+
talents = talents_res.scalars().all()
|
| 534 |
+
|
| 535 |
+
data = []
|
| 536 |
+
for t in talents:
|
| 537 |
+
data.append({
|
| 538 |
+
"talentId": t.talent_id,
|
| 539 |
+
"nama": t.name,
|
| 540 |
+
"kategori": t.category or "-",
|
| 541 |
+
"email": t.email,
|
| 542 |
+
"status": t.verification_status or "New",
|
| 543 |
+
"analysis": t.analysis or "-",
|
| 544 |
+
"cvLink": t.cv_link or "-"
|
| 545 |
+
})
|
| 546 |
+
return {"success": True, "data": data}
|
| 547 |
+
|
| 548 |
+
elif action == "getAdminEmployersServer":
|
| 549 |
+
if len(params) < 2:
|
| 550 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 551 |
+
admin_email, admin_token = params[0], params[1]
|
| 552 |
+
if not await local_verify_session(db, admin_email, admin_token):
|
| 553 |
+
return {"success": False, "error": "Sesi admin tidak valid."}
|
| 554 |
+
|
| 555 |
+
stmt = select(ClientAccount, Company).join(Company, ClientAccount.company_id == Company.id)
|
| 556 |
+
res = await db.execute(stmt)
|
| 557 |
+
|
| 558 |
+
data = []
|
| 559 |
+
for client, company in res.all():
|
| 560 |
+
data.append({
|
| 561 |
+
"email": client.email,
|
| 562 |
+
"name": client.name,
|
| 563 |
+
"perusahaan": company.name,
|
| 564 |
+
"role": client.role,
|
| 565 |
+
"tokens": company.credit_balance or 0,
|
| 566 |
+
"tier": company.tier or "free",
|
| 567 |
+
"status": client.status or "PENDING"
|
| 568 |
+
})
|
| 569 |
+
return {"success": True, "data": data}
|
| 570 |
+
|
| 571 |
+
elif action == "getPendingApprovalsServer":
|
| 572 |
+
if len(params) < 2:
|
| 573 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 574 |
+
admin_email, admin_token = params[0], params[1]
|
| 575 |
+
if not await local_verify_session(db, admin_email, admin_token):
|
| 576 |
+
return {"success": False, "error": "Sesi admin tidak valid."}
|
| 577 |
+
|
| 578 |
+
stmt = select(PendingEmployer).where(PendingEmployer.status == "PENDING")
|
| 579 |
+
pendings_res = await db.execute(stmt)
|
| 580 |
+
pendings = pendings_res.scalars().all()
|
| 581 |
+
|
| 582 |
+
data = []
|
| 583 |
+
for p in pendings:
|
| 584 |
+
data.append({
|
| 585 |
+
"type": "employer",
|
| 586 |
+
"id": p.email,
|
| 587 |
+
"name": p.pic_name,
|
| 588 |
+
"entitas": p.entity_name,
|
| 589 |
+
"website": p.website,
|
| 590 |
+
"jabatan": p.pic_jabatan,
|
| 591 |
+
"detail": "Registrasi Akun Korporasi",
|
| 592 |
+
"timestamp": p.timestamp.isoformat() if p.timestamp else None
|
| 593 |
+
})
|
| 594 |
+
return {"success": True, "data": data}
|
| 595 |
+
|
| 596 |
+
elif action == "prosesMeetingRequest":
|
| 597 |
+
if len(params) < 3:
|
| 598 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 599 |
+
email, token, data_meeting = params[0], params[1], params[2]
|
| 600 |
+
|
| 601 |
+
if not await local_verify_session(db, email, token):
|
| 602 |
+
return {"success": False, "error": "Sesi tidak valid."}
|
| 603 |
+
|
| 604 |
+
client_email = data_meeting.get("email")
|
| 605 |
+
perusahaan = data_meeting.get("perusahaan", "MOCK CORP")
|
| 606 |
+
nama = data_meeting.get("nama", "Recruiter")
|
| 607 |
+
topik = data_meeting.get("topik", "ESG Partnership")
|
| 608 |
+
pesan = data_meeting.get("pesan", "-")
|
| 609 |
+
selected_date = data_meeting.get("date", "")
|
| 610 |
+
selected_time = data_meeting.get("time", "")
|
| 611 |
+
|
| 612 |
+
date_text = f"{selected_date} {selected_time} WIB"
|
| 613 |
+
meet_url = f"https://meet.google.com/brg-esg-{secrets.token_hex(3)}"
|
| 614 |
+
|
| 615 |
+
subject = f"Thank You & Meeting Minutes: ESG Partnership Exploration - {perusahaan}"
|
| 616 |
+
html_body = f"""
|
| 617 |
+
<h3>Dear {nama},</h3>
|
| 618 |
+
<p>Thank you for scheduling the B2B ESG Partnership Exploration with the Brigawan Sustainability Advisor team.</p>
|
| 619 |
+
<p><strong>Meeting Details:</strong></p>
|
| 620 |
+
<ul>
|
| 621 |
+
<li><strong>Topic:</strong> {topik}</li>
|
| 622 |
+
<li><strong>Company:</strong> {perusahaan}</li>
|
| 623 |
+
<li><strong>Date & Time:</strong> {date_text}</li>
|
| 624 |
+
<li><strong>Google Meet Room:</strong> <a href="{meet_url}">{meet_url}</a></li>
|
| 625 |
+
</ul>
|
| 626 |
+
<p>Best regards,<br/>yabeskn@briga.id<br/>Brigawan AI Notetaker & Compliance Assistant</p>
|
| 627 |
+
"""
|
| 628 |
+
await asyncio.to_thread(email_service.send_html_email, client_email, subject, html_body)
|
| 629 |
+
|
| 630 |
+
admin_subject = f"[NEW BOOKING] ESG B2B Meeting - {perusahaan}"
|
| 631 |
+
admin_body = f"""
|
| 632 |
+
Ada permintaan meeting terverifikasi baru:<br/><br/>
|
| 633 |
+
Nama: {nama}<br/>
|
| 634 |
+
Perusahaan: {perusahaan}<br/>
|
| 635 |
+
Email Klien: {client_email}<br/>
|
| 636 |
+
Topik: {topik}<br/>
|
| 637 |
+
Waktu: {date_text}<br/>
|
| 638 |
+
Google Meet Link: <a href="{meet_url}">{meet_url}</a><br/><br/>
|
| 639 |
+
Pesan Klien:<br/>
|
| 640 |
+
{pesan}
|
| 641 |
+
"""
|
| 642 |
+
await asyncio.to_thread(email_service.send_html_email, "info@briga.id", admin_subject, admin_body)
|
| 643 |
+
|
| 644 |
+
return {
|
| 645 |
+
"success": True,
|
| 646 |
+
"meetUrl": meet_url,
|
| 647 |
+
"dateText": date_text,
|
| 648 |
+
"host": "Brigawan Sustainability Advisor"
|
| 649 |
+
}
|
| 650 |
+
|
| 651 |
+
elif action == "submitTalentRegistration":
|
| 652 |
+
if len(params) < 1:
|
| 653 |
+
return {"success": False, "error": "Parameter kurang."}
|
| 654 |
+
form_data = params[0]
|
| 655 |
+
|
| 656 |
+
name = form_data.get("nama")
|
| 657 |
+
email = form_data.get("email")
|
| 658 |
+
password = form_data.get("password")
|
| 659 |
+
|
| 660 |
+
if not email or not name or not password:
|
| 661 |
+
return {"success": False, "error": "Nama, email, dan password wajib diisi."}
|
| 662 |
+
|
| 663 |
+
from app.services.auth_service import register_talent
|
| 664 |
+
reg_data = {
|
| 665 |
+
"name": name,
|
| 666 |
+
"email": email,
|
| 667 |
+
"password": password,
|
| 668 |
+
"phone": form_data.get("telepon", ""),
|
| 669 |
+
"education": form_data.get("pendidikan", ""),
|
| 670 |
+
"experience": form_data.get("pengalaman", ""),
|
| 671 |
+
"location": form_data.get("kota", ""),
|
| 672 |
+
"skill_tags": form_data.get("sertifikasiLain", ""),
|
| 673 |
+
"cv_link": form_data.get("cvLink", "")
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
try:
|
| 677 |
+
res = await register_talent(db, reg_data)
|
| 678 |
+
welcome_subject = "Selamat Datang di Brigawan - Portal Green Talent"
|
| 679 |
+
welcome_html = f"""
|
| 680 |
+
<h3>Halo {name}!</h3>
|
| 681 |
+
<p>Pendaftaran akun Anda di portal Brigawan telah berhasil dilakukan.</p>
|
| 682 |
+
<p>3 koin gratis trial Anda telah diaktifkan untuk memulai navigasi karir hijau Anda.</p>
|
| 683 |
+
"""
|
| 684 |
+
await asyncio.to_thread(email_service.send_html_email, email, welcome_subject, welcome_html)
|
| 685 |
+
|
| 686 |
+
talent_id = res.get("user", {}).get("id", "BRIGA-GT-MOCK")
|
| 687 |
+
return {
|
| 688 |
+
"success": True,
|
| 689 |
+
"talentId": talent_id,
|
| 690 |
+
"data": {
|
| 691 |
+
"id": talent_id,
|
| 692 |
+
"name": name,
|
| 693 |
+
"email": email,
|
| 694 |
+
"verification": "Pending Docs",
|
| 695 |
+
"score": 70,
|
| 696 |
+
"kategori": "Semi-Skilled"
|
| 697 |
+
},
|
| 698 |
+
"evaluation": {
|
| 699 |
+
"nama": name,
|
| 700 |
+
"skor": "70",
|
| 701 |
+
"kategori": "Semi-Skilled",
|
| 702 |
+
"analisis": "Initial Registration Vetting",
|
| 703 |
+
"advisory": "-",
|
| 704 |
+
"skills": [],
|
| 705 |
+
"verified": False
|
| 706 |
+
}
|
| 707 |
+
}
|
| 708 |
+
except Exception as e:
|
| 709 |
+
return {"success": False, "error": str(e)}
|
| 710 |
+
|
| 711 |
+
elif action == "purgeSheetTalent":
|
| 712 |
+
return {"success": True}
|
| 713 |
+
|
| 714 |
+
else:
|
| 715 |
+
logger.warning(f"[LegacyGASCompat] Unknown Action: {action}")
|
| 716 |
+
return {"success": False, "error": f"Aksi '{action}' belum didukung."}
|
| 717 |
+
|
| 718 |
+
except Exception as ex:
|
| 719 |
+
logger.error(f"[LegacyGASCompat] Error during action {action}: {ex}")
|
| 720 |
+
return {"success": False, "error": str(ex)}
|
app/api/talent.py
CHANGED
|
@@ -1,876 +1,876 @@
|
|
| 1 |
-
"""Talent API Routes — Profile, Pathway, Green Score, Interview, Secure Data.
|
| 2 |
-
|
| 3 |
-
All endpoints require authentication via JWT middleware.
|
| 4 |
-
Public endpoints: /v1/talent/verify-certificate
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import base64
|
| 8 |
-
import re
|
| 9 |
-
from datetime import datetime, timezone
|
| 10 |
-
from typing import Optional, Dict, Any
|
| 11 |
-
|
| 12 |
-
from fastapi import APIRouter, Depends, Query, Request, UploadFile, File, Form
|
| 13 |
-
from pydantic import BaseModel
|
| 14 |
-
from sqlalchemy import select, func
|
| 15 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 16 |
-
import httpx
|
| 17 |
-
from loguru import logger
|
| 18 |
-
|
| 19 |
-
from app.database import get_db
|
| 20 |
-
from app.models.talent import Talent
|
| 21 |
-
from app.models.job import TalentPathway
|
| 22 |
-
from app.config.settings import settings
|
| 23 |
-
from app.services.security_service import security_service
|
| 24 |
-
from app.services.ai_service import verify_screenshot_with_gemini
|
| 25 |
-
|
| 26 |
-
from app.schemas.talent import (
|
| 27 |
-
CertificateResponse,
|
| 28 |
-
ChatRequest,
|
| 29 |
-
ChatResponse,
|
| 30 |
-
EvaluateGrillMeRequest,
|
| 31 |
-
EvaluateGrillMeResponse,
|
| 32 |
-
GrillMeQuestionsResponse,
|
| 33 |
-
PathwayResponse,
|
| 34 |
-
SecureTalentDataResponse,
|
| 35 |
-
SubmitProofRequest,
|
| 36 |
-
SubmitProofResponse,
|
| 37 |
-
SubmitQuizRequest,
|
| 38 |
-
SubmitQuizResponse,
|
| 39 |
-
TalentProfileResponse,
|
| 40 |
-
UpdateProfileRequest,
|
| 41 |
-
UpdateProfileResponse,
|
| 42 |
-
VerifyCertificateRequest,
|
| 43 |
-
VerifyCertificateResponse,
|
| 44 |
-
)
|
| 45 |
-
from app.services.talent_service import (
|
| 46 |
-
_get_chat_stats,
|
| 47 |
-
_get_pathway,
|
| 48 |
-
chat_with_brigawan,
|
| 49 |
-
evaluate_grillme,
|
| 50 |
-
generate_career_pathway,
|
| 51 |
-
generate_grillme_questions,
|
| 52 |
-
get_pathway_certificate,
|
| 53 |
-
get_secure_talent_data,
|
| 54 |
-
get_talent_profile,
|
| 55 |
-
submit_action_proof,
|
| 56 |
-
submit_quiz_answers,
|
| 57 |
-
update_talent_profile,
|
| 58 |
-
verify_certificate,
|
| 59 |
-
)
|
| 60 |
-
|
| 61 |
-
router = APIRouter(prefix="/v1/talent", tags=["Talent"])
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
class LinkedInOAuthRequest(BaseModel):
|
| 65 |
-
code: str
|
| 66 |
-
redirect_uri: str
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def _calc_green_score(progress, completed):
|
| 70 |
-
from app.services.talent_service import POINTS_PROOF, POINTS_QUIZ
|
| 71 |
-
score = 0
|
| 72 |
-
for stg_key, actions in (progress or {}).items():
|
| 73 |
-
if isinstance(actions, list):
|
| 74 |
-
for a in actions:
|
| 75 |
-
if isinstance(a, dict) and a.get("done"):
|
| 76 |
-
score += POINTS_PROOF
|
| 77 |
-
score += len(completed or []) * POINTS_QUIZ
|
| 78 |
-
return score
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def _check_auth(req: Request) -> Optional[str]:
|
| 82 |
-
"""Check authentication from middleware. Returns user email or None."""
|
| 83 |
-
email = getattr(req.state, "user_email", None)
|
| 84 |
-
if not email:
|
| 85 |
-
return None
|
| 86 |
-
return email
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
# ─── Profile ────────────────────────────────────────────────────────────────
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
@router.get("/profile", response_model=TalentProfileResponse)
|
| 93 |
-
async def api_get_talent_profile(
|
| 94 |
-
req: Request,
|
| 95 |
-
db: AsyncSession = Depends(get_db),
|
| 96 |
-
):
|
| 97 |
-
"""Get full talent dashboard profile with badges, pathway, academy, chat stats."""
|
| 98 |
-
email = _check_auth(req)
|
| 99 |
-
if not email:
|
| 100 |
-
return TalentProfileResponse(success=False, error="Authentication required.")
|
| 101 |
-
|
| 102 |
-
result = await get_talent_profile(db, email)
|
| 103 |
-
return TalentProfileResponse(
|
| 104 |
-
success=result.get("success", False),
|
| 105 |
-
data=result.get("data"),
|
| 106 |
-
error=result.get("error"),
|
| 107 |
-
)
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
@router.put("/profile", response_model=UpdateProfileResponse)
|
| 111 |
-
async def api_update_talent_profile(
|
| 112 |
-
req: Request,
|
| 113 |
-
form_data: UpdateProfileRequest,
|
| 114 |
-
db: AsyncSession = Depends(get_db),
|
| 115 |
-
):
|
| 116 |
-
"""Update talent profile fields."""
|
| 117 |
-
email = _check_auth(req)
|
| 118 |
-
if not email:
|
| 119 |
-
return UpdateProfileResponse(success=False, error="Authentication required.")
|
| 120 |
-
|
| 121 |
-
result = await update_talent_profile(db, email, form_data.model_dump(exclude_none=True))
|
| 122 |
-
return UpdateProfileResponse(
|
| 123 |
-
success=result.get("success", False),
|
| 124 |
-
message=result.get("message", ""),
|
| 125 |
-
error=result.get("error"),
|
| 126 |
-
)
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
# ─── Career Pathway ─────────────────────────────────────────────────────────
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
@router.get("/pathway", response_model=PathwayResponse)
|
| 133 |
-
async def api_get_pathway(
|
| 134 |
-
req: Request,
|
| 135 |
-
db: AsyncSession = Depends(get_db),
|
| 136 |
-
):
|
| 137 |
-
"""Get existing career pathway for the authenticated talent."""
|
| 138 |
-
email = _check_auth(req)
|
| 139 |
-
if not email:
|
| 140 |
-
return PathwayResponse(success=False, error="Authentication required.")
|
| 141 |
-
|
| 142 |
-
result = await _get_pathway(db, email)
|
| 143 |
-
return PathwayResponse(
|
| 144 |
-
success=True,
|
| 145 |
-
pathway=result.get("pathway", []),
|
| 146 |
-
progress=result.get("progress", {}),
|
| 147 |
-
completedStages=result.get("completedStages", []),
|
| 148 |
-
greenScore=result.get("greenScore", 0),
|
| 149 |
-
cached=True,
|
| 150 |
-
)
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
@router.post("/pathway/generate", response_model=PathwayResponse)
|
| 154 |
-
async def api_generate_pathway(
|
| 155 |
-
req: Request,
|
| 156 |
-
db: AsyncSession = Depends(get_db),
|
| 157 |
-
):
|
| 158 |
-
"""Generate AI-powered career pathway (5 stages with actions, quizzes).
|
| 159 |
-
Returns cached version if exists.
|
| 160 |
-
"""
|
| 161 |
-
email = _check_auth(req)
|
| 162 |
-
if not email:
|
| 163 |
-
return PathwayResponse(success=False, error="Authentication required.")
|
| 164 |
-
|
| 165 |
-
result = await generate_career_pathway(db, email)
|
| 166 |
-
return PathwayResponse(
|
| 167 |
-
success=result.get("success", False),
|
| 168 |
-
pathway=result.get("pathway", []),
|
| 169 |
-
progress=result.get("progress", {}),
|
| 170 |
-
completedStages=result.get("completedStages", []),
|
| 171 |
-
greenScore=result.get("greenScore", 0),
|
| 172 |
-
cached=result.get("cached", False),
|
| 173 |
-
error=result.get("error"),
|
| 174 |
-
)
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
@router.post("/pathway/proof", response_model=SubmitProofResponse)
|
| 178 |
-
async def api_submit_proof(
|
| 179 |
-
req: Request,
|
| 180 |
-
body: SubmitProofRequest,
|
| 181 |
-
db: AsyncSession = Depends(get_db),
|
| 182 |
-
):
|
| 183 |
-
"""Submit proof for a specific action in the career pathway."""
|
| 184 |
-
email = _check_auth(req)
|
| 185 |
-
if not email:
|
| 186 |
-
return SubmitProofResponse(success=False, error="Authentication required.")
|
| 187 |
-
|
| 188 |
-
result = await submit_action_proof(db, email, body.stage, body.action_index, body.proof_text)
|
| 189 |
-
return SubmitProofResponse(
|
| 190 |
-
success=result.get("success", False),
|
| 191 |
-
progress=result.get("progress", {}),
|
| 192 |
-
completedStages=result.get("completedStages", []),
|
| 193 |
-
greenScore=result.get("greenScore", 0),
|
| 194 |
-
allActionsProven=result.get("allActionsProven", False),
|
| 195 |
-
error=result.get("error"),
|
| 196 |
-
)
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
@router.post("/pathway/quiz", response_model=SubmitQuizResponse)
|
| 200 |
-
async def api_submit_quiz(
|
| 201 |
-
req: Request,
|
| 202 |
-
body: SubmitQuizRequest,
|
| 203 |
-
db: AsyncSession = Depends(get_db),
|
| 204 |
-
):
|
| 205 |
-
"""Submit quiz answers for a stage. All actions must be proven first.
|
| 206 |
-
All answers must be correct to pass.
|
| 207 |
-
"""
|
| 208 |
-
email = _check_auth(req)
|
| 209 |
-
if not email:
|
| 210 |
-
return SubmitQuizResponse(success=False, error="Authentication required.")
|
| 211 |
-
|
| 212 |
-
result = await submit_quiz_answers(db, email, body.stage, body.answers)
|
| 213 |
-
return SubmitQuizResponse(
|
| 214 |
-
success=result.get("success", False),
|
| 215 |
-
completedStages=result.get("completedStages", []),
|
| 216 |
-
greenScore=result.get("greenScore", 0),
|
| 217 |
-
stageCompleted=result.get("stageCompleted", False),
|
| 218 |
-
completedStageTitle=result.get("completedStageTitle", ""),
|
| 219 |
-
error=result.get("error"),
|
| 220 |
-
)
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
@router.get("/pathway/certificate", response_model=CertificateResponse)
|
| 224 |
-
async def api_get_certificate(
|
| 225 |
-
req: Request,
|
| 226 |
-
stage: int = Query(..., description="Stage number (1-5)"),
|
| 227 |
-
db: AsyncSession = Depends(get_db),
|
| 228 |
-
):
|
| 229 |
-
"""Get certificate for a completed stage."""
|
| 230 |
-
email = _check_auth(req)
|
| 231 |
-
if not email:
|
| 232 |
-
return CertificateResponse(success=False, error="Authentication required.")
|
| 233 |
-
|
| 234 |
-
result = await get_pathway_certificate(db, email, stage)
|
| 235 |
-
return CertificateResponse(
|
| 236 |
-
success=result.get("success", False),
|
| 237 |
-
certificate=result.get("certificate"),
|
| 238 |
-
error=result.get("error"),
|
| 239 |
-
)
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
@router.post("/linkedin-oauth")
|
| 243 |
-
async def api_linkedin_oauth(
|
| 244 |
-
req: Request,
|
| 245 |
-
body: LinkedInOAuthRequest,
|
| 246 |
-
db: AsyncSession = Depends(get_db)
|
| 247 |
-
):
|
| 248 |
-
"""Exchange OAuth code for LinkedIn Access Token, verify name, encrypt, and save to DB."""
|
| 249 |
-
email = _check_auth(req)
|
| 250 |
-
if not email:
|
| 251 |
-
return {"success": False, "error": "Authentication required."}
|
| 252 |
-
|
| 253 |
-
# 1. Fetch Talent from DB
|
| 254 |
-
result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
|
| 255 |
-
talent = result.scalar_one_or_none()
|
| 256 |
-
if not talent:
|
| 257 |
-
return {"success": False, "error": "Profil talent tidak ditemukan."}
|
| 258 |
-
|
| 259 |
-
# Mock/Bypass mode for development
|
| 260 |
-
if settings.debug and (body.code.startswith("mock_code_") or not settings.linkedin_client_id or settings.linkedin_client_id == "YOUR_LINKEDIN_CLIENT_ID"):
|
| 261 |
-
if body.code.startswith("mock_code_"):
|
| 262 |
-
linkedin_name = body.code.replace("mock_code_", "").replace("_", " ").strip()
|
| 263 |
-
else:
|
| 264 |
-
linkedin_name = talent.name
|
| 265 |
-
|
| 266 |
-
import difflib
|
| 267 |
-
n1 = " ".join(talent.name.lower().strip().split())
|
| 268 |
-
n2 = " ".join(linkedin_name.lower().strip().split())
|
| 269 |
-
similarity_ratio = difflib.SequenceMatcher(None, n1, n2).ratio()
|
| 270 |
-
|
| 271 |
-
n1_words = n1.split()
|
| 272 |
-
n2_words = n2.split()
|
| 273 |
-
common_words = set(n1_words).intersection(set(n2_words))
|
| 274 |
-
num_common_words = len(common_words)
|
| 275 |
-
either_single_word = (len(n1_words) <= 1 or len(n2_words) <= 1)
|
| 276 |
-
|
| 277 |
-
is_valid = (
|
| 278 |
-
similarity_ratio >= 0.75 or
|
| 279 |
-
num_common_words >= 2 or
|
| 280 |
-
(either_single_word and num_common_words >= 1)
|
| 281 |
-
)
|
| 282 |
-
|
| 283 |
-
logger.info(f"[Mock OAuth] Name comparison: Talent='{talent.name}', LinkedIn='{linkedin_name}', ratio={similarity_ratio:.4f}, common={num_common_words}")
|
| 284 |
-
|
| 285 |
-
if not is_valid:
|
| 286 |
-
return {
|
| 287 |
-
"success": False,
|
| 288 |
-
"error": f"Nama akun LinkedIn ('{linkedin_name}') tidak sesuai dengan nama profil Anda ('{talent.name}')."
|
| 289 |
-
}
|
| 290 |
-
|
| 291 |
-
dek = await security_service.get_or_create_profile_dek(db, talent.id)
|
| 292 |
-
mock_token = f"mock_access_token_{linkedin_name.replace(' ', '_')}"
|
| 293 |
-
encrypted_token = security_service._encrypt_with_dek(dek, mock_token)
|
| 294 |
-
|
| 295 |
-
talent.linkedin_token = encrypted_token
|
| 296 |
-
if not talent.linkedin_link:
|
| 297 |
-
talent.linkedin_link = f"https://linkedin.com/in/mock_{linkedin_name.replace(' ', '_').lower()}"
|
| 298 |
-
|
| 299 |
-
db.add(talent)
|
| 300 |
-
await db.commit()
|
| 301 |
-
|
| 302 |
-
return {
|
| 303 |
-
"success": True,
|
| 304 |
-
"message": "Akun LinkedIn berhasil dihubungkan dan diverifikasi (Mock Mode).",
|
| 305 |
-
"linkedin_name": linkedin_name
|
| 306 |
-
}
|
| 307 |
-
|
| 308 |
-
# 2. Call LinkedIn Token API
|
| 309 |
-
token_url = "https://www.linkedin.com/oauth/v2/accessToken"
|
| 310 |
-
payload = {
|
| 311 |
-
"grant_type": "authorization_code",
|
| 312 |
-
"code": body.code,
|
| 313 |
-
"redirect_uri": body.redirect_uri,
|
| 314 |
-
"client_id": settings.linkedin_client_id,
|
| 315 |
-
"client_secret": settings.linkedin_client_secret
|
| 316 |
-
}
|
| 317 |
-
|
| 318 |
-
try:
|
| 319 |
-
async with httpx.AsyncClient(timeout=15.0) as client:
|
| 320 |
-
resp = await client.post(token_url, data=payload)
|
| 321 |
-
if resp.status_code != 200:
|
| 322 |
-
logger.error(f"LinkedIn Token Exchange failed: {resp.status_code} - {resp.text}")
|
| 323 |
-
return {"success": False, "error": "Gagal menukarkan kode otorisasi LinkedIn."}
|
| 324 |
-
|
| 325 |
-
token_data = resp.json()
|
| 326 |
-
access_token = token_data.get("access_token")
|
| 327 |
-
if not access_token:
|
| 328 |
-
return {"success": False, "error": "Token otorisasi kosong dari LinkedIn."}
|
| 329 |
-
|
| 330 |
-
# 3. Retrieve User Profile from LinkedIn (OpenID Connect /userinfo or /v2/me)
|
| 331 |
-
# Modern OIDC endpoint returns full name & email
|
| 332 |
-
profile_url = "https://api.linkedin.com/v2/userinfo"
|
| 333 |
-
headers = {"Authorization": f"Bearer {access_token}"}
|
| 334 |
-
profile_resp = await client.get(profile_url, headers=headers)
|
| 335 |
-
|
| 336 |
-
if profile_resp.status_code != 200:
|
| 337 |
-
# Fallback to legacy v2 profile endpoint if OIDC is not active
|
| 338 |
-
profile_url = "https://api.linkedin.com/v2/me"
|
| 339 |
-
profile_resp = await client.get(profile_url, headers=headers)
|
| 340 |
-
|
| 341 |
-
if profile_resp.status_code != 200:
|
| 342 |
-
return {"success": False, "error": "Gagal mengambil profil akun LinkedIn Anda."}
|
| 343 |
-
|
| 344 |
-
profile_data = profile_resp.json()
|
| 345 |
-
# Try to resolve full name
|
| 346 |
-
linkedin_name = profile_data.get("name")
|
| 347 |
-
if not linkedin_name:
|
| 348 |
-
given_name = profile_data.get("givenName", {}).get("localized", {}).get("en_US", "")
|
| 349 |
-
family_name = profile_data.get("familyName", {}).get("localized", {}).get("en_US", "")
|
| 350 |
-
linkedin_name = f"{given_name} {family_name}".strip()
|
| 351 |
-
|
| 352 |
-
if not linkedin_name:
|
| 353 |
-
linkedin_name = f"{profile_data.get('given_name', '')} {profile_data.get('family_name', '')}".strip()
|
| 354 |
-
|
| 355 |
-
# 4. Perform Name Verification (Enhanced Similarity Match via difflib)
|
| 356 |
-
import difflib
|
| 357 |
-
n1 = " ".join(talent.name.lower().strip().split())
|
| 358 |
-
n2 = " ".join(linkedin_name.lower().strip().split())
|
| 359 |
-
|
| 360 |
-
similarity_ratio = difflib.SequenceMatcher(None, n1, n2).ratio()
|
| 361 |
-
|
| 362 |
-
n1_words = n1.split()
|
| 363 |
-
n2_words = n2.split()
|
| 364 |
-
common_words = set(n1_words).intersection(set(n2_words))
|
| 365 |
-
num_common_words = len(common_words)
|
| 366 |
-
either_single_word = (len(n1_words) <= 1 or len(n2_words) <= 1)
|
| 367 |
-
|
| 368 |
-
is_valid = (
|
| 369 |
-
similarity_ratio >= 0.75 or
|
| 370 |
-
num_common_words >= 2 or
|
| 371 |
-
(either_single_word and num_common_words >= 1)
|
| 372 |
-
)
|
| 373 |
-
|
| 374 |
-
logger.info(f"LinkedIn Name comparison details: Talent='{talent.name}', LinkedIn='{linkedin_name}', ratio={similarity_ratio:.4f}, common={num_common_words}")
|
| 375 |
-
|
| 376 |
-
if not is_valid:
|
| 377 |
-
logger.warning(f"LinkedIn Identity verification failed: Talent='{talent.name}', LinkedIn='{linkedin_name}' (ratio={similarity_ratio:.4f}, common={num_common_words})")
|
| 378 |
-
return {
|
| 379 |
-
"success": False,
|
| 380 |
-
"error": f"Nama akun LinkedIn ('{linkedin_name}') tidak sesuai dengan nama profil Anda ('{talent.name}')."
|
| 381 |
-
}
|
| 382 |
-
|
| 383 |
-
# 5. Encrypt access token using DEK Envelope Encryption
|
| 384 |
-
dek = await security_service.get_or_create_profile_dek(db, talent.id)
|
| 385 |
-
encrypted_token = security_service._encrypt_with_dek(dek, access_token)
|
| 386 |
-
|
| 387 |
-
# 6. Save encrypted token and LinkedIn link to DB
|
| 388 |
-
talent.linkedin_token = encrypted_token
|
| 389 |
-
# Optionally sync the public LinkedIn link if found or set it
|
| 390 |
-
sub_id = profile_data.get("sub", "")
|
| 391 |
-
if sub_id and not talent.linkedin_link:
|
| 392 |
-
talent.linkedin_link = f"https://linkedin.com/in/{sub_id}"
|
| 393 |
-
|
| 394 |
-
db.add(talent)
|
| 395 |
-
await db.commit()
|
| 396 |
-
|
| 397 |
-
return {
|
| 398 |
-
"success": True,
|
| 399 |
-
"message": "Akun LinkedIn berhasil dihubungkan dan diverifikasi.",
|
| 400 |
-
"linkedin_name": linkedin_name
|
| 401 |
-
}
|
| 402 |
-
|
| 403 |
-
except Exception as e:
|
| 404 |
-
logger.error(f"api_linkedin_oauth exception: {e}")
|
| 405 |
-
return {"success": False, "error": f"Kesalahan sistem: {str(e)}"}
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
@router.post("/pathway/verify-linkedin-api")
|
| 409 |
-
async def api_verify_pathway_linkedin(
|
| 410 |
-
req: Request,
|
| 411 |
-
body: Dict[str, Any], # expects stage, action_index
|
| 412 |
-
db: AsyncSession = Depends(get_db)
|
| 413 |
-
):
|
| 414 |
-
"""Pulls connected talent's posts from LinkedIn, verifies hashtag and Talent ID to approve action."""
|
| 415 |
-
email = _check_auth(req)
|
| 416 |
-
if not email:
|
| 417 |
-
return {"success": False, "error": "Authentication required."}
|
| 418 |
-
|
| 419 |
-
stage = body.get("stage")
|
| 420 |
-
action_index = body.get("action_index")
|
| 421 |
-
if stage is None or action_index is None:
|
| 422 |
-
return {"success": False, "error": "Parameters 'stage' and 'action_index' are required."}
|
| 423 |
-
|
| 424 |
-
# 1. Fetch Talent & Pathway
|
| 425 |
-
t_result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
|
| 426 |
-
talent = t_result.scalar_one_or_none()
|
| 427 |
-
|
| 428 |
-
pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1))
|
| 429 |
-
pw = pw_result.scalar_one_or_none()
|
| 430 |
-
|
| 431 |
-
if not talent or not pw:
|
| 432 |
-
return {"success": False, "error": "Data profil atau pathway tidak ditemukan."}
|
| 433 |
-
|
| 434 |
-
if not talent.linkedin_token:
|
| 435 |
-
return {"success": False, "error": "Silakan hubungkan akun LinkedIn Anda terlebih dahulu."}
|
| 436 |
-
|
| 437 |
-
# 2. Decrypt LinkedIn token
|
| 438 |
-
dek = await security_service.get_or_create_profile_dek(db, talent.id)
|
| 439 |
-
access_token = security_service._decrypt_with_dek(dek, talent.linkedin_token)
|
| 440 |
-
|
| 441 |
-
challenge_code = f"BRG-CH-{stage}-{action_index + 1}"
|
| 442 |
-
verified_post_link = None
|
| 443 |
-
|
| 444 |
-
# 3. Handle Mock Verification Mode
|
| 445 |
-
if settings.debug and access_token.startswith("mock_"):
|
| 446 |
-
logger.info(f"[Mock OAuth] Simulating successful LinkedIn post validation for {challenge_code}")
|
| 447 |
-
verified_post_link = f"https://www.linkedin.com/feed/update/urn:li:share:mock_{challenge_code}"
|
| 448 |
-
else:
|
| 449 |
-
# Pull posts from LinkedIn API
|
| 450 |
-
# Retrieves author's posts/shares
|
| 451 |
-
sub_id = None
|
| 452 |
-
try:
|
| 453 |
-
async with httpx.AsyncClient(timeout=10.0) as client:
|
| 454 |
-
# Try userinfo (OIDC)
|
| 455 |
-
me_resp = await client.get("https://api.linkedin.com/v2/userinfo", headers={"Authorization": f"Bearer {access_token}"})
|
| 456 |
-
if me_resp.status_code == 200:
|
| 457 |
-
sub_id = me_resp.json().get("sub", "")
|
| 458 |
-
else:
|
| 459 |
-
# Try legacy v2/me
|
| 460 |
-
me_resp = await client.get("https://api.linkedin.com/v2/me", headers={"Authorization": f"Bearer {access_token}"})
|
| 461 |
-
if me_resp.status_code == 200:
|
| 462 |
-
sub_id = me_resp.json().get("id", "")
|
| 463 |
-
except Exception as e:
|
| 464 |
-
logger.error(f"Failed to fetch LinkedIn me profile URN: {e}")
|
| 465 |
-
|
| 466 |
-
if not sub_id:
|
| 467 |
-
# Fallback to parsed vanity URL link ONLY if API fetches failed
|
| 468 |
-
if talent.linkedin_link:
|
| 469 |
-
sub_id = talent.linkedin_link.split("/in/")[-1].split("?")[0].strip("/")
|
| 470 |
-
if not sub_id or sub_id == "me":
|
| 471 |
-
sub_id = "me"
|
| 472 |
-
|
| 473 |
-
shares_url = f"https://api.linkedin.com/v2/shares?q=owners&owners=urn:li:person:{sub_id}&count=20"
|
| 474 |
-
headers = {"Authorization": f"Bearer {access_token}", "X-Restli-Protocol-Version": "2.0.0"}
|
| 475 |
-
|
| 476 |
-
try:
|
| 477 |
-
async with httpx.AsyncClient(timeout=15.0) as client:
|
| 478 |
-
resp = await client.get(shares_url, headers=headers)
|
| 479 |
-
if resp.status_code != 200:
|
| 480 |
-
logger.error(f"Failed to fetch LinkedIn shares: {resp.status_code} - {resp.text}")
|
| 481 |
-
return {"success": False, "error": "Gagal menarik kiriman dari LinkedIn. Silakan coba beberapa saat lagi."}
|
| 482 |
-
|
| 483 |
-
posts_data = resp.json()
|
| 484 |
-
elements = posts_data.get("elements", [])
|
| 485 |
-
|
| 486 |
-
# 4. Search elements for validation criteria
|
| 487 |
-
# Hashtag: #BrigaPathway
|
| 488 |
-
# Text contains challenge_code (e.g. BRG-CH-1-1)
|
| 489 |
-
hashtag_pattern = re.compile(r"#BrigaPathway", re.IGNORECASE)
|
| 490 |
-
code_pattern = re.compile(re.escape(challenge_code), re.IGNORECASE)
|
| 491 |
-
|
| 492 |
-
for post in elements:
|
| 493 |
-
text = post.get("text", {}).get("text", "")
|
| 494 |
-
if hashtag_pattern.search(text) and code_pattern.search(text):
|
| 495 |
-
activity_urn = post.get("activity", "")
|
| 496 |
-
# Construct public URL template
|
| 497 |
-
verified_post_link = f"https://www.linkedin.com/feed/update/{activity_urn}"
|
| 498 |
-
break
|
| 499 |
-
|
| 500 |
-
if not verified_post_link:
|
| 501 |
-
return {
|
| 502 |
-
"success": False,
|
| 503 |
-
"error": f"Kiriman LinkedIn tidak ditemukan. Pastikan Anda telah memposting dengan hashtag '#BrigaPathway' dan Kode Tantangan '{challenge_code}' secara publik."
|
| 504 |
-
}
|
| 505 |
-
except Exception as e:
|
| 506 |
-
logger.error(f"api_verify_pathway_linkedin API call exception: {e}")
|
| 507 |
-
return {"success": False, "error": f"Gagal menghubungi server LinkedIn: {str(e)}"}
|
| 508 |
-
|
| 509 |
-
try:
|
| 510 |
-
# 5. Update Pathway Progress
|
| 511 |
-
progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
|
| 512 |
-
completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
|
| 513 |
-
pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
|
| 514 |
-
|
| 515 |
-
sk = str(stage)
|
| 516 |
-
if sk not in progress:
|
| 517 |
-
progress[sk] = []
|
| 518 |
-
|
| 519 |
-
while len(progress[sk]) <= action_index:
|
| 520 |
-
progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
|
| 521 |
-
|
| 522 |
-
progress[sk][action_index] = {
|
| 523 |
-
"done": True,
|
| 524 |
-
"proof": f"LinkedIn Verified Post: {verified_post_link}",
|
| 525 |
-
"ts": datetime.now(timezone.utc).isoformat(),
|
| 526 |
-
"status": "Approved"
|
| 527 |
-
}
|
| 528 |
-
|
| 529 |
-
# Recalculate score and save
|
| 530 |
-
new_score = _calc_green_score(progress, completed)
|
| 531 |
-
pw.progress_json = progress
|
| 532 |
-
pw.green_score = new_score
|
| 533 |
-
db.add(pw)
|
| 534 |
-
talent.green_score = new_score
|
| 535 |
-
db.add(talent)
|
| 536 |
-
await db.commit()
|
| 537 |
-
|
| 538 |
-
# Check if all actions in this stage are completed
|
| 539 |
-
stage_data = next((s for s in pathway if s.get("stage") == stage), None)
|
| 540 |
-
all_proven = False
|
| 541 |
-
if stage_data:
|
| 542 |
-
expected = len(stage_data.get("actions", []))
|
| 543 |
-
all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
|
| 544 |
-
|
| 545 |
-
return {
|
| 546 |
-
"success": True,
|
| 547 |
-
"progress": progress,
|
| 548 |
-
"completedStages": [str(s) for s in completed],
|
| 549 |
-
"greenScore": new_score,
|
| 550 |
-
"allActionsProven": all_proven,
|
| 551 |
-
"feedback": "Kiriman LinkedIn berhasil diverifikasi secara otomatis via API!"
|
| 552 |
-
}
|
| 553 |
-
|
| 554 |
-
except Exception as e:
|
| 555 |
-
logger.error(f"api_verify_pathway_linkedin exception: {e}")
|
| 556 |
-
return {"success": False, "error": f"Kesalahan sistem: {str(e)}"}
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
@router.post("/pathway/verify-linkedin-screenshot")
|
| 560 |
-
async def api_verify_pathway_screenshot(
|
| 561 |
-
req: Request,
|
| 562 |
-
file: UploadFile = File(...),
|
| 563 |
-
stage: int = Form(...),
|
| 564 |
-
action_index: int = Form(...),
|
| 565 |
-
db: AsyncSession = Depends(get_db)
|
| 566 |
-
):
|
| 567 |
-
"""Upload screenshot of LinkedIn post and use Gemini Vision to vet post contents."""
|
| 568 |
-
email = _check_auth(req)
|
| 569 |
-
if not email:
|
| 570 |
-
return {"success": False, "error": "Authentication required."}
|
| 571 |
-
|
| 572 |
-
# 1. Fetch Talent & Pathway
|
| 573 |
-
t_result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
|
| 574 |
-
talent = t_result.scalar_one_or_none()
|
| 575 |
-
|
| 576 |
-
pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1))
|
| 577 |
-
pw = pw_result.scalar_one_or_none()
|
| 578 |
-
|
| 579 |
-
if not talent or not pw:
|
| 580 |
-
return {"success": False, "error": "Data profil atau pathway tidak ditemukan."}
|
| 581 |
-
|
| 582 |
-
# 2. Read image bytes
|
| 583 |
-
try:
|
| 584 |
-
image_bytes = await file.read()
|
| 585 |
-
except Exception as e:
|
| 586 |
-
return {"success": False, "error": f"Gagal membaca file gambar: {str(e)}"}
|
| 587 |
-
|
| 588 |
-
challenge_code = f"BRG-CH-{stage}-{action_index + 1}"
|
| 589 |
-
|
| 590 |
-
# 3. Call AI Service Vetting Function or Bypass in Mock mode
|
| 591 |
-
if settings.debug and file.filename and "mock" in file.filename.lower():
|
| 592 |
-
logger.info(f"[Mock Vision] Bypassing Gemini Vision API for screenshot file {file.filename}")
|
| 593 |
-
vetting_result = {
|
| 594 |
-
"success": True,
|
| 595 |
-
"match": True,
|
| 596 |
-
"extracted_name": talent.name,
|
| 597 |
-
"has_hashtag": True,
|
| 598 |
-
"has_challenge_code": True,
|
| 599 |
-
"confidence": 0.95,
|
| 600 |
-
"feedback": "Screenshot postingan LinkedIn berhasil diverifikasi secara otomatis via AI (Mock Mode)."
|
| 601 |
-
}
|
| 602 |
-
else:
|
| 603 |
-
vetting_result = await verify_screenshot_with_gemini(
|
| 604 |
-
image_bytes=image_bytes,
|
| 605 |
-
talent_name=talent.name,
|
| 606 |
-
challenge_code=challenge_code
|
| 607 |
-
)
|
| 608 |
-
|
| 609 |
-
if not vetting_result.get("success"):
|
| 610 |
-
return {
|
| 611 |
-
"success": False,
|
| 612 |
-
"error": vetting_result.get("feedback", "Gagal menganalisis gambar screenshot via AI.")
|
| 613 |
-
}
|
| 614 |
-
|
| 615 |
-
if not vetting_result.get("match"):
|
| 616 |
-
return {
|
| 617 |
-
"success": False,
|
| 618 |
-
"error": vetting_result.get("feedback", "Hasil analisis AI: Gambar tidak memenuhi kriteria verifikasi.")
|
| 619 |
-
}
|
| 620 |
-
|
| 621 |
-
# 4. AI Verification Successful - Update Progress
|
| 622 |
-
progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
|
| 623 |
-
completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
|
| 624 |
-
pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
|
| 625 |
-
|
| 626 |
-
sk = str(stage)
|
| 627 |
-
if sk not in progress:
|
| 628 |
-
progress[sk] = []
|
| 629 |
-
|
| 630 |
-
while len(progress[sk]) <= action_index:
|
| 631 |
-
progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
|
| 632 |
-
|
| 633 |
-
progress[sk][action_index] = {
|
| 634 |
-
"done": True,
|
| 635 |
-
"proof": f"LinkedIn Screenshot verified by Gemini (Name: {vetting_result.get('extracted_name')}, Conf: {vetting_result.get('confidence')})",
|
| 636 |
-
"ts": datetime.now(timezone.utc).isoformat(),
|
| 637 |
-
"status": "Approved"
|
| 638 |
-
}
|
| 639 |
-
|
| 640 |
-
new_score = _calc_green_score(progress, completed)
|
| 641 |
-
pw.progress_json = progress
|
| 642 |
-
pw.green_score = new_score
|
| 643 |
-
db.add(pw)
|
| 644 |
-
talent.green_score = new_score
|
| 645 |
-
db.add(talent)
|
| 646 |
-
await db.commit()
|
| 647 |
-
|
| 648 |
-
stage_data = next((s for s in pathway if s.get("stage") == stage), None)
|
| 649 |
-
all_proven = False
|
| 650 |
-
if stage_data:
|
| 651 |
-
expected = len(stage_data.get("actions", []))
|
| 652 |
-
all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
|
| 653 |
-
|
| 654 |
-
return {
|
| 655 |
-
"success": True,
|
| 656 |
-
"progress": progress,
|
| 657 |
-
"completedStages": [str(s) for s in completed],
|
| 658 |
-
"greenScore": new_score,
|
| 659 |
-
"allActionsProven": all_proven,
|
| 660 |
-
"feedback": vetting_result.get("feedback", "Screenshot postingan LinkedIn berhasil diverifikasi secara otomatis via AI!")
|
| 661 |
-
}
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
# ─── AI Chat (Brigawan Career Coach) ────────────────────────────────────────
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
@router.post("/chat", response_model=ChatResponse)
|
| 668 |
-
async def api_chat(
|
| 669 |
-
req: Request,
|
| 670 |
-
body: ChatRequest,
|
| 671 |
-
db: AsyncSession = Depends(get_db),
|
| 672 |
-
):
|
| 673 |
-
"""Chat with Brigawan AI Career Coach. Limited to 10 chats per 24 hours."""
|
| 674 |
-
email = _check_auth(req)
|
| 675 |
-
if not email:
|
| 676 |
-
return ChatResponse(success=False, error="Authentication required.")
|
| 677 |
-
|
| 678 |
-
result = await chat_with_brigawan(db, email, body.message)
|
| 679 |
-
return ChatResponse(
|
| 680 |
-
success=result.get("success", False),
|
| 681 |
-
reply=result.get("reply", ""),
|
| 682 |
-
chatUsed=result.get("chatUsed", 0),
|
| 683 |
-
chatLimit=result.get("chatLimit", 10),
|
| 684 |
-
chatExpiry=result.get("chatExpiry", "-"),
|
| 685 |
-
limitReached=result.get("limitReached", False),
|
| 686 |
-
error=result.get("error"),
|
| 687 |
-
)
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
@router.get("/chat/stats", response_model=ChatResponse)
|
| 691 |
-
async def api_chat_stats(
|
| 692 |
-
req: Request,
|
| 693 |
-
db: AsyncSession = Depends(get_db),
|
| 694 |
-
):
|
| 695 |
-
"""Get AI chat usage statistics."""
|
| 696 |
-
email = _check_auth(req)
|
| 697 |
-
if not email:
|
| 698 |
-
return ChatResponse(success=False, error="Authentication required.")
|
| 699 |
-
|
| 700 |
-
stats = await _get_chat_stats(db, email)
|
| 701 |
-
return ChatResponse(
|
| 702 |
-
success=True,
|
| 703 |
-
chatUsed=stats.get("used", 0),
|
| 704 |
-
chatLimit=10,
|
| 705 |
-
chatExpiry=stats.get("expiryTime", "-"),
|
| 706 |
-
limitReached=stats.get("used", 0) >= 10,
|
| 707 |
-
)
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
# ─── Grill-Me Interview Simulation ──────────────────────────────────────────
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
@router.get("/grillme/questions", response_model=GrillMeQuestionsResponse)
|
| 714 |
-
async def api_grillme_questions(
|
| 715 |
-
req: Request,
|
| 716 |
-
category: str = Query("ESG Specialist", description="Green job category"),
|
| 717 |
-
):
|
| 718 |
-
"""Generate 3 interview simulation questions for a green job category."""
|
| 719 |
-
email = _check_auth(req)
|
| 720 |
-
if not email:
|
| 721 |
-
return GrillMeQuestionsResponse(success=False, error="Authentication required.")
|
| 722 |
-
|
| 723 |
-
result = generate_grillme_questions(category)
|
| 724 |
-
return GrillMeQuestionsResponse(
|
| 725 |
-
success=result.get("success", False),
|
| 726 |
-
questions=result.get("questions", []),
|
| 727 |
-
isFallback=result.get("isFallback", False),
|
| 728 |
-
error=result.get("error"),
|
| 729 |
-
)
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
@router.post("/grillme/evaluate", response_model=EvaluateGrillMeResponse)
|
| 733 |
-
async def api_grillme_evaluate(
|
| 734 |
-
req: Request,
|
| 735 |
-
body: EvaluateGrillMeRequest,
|
| 736 |
-
):
|
| 737 |
-
"""Evaluate interview answers and generate SWOT analysis."""
|
| 738 |
-
email = _check_auth(req)
|
| 739 |
-
if not email:
|
| 740 |
-
return EvaluateGrillMeResponse(success=False, error="Authentication required.")
|
| 741 |
-
|
| 742 |
-
result = evaluate_grillme(body.category, body.questions, body.answers)
|
| 743 |
-
return EvaluateGrillMeResponse(
|
| 744 |
-
success=result.get("success", False),
|
| 745 |
-
score=result.get("score", 0),
|
| 746 |
-
swot=result.get("swot"),
|
| 747 |
-
rawSWOTText=result.get("rawSWOTText", ""),
|
| 748 |
-
error=result.get("error"),
|
| 749 |
-
)
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
# ─── Secure Talent Data (PDP Compliant) ──────
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
@router.get("/secure/{talent_id}", response_model=SecureTalentDataResponse)
|
| 756 |
-
async def api_secure_talent_data(
|
| 757 |
-
req: Request,
|
| 758 |
-
talent_id: str,
|
| 759 |
-
db: AsyncSession = Depends(get_db),
|
| 760 |
-
):
|
| 761 |
-
"""Get secure talent data with PDP-compliant masking.
|
| 762 |
-
Returns full data if requester has unlocked this candidate, masked otherwise.
|
| 763 |
-
"""
|
| 764 |
-
email = _check_auth(req)
|
| 765 |
-
if not email:
|
| 766 |
-
return SecureTalentDataResponse(success=False, error="Authentication required.")
|
| 767 |
-
|
| 768 |
-
result = await get_secure_talent_data(db, talent_id, email)
|
| 769 |
-
return SecureTalentDataResponse(
|
| 770 |
-
success=result.get("success", False),
|
| 771 |
-
id_kandidat=result.get("id_kandidat", ""),
|
| 772 |
-
nama=result.get("nama", ""),
|
| 773 |
-
email=result.get("email", "[LOCKED]"),
|
| 774 |
-
pendidikan=result.get("pendidikan", ""),
|
| 775 |
-
pengalaman=result.get("pengalaman", ""),
|
| 776 |
-
k3_dasar=result.get("k3_dasar", ""),
|
| 777 |
-
k3_khusus=result.get("k3_khusus", ""),
|
| 778 |
-
sertifikasi=result.get("sertifikasi", ""),
|
| 779 |
-
bahasa=result.get("bahasa", ""),
|
| 780 |
-
cv_link=result.get("cv_link", "[LOCKED - Reveal to Download]"),
|
| 781 |
-
skor=result.get("skor", 0),
|
| 782 |
-
kategori=result.get("kategori", ""),
|
| 783 |
-
analisis=result.get("analisis", ""),
|
| 784 |
-
status=result.get("status", ""),
|
| 785 |
-
unlocked=result.get("unlocked", False),
|
| 786 |
-
error=result.get("error"),
|
| 787 |
-
)
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
# ─── Public: Certificate Verification ───────────────────────────────────────
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
@router.post("/verify-certificate", response_model=VerifyCertificateResponse)
|
| 794 |
-
async def api_verify_certificate(
|
| 795 |
-
body: VerifyCertificateRequest,
|
| 796 |
-
db: AsyncSession = Depends(get_db),
|
| 797 |
-
):
|
| 798 |
-
"""Public certificate verification via talent ID or SHA-256 hash.
|
| 799 |
-
No authentication required — used for shareable certificate links.
|
| 800 |
-
"""
|
| 801 |
-
result = await verify_certificate(db, body.talent_id, body.stage)
|
| 802 |
-
return VerifyCertificateResponse(
|
| 803 |
-
success=result.get("success", False),
|
| 804 |
-
data=result.get("data"),
|
| 805 |
-
error=result.get("error"),
|
| 806 |
-
)
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
# ─── Public: Magic Fill CV Vetting (Local Converter) ───────────────────────
|
| 810 |
-
|
| 811 |
-
from pydantic import BaseModel
|
| 812 |
-
|
| 813 |
-
class MagicFillRequest(BaseModel):
|
| 814 |
-
name: str
|
| 815 |
-
type: str
|
| 816 |
-
base64: str
|
| 817 |
-
|
| 818 |
-
@router.post("/magic-fill")
|
| 819 |
-
async def api_magic_fill_cv(
|
| 820 |
-
body: MagicFillRequest,
|
| 821 |
-
):
|
| 822 |
-
"""Refined CV Parsing: Convert PDF to MD using markitdown, then extract profile with Gemini.
|
| 823 |
-
No authentication required (called during signup flow).
|
| 824 |
-
"""
|
| 825 |
-
import base64
|
| 826 |
-
import tempfile
|
| 827 |
-
import os
|
| 828 |
-
from markitdown import MarkItDown
|
| 829 |
-
from app.services.ai_service import extract_cv_metadata
|
| 830 |
-
from loguru import logger
|
| 831 |
-
|
| 832 |
-
try:
|
| 833 |
-
# 1. Decode base64 to bytes
|
| 834 |
-
file_bytes = base64.b64decode(body.base64)
|
| 835 |
-
|
| 836 |
-
# 2. Determine file suffix
|
| 837 |
-
ext = ".pdf"
|
| 838 |
-
if "word" in body.type or body.name.lower().endswith(".docx"):
|
| 839 |
-
ext = ".docx"
|
| 840 |
-
elif body.name.lower().endswith(".doc"):
|
| 841 |
-
ext = ".doc"
|
| 842 |
-
elif body.name.lower().endswith(".html") or body.name.lower().endswith(".htm"):
|
| 843 |
-
ext = ".html"
|
| 844 |
-
elif body.name.lower().endswith(".txt"):
|
| 845 |
-
ext = ".txt"
|
| 846 |
-
|
| 847 |
-
# 3. Write temporarily to local storage
|
| 848 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp_file:
|
| 849 |
-
temp_file.write(file_bytes)
|
| 850 |
-
temp_path = temp_file.name
|
| 851 |
-
|
| 852 |
-
# 4. Process conversion via local markitdown
|
| 853 |
-
try:
|
| 854 |
-
markitdown = MarkItDown()
|
| 855 |
-
result = markitdown.convert(temp_path)
|
| 856 |
-
cv_markdown = result.text_content
|
| 857 |
-
finally:
|
| 858 |
-
# Clean up temp file safely
|
| 859 |
-
if os.path.exists(temp_path):
|
| 860 |
-
os.remove(temp_path)
|
| 861 |
-
|
| 862 |
-
# 5. Extract JSON metadata from the Markdown text using Gemini
|
| 863 |
-
if not cv_markdown or len(cv_markdown.strip()) < 50:
|
| 864 |
-
return {"success": False, "error": "Teks CV terlalu pendek atau kosong untuk dianalisis."}
|
| 865 |
-
|
| 866 |
-
extracted_data = await extract_cv_metadata(cv_markdown)
|
| 867 |
-
|
| 868 |
-
if "error" in extracted_data:
|
| 869 |
-
return {"success": False, "error": extracted_data["error"]}
|
| 870 |
-
|
| 871 |
-
return {"success": True, "data": extracted_data}
|
| 872 |
-
|
| 873 |
-
except Exception as e:
|
| 874 |
-
logger.error(f"api_magic_fill_cv error: {e}")
|
| 875 |
-
return {"success": False, "error": f"Gagal mengekstrak berkas CV: {str(e)}"}
|
| 876 |
-
|
|
|
|
| 1 |
+
"""Talent API Routes — Profile, Pathway, Green Score, Interview, Secure Data.
|
| 2 |
+
|
| 3 |
+
All endpoints require authentication via JWT middleware.
|
| 4 |
+
Public endpoints: /v1/talent/verify-certificate
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import base64
|
| 8 |
+
import re
|
| 9 |
+
from datetime import datetime, timezone
|
| 10 |
+
from typing import Optional, Dict, Any
|
| 11 |
+
|
| 12 |
+
from fastapi import APIRouter, Depends, Query, Request, UploadFile, File, Form
|
| 13 |
+
from pydantic import BaseModel
|
| 14 |
+
from sqlalchemy import select, func
|
| 15 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 16 |
+
import httpx
|
| 17 |
+
from loguru import logger
|
| 18 |
+
|
| 19 |
+
from app.database import get_db
|
| 20 |
+
from app.models.talent import Talent
|
| 21 |
+
from app.models.job import TalentPathway
|
| 22 |
+
from app.config.settings import settings
|
| 23 |
+
from app.services.security_service import security_service
|
| 24 |
+
from app.services.ai_service import verify_screenshot_with_gemini
|
| 25 |
+
|
| 26 |
+
from app.schemas.talent import (
|
| 27 |
+
CertificateResponse,
|
| 28 |
+
ChatRequest,
|
| 29 |
+
ChatResponse,
|
| 30 |
+
EvaluateGrillMeRequest,
|
| 31 |
+
EvaluateGrillMeResponse,
|
| 32 |
+
GrillMeQuestionsResponse,
|
| 33 |
+
PathwayResponse,
|
| 34 |
+
SecureTalentDataResponse,
|
| 35 |
+
SubmitProofRequest,
|
| 36 |
+
SubmitProofResponse,
|
| 37 |
+
SubmitQuizRequest,
|
| 38 |
+
SubmitQuizResponse,
|
| 39 |
+
TalentProfileResponse,
|
| 40 |
+
UpdateProfileRequest,
|
| 41 |
+
UpdateProfileResponse,
|
| 42 |
+
VerifyCertificateRequest,
|
| 43 |
+
VerifyCertificateResponse,
|
| 44 |
+
)
|
| 45 |
+
from app.services.talent_service import (
|
| 46 |
+
_get_chat_stats,
|
| 47 |
+
_get_pathway,
|
| 48 |
+
chat_with_brigawan,
|
| 49 |
+
evaluate_grillme,
|
| 50 |
+
generate_career_pathway,
|
| 51 |
+
generate_grillme_questions,
|
| 52 |
+
get_pathway_certificate,
|
| 53 |
+
get_secure_talent_data,
|
| 54 |
+
get_talent_profile,
|
| 55 |
+
submit_action_proof,
|
| 56 |
+
submit_quiz_answers,
|
| 57 |
+
update_talent_profile,
|
| 58 |
+
verify_certificate,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
router = APIRouter(prefix="/v1/talent", tags=["Talent"])
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class LinkedInOAuthRequest(BaseModel):
|
| 65 |
+
code: str
|
| 66 |
+
redirect_uri: str
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _calc_green_score(progress, completed):
|
| 70 |
+
from app.services.talent_service import POINTS_PROOF, POINTS_QUIZ
|
| 71 |
+
score = 0
|
| 72 |
+
for stg_key, actions in (progress or {}).items():
|
| 73 |
+
if isinstance(actions, list):
|
| 74 |
+
for a in actions:
|
| 75 |
+
if isinstance(a, dict) and a.get("done"):
|
| 76 |
+
score += POINTS_PROOF
|
| 77 |
+
score += len(completed or []) * POINTS_QUIZ
|
| 78 |
+
return score
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _check_auth(req: Request) -> Optional[str]:
|
| 82 |
+
"""Check authentication from middleware. Returns user email or None."""
|
| 83 |
+
email = getattr(req.state, "user_email", None)
|
| 84 |
+
if not email:
|
| 85 |
+
return None
|
| 86 |
+
return email
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# ─── Profile ────────────────────────────────────────────────────────────────
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@router.get("/profile", response_model=TalentProfileResponse)
|
| 93 |
+
async def api_get_talent_profile(
|
| 94 |
+
req: Request,
|
| 95 |
+
db: AsyncSession = Depends(get_db),
|
| 96 |
+
):
|
| 97 |
+
"""Get full talent dashboard profile with badges, pathway, academy, chat stats."""
|
| 98 |
+
email = _check_auth(req)
|
| 99 |
+
if not email:
|
| 100 |
+
return TalentProfileResponse(success=False, error="Authentication required.")
|
| 101 |
+
|
| 102 |
+
result = await get_talent_profile(db, email)
|
| 103 |
+
return TalentProfileResponse(
|
| 104 |
+
success=result.get("success", False),
|
| 105 |
+
data=result.get("data"),
|
| 106 |
+
error=result.get("error"),
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@router.put("/profile", response_model=UpdateProfileResponse)
|
| 111 |
+
async def api_update_talent_profile(
|
| 112 |
+
req: Request,
|
| 113 |
+
form_data: UpdateProfileRequest,
|
| 114 |
+
db: AsyncSession = Depends(get_db),
|
| 115 |
+
):
|
| 116 |
+
"""Update talent profile fields."""
|
| 117 |
+
email = _check_auth(req)
|
| 118 |
+
if not email:
|
| 119 |
+
return UpdateProfileResponse(success=False, error="Authentication required.")
|
| 120 |
+
|
| 121 |
+
result = await update_talent_profile(db, email, form_data.model_dump(exclude_none=True))
|
| 122 |
+
return UpdateProfileResponse(
|
| 123 |
+
success=result.get("success", False),
|
| 124 |
+
message=result.get("message", ""),
|
| 125 |
+
error=result.get("error"),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# ─── Career Pathway ─────────────────────────────────────────────────────────
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@router.get("/pathway", response_model=PathwayResponse)
|
| 133 |
+
async def api_get_pathway(
|
| 134 |
+
req: Request,
|
| 135 |
+
db: AsyncSession = Depends(get_db),
|
| 136 |
+
):
|
| 137 |
+
"""Get existing career pathway for the authenticated talent."""
|
| 138 |
+
email = _check_auth(req)
|
| 139 |
+
if not email:
|
| 140 |
+
return PathwayResponse(success=False, error="Authentication required.")
|
| 141 |
+
|
| 142 |
+
result = await _get_pathway(db, email)
|
| 143 |
+
return PathwayResponse(
|
| 144 |
+
success=True,
|
| 145 |
+
pathway=result.get("pathway", []),
|
| 146 |
+
progress=result.get("progress", {}),
|
| 147 |
+
completedStages=result.get("completedStages", []),
|
| 148 |
+
greenScore=result.get("greenScore", 0),
|
| 149 |
+
cached=True,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@router.post("/pathway/generate", response_model=PathwayResponse)
|
| 154 |
+
async def api_generate_pathway(
|
| 155 |
+
req: Request,
|
| 156 |
+
db: AsyncSession = Depends(get_db),
|
| 157 |
+
):
|
| 158 |
+
"""Generate AI-powered career pathway (5 stages with actions, quizzes).
|
| 159 |
+
Returns cached version if exists.
|
| 160 |
+
"""
|
| 161 |
+
email = _check_auth(req)
|
| 162 |
+
if not email:
|
| 163 |
+
return PathwayResponse(success=False, error="Authentication required.")
|
| 164 |
+
|
| 165 |
+
result = await generate_career_pathway(db, email)
|
| 166 |
+
return PathwayResponse(
|
| 167 |
+
success=result.get("success", False),
|
| 168 |
+
pathway=result.get("pathway", []),
|
| 169 |
+
progress=result.get("progress", {}),
|
| 170 |
+
completedStages=result.get("completedStages", []),
|
| 171 |
+
greenScore=result.get("greenScore", 0),
|
| 172 |
+
cached=result.get("cached", False),
|
| 173 |
+
error=result.get("error"),
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@router.post("/pathway/proof", response_model=SubmitProofResponse)
|
| 178 |
+
async def api_submit_proof(
|
| 179 |
+
req: Request,
|
| 180 |
+
body: SubmitProofRequest,
|
| 181 |
+
db: AsyncSession = Depends(get_db),
|
| 182 |
+
):
|
| 183 |
+
"""Submit proof for a specific action in the career pathway."""
|
| 184 |
+
email = _check_auth(req)
|
| 185 |
+
if not email:
|
| 186 |
+
return SubmitProofResponse(success=False, error="Authentication required.")
|
| 187 |
+
|
| 188 |
+
result = await submit_action_proof(db, email, body.stage, body.action_index, body.proof_text)
|
| 189 |
+
return SubmitProofResponse(
|
| 190 |
+
success=result.get("success", False),
|
| 191 |
+
progress=result.get("progress", {}),
|
| 192 |
+
completedStages=result.get("completedStages", []),
|
| 193 |
+
greenScore=result.get("greenScore", 0),
|
| 194 |
+
allActionsProven=result.get("allActionsProven", False),
|
| 195 |
+
error=result.get("error"),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@router.post("/pathway/quiz", response_model=SubmitQuizResponse)
|
| 200 |
+
async def api_submit_quiz(
|
| 201 |
+
req: Request,
|
| 202 |
+
body: SubmitQuizRequest,
|
| 203 |
+
db: AsyncSession = Depends(get_db),
|
| 204 |
+
):
|
| 205 |
+
"""Submit quiz answers for a stage. All actions must be proven first.
|
| 206 |
+
All answers must be correct to pass.
|
| 207 |
+
"""
|
| 208 |
+
email = _check_auth(req)
|
| 209 |
+
if not email:
|
| 210 |
+
return SubmitQuizResponse(success=False, error="Authentication required.")
|
| 211 |
+
|
| 212 |
+
result = await submit_quiz_answers(db, email, body.stage, body.answers)
|
| 213 |
+
return SubmitQuizResponse(
|
| 214 |
+
success=result.get("success", False),
|
| 215 |
+
completedStages=result.get("completedStages", []),
|
| 216 |
+
greenScore=result.get("greenScore", 0),
|
| 217 |
+
stageCompleted=result.get("stageCompleted", False),
|
| 218 |
+
completedStageTitle=result.get("completedStageTitle", ""),
|
| 219 |
+
error=result.get("error"),
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@router.get("/pathway/certificate", response_model=CertificateResponse)
|
| 224 |
+
async def api_get_certificate(
|
| 225 |
+
req: Request,
|
| 226 |
+
stage: int = Query(..., description="Stage number (1-5)"),
|
| 227 |
+
db: AsyncSession = Depends(get_db),
|
| 228 |
+
):
|
| 229 |
+
"""Get certificate for a completed stage."""
|
| 230 |
+
email = _check_auth(req)
|
| 231 |
+
if not email:
|
| 232 |
+
return CertificateResponse(success=False, error="Authentication required.")
|
| 233 |
+
|
| 234 |
+
result = await get_pathway_certificate(db, email, stage)
|
| 235 |
+
return CertificateResponse(
|
| 236 |
+
success=result.get("success", False),
|
| 237 |
+
certificate=result.get("certificate"),
|
| 238 |
+
error=result.get("error"),
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@router.post("/linkedin-oauth")
|
| 243 |
+
async def api_linkedin_oauth(
|
| 244 |
+
req: Request,
|
| 245 |
+
body: LinkedInOAuthRequest,
|
| 246 |
+
db: AsyncSession = Depends(get_db)
|
| 247 |
+
):
|
| 248 |
+
"""Exchange OAuth code for LinkedIn Access Token, verify name, encrypt, and save to DB."""
|
| 249 |
+
email = _check_auth(req)
|
| 250 |
+
if not email:
|
| 251 |
+
return {"success": False, "error": "Authentication required."}
|
| 252 |
+
|
| 253 |
+
# 1. Fetch Talent from DB
|
| 254 |
+
result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
|
| 255 |
+
talent = result.scalar_one_or_none()
|
| 256 |
+
if not talent:
|
| 257 |
+
return {"success": False, "error": "Profil talent tidak ditemukan."}
|
| 258 |
+
|
| 259 |
+
# Mock/Bypass mode for development
|
| 260 |
+
if settings.debug and (body.code.startswith("mock_code_") or not settings.linkedin_client_id or settings.linkedin_client_id == "YOUR_LINKEDIN_CLIENT_ID"):
|
| 261 |
+
if body.code.startswith("mock_code_"):
|
| 262 |
+
linkedin_name = body.code.replace("mock_code_", "").replace("_", " ").strip()
|
| 263 |
+
else:
|
| 264 |
+
linkedin_name = talent.name
|
| 265 |
+
|
| 266 |
+
import difflib
|
| 267 |
+
n1 = " ".join(talent.name.lower().strip().split())
|
| 268 |
+
n2 = " ".join(linkedin_name.lower().strip().split())
|
| 269 |
+
similarity_ratio = difflib.SequenceMatcher(None, n1, n2).ratio()
|
| 270 |
+
|
| 271 |
+
n1_words = n1.split()
|
| 272 |
+
n2_words = n2.split()
|
| 273 |
+
common_words = set(n1_words).intersection(set(n2_words))
|
| 274 |
+
num_common_words = len(common_words)
|
| 275 |
+
either_single_word = (len(n1_words) <= 1 or len(n2_words) <= 1)
|
| 276 |
+
|
| 277 |
+
is_valid = (
|
| 278 |
+
similarity_ratio >= 0.75 or
|
| 279 |
+
num_common_words >= 2 or
|
| 280 |
+
(either_single_word and num_common_words >= 1)
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
logger.info(f"[Mock OAuth] Name comparison: Talent='{talent.name}', LinkedIn='{linkedin_name}', ratio={similarity_ratio:.4f}, common={num_common_words}")
|
| 284 |
+
|
| 285 |
+
if not is_valid:
|
| 286 |
+
return {
|
| 287 |
+
"success": False,
|
| 288 |
+
"error": f"Nama akun LinkedIn ('{linkedin_name}') tidak sesuai dengan nama profil Anda ('{talent.name}')."
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
dek = await security_service.get_or_create_profile_dek(db, talent.id)
|
| 292 |
+
mock_token = f"mock_access_token_{linkedin_name.replace(' ', '_')}"
|
| 293 |
+
encrypted_token = security_service._encrypt_with_dek(dek, mock_token)
|
| 294 |
+
|
| 295 |
+
talent.linkedin_token = encrypted_token
|
| 296 |
+
if not talent.linkedin_link:
|
| 297 |
+
talent.linkedin_link = f"https://linkedin.com/in/mock_{linkedin_name.replace(' ', '_').lower()}"
|
| 298 |
+
|
| 299 |
+
db.add(talent)
|
| 300 |
+
await db.commit()
|
| 301 |
+
|
| 302 |
+
return {
|
| 303 |
+
"success": True,
|
| 304 |
+
"message": "Akun LinkedIn berhasil dihubungkan dan diverifikasi (Mock Mode).",
|
| 305 |
+
"linkedin_name": linkedin_name
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
# 2. Call LinkedIn Token API
|
| 309 |
+
token_url = "https://www.linkedin.com/oauth/v2/accessToken"
|
| 310 |
+
payload = {
|
| 311 |
+
"grant_type": "authorization_code",
|
| 312 |
+
"code": body.code,
|
| 313 |
+
"redirect_uri": body.redirect_uri,
|
| 314 |
+
"client_id": settings.linkedin_client_id,
|
| 315 |
+
"client_secret": settings.linkedin_client_secret
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
try:
|
| 319 |
+
async with httpx.AsyncClient(timeout=15.0) as client:
|
| 320 |
+
resp = await client.post(token_url, data=payload)
|
| 321 |
+
if resp.status_code != 200:
|
| 322 |
+
logger.error(f"LinkedIn Token Exchange failed: {resp.status_code} - {resp.text}")
|
| 323 |
+
return {"success": False, "error": "Gagal menukarkan kode otorisasi LinkedIn."}
|
| 324 |
+
|
| 325 |
+
token_data = resp.json()
|
| 326 |
+
access_token = token_data.get("access_token")
|
| 327 |
+
if not access_token:
|
| 328 |
+
return {"success": False, "error": "Token otorisasi kosong dari LinkedIn."}
|
| 329 |
+
|
| 330 |
+
# 3. Retrieve User Profile from LinkedIn (OpenID Connect /userinfo or /v2/me)
|
| 331 |
+
# Modern OIDC endpoint returns full name & email
|
| 332 |
+
profile_url = "https://api.linkedin.com/v2/userinfo"
|
| 333 |
+
headers = {"Authorization": f"Bearer {access_token}"}
|
| 334 |
+
profile_resp = await client.get(profile_url, headers=headers)
|
| 335 |
+
|
| 336 |
+
if profile_resp.status_code != 200:
|
| 337 |
+
# Fallback to legacy v2 profile endpoint if OIDC is not active
|
| 338 |
+
profile_url = "https://api.linkedin.com/v2/me"
|
| 339 |
+
profile_resp = await client.get(profile_url, headers=headers)
|
| 340 |
+
|
| 341 |
+
if profile_resp.status_code != 200:
|
| 342 |
+
return {"success": False, "error": "Gagal mengambil profil akun LinkedIn Anda."}
|
| 343 |
+
|
| 344 |
+
profile_data = profile_resp.json()
|
| 345 |
+
# Try to resolve full name
|
| 346 |
+
linkedin_name = profile_data.get("name")
|
| 347 |
+
if not linkedin_name:
|
| 348 |
+
given_name = profile_data.get("givenName", {}).get("localized", {}).get("en_US", "")
|
| 349 |
+
family_name = profile_data.get("familyName", {}).get("localized", {}).get("en_US", "")
|
| 350 |
+
linkedin_name = f"{given_name} {family_name}".strip()
|
| 351 |
+
|
| 352 |
+
if not linkedin_name:
|
| 353 |
+
linkedin_name = f"{profile_data.get('given_name', '')} {profile_data.get('family_name', '')}".strip()
|
| 354 |
+
|
| 355 |
+
# 4. Perform Name Verification (Enhanced Similarity Match via difflib)
|
| 356 |
+
import difflib
|
| 357 |
+
n1 = " ".join(talent.name.lower().strip().split())
|
| 358 |
+
n2 = " ".join(linkedin_name.lower().strip().split())
|
| 359 |
+
|
| 360 |
+
similarity_ratio = difflib.SequenceMatcher(None, n1, n2).ratio()
|
| 361 |
+
|
| 362 |
+
n1_words = n1.split()
|
| 363 |
+
n2_words = n2.split()
|
| 364 |
+
common_words = set(n1_words).intersection(set(n2_words))
|
| 365 |
+
num_common_words = len(common_words)
|
| 366 |
+
either_single_word = (len(n1_words) <= 1 or len(n2_words) <= 1)
|
| 367 |
+
|
| 368 |
+
is_valid = (
|
| 369 |
+
similarity_ratio >= 0.75 or
|
| 370 |
+
num_common_words >= 2 or
|
| 371 |
+
(either_single_word and num_common_words >= 1)
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
logger.info(f"LinkedIn Name comparison details: Talent='{talent.name}', LinkedIn='{linkedin_name}', ratio={similarity_ratio:.4f}, common={num_common_words}")
|
| 375 |
+
|
| 376 |
+
if not is_valid:
|
| 377 |
+
logger.warning(f"LinkedIn Identity verification failed: Talent='{talent.name}', LinkedIn='{linkedin_name}' (ratio={similarity_ratio:.4f}, common={num_common_words})")
|
| 378 |
+
return {
|
| 379 |
+
"success": False,
|
| 380 |
+
"error": f"Nama akun LinkedIn ('{linkedin_name}') tidak sesuai dengan nama profil Anda ('{talent.name}')."
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
# 5. Encrypt access token using DEK Envelope Encryption
|
| 384 |
+
dek = await security_service.get_or_create_profile_dek(db, talent.id)
|
| 385 |
+
encrypted_token = security_service._encrypt_with_dek(dek, access_token)
|
| 386 |
+
|
| 387 |
+
# 6. Save encrypted token and LinkedIn link to DB
|
| 388 |
+
talent.linkedin_token = encrypted_token
|
| 389 |
+
# Optionally sync the public LinkedIn link if found or set it
|
| 390 |
+
sub_id = profile_data.get("sub", "")
|
| 391 |
+
if sub_id and not talent.linkedin_link:
|
| 392 |
+
talent.linkedin_link = f"https://linkedin.com/in/{sub_id}"
|
| 393 |
+
|
| 394 |
+
db.add(talent)
|
| 395 |
+
await db.commit()
|
| 396 |
+
|
| 397 |
+
return {
|
| 398 |
+
"success": True,
|
| 399 |
+
"message": "Akun LinkedIn berhasil dihubungkan dan diverifikasi.",
|
| 400 |
+
"linkedin_name": linkedin_name
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
except Exception as e:
|
| 404 |
+
logger.error(f"api_linkedin_oauth exception: {e}")
|
| 405 |
+
return {"success": False, "error": f"Kesalahan sistem: {str(e)}"}
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
@router.post("/pathway/verify-linkedin-api")
|
| 409 |
+
async def api_verify_pathway_linkedin(
|
| 410 |
+
req: Request,
|
| 411 |
+
body: Dict[str, Any], # expects stage, action_index
|
| 412 |
+
db: AsyncSession = Depends(get_db)
|
| 413 |
+
):
|
| 414 |
+
"""Pulls connected talent's posts from LinkedIn, verifies hashtag and Talent ID to approve action."""
|
| 415 |
+
email = _check_auth(req)
|
| 416 |
+
if not email:
|
| 417 |
+
return {"success": False, "error": "Authentication required."}
|
| 418 |
+
|
| 419 |
+
stage = body.get("stage")
|
| 420 |
+
action_index = body.get("action_index")
|
| 421 |
+
if stage is None or action_index is None:
|
| 422 |
+
return {"success": False, "error": "Parameters 'stage' and 'action_index' are required."}
|
| 423 |
+
|
| 424 |
+
# 1. Fetch Talent & Pathway
|
| 425 |
+
t_result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
|
| 426 |
+
talent = t_result.scalar_one_or_none()
|
| 427 |
+
|
| 428 |
+
pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1))
|
| 429 |
+
pw = pw_result.scalar_one_or_none()
|
| 430 |
+
|
| 431 |
+
if not talent or not pw:
|
| 432 |
+
return {"success": False, "error": "Data profil atau pathway tidak ditemukan."}
|
| 433 |
+
|
| 434 |
+
if not talent.linkedin_token:
|
| 435 |
+
return {"success": False, "error": "Silakan hubungkan akun LinkedIn Anda terlebih dahulu."}
|
| 436 |
+
|
| 437 |
+
# 2. Decrypt LinkedIn token
|
| 438 |
+
dek = await security_service.get_or_create_profile_dek(db, talent.id)
|
| 439 |
+
access_token = security_service._decrypt_with_dek(dek, talent.linkedin_token)
|
| 440 |
+
|
| 441 |
+
challenge_code = f"BRG-CH-{stage}-{action_index + 1}"
|
| 442 |
+
verified_post_link = None
|
| 443 |
+
|
| 444 |
+
# 3. Handle Mock Verification Mode
|
| 445 |
+
if settings.debug and access_token.startswith("mock_"):
|
| 446 |
+
logger.info(f"[Mock OAuth] Simulating successful LinkedIn post validation for {challenge_code}")
|
| 447 |
+
verified_post_link = f"https://www.linkedin.com/feed/update/urn:li:share:mock_{challenge_code}"
|
| 448 |
+
else:
|
| 449 |
+
# Pull posts from LinkedIn API
|
| 450 |
+
# Retrieves author's posts/shares
|
| 451 |
+
sub_id = None
|
| 452 |
+
try:
|
| 453 |
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
| 454 |
+
# Try userinfo (OIDC)
|
| 455 |
+
me_resp = await client.get("https://api.linkedin.com/v2/userinfo", headers={"Authorization": f"Bearer {access_token}"})
|
| 456 |
+
if me_resp.status_code == 200:
|
| 457 |
+
sub_id = me_resp.json().get("sub", "")
|
| 458 |
+
else:
|
| 459 |
+
# Try legacy v2/me
|
| 460 |
+
me_resp = await client.get("https://api.linkedin.com/v2/me", headers={"Authorization": f"Bearer {access_token}"})
|
| 461 |
+
if me_resp.status_code == 200:
|
| 462 |
+
sub_id = me_resp.json().get("id", "")
|
| 463 |
+
except Exception as e:
|
| 464 |
+
logger.error(f"Failed to fetch LinkedIn me profile URN: {e}")
|
| 465 |
+
|
| 466 |
+
if not sub_id:
|
| 467 |
+
# Fallback to parsed vanity URL link ONLY if API fetches failed
|
| 468 |
+
if talent.linkedin_link:
|
| 469 |
+
sub_id = talent.linkedin_link.split("/in/")[-1].split("?")[0].strip("/")
|
| 470 |
+
if not sub_id or sub_id == "me":
|
| 471 |
+
sub_id = "me"
|
| 472 |
+
|
| 473 |
+
shares_url = f"https://api.linkedin.com/v2/shares?q=owners&owners=urn:li:person:{sub_id}&count=20"
|
| 474 |
+
headers = {"Authorization": f"Bearer {access_token}", "X-Restli-Protocol-Version": "2.0.0"}
|
| 475 |
+
|
| 476 |
+
try:
|
| 477 |
+
async with httpx.AsyncClient(timeout=15.0) as client:
|
| 478 |
+
resp = await client.get(shares_url, headers=headers)
|
| 479 |
+
if resp.status_code != 200:
|
| 480 |
+
logger.error(f"Failed to fetch LinkedIn shares: {resp.status_code} - {resp.text}")
|
| 481 |
+
return {"success": False, "error": "Gagal menarik kiriman dari LinkedIn. Silakan coba beberapa saat lagi."}
|
| 482 |
+
|
| 483 |
+
posts_data = resp.json()
|
| 484 |
+
elements = posts_data.get("elements", [])
|
| 485 |
+
|
| 486 |
+
# 4. Search elements for validation criteria
|
| 487 |
+
# Hashtag: #BrigaPathway
|
| 488 |
+
# Text contains challenge_code (e.g. BRG-CH-1-1)
|
| 489 |
+
hashtag_pattern = re.compile(r"#BrigaPathway", re.IGNORECASE)
|
| 490 |
+
code_pattern = re.compile(re.escape(challenge_code), re.IGNORECASE)
|
| 491 |
+
|
| 492 |
+
for post in elements:
|
| 493 |
+
text = post.get("text", {}).get("text", "")
|
| 494 |
+
if hashtag_pattern.search(text) and code_pattern.search(text):
|
| 495 |
+
activity_urn = post.get("activity", "")
|
| 496 |
+
# Construct public URL template
|
| 497 |
+
verified_post_link = f"https://www.linkedin.com/feed/update/{activity_urn}"
|
| 498 |
+
break
|
| 499 |
+
|
| 500 |
+
if not verified_post_link:
|
| 501 |
+
return {
|
| 502 |
+
"success": False,
|
| 503 |
+
"error": f"Kiriman LinkedIn tidak ditemukan. Pastikan Anda telah memposting dengan hashtag '#BrigaPathway' dan Kode Tantangan '{challenge_code}' secara publik."
|
| 504 |
+
}
|
| 505 |
+
except Exception as e:
|
| 506 |
+
logger.error(f"api_verify_pathway_linkedin API call exception: {e}")
|
| 507 |
+
return {"success": False, "error": f"Gagal menghubungi server LinkedIn: {str(e)}"}
|
| 508 |
+
|
| 509 |
+
try:
|
| 510 |
+
# 5. Update Pathway Progress
|
| 511 |
+
progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
|
| 512 |
+
completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
|
| 513 |
+
pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
|
| 514 |
+
|
| 515 |
+
sk = str(stage)
|
| 516 |
+
if sk not in progress:
|
| 517 |
+
progress[sk] = []
|
| 518 |
+
|
| 519 |
+
while len(progress[sk]) <= action_index:
|
| 520 |
+
progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
|
| 521 |
+
|
| 522 |
+
progress[sk][action_index] = {
|
| 523 |
+
"done": True,
|
| 524 |
+
"proof": f"LinkedIn Verified Post: {verified_post_link}",
|
| 525 |
+
"ts": datetime.now(timezone.utc).isoformat(),
|
| 526 |
+
"status": "Approved"
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
# Recalculate score and save
|
| 530 |
+
new_score = _calc_green_score(progress, completed)
|
| 531 |
+
pw.progress_json = progress
|
| 532 |
+
pw.green_score = new_score
|
| 533 |
+
db.add(pw)
|
| 534 |
+
talent.green_score = new_score
|
| 535 |
+
db.add(talent)
|
| 536 |
+
await db.commit()
|
| 537 |
+
|
| 538 |
+
# Check if all actions in this stage are completed
|
| 539 |
+
stage_data = next((s for s in pathway if s.get("stage") == stage), None)
|
| 540 |
+
all_proven = False
|
| 541 |
+
if stage_data:
|
| 542 |
+
expected = len(stage_data.get("actions", []))
|
| 543 |
+
all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
|
| 544 |
+
|
| 545 |
+
return {
|
| 546 |
+
"success": True,
|
| 547 |
+
"progress": progress,
|
| 548 |
+
"completedStages": [str(s) for s in completed],
|
| 549 |
+
"greenScore": new_score,
|
| 550 |
+
"allActionsProven": all_proven,
|
| 551 |
+
"feedback": "Kiriman LinkedIn berhasil diverifikasi secara otomatis via API!"
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
except Exception as e:
|
| 555 |
+
logger.error(f"api_verify_pathway_linkedin exception: {e}")
|
| 556 |
+
return {"success": False, "error": f"Kesalahan sistem: {str(e)}"}
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
@router.post("/pathway/verify-linkedin-screenshot")
|
| 560 |
+
async def api_verify_pathway_screenshot(
|
| 561 |
+
req: Request,
|
| 562 |
+
file: UploadFile = File(...),
|
| 563 |
+
stage: int = Form(...),
|
| 564 |
+
action_index: int = Form(...),
|
| 565 |
+
db: AsyncSession = Depends(get_db)
|
| 566 |
+
):
|
| 567 |
+
"""Upload screenshot of LinkedIn post and use Gemini Vision to vet post contents."""
|
| 568 |
+
email = _check_auth(req)
|
| 569 |
+
if not email:
|
| 570 |
+
return {"success": False, "error": "Authentication required."}
|
| 571 |
+
|
| 572 |
+
# 1. Fetch Talent & Pathway
|
| 573 |
+
t_result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
|
| 574 |
+
talent = t_result.scalar_one_or_none()
|
| 575 |
+
|
| 576 |
+
pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1))
|
| 577 |
+
pw = pw_result.scalar_one_or_none()
|
| 578 |
+
|
| 579 |
+
if not talent or not pw:
|
| 580 |
+
return {"success": False, "error": "Data profil atau pathway tidak ditemukan."}
|
| 581 |
+
|
| 582 |
+
# 2. Read image bytes
|
| 583 |
+
try:
|
| 584 |
+
image_bytes = await file.read()
|
| 585 |
+
except Exception as e:
|
| 586 |
+
return {"success": False, "error": f"Gagal membaca file gambar: {str(e)}"}
|
| 587 |
+
|
| 588 |
+
challenge_code = f"BRG-CH-{stage}-{action_index + 1}"
|
| 589 |
+
|
| 590 |
+
# 3. Call AI Service Vetting Function or Bypass in Mock mode
|
| 591 |
+
if settings.debug and file.filename and "mock" in file.filename.lower():
|
| 592 |
+
logger.info(f"[Mock Vision] Bypassing Gemini Vision API for screenshot file {file.filename}")
|
| 593 |
+
vetting_result = {
|
| 594 |
+
"success": True,
|
| 595 |
+
"match": True,
|
| 596 |
+
"extracted_name": talent.name,
|
| 597 |
+
"has_hashtag": True,
|
| 598 |
+
"has_challenge_code": True,
|
| 599 |
+
"confidence": 0.95,
|
| 600 |
+
"feedback": "Screenshot postingan LinkedIn berhasil diverifikasi secara otomatis via AI (Mock Mode)."
|
| 601 |
+
}
|
| 602 |
+
else:
|
| 603 |
+
vetting_result = await verify_screenshot_with_gemini(
|
| 604 |
+
image_bytes=image_bytes,
|
| 605 |
+
talent_name=talent.name,
|
| 606 |
+
challenge_code=challenge_code
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
if not vetting_result.get("success"):
|
| 610 |
+
return {
|
| 611 |
+
"success": False,
|
| 612 |
+
"error": vetting_result.get("feedback", "Gagal menganalisis gambar screenshot via AI.")
|
| 613 |
+
}
|
| 614 |
+
|
| 615 |
+
if not vetting_result.get("match"):
|
| 616 |
+
return {
|
| 617 |
+
"success": False,
|
| 618 |
+
"error": vetting_result.get("feedback", "Hasil analisis AI: Gambar tidak memenuhi kriteria verifikasi.")
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
# 4. AI Verification Successful - Update Progress
|
| 622 |
+
progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
|
| 623 |
+
completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
|
| 624 |
+
pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
|
| 625 |
+
|
| 626 |
+
sk = str(stage)
|
| 627 |
+
if sk not in progress:
|
| 628 |
+
progress[sk] = []
|
| 629 |
+
|
| 630 |
+
while len(progress[sk]) <= action_index:
|
| 631 |
+
progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
|
| 632 |
+
|
| 633 |
+
progress[sk][action_index] = {
|
| 634 |
+
"done": True,
|
| 635 |
+
"proof": f"LinkedIn Screenshot verified by Gemini (Name: {vetting_result.get('extracted_name')}, Conf: {vetting_result.get('confidence')})",
|
| 636 |
+
"ts": datetime.now(timezone.utc).isoformat(),
|
| 637 |
+
"status": "Approved"
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
new_score = _calc_green_score(progress, completed)
|
| 641 |
+
pw.progress_json = progress
|
| 642 |
+
pw.green_score = new_score
|
| 643 |
+
db.add(pw)
|
| 644 |
+
talent.green_score = new_score
|
| 645 |
+
db.add(talent)
|
| 646 |
+
await db.commit()
|
| 647 |
+
|
| 648 |
+
stage_data = next((s for s in pathway if s.get("stage") == stage), None)
|
| 649 |
+
all_proven = False
|
| 650 |
+
if stage_data:
|
| 651 |
+
expected = len(stage_data.get("actions", []))
|
| 652 |
+
all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
|
| 653 |
+
|
| 654 |
+
return {
|
| 655 |
+
"success": True,
|
| 656 |
+
"progress": progress,
|
| 657 |
+
"completedStages": [str(s) for s in completed],
|
| 658 |
+
"greenScore": new_score,
|
| 659 |
+
"allActionsProven": all_proven,
|
| 660 |
+
"feedback": vetting_result.get("feedback", "Screenshot postingan LinkedIn berhasil diverifikasi secara otomatis via AI!")
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
# ─── AI Chat (Brigawan Career Coach) ────────────────────────────────────────
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
@router.post("/chat", response_model=ChatResponse)
|
| 668 |
+
async def api_chat(
|
| 669 |
+
req: Request,
|
| 670 |
+
body: ChatRequest,
|
| 671 |
+
db: AsyncSession = Depends(get_db),
|
| 672 |
+
):
|
| 673 |
+
"""Chat with Brigawan AI Career Coach. Limited to 10 chats per 24 hours."""
|
| 674 |
+
email = _check_auth(req)
|
| 675 |
+
if not email:
|
| 676 |
+
return ChatResponse(success=False, error="Authentication required.")
|
| 677 |
+
|
| 678 |
+
result = await chat_with_brigawan(db, email, body.message)
|
| 679 |
+
return ChatResponse(
|
| 680 |
+
success=result.get("success", False),
|
| 681 |
+
reply=result.get("reply", ""),
|
| 682 |
+
chatUsed=result.get("chatUsed", 0),
|
| 683 |
+
chatLimit=result.get("chatLimit", 10),
|
| 684 |
+
chatExpiry=result.get("chatExpiry", "-"),
|
| 685 |
+
limitReached=result.get("limitReached", False),
|
| 686 |
+
error=result.get("error"),
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
@router.get("/chat/stats", response_model=ChatResponse)
|
| 691 |
+
async def api_chat_stats(
|
| 692 |
+
req: Request,
|
| 693 |
+
db: AsyncSession = Depends(get_db),
|
| 694 |
+
):
|
| 695 |
+
"""Get AI chat usage statistics."""
|
| 696 |
+
email = _check_auth(req)
|
| 697 |
+
if not email:
|
| 698 |
+
return ChatResponse(success=False, error="Authentication required.")
|
| 699 |
+
|
| 700 |
+
stats = await _get_chat_stats(db, email)
|
| 701 |
+
return ChatResponse(
|
| 702 |
+
success=True,
|
| 703 |
+
chatUsed=stats.get("used", 0),
|
| 704 |
+
chatLimit=10,
|
| 705 |
+
chatExpiry=stats.get("expiryTime", "-"),
|
| 706 |
+
limitReached=stats.get("used", 0) >= 10,
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
# ─── Grill-Me Interview Simulation ──────────────────────────────────────────
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
@router.get("/grillme/questions", response_model=GrillMeQuestionsResponse)
|
| 714 |
+
async def api_grillme_questions(
|
| 715 |
+
req: Request,
|
| 716 |
+
category: str = Query("ESG Specialist", description="Green job category"),
|
| 717 |
+
):
|
| 718 |
+
"""Generate 3 interview simulation questions for a green job category."""
|
| 719 |
+
email = _check_auth(req)
|
| 720 |
+
if not email:
|
| 721 |
+
return GrillMeQuestionsResponse(success=False, error="Authentication required.")
|
| 722 |
+
|
| 723 |
+
result = generate_grillme_questions(category)
|
| 724 |
+
return GrillMeQuestionsResponse(
|
| 725 |
+
success=result.get("success", False),
|
| 726 |
+
questions=result.get("questions", []),
|
| 727 |
+
isFallback=result.get("isFallback", False),
|
| 728 |
+
error=result.get("error"),
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
@router.post("/grillme/evaluate", response_model=EvaluateGrillMeResponse)
|
| 733 |
+
async def api_grillme_evaluate(
|
| 734 |
+
req: Request,
|
| 735 |
+
body: EvaluateGrillMeRequest,
|
| 736 |
+
):
|
| 737 |
+
"""Evaluate interview answers and generate SWOT analysis."""
|
| 738 |
+
email = _check_auth(req)
|
| 739 |
+
if not email:
|
| 740 |
+
return EvaluateGrillMeResponse(success=False, error="Authentication required.")
|
| 741 |
+
|
| 742 |
+
result = evaluate_grillme(body.category, body.questions, body.answers)
|
| 743 |
+
return EvaluateGrillMeResponse(
|
| 744 |
+
success=result.get("success", False),
|
| 745 |
+
score=result.get("score", 0),
|
| 746 |
+
swot=result.get("swot"),
|
| 747 |
+
rawSWOTText=result.get("rawSWOTText", ""),
|
| 748 |
+
error=result.get("error"),
|
| 749 |
+
)
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
# ─── Secure Talent Data (PDP Compliant) ─────────────────────────────────────
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
@router.get("/secure/{talent_id}", response_model=SecureTalentDataResponse)
|
| 756 |
+
async def api_secure_talent_data(
|
| 757 |
+
req: Request,
|
| 758 |
+
talent_id: str,
|
| 759 |
+
db: AsyncSession = Depends(get_db),
|
| 760 |
+
):
|
| 761 |
+
"""Get secure talent data with PDP-compliant masking.
|
| 762 |
+
Returns full data if requester has unlocked this candidate, masked otherwise.
|
| 763 |
+
"""
|
| 764 |
+
email = _check_auth(req)
|
| 765 |
+
if not email:
|
| 766 |
+
return SecureTalentDataResponse(success=False, error="Authentication required.")
|
| 767 |
+
|
| 768 |
+
result = await get_secure_talent_data(db, talent_id, email)
|
| 769 |
+
return SecureTalentDataResponse(
|
| 770 |
+
success=result.get("success", False),
|
| 771 |
+
id_kandidat=result.get("id_kandidat", ""),
|
| 772 |
+
nama=result.get("nama", ""),
|
| 773 |
+
email=result.get("email", "[LOCKED]"),
|
| 774 |
+
pendidikan=result.get("pendidikan", ""),
|
| 775 |
+
pengalaman=result.get("pengalaman", ""),
|
| 776 |
+
k3_dasar=result.get("k3_dasar", ""),
|
| 777 |
+
k3_khusus=result.get("k3_khusus", ""),
|
| 778 |
+
sertifikasi=result.get("sertifikasi", ""),
|
| 779 |
+
bahasa=result.get("bahasa", ""),
|
| 780 |
+
cv_link=result.get("cv_link", "[LOCKED - Reveal to Download]"),
|
| 781 |
+
skor=result.get("skor", 0),
|
| 782 |
+
kategori=result.get("kategori", ""),
|
| 783 |
+
analisis=result.get("analisis", ""),
|
| 784 |
+
status=result.get("status", ""),
|
| 785 |
+
unlocked=result.get("unlocked", False),
|
| 786 |
+
error=result.get("error"),
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
# ─── Public: Certificate Verification ───────────────────────────────────────
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
@router.post("/verify-certificate", response_model=VerifyCertificateResponse)
|
| 794 |
+
async def api_verify_certificate(
|
| 795 |
+
body: VerifyCertificateRequest,
|
| 796 |
+
db: AsyncSession = Depends(get_db),
|
| 797 |
+
):
|
| 798 |
+
"""Public certificate verification via talent ID or SHA-256 hash.
|
| 799 |
+
No authentication required — used for shareable certificate links.
|
| 800 |
+
"""
|
| 801 |
+
result = await verify_certificate(db, body.talent_id, body.stage)
|
| 802 |
+
return VerifyCertificateResponse(
|
| 803 |
+
success=result.get("success", False),
|
| 804 |
+
data=result.get("data"),
|
| 805 |
+
error=result.get("error"),
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
# ─── Public: Magic Fill CV Vetting (Local Converter) ───────────────────────
|
| 810 |
+
|
| 811 |
+
from pydantic import BaseModel
|
| 812 |
+
|
| 813 |
+
class MagicFillRequest(BaseModel):
|
| 814 |
+
name: str
|
| 815 |
+
type: str
|
| 816 |
+
base64: str
|
| 817 |
+
|
| 818 |
+
@router.post("/magic-fill")
|
| 819 |
+
async def api_magic_fill_cv(
|
| 820 |
+
body: MagicFillRequest,
|
| 821 |
+
):
|
| 822 |
+
"""Refined CV Parsing: Convert PDF to MD using markitdown, then extract profile with Gemini.
|
| 823 |
+
No authentication required (called during signup flow).
|
| 824 |
+
"""
|
| 825 |
+
import base64
|
| 826 |
+
import tempfile
|
| 827 |
+
import os
|
| 828 |
+
from markitdown import MarkItDown
|
| 829 |
+
from app.services.ai_service import extract_cv_metadata
|
| 830 |
+
from loguru import logger
|
| 831 |
+
|
| 832 |
+
try:
|
| 833 |
+
# 1. Decode base64 to bytes
|
| 834 |
+
file_bytes = base64.b64decode(body.base64)
|
| 835 |
+
|
| 836 |
+
# 2. Determine file suffix
|
| 837 |
+
ext = ".pdf"
|
| 838 |
+
if "word" in body.type or body.name.lower().endswith(".docx"):
|
| 839 |
+
ext = ".docx"
|
| 840 |
+
elif body.name.lower().endswith(".doc"):
|
| 841 |
+
ext = ".doc"
|
| 842 |
+
elif body.name.lower().endswith(".html") or body.name.lower().endswith(".htm"):
|
| 843 |
+
ext = ".html"
|
| 844 |
+
elif body.name.lower().endswith(".txt"):
|
| 845 |
+
ext = ".txt"
|
| 846 |
+
|
| 847 |
+
# 3. Write temporarily to local storage
|
| 848 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp_file:
|
| 849 |
+
temp_file.write(file_bytes)
|
| 850 |
+
temp_path = temp_file.name
|
| 851 |
+
|
| 852 |
+
# 4. Process conversion via local markitdown
|
| 853 |
+
try:
|
| 854 |
+
markitdown = MarkItDown()
|
| 855 |
+
result = markitdown.convert(temp_path)
|
| 856 |
+
cv_markdown = result.text_content
|
| 857 |
+
finally:
|
| 858 |
+
# Clean up temp file safely
|
| 859 |
+
if os.path.exists(temp_path):
|
| 860 |
+
os.remove(temp_path)
|
| 861 |
+
|
| 862 |
+
# 5. Extract JSON metadata from the Markdown text using Gemini
|
| 863 |
+
if not cv_markdown or len(cv_markdown.strip()) < 50:
|
| 864 |
+
return {"success": False, "error": "Teks CV terlalu pendek atau kosong untuk dianalisis."}
|
| 865 |
+
|
| 866 |
+
extracted_data = await extract_cv_metadata(cv_markdown)
|
| 867 |
+
|
| 868 |
+
if "error" in extracted_data:
|
| 869 |
+
return {"success": False, "error": extracted_data["error"]}
|
| 870 |
+
|
| 871 |
+
return {"success": True, "data": extracted_data}
|
| 872 |
+
|
| 873 |
+
except Exception as e:
|
| 874 |
+
logger.error(f"api_magic_fill_cv error: {e}")
|
| 875 |
+
return {"success": False, "error": f"Gagal mengekstrak berkas CV: {str(e)}"}
|
| 876 |
+
|
app/api/telegram.py
CHANGED
|
@@ -1,39 +1,39 @@
|
|
| 1 |
-
"""Telegram Webhook API — Executive Command Gateway."""
|
| 2 |
-
|
| 3 |
-
from fastapi import APIRouter, Depends, Request, Header, HTTPException, status
|
| 4 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 5 |
-
from app.database import get_db
|
| 6 |
-
from app.services.telegram_ceo_service import TelegramCEOService
|
| 7 |
-
from app.config.settings import settings
|
| 8 |
-
from typing import Optional
|
| 9 |
-
import httpx
|
| 10 |
-
from loguru import logger
|
| 11 |
-
|
| 12 |
-
router = APIRouter(tags=["Executive Control"])
|
| 13 |
-
|
| 14 |
-
@router.post("/webhook/telegram")
|
| 15 |
-
@router.post("/v1/webhook/telegram")
|
| 16 |
-
async def telegram_webhook(
|
| 17 |
-
request: Request,
|
| 18 |
-
db: AsyncSession = Depends(get_db),
|
| 19 |
-
x_webhook_token: Optional[str] = Header(None)
|
| 20 |
-
):
|
| 21 |
-
"""Receives commands/updates directly from Telegram or API clients."""
|
| 22 |
-
data = await request.json()
|
| 23 |
-
|
| 24 |
-
# Check if this is a standard Telegram payload
|
| 25 |
-
is_telegram_payload = ("message" in data or "callback_query" in data or "edited_message" in data)
|
| 26 |
-
|
| 27 |
-
# Security Check: Only enforce for non-Telegram clients
|
| 28 |
-
if not is_telegram_payload:
|
| 29 |
-
expected_secret = settings.webhook_secret or settings.security_webhook_token
|
| 30 |
-
if expected_secret and x_webhook_token != expected_secret:
|
| 31 |
-
logger.warning("[Telegram Webhook] Unauthorized access attempt.")
|
| 32 |
-
return {"status": "unauthorized"}
|
| 33 |
-
|
| 34 |
-
ceo_service = TelegramCEOService(db)
|
| 35 |
-
|
| 36 |
-
# Process webhook natively via the service
|
| 37 |
-
result = await ceo_service.handle_webhook(data)
|
| 38 |
-
return result
|
| 39 |
-
|
|
|
|
| 1 |
+
"""Telegram Webhook API — Executive Command Gateway."""
|
| 2 |
+
|
| 3 |
+
from fastapi import APIRouter, Depends, Request, Header, HTTPException, status
|
| 4 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 5 |
+
from app.database import get_db
|
| 6 |
+
from app.services.telegram_ceo_service import TelegramCEOService
|
| 7 |
+
from app.config.settings import settings
|
| 8 |
+
from typing import Optional
|
| 9 |
+
import httpx
|
| 10 |
+
from loguru import logger
|
| 11 |
+
|
| 12 |
+
router = APIRouter(tags=["Executive Control"])
|
| 13 |
+
|
| 14 |
+
@router.post("/webhook/telegram")
|
| 15 |
+
@router.post("/v1/webhook/telegram")
|
| 16 |
+
async def telegram_webhook(
|
| 17 |
+
request: Request,
|
| 18 |
+
db: AsyncSession = Depends(get_db),
|
| 19 |
+
x_webhook_token: Optional[str] = Header(None)
|
| 20 |
+
):
|
| 21 |
+
"""Receives commands/updates directly from Telegram or API clients."""
|
| 22 |
+
data = await request.json()
|
| 23 |
+
|
| 24 |
+
# Check if this is a standard Telegram payload
|
| 25 |
+
is_telegram_payload = ("message" in data or "callback_query" in data or "edited_message" in data)
|
| 26 |
+
|
| 27 |
+
# Security Check: Only enforce for non-Telegram clients
|
| 28 |
+
if not is_telegram_payload:
|
| 29 |
+
expected_secret = settings.webhook_secret or settings.security_webhook_token
|
| 30 |
+
if expected_secret and x_webhook_token != expected_secret:
|
| 31 |
+
logger.warning("[Telegram Webhook] Unauthorized access attempt.")
|
| 32 |
+
return {"status": "unauthorized"}
|
| 33 |
+
|
| 34 |
+
ceo_service = TelegramCEOService(db)
|
| 35 |
+
|
| 36 |
+
# Process webhook natively via the service
|
| 37 |
+
result = await ceo_service.handle_webhook(data)
|
| 38 |
+
return result
|
| 39 |
+
|
app/api/whatsapp.py
CHANGED
|
@@ -1,106 +1,106 @@
|
|
| 1 |
-
"""WhatsApp Control API — Link your device and monitor status."""
|
| 2 |
-
|
| 3 |
-
from fastapi import APIRouter, Depends, Request, Header, HTTPException
|
| 4 |
-
from app.services.whatsapp_service import whatsapp_bot
|
| 5 |
-
from app.services.whatsapp.flow_handler import WhatsAppFlowHandler
|
| 6 |
-
from app.utils.wa_guardrail import guardrail
|
| 7 |
-
from app.database import get_db
|
| 8 |
-
from app.config.settings import settings
|
| 9 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 10 |
-
from typing import Dict, Any, Optional
|
| 11 |
-
from loguru import logger
|
| 12 |
-
|
| 13 |
-
router = APIRouter(prefix="/v1/whatsapp", tags=["WhatsApp Hub"])
|
| 14 |
-
|
| 15 |
-
@router.post("/webhook")
|
| 16 |
-
async def whatsapp_webhook(
|
| 17 |
-
request: Request,
|
| 18 |
-
db: AsyncSession = Depends(get_db),
|
| 19 |
-
x_webhook_token: Optional[str] = Header(None)
|
| 20 |
-
):
|
| 21 |
-
"""Receives and processes incoming WhatsApp messages with security."""
|
| 22 |
-
# 1. Security Check
|
| 23 |
-
if settings.webhook_secret and x_webhook_token != settings.webhook_secret:
|
| 24 |
-
logger.warning("[WhatsApp Webhook] Unauthorized access attempt.")
|
| 25 |
-
return {"status": "unauthorized"}
|
| 26 |
-
|
| 27 |
-
try:
|
| 28 |
-
data = await request.json()
|
| 29 |
-
# logger.info(f"[WhatsApp Webhook] Received payload: {data}") # SANITIZED: Removed full payload logging
|
| 30 |
-
|
| 31 |
-
sender = None
|
| 32 |
-
message = ""
|
| 33 |
-
media_info = None
|
| 34 |
-
|
| 35 |
-
# Evolution API Format
|
| 36 |
-
if data.get("event") == "messages.upsert":
|
| 37 |
-
msg_data = data.get("data", {})
|
| 38 |
-
sender = msg_data.get("key", {}).get("remoteJid")
|
| 39 |
-
message_id = msg_data.get("key", {}).get("id")
|
| 40 |
-
instance = data.get("instance")
|
| 41 |
-
msg_content = msg_data.get("message", {})
|
| 42 |
-
|
| 43 |
-
# Text Message
|
| 44 |
-
message = msg_content.get("conversation") or \
|
| 45 |
-
msg_content.get("extendedTextMessage", {}).get("text") or \
|
| 46 |
-
""
|
| 47 |
-
|
| 48 |
-
# Media/Document Message (CV Upload)
|
| 49 |
-
if "documentMessage" in msg_content:
|
| 50 |
-
doc = msg_content["documentMessage"]
|
| 51 |
-
media_info = {
|
| 52 |
-
"type": "document",
|
| 53 |
-
"mimetype": doc.get("mimetype"),
|
| 54 |
-
"title": doc.get("title") or doc.get("fileName"),
|
| 55 |
-
"url": doc.get("url"),
|
| 56 |
-
"message_id": message_id,
|
| 57 |
-
"instance": instance
|
| 58 |
-
}
|
| 59 |
-
message = f"[Sent a document: {media_info['title']}]"
|
| 60 |
-
|
| 61 |
-
# Simplified Format
|
| 62 |
-
else:
|
| 63 |
-
sender = data.get("sender")
|
| 64 |
-
message = data.get("message", "")
|
| 65 |
-
|
| 66 |
-
if not sender:
|
| 67 |
-
return {"status": "ignored", "reason": "No sender found"}
|
| 68 |
-
|
| 69 |
-
# 2. Rate Limiting
|
| 70 |
-
if guardrail.is_rate_limited(sender):
|
| 71 |
-
return {"status": "error", "message": "Too many requests"}
|
| 72 |
-
|
| 73 |
-
# 3. Input Sanitization & Privacy (Skip for media info if needed, but safe for text)
|
| 74 |
-
clean_message = guardrail.sanitize_input(message)
|
| 75 |
-
safe_message = guardrail.filter_pii_for_ai(clean_message)
|
| 76 |
-
|
| 77 |
-
# 4. Process Flow
|
| 78 |
-
flow_handler = WhatsAppFlowHandler(db)
|
| 79 |
-
# We pass media_info to handle_message
|
| 80 |
-
await flow_handler.handle_message(sender, safe_message, media_info=media_info)
|
| 81 |
-
|
| 82 |
-
return {"status": "success"}
|
| 83 |
-
except Exception as e:
|
| 84 |
-
logger.error(f"[WhatsApp Webhook] Error: {e}")
|
| 85 |
-
return {"status": "error", "detail": str(e)}
|
| 86 |
-
|
| 87 |
-
@router.get("/status")
|
| 88 |
-
async def get_whatsapp_status():
|
| 89 |
-
"""Checks the connection status of the WhatsApp bot."""
|
| 90 |
-
return await whatsapp_bot.get_status()
|
| 91 |
-
|
| 92 |
-
@router.get("/qr")
|
| 93 |
-
async def get_whatsapp_qr():
|
| 94 |
-
"""Returns a base64 QR code for scanning."""
|
| 95 |
-
qr_base64 = await whatsapp_bot.get_qr_base64()
|
| 96 |
-
if qr_base64:
|
| 97 |
-
return {"status": "success", "qr": qr_base64}
|
| 98 |
-
return {"status": "error", "message": "Failed to generate QR or instance busy."}
|
| 99 |
-
|
| 100 |
-
@router.post("/logout")
|
| 101 |
-
async def logout_whatsapp():
|
| 102 |
-
"""Logs out the current WhatsApp session."""
|
| 103 |
-
success = await whatsapp_bot.logout_instance()
|
| 104 |
-
if success:
|
| 105 |
-
return {"status": "success", "message": "Logged out successfully."}
|
| 106 |
-
return {"status": "error", "message": "Logout failed."}
|
|
|
|
| 1 |
+
"""WhatsApp Control API — Link your device and monitor status."""
|
| 2 |
+
|
| 3 |
+
from fastapi import APIRouter, Depends, Request, Header, HTTPException
|
| 4 |
+
from app.services.whatsapp_service import whatsapp_bot
|
| 5 |
+
from app.services.whatsapp.flow_handler import WhatsAppFlowHandler
|
| 6 |
+
from app.utils.wa_guardrail import guardrail
|
| 7 |
+
from app.database import get_db
|
| 8 |
+
from app.config.settings import settings
|
| 9 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 10 |
+
from typing import Dict, Any, Optional
|
| 11 |
+
from loguru import logger
|
| 12 |
+
|
| 13 |
+
router = APIRouter(prefix="/v1/whatsapp", tags=["WhatsApp Hub"])
|
| 14 |
+
|
| 15 |
+
@router.post("/webhook")
|
| 16 |
+
async def whatsapp_webhook(
|
| 17 |
+
request: Request,
|
| 18 |
+
db: AsyncSession = Depends(get_db),
|
| 19 |
+
x_webhook_token: Optional[str] = Header(None)
|
| 20 |
+
):
|
| 21 |
+
"""Receives and processes incoming WhatsApp messages with security."""
|
| 22 |
+
# 1. Security Check
|
| 23 |
+
if settings.webhook_secret and x_webhook_token != settings.webhook_secret:
|
| 24 |
+
logger.warning("[WhatsApp Webhook] Unauthorized access attempt.")
|
| 25 |
+
return {"status": "unauthorized"}
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
data = await request.json()
|
| 29 |
+
# logger.info(f"[WhatsApp Webhook] Received payload: {data}") # SANITIZED: Removed full payload logging
|
| 30 |
+
|
| 31 |
+
sender = None
|
| 32 |
+
message = ""
|
| 33 |
+
media_info = None
|
| 34 |
+
|
| 35 |
+
# Evolution API Format
|
| 36 |
+
if data.get("event") == "messages.upsert":
|
| 37 |
+
msg_data = data.get("data", {})
|
| 38 |
+
sender = msg_data.get("key", {}).get("remoteJid")
|
| 39 |
+
message_id = msg_data.get("key", {}).get("id")
|
| 40 |
+
instance = data.get("instance")
|
| 41 |
+
msg_content = msg_data.get("message", {})
|
| 42 |
+
|
| 43 |
+
# Text Message
|
| 44 |
+
message = msg_content.get("conversation") or \
|
| 45 |
+
msg_content.get("extendedTextMessage", {}).get("text") or \
|
| 46 |
+
""
|
| 47 |
+
|
| 48 |
+
# Media/Document Message (CV Upload)
|
| 49 |
+
if "documentMessage" in msg_content:
|
| 50 |
+
doc = msg_content["documentMessage"]
|
| 51 |
+
media_info = {
|
| 52 |
+
"type": "document",
|
| 53 |
+
"mimetype": doc.get("mimetype"),
|
| 54 |
+
"title": doc.get("title") or doc.get("fileName"),
|
| 55 |
+
"url": doc.get("url"),
|
| 56 |
+
"message_id": message_id,
|
| 57 |
+
"instance": instance
|
| 58 |
+
}
|
| 59 |
+
message = f"[Sent a document: {media_info['title']}]"
|
| 60 |
+
|
| 61 |
+
# Simplified Format
|
| 62 |
+
else:
|
| 63 |
+
sender = data.get("sender")
|
| 64 |
+
message = data.get("message", "")
|
| 65 |
+
|
| 66 |
+
if not sender:
|
| 67 |
+
return {"status": "ignored", "reason": "No sender found"}
|
| 68 |
+
|
| 69 |
+
# 2. Rate Limiting
|
| 70 |
+
if guardrail.is_rate_limited(sender):
|
| 71 |
+
return {"status": "error", "message": "Too many requests"}
|
| 72 |
+
|
| 73 |
+
# 3. Input Sanitization & Privacy (Skip for media info if needed, but safe for text)
|
| 74 |
+
clean_message = guardrail.sanitize_input(message)
|
| 75 |
+
safe_message = guardrail.filter_pii_for_ai(clean_message)
|
| 76 |
+
|
| 77 |
+
# 4. Process Flow
|
| 78 |
+
flow_handler = WhatsAppFlowHandler(db)
|
| 79 |
+
# We pass media_info to handle_message
|
| 80 |
+
await flow_handler.handle_message(sender, safe_message, media_info=media_info)
|
| 81 |
+
|
| 82 |
+
return {"status": "success"}
|
| 83 |
+
except Exception as e:
|
| 84 |
+
logger.error(f"[WhatsApp Webhook] Error: {e}")
|
| 85 |
+
return {"status": "error", "detail": str(e)}
|
| 86 |
+
|
| 87 |
+
@router.get("/status")
|
| 88 |
+
async def get_whatsapp_status():
|
| 89 |
+
"""Checks the connection status of the WhatsApp bot."""
|
| 90 |
+
return await whatsapp_bot.get_status()
|
| 91 |
+
|
| 92 |
+
@router.get("/qr")
|
| 93 |
+
async def get_whatsapp_qr():
|
| 94 |
+
"""Returns a base64 QR code for scanning."""
|
| 95 |
+
qr_base64 = await whatsapp_bot.get_qr_base64()
|
| 96 |
+
if qr_base64:
|
| 97 |
+
return {"status": "success", "qr": qr_base64}
|
| 98 |
+
return {"status": "error", "message": "Failed to generate QR or instance busy."}
|
| 99 |
+
|
| 100 |
+
@router.post("/logout")
|
| 101 |
+
async def logout_whatsapp():
|
| 102 |
+
"""Logs out the current WhatsApp session."""
|
| 103 |
+
success = await whatsapp_bot.logout_instance()
|
| 104 |
+
if success:
|
| 105 |
+
return {"status": "success", "message": "Logged out successfully."}
|
| 106 |
+
return {"status": "error", "message": "Logout failed."}
|
app/config/settings.py
CHANGED
|
@@ -80,6 +80,10 @@ class Settings(BaseSettings):
|
|
| 80 |
vertex_ai_location: str = "asia-southeast2"
|
| 81 |
vertex_ai_model: str = "gemini-3.5-flash"
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
model_config = {
|
| 84 |
"env_file": ".env",
|
| 85 |
"env_file_encoding": "utf-8",
|
|
|
|
| 80 |
vertex_ai_location: str = "asia-southeast2"
|
| 81 |
vertex_ai_model: str = "gemini-3.5-flash"
|
| 82 |
|
| 83 |
+
# Supabase credentials for Auth verification
|
| 84 |
+
supabase_url: str = "https://apuktsmdegylgvtyaawc.supabase.co"
|
| 85 |
+
supabase_anon_key: str = ""
|
| 86 |
+
|
| 87 |
model_config = {
|
| 88 |
"env_file": ".env",
|
| 89 |
"env_file_encoding": "utf-8",
|
app/config/vetting_rules.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vetting Rules & Career Transition Database for Brigawan AI
|
| 2 |
+
# Ported from VettingPrompts.gs and CareerTransitionData.gs
|
| 3 |
+
|
| 4 |
+
VETTING_RULES = {
|
| 5 |
+
"categories": {
|
| 6 |
+
"Skilled": "Memiliki kualifikasi pendidikan linier, pengalaman kerja nyata >3 tahun di sektor terkait, atau sertifikasi keahlian tinggi (BNSP/Internasional).",
|
| 7 |
+
"Semi-Skilled": "Memiliki dasar pendidikan teknis, pengalaman <3 tahun, atau baru memiliki sertifikasi dasar (K3 Umum).",
|
| 8 |
+
"Unskilled": "Generalis tanpa latar belakang teknis atau industri hijau yang spesifik."
|
| 9 |
+
},
|
| 10 |
+
"green_sectors": [
|
| 11 |
+
"Renewable Energy (Solar, Wind, Geothermal, Hydro)",
|
| 12 |
+
"ESG & Sustainability Reporting",
|
| 13 |
+
"Carbon Accounting & Carbon Market",
|
| 14 |
+
"Circular Economy & Waste Management",
|
| 15 |
+
"HSE / K3 (Industry Safety)",
|
| 16 |
+
"Environmental Engineering"
|
| 17 |
+
]
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
CAREER_TRANSITION_DB = [
|
| 21 |
+
# --- ENERGI TERBARUKAN ---
|
| 22 |
+
{
|
| 23 |
+
"sector": "Energi Terbarukan",
|
| 24 |
+
"targetJob": "Renewable Energy Engineer / PLTS Installer",
|
| 25 |
+
"salary": "Rp 8 – 20 juta",
|
| 26 |
+
"skills": ["Desain sistem kelistrikan", "AutoCAD", "PVsyst", "Troubleshooting kelistrikan"],
|
| 27 |
+
"sources": [
|
| 28 |
+
{"from": "Teknisi listrik gedung", "to": "PLTS installer"},
|
| 29 |
+
{"from": "Teknisi industri", "to": "PLTS installer"},
|
| 30 |
+
{"from": "Teknisi genset", "to": "Maintenance EBT"},
|
| 31 |
+
{"from": "power plant batu bara", "to": "Maintenance EBT"},
|
| 32 |
+
{"from": "Electrical engineer manufaktur", "to": "System designer EBT"}
|
| 33 |
+
]
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"sector": "Energi Terbarukan",
|
| 37 |
+
"targetJob": "ESHS Officer",
|
| 38 |
+
"salary": "Rp 7 – 18 juta",
|
| 39 |
+
"skills": ["Implementasi kebijakan CSR", "Audit lingkungan & sosial", "Manajemen K3"],
|
| 40 |
+
"sources": [
|
| 41 |
+
{"from": "HSE officer tambang", "to": "ESHS officer EBT"},
|
| 42 |
+
{"from": "HSE officer migas", "to": "ESHS officer EBT"},
|
| 43 |
+
{"from": "Safety officer pabrik", "to": "HSE proyek PLTS/PLTB"},
|
| 44 |
+
{"from": "Safety officer konstruksi", "to": "HSE proyek PLTS/PLTB"},
|
| 45 |
+
{"from": "Perawat industri", "to": "Occupational health EBT"},
|
| 46 |
+
{"from": "paramedis industri", "to": "Occupational health EBT"}
|
| 47 |
+
]
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"sector": "Energi Terbarukan",
|
| 51 |
+
"targetJob": "Energy Transition Analyst / Project Manager EBT",
|
| 52 |
+
"salary": "Rp 12 – 30 juta",
|
| 53 |
+
"skills": ["Analisis biaya", "Manajemen proyek EPC", "ETAP", "PowerFactory"],
|
| 54 |
+
"sources": [
|
| 55 |
+
{"from": "Project manager konstruksi", "to": "PM proyek EBT"},
|
| 56 |
+
{"from": "EPC migas", "to": "PM proyek EBT"},
|
| 57 |
+
{"from": "Analis energi PLN", "to": "Energy transition analyst"},
|
| 58 |
+
{"from": "Analis batu bara", "to": "Energy transition analyst"},
|
| 59 |
+
{"from": "Konsultan infrastruktur", "to": "Konsultan EBT"}
|
| 60 |
+
]
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"sector": "Energi Terbarukan",
|
| 64 |
+
"targetJob": "Solar PV / Wind System Designer",
|
| 65 |
+
"salary": "Rp 10 – 25 juta",
|
| 66 |
+
"skills": ["PVsyst", "Helioscope", "WindPRO", "Analisis finansial proyek"],
|
| 67 |
+
"sources": [
|
| 68 |
+
{"from": "Drafter", "to": "PV system designer"},
|
| 69 |
+
{"from": "desainer MEP gedung", "to": "PV system designer"},
|
| 70 |
+
{"from": "Engineer perencanaan jaringan listrik", "to": "Grid integration designer"},
|
| 71 |
+
{"from": "Arsitek", "to": "Green building designer"},
|
| 72 |
+
{"from": "civil engineer", "to": "Green building designer"}
|
| 73 |
+
]
|
| 74 |
+
},
|
| 75 |
+
# --- KEHUTANAN & LAHAN ---
|
| 76 |
+
{
|
| 77 |
+
"sector": "Kehutanan & Lahan",
|
| 78 |
+
"targetJob": "Carbon Project Specialist",
|
| 79 |
+
"salary": "Rp 10 – 30 juta",
|
| 80 |
+
"skills": ["Penulisan proposal karbon", "MRV", "GIS", "remote sensing"],
|
| 81 |
+
"sources": [
|
| 82 |
+
{"from": "Peneliti", "to": "Carbon project developer"},
|
| 83 |
+
{"from": "akademisi kehutanan", "to": "Carbon project developer"},
|
| 84 |
+
{"from": "Auditor lingkungan sawit", "to": "Carbon auditor"},
|
| 85 |
+
{"from": "GIS analyst pertambangan", "to": "Remote sensing carbon MRV"}
|
| 86 |
+
]
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"sector": "Kehutanan & Lahan",
|
| 90 |
+
"targetJob": "Forest Planning & Restoration Specialist",
|
| 91 |
+
"salary": "Rp 8 – 22 juta",
|
| 92 |
+
"skills": ["Perencanaan tata guna lahan", "Restorasi ekologi", "AMDAL"],
|
| 93 |
+
"sources": [
|
| 94 |
+
{"from": "Penyuluh kehutanan", "to": "Restoration specialist"},
|
| 95 |
+
{"from": "KLHK", "to": "Restoration specialist"},
|
| 96 |
+
{"from": "Staf AMDAL tambang", "to": "Environmental planner hijau"},
|
| 97 |
+
{"from": "Land surveyor perkebunan", "to": "Land use planner"}
|
| 98 |
+
]
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"sector": "Kehutanan & Lahan",
|
| 102 |
+
"targetJob": "Forest Monitoring & Field Operations Officer",
|
| 103 |
+
"salary": "Rp 5 – 12 juta",
|
| 104 |
+
"skills": ["Monitoring kualitas lingkungan", "Manajemen data PPKH", "Inspeksi hutan"],
|
| 105 |
+
"sources": [
|
| 106 |
+
{"from": "Petugas lapangan perkebunan sawit", "to": "Field monitoring officer"},
|
| 107 |
+
{"from": "Ranger", "to": "Conservation field officer"},
|
| 108 |
+
{"from": "polhut", "to": "Conservation field officer"},
|
| 109 |
+
{"from": "Enumerator", "to": "Data field officer kehutanan"},
|
| 110 |
+
{"from": "surveyor pertanahan", "to": "Data field officer kehutanan"}
|
| 111 |
+
]
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"sector": "Kehutanan & Lahan",
|
| 115 |
+
"targetJob": "CSR Analyst (Kehutanan)",
|
| 116 |
+
"salary": "Rp 7 – 18 juta",
|
| 117 |
+
"skills": ["Perencanaan program CSR", "Public affairs", "Analisis dampak sosial"],
|
| 118 |
+
"sources": [
|
| 119 |
+
{"from": "Staf CSR tambang", "to": "CSR analyst green company"},
|
| 120 |
+
{"from": "Staf CSR migas", "to": "CSR analyst green company"},
|
| 121 |
+
{"from": "Community development officer", "to": "Social impact analyst"},
|
| 122 |
+
{"from": "Jurnalis", "to": "Sustainability comms & CSR"},
|
| 123 |
+
{"from": "komunikasi korporat", "to": "Sustainability comms & CSR"}
|
| 124 |
+
]
|
| 125 |
+
},
|
| 126 |
+
# --- PENGELOLAAN LIMBAH ---
|
| 127 |
+
{
|
| 128 |
+
"sector": "Pengelolaan Limbah",
|
| 129 |
+
"targetJob": "Circular Economy Implementation Manager",
|
| 130 |
+
"salary": "Rp 10 – 25 juta",
|
| 131 |
+
"skills": ["Stakeholder engagement", "Project management", "Monitoring & evaluasi"],
|
| 132 |
+
"sources": [
|
| 133 |
+
{"from": "Project manager manufaktur", "to": "Circular economy PM"},
|
| 134 |
+
{"from": "Operations manager pabrik", "to": "Waste-to-resource ops"},
|
| 135 |
+
{"from": "Supply chain manager", "to": "Circular supply chain manager"}
|
| 136 |
+
]
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"sector": "Pengelolaan Limbah",
|
| 140 |
+
"targetJob": "Environmental Management & Waste Specialist",
|
| 141 |
+
"salary": "Rp 7 – 16 juta",
|
| 142 |
+
"skills": ["Operasional WWTP", "Pengolahan limbah", "Sampling air"],
|
| 143 |
+
"sources": [
|
| 144 |
+
{"from": "Operator WWTP pabrik", "to": "Waste treatment specialist"},
|
| 145 |
+
{"from": "Operator PDAM", "to": "Waste treatment specialist"},
|
| 146 |
+
{"from": "Teknisi lab pertambangan", "to": "Environmental lab specialist"},
|
| 147 |
+
{"from": "Sanitarian", "to": "Environmental health specialist"},
|
| 148 |
+
{"from": "kesehatan lingkungan", "to": "Environmental health specialist"}
|
| 149 |
+
]
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"sector": "Pengelolaan Limbah",
|
| 153 |
+
"targetJob": "Circular Economy Research & Policy Analyst",
|
| 154 |
+
"salary": "Rp 6 – 20 juta",
|
| 155 |
+
"skills": ["Data collection", "Policy analysis", "Pemahaman circular material"],
|
| 156 |
+
"sources": [
|
| 157 |
+
{"from": "Peneliti lingkungan", "to": "Circular economy researcher"},
|
| 158 |
+
{"from": "dosen ilmu lingkungan", "to": "Circular economy researcher"},
|
| 159 |
+
{"from": "Analis kebijakan pemerintah", "to": "Green policy analyst"},
|
| 160 |
+
{"from": "Market researcher", "to": "Sustainability data analyst"},
|
| 161 |
+
{"from": "data analyst", "to": "Sustainability data analyst"}
|
| 162 |
+
]
|
| 163 |
+
},
|
| 164 |
+
# --- PERTANIAN ---
|
| 165 |
+
{
|
| 166 |
+
"sector": "Pertanian Berkelanjutan",
|
| 167 |
+
"targetJob": "Head of Sustainability & Corporate Affairs",
|
| 168 |
+
"salary": "Rp 25 – 50 juta",
|
| 169 |
+
"skills": ["Sustainability Strategy", "Stakeholder Partnership", "Manajemen rantai pasok"],
|
| 170 |
+
"sources": [
|
| 171 |
+
{"from": "Direktur agribisnis", "to": "Head of sustainability"},
|
| 172 |
+
{"from": "VP operasional agribisnis", "to": "Head of sustainability"},
|
| 173 |
+
{"from": "Government relations manager", "to": "Policy & corporate affairs"},
|
| 174 |
+
{"from": "Senior consultant manajemen", "to": "Sustainability strategy lead"}
|
| 175 |
+
]
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"sector": "Pertanian Berkelanjutan",
|
| 179 |
+
"targetJob": "Regenerative Agriculture Manager",
|
| 180 |
+
"salary": "Rp 15 – 35 juta",
|
| 181 |
+
"skills": ["Pertanian regeneratif", "Valuasi ekosistem", "Kredit karbon"],
|
| 182 |
+
"sources": [
|
| 183 |
+
{"from": "Agronomis", "to": "Regenerative agro manager"},
|
| 184 |
+
{"from": "peneliti pertanian", "to": "Regenerative agro manager"},
|
| 185 |
+
{"from": "Manajer kebun", "to": "Sustainable plantation manager"},
|
| 186 |
+
{"from": "plantation manager", "to": "Sustainable plantation manager"},
|
| 187 |
+
{"from": "Penyuluh pertanian", "to": "Regenerative agriculture advisor"}
|
| 188 |
+
]
|
| 189 |
+
},
|
| 190 |
+
# --- LINTAS SEKTOR (CROSS) ---
|
| 191 |
+
{
|
| 192 |
+
"sector": "Cross-Sectoral",
|
| 193 |
+
"targetJob": "Sustainability & ESG Advisory Specialist",
|
| 194 |
+
"salary": "Rp 15 – 31 juta",
|
| 195 |
+
"skills": ["ESG assessment", "Analisis risiko karbon", "Sustainability auditing"],
|
| 196 |
+
"sources": [
|
| 197 |
+
{"from": "Konsultan manajemen", "to": "ESG advisory consultant"},
|
| 198 |
+
{"from": "Auditor keuangan", "to": "Sustainability auditor"},
|
| 199 |
+
{"from": "akuntan publik", "to": "Sustainability auditor"},
|
| 200 |
+
{"from": "Analis risiko perbankan", "to": "Climate risk analyst"}
|
| 201 |
+
]
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"sector": "Cross-Sectoral",
|
| 205 |
+
"targetJob": "GHG Inventory & Climate Risk Analyst",
|
| 206 |
+
"salary": "Rp 12 – 35 juta",
|
| 207 |
+
"skills": ["GHG Inventory", "Analisis risiko iklim", "OpenLCA", "SimaPro"],
|
| 208 |
+
"sources": [
|
| 209 |
+
{"from": "Analis energi migas", "to": "GHG inventory analyst"},
|
| 210 |
+
{"from": "Analis energi batu bara", "to": "GHG inventory analyst"},
|
| 211 |
+
{"from": "Auditor ISO lingkungan", "to": "GHG auditor"},
|
| 212 |
+
{"from": "Aktuaria", "to": "Climate risk modeler"},
|
| 213 |
+
{"from": "risk analyst asuransi", "to": "Climate risk modeler"}
|
| 214 |
+
]
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"sector": "Cross-Sectoral",
|
| 218 |
+
"targetJob": "Green Finance / Sustainable Investment Analyst",
|
| 219 |
+
"salary": "Rp 12 – 40 juta",
|
| 220 |
+
"skills": ["Green bond", "ESG due diligence", "Financial modeling"],
|
| 221 |
+
"sources": [
|
| 222 |
+
{"from": "Analis kredit", "to": "Green finance analyst"},
|
| 223 |
+
{"from": "investment banking", "to": "Green finance analyst"},
|
| 224 |
+
{"from": "Fund manager konvensional", "to": "ESG fund manager"},
|
| 225 |
+
{"from": "Analis saham", "to": "ESG equity analyst"},
|
| 226 |
+
{"from": "equity research", "to": "ESG equity analyst"}
|
| 227 |
+
]
|
| 228 |
+
},
|
| 229 |
+
# --- TRANSPORTASI ---
|
| 230 |
+
{
|
| 231 |
+
"sector": "Transportasi",
|
| 232 |
+
"targetJob": "Business Development EV / Battery Swap",
|
| 233 |
+
"salary": "Rp 8 – 20 juta",
|
| 234 |
+
"skills": ["Negosiasi kontrak B2B", "Site hunting", "Kemitraan strategis"],
|
| 235 |
+
"sources": [
|
| 236 |
+
{"from": "Sales executive otomotif", "to": "Sales EV & battery swap"},
|
| 237 |
+
{"from": "dealer mobil", "to": "Sales EV & battery swap"},
|
| 238 |
+
{"from": "dealer motor BBM", "to": "Sales EV & battery swap"},
|
| 239 |
+
{"from": "Business development SPBU", "to": "BD charging station network"},
|
| 240 |
+
{"from": "Pertamina", "to": "BD charging station network"},
|
| 241 |
+
{"from": "Area manager ritel", "to": "Site expansion EV station"},
|
| 242 |
+
{"from": "Area manager minimarket", "to": "Site expansion EV station"}
|
| 243 |
+
]
|
| 244 |
+
},
|
| 245 |
+
{
|
| 246 |
+
"sector": "Transportasi",
|
| 247 |
+
"targetJob": "Electrical Engineer EV Charging Stations",
|
| 248 |
+
"salary": "Rp 10 – 22 juta",
|
| 249 |
+
"skills": ["Sistem kelistrikan EV", "Supervisi konstruksi", "Manajemen kontrak"],
|
| 250 |
+
"sources": [
|
| 251 |
+
{"from": "Teknisi listrik bengkel", "to": "EV charging installer"},
|
| 252 |
+
{"from": "Teknisi SPBU", "to": "EV charging installer"},
|
| 253 |
+
{"from": "Electrical engineer gedung", "to": "EV infrastructure engineer"},
|
| 254 |
+
{"from": "Teknisi mesin kendaraan", "to": "EV mechanic & service tech"}
|
| 255 |
+
]
|
| 256 |
+
},
|
| 257 |
+
# --- PARIWISATA ---
|
| 258 |
+
{
|
| 259 |
+
"sector": "Pariwisata Berkelanjutan",
|
| 260 |
+
"targetJob": "Ecotourism Specialist",
|
| 261 |
+
"salary": "Rp 5 – 15 juta",
|
| 262 |
+
"skills": ["Merancang program ekowisata", "Pemberdayaan komunitas", "Monitoring dampak"],
|
| 263 |
+
"sources": [
|
| 264 |
+
{"from": "Tour guide", "to": "Ecotourism guide & specialist"},
|
| 265 |
+
{"from": "pemandu wisata konvensional", "to": "Ecotourism guide & specialist"},
|
| 266 |
+
{"from": "Travel agent", "to": "Sustainable tour package designer"},
|
| 267 |
+
{"from": "event organizer wisata", "to": "Sustainable tour package designer"},
|
| 268 |
+
{"from": "Staf hotel", "to": "Eco-lodge & sustainable hospitality"}
|
| 269 |
+
]
|
| 270 |
+
},
|
| 271 |
+
# --- MANUFAKTUR ---
|
| 272 |
+
{
|
| 273 |
+
"sector": "Manufaktur & Konstruksi",
|
| 274 |
+
"targetJob": "Sustainability Specialist & Auditor",
|
| 275 |
+
"salary": "Rp 10 – 27 juta",
|
| 276 |
+
"skills": ["Life Cycle Assessment", "Analisis keberlanjutan", "Efisiensi energi"],
|
| 277 |
+
"sources": [
|
| 278 |
+
{"from": "Auditor ISO", "to": "Sustainability auditor"},
|
| 279 |
+
{"from": "Process engineer", "to": "Green process engineer"},
|
| 280 |
+
{"from": "industrial engineer", "to": "Green process engineer"},
|
| 281 |
+
{"from": "R&D engineer", "to": "Sustainable product designer"},
|
| 282 |
+
{"from": "R&D manufaktur", "to": "Sustainable product designer"}
|
| 283 |
+
]
|
| 284 |
+
},
|
| 285 |
+
# --- TEKNOLOGI & DATA ---
|
| 286 |
+
{
|
| 287 |
+
"sector": "Teknologi & Digital",
|
| 288 |
+
"targetJob": "Sustainability Data Analyst",
|
| 289 |
+
"salary": "Rp 12 – 28 juta",
|
| 290 |
+
"skills": ["SQL", "Tableau/PowerBI", "Python untuk Sustainability", "Analisis emisi data"],
|
| 291 |
+
"sources": [
|
| 292 |
+
{"from": "Data analyst", "to": "Sustainability data analyst"},
|
| 293 |
+
{"from": "Business intelligence", "to": "ESG data specialist"},
|
| 294 |
+
{"from": "Data engineer", "to": "Carbon accounting software dev"},
|
| 295 |
+
{"from": "Web developer", "to": "Green software engineer"}
|
| 296 |
+
]
|
| 297 |
+
},
|
| 298 |
+
# --- ADMINISTRASI & HR ---
|
| 299 |
+
{
|
| 300 |
+
"sector": "Manajemen & Operasional",
|
| 301 |
+
"targetJob": "ESG / Sustainability Coordinator",
|
| 302 |
+
"salary": "Rp 8 – 20 juta",
|
| 303 |
+
"skills": ["Pelaporan ESG", "Admin proyek", "Stakeholder communications"],
|
| 304 |
+
"sources": [
|
| 305 |
+
{"from": "Sekretaris", "to": "Sustainability coordinator"},
|
| 306 |
+
{"from": "Admin kantor", "to": "ESG administrative support"},
|
| 307 |
+
{"from": "General affair", "to": "Green office coordinator"},
|
| 308 |
+
{"from": "Accounting", "to": "Climate finance support"}
|
| 309 |
+
]
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"sector": "Sumber Daya Manusia",
|
| 313 |
+
"targetJob": "Green Talent Acquisition / People & Culture",
|
| 314 |
+
"salary": "Rp 10 – 22 juta",
|
| 315 |
+
"skills": ["Keahlian rekrutmen hijau", "Culture building", "Manajemen perubahan"],
|
| 316 |
+
"sources": [
|
| 317 |
+
{"from": "HR generalist", "to": "People & culture lead"},
|
| 318 |
+
{"from": "Recruiter", "to": "ESG talent acquisition"},
|
| 319 |
+
{"from": "Training manager", "to": "Sustainability training lead"}
|
| 320 |
+
]
|
| 321 |
+
}
|
| 322 |
+
]
|
app/main.py
CHANGED
|
@@ -1,715 +1,506 @@
|
|
| 1 |
-
"""Brigawan
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
from
|
| 13 |
-
|
| 14 |
-
from
|
| 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 |
-
app.
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
}
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
-
|
| 143 |
-
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
background:
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
}
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
}
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
padding:
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
}
|
| 241 |
-
.
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
}
|
| 252 |
-
.
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
.
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
}
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
<div class="endpoint-item"><span class="route-path">/job/create</span><span class="method-badge method-post">POST</span></div>
|
| 508 |
-
<div class="endpoint-item"><span class="route-path">/job/{job_id}</span><span class="method-badge method-get">GET</span></div>
|
| 509 |
-
<div class="endpoint-item"><span class="route-path">/job/{job_id}/apply</span><span class="method-badge method-post">POST</span></div>
|
| 510 |
-
<div class="endpoint-item"><span class="route-path">/search/jobs</span><span class="method-badge method-get">GET</span></div>
|
| 511 |
-
</div>
|
| 512 |
-
</div>
|
| 513 |
-
|
| 514 |
-
<!-- Talent Group -->
|
| 515 |
-
<div class="endpoint-group">
|
| 516 |
-
<div class="endpoint-group-header" onclick="toggleGroup(this)">
|
| 517 |
-
<div class="group-title-container">
|
| 518 |
-
<span class="group-icon">👤</span>
|
| 519 |
-
<span class="group-title">Talenta & Kandidat (/talent)</span>
|
| 520 |
-
</div>
|
| 521 |
-
<span class="group-badge">4 routes</span>
|
| 522 |
-
</div>
|
| 523 |
-
<div class="endpoint-list">
|
| 524 |
-
<div class="endpoint-item"><span class="route-path">/talent/profile</span><span class="method-badge method-get">GET</span></div>
|
| 525 |
-
<div class="endpoint-item"><span class="route-path">/talent/profile/update</span><span class="method-badge method-put">PUT</span></div>
|
| 526 |
-
<div class="endpoint-item"><span class="route-path">/talent/resume/upload</span><span class="method-badge method-post">POST</span></div>
|
| 527 |
-
<div class="endpoint-item"><span class="route-path">/talent/resume/parse</span><span class="method-badge method-post">POST</span></div>
|
| 528 |
-
</div>
|
| 529 |
-
</div>
|
| 530 |
-
|
| 531 |
-
<!-- Employer Group -->
|
| 532 |
-
<div class="endpoint-group">
|
| 533 |
-
<div class="endpoint-group-header" onclick="toggleGroup(this)">
|
| 534 |
-
<div class="group-title-container">
|
| 535 |
-
<span class="group-icon">🏢</span>
|
| 536 |
-
<span class="group-title">Rekruter & Korporat (/employer)</span>
|
| 537 |
-
</div>
|
| 538 |
-
<span class="group-badge">3 routes</span>
|
| 539 |
-
</div>
|
| 540 |
-
<div class="endpoint-list">
|
| 541 |
-
<div class="endpoint-item"><span class="route-path">/employer/profile</span><span class="method-badge method-get">GET</span></div>
|
| 542 |
-
<div class="endpoint-item"><span class="route-path">/employer/credits/balance</span><span class="method-badge method-get">GET</span></div>
|
| 543 |
-
<div class="endpoint-item"><span class="route-path">/employer/checkout</span><span class="method-badge method-post">POST</span></div>
|
| 544 |
-
</div>
|
| 545 |
-
</div>
|
| 546 |
-
|
| 547 |
-
<!-- Academy Group -->
|
| 548 |
-
<div class="endpoint-group">
|
| 549 |
-
<div class="endpoint-group-header" onclick="toggleGroup(this)">
|
| 550 |
-
<div class="group-title-container">
|
| 551 |
-
<span class="group-icon">🏫</span>
|
| 552 |
-
<span class="group-title">Mitra LPK & Rekomendasi (/academy)</span>
|
| 553 |
-
</div>
|
| 554 |
-
<span class="group-badge">2 routes</span>
|
| 555 |
-
</div>
|
| 556 |
-
<div class="endpoint-list">
|
| 557 |
-
<div class="endpoint-item"><span class="route-path">/academy/recommendations</span><span class="method-badge method-get">GET</span></div>
|
| 558 |
-
<div class="endpoint-item"><span class="route-path">/academy/lpk/list</span><span class="method-badge method-get">GET</span></div>
|
| 559 |
-
</div>
|
| 560 |
-
</div>
|
| 561 |
-
|
| 562 |
-
<!-- Integrations Group -->
|
| 563 |
-
<div class="endpoint-group">
|
| 564 |
-
<div class="endpoint-group-header" onclick="toggleGroup(this)">
|
| 565 |
-
<div class="group-title-container">
|
| 566 |
-
<span class="group-icon">📡</span>
|
| 567 |
-
<span class="group-title">Bot & Integrasi Eksternal</span>
|
| 568 |
-
</div>
|
| 569 |
-
<span class="group-badge">3 routes</span>
|
| 570 |
-
</div>
|
| 571 |
-
<div class="endpoint-list">
|
| 572 |
-
<div class="endpoint-item"><span class="route-path">/telegram/webhook</span><span class="method-badge method-post">POST</span></div>
|
| 573 |
-
<div class="endpoint-item"><span class="route-path">/whatsapp/send</span><span class="method-badge method-post">POST</span></div>
|
| 574 |
-
<div class="endpoint-item"><span class="route-path">/legacy-compat/sync</span><span class="method-badge method-post">POST</span></div>
|
| 575 |
-
</div>
|
| 576 |
-
</div>
|
| 577 |
-
|
| 578 |
-
</div>
|
| 579 |
-
</div>
|
| 580 |
-
|
| 581 |
-
</div>
|
| 582 |
-
|
| 583 |
-
<!-- Footer -->
|
| 584 |
-
<footer>
|
| 585 |
-
<p>© 2026 BRIGA.ID — Green Career & B2B Sustainability Recruitment. All rights reserved.</p>
|
| 586 |
-
</footer>
|
| 587 |
-
</div>
|
| 588 |
-
|
| 589 |
-
<script>
|
| 590 |
-
function toggleGroup(header) {
|
| 591 |
-
const list = header.nextElementSibling;
|
| 592 |
-
if (list.style.display === "flex") {
|
| 593 |
-
list.style.display = "none";
|
| 594 |
-
} else {
|
| 595 |
-
list.style.display = "flex";
|
| 596 |
-
}
|
| 597 |
-
}
|
| 598 |
-
|
| 599 |
-
async function runDiagnostics() {
|
| 600 |
-
const consoleEl = document.getElementById("console-output");
|
| 601 |
-
const dbLabel = document.getElementById("db-status-label");
|
| 602 |
-
const aiLabel = document.getElementById("ai-status-label");
|
| 603 |
-
|
| 604 |
-
consoleEl.innerHTML += "[System] Ping health endpoint...<br>";
|
| 605 |
-
consoleEl.scrollTop = consoleEl.scrollHeight;
|
| 606 |
-
|
| 607 |
-
try {
|
| 608 |
-
const start = Date.now();
|
| 609 |
-
const res = await fetch('/health');
|
| 610 |
-
const data = await res.json();
|
| 611 |
-
const latency = Date.now() - start;
|
| 612 |
-
|
| 613 |
-
consoleEl.innerHTML += `[Health] Status: ${data.status} (${latency}ms)<br>`;
|
| 614 |
-
|
| 615 |
-
if (data.database && data.database.status === 'healthy') {
|
| 616 |
-
dbLabel.innerText = "● Healthy";
|
| 617 |
-
dbLabel.style.color = "var(--accent-green)";
|
| 618 |
-
consoleEl.innerHTML += `[Database] Status: healthy<br>`;
|
| 619 |
-
} else {
|
| 620 |
-
dbLabel.innerText = "● Error";
|
| 621 |
-
dbLabel.style.color = "#dc2626";
|
| 622 |
-
consoleEl.innerHTML += `[Database] Connection Error: ${data.database ? data.database.error : 'unknown'}<br>`;
|
| 623 |
-
}
|
| 624 |
-
|
| 625 |
-
if (data.ai && data.ai.status === 'ready') {
|
| 626 |
-
aiLabel.innerText = "● Ready";
|
| 627 |
-
aiLabel.style.color = "var(--accent-green)";
|
| 628 |
-
consoleEl.innerHTML += `[AI Engine] Model: ${data.ai.model} (Ready)<br>`;
|
| 629 |
-
} else {
|
| 630 |
-
aiLabel.innerText = "● Degraded";
|
| 631 |
-
aiLabel.style.color = "#d97706";
|
| 632 |
-
consoleEl.innerHTML += `[AI Engine] Status degraded<br>`;
|
| 633 |
-
}
|
| 634 |
-
} catch (err) {
|
| 635 |
-
consoleEl.innerHTML += `<span style="color:#dc2626">[Error] Failed to connect to health endpoint: ${err.message}</span><br>`;
|
| 636 |
-
dbLabel.innerText = "● Error";
|
| 637 |
-
dbLabel.style.color = "#dc2626";
|
| 638 |
-
aiLabel.innerText = "● Error";
|
| 639 |
-
aiLabel.style.color = "#dc2626";
|
| 640 |
-
}
|
| 641 |
-
consoleEl.scrollTop = consoleEl.scrollHeight;
|
| 642 |
-
}
|
| 643 |
-
|
| 644 |
-
// Run diagnostic automatically on load
|
| 645 |
-
window.addEventListener('load', () => {
|
| 646 |
-
setTimeout(runDiagnostics, 500);
|
| 647 |
-
});
|
| 648 |
-
</script>
|
| 649 |
-
</body>
|
| 650 |
-
</html>
|
| 651 |
-
"""
|
| 652 |
-
return HTMLResponse(content=html_content)
|
| 653 |
-
|
| 654 |
-
@app.api_route("/health", methods=["GET", "HEAD"], tags=["Health"])
|
| 655 |
-
async def health_check():
|
| 656 |
-
import sqlalchemy
|
| 657 |
-
from app.database import AsyncSessionLocal
|
| 658 |
-
from sqlalchemy import text
|
| 659 |
-
|
| 660 |
-
db_status = "healthy"
|
| 661 |
-
db_error = None
|
| 662 |
-
try:
|
| 663 |
-
async with AsyncSessionLocal() as session:
|
| 664 |
-
await session.execute(text("SELECT 1"))
|
| 665 |
-
except Exception as e:
|
| 666 |
-
db_status = "unhealthy"
|
| 667 |
-
db_error = str(e)
|
| 668 |
-
logger.error(f"Health check DB connection failed: {e}")
|
| 669 |
-
|
| 670 |
-
ai_status = check_ai_status()
|
| 671 |
-
is_healthy = (db_status == "healthy") and (ai_status.get("status") == "ready")
|
| 672 |
-
|
| 673 |
-
return {
|
| 674 |
-
"status": "ok" if is_healthy else "degraded",
|
| 675 |
-
"version": "2.0.0",
|
| 676 |
-
"service": "briga-core-api",
|
| 677 |
-
"database": {
|
| 678 |
-
"status": db_status,
|
| 679 |
-
"error": db_error
|
| 680 |
-
},
|
| 681 |
-
"ai": ai_status
|
| 682 |
-
}
|
| 683 |
-
|
| 684 |
-
from app.api.auth import router as auth_router
|
| 685 |
-
from app.api.career import router as career_router
|
| 686 |
-
from app.api.search import router as search_router
|
| 687 |
-
from app.api.chat import router as chat_router
|
| 688 |
-
from app.api.employer import router as employer_router
|
| 689 |
-
from app.api.talent import router as talent_router
|
| 690 |
-
from app.api.job import router as job_router
|
| 691 |
-
from app.api.interview import router as interview_router
|
| 692 |
-
from app.api.academy import router as academy_router
|
| 693 |
-
from app.api.admin import router as admin_router
|
| 694 |
-
from app.api.legacy_compat import router as legacy_compat_router
|
| 695 |
-
from app.api.debug_admin import router as debug_admin_router
|
| 696 |
-
from app.api.telegram import router as telegram_router
|
| 697 |
-
from app.api.whatsapp import router as whatsapp_router
|
| 698 |
-
from app.middleware.ab_assign import ABAssignMiddleware
|
| 699 |
-
|
| 700 |
-
app.add_middleware(ABAssignMiddleware)
|
| 701 |
-
|
| 702 |
-
app.include_router(auth_router)
|
| 703 |
-
app.include_router(career_router)
|
| 704 |
-
app.include_router(search_router)
|
| 705 |
-
app.include_router(chat_router)
|
| 706 |
-
app.include_router(employer_router)
|
| 707 |
-
app.include_router(talent_router)
|
| 708 |
-
app.include_router(job_router)
|
| 709 |
-
app.include_router(interview_router)
|
| 710 |
-
app.include_router(academy_router)
|
| 711 |
-
app.include_router(admin_router)
|
| 712 |
-
app.include_router(legacy_compat_router)
|
| 713 |
-
app.include_router(debug_admin_router)
|
| 714 |
-
app.include_router(telegram_router)
|
| 715 |
-
app.include_router(whatsapp_router)
|
|
|
|
| 1 |
+
"""Brigawan Backend — FastAPI Application Entry Point.
|
| 2 |
+
|
| 3 |
+
Replaces Code.gs (GAS router) with a FastAPI async server on Cloud Run.
|
| 4 |
+
Mounts all API routers and middleware.
|
| 5 |
+
|
| 6 |
+
Zero-cost architecture:
|
| 7 |
+
- Auth via Google OAuth (free) + email/password
|
| 8 |
+
- Rate limiting in-memory (no Redis)
|
| 9 |
+
- Free tier: 3 credits, 1 job, no AI matching
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from contextlib import asynccontextmanager
|
| 13 |
+
|
| 14 |
+
from fastapi import FastAPI
|
| 15 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
+
from fastapi.responses import HTMLResponse
|
| 17 |
+
from loguru import logger
|
| 18 |
+
import os
|
| 19 |
+
from dotenv import load_dotenv
|
| 20 |
+
|
| 21 |
+
# --- LOAD ENVIRONMENT ---
|
| 22 |
+
# Load from current dir or search upwards for .env
|
| 23 |
+
load_dotenv()
|
| 24 |
+
if not os.environ.get("DATABASE_URL"):
|
| 25 |
+
# Fallback to subdirectory if started from root
|
| 26 |
+
load_dotenv(os.path.join(os.path.dirname(__file__), "..", ".env"))
|
| 27 |
+
# ------------------------
|
| 28 |
+
|
| 29 |
+
# --- HF PROXY CLEANUP ---
|
| 30 |
+
removed_proxies = []
|
| 31 |
+
for var in ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"]:
|
| 32 |
+
if var in os.environ:
|
| 33 |
+
os.environ.pop(var, None)
|
| 34 |
+
removed_proxies.append(var)
|
| 35 |
+
if removed_proxies:
|
| 36 |
+
print(f">>> [SYSTEM] Cleaned proxy variables from environment: {removed_proxies}")
|
| 37 |
+
|
| 38 |
+
# --- HF STARTUP DEBUG ---
|
| 39 |
+
print(">>> [SYSTEM] Python main.py script loaded!")
|
| 40 |
+
logger.info(f"Checking Environment: DATABASE_URL is {'SET' if os.environ.get('DATABASE_URL') else 'MISSING'}")
|
| 41 |
+
gemini_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GEMINI_API_KEYS")
|
| 42 |
+
logger.info(f"Checking Environment: GEMINI_API_KEY is {'SET' if gemini_key else 'MISSING'}")
|
| 43 |
+
# ------------------------
|
| 44 |
+
|
| 45 |
+
from app.database import close_db, init_db
|
| 46 |
+
from app.middleware.auth import AuthMiddleware
|
| 47 |
+
from app.middleware.correlation import CorrelationIDMiddleware
|
| 48 |
+
from app.services.ai_service import check_ai_status
|
| 49 |
+
from app.utils.cache import get_ai_cache_stats
|
| 50 |
+
from app.services.autonomous_dev_service import AutonomousDevService
|
| 51 |
+
import asyncio
|
| 52 |
+
|
| 53 |
+
# --- FIX (2026-09): Persist logs to file so AutonomousDevService.monitor_logs()
|
| 54 |
+
# can actually detect errors. Previously loguru only wrote to stderr (default),
|
| 55 |
+
# so the self-healing loop watched a file that never existed.
|
| 56 |
+
try:
|
| 57 |
+
_LOG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
| 58 |
+
_LOG_FILE = os.path.join(_LOG_DIR, "server.log")
|
| 59 |
+
logger.add(
|
| 60 |
+
_LOG_FILE,
|
| 61 |
+
rotation="10 MB",
|
| 62 |
+
retention=5,
|
| 63 |
+
level="INFO",
|
| 64 |
+
enqueue=True,
|
| 65 |
+
serialize=False,
|
| 66 |
+
)
|
| 67 |
+
logger.info(f"[Logging] server.log sink configured at {_LOG_FILE}")
|
| 68 |
+
except Exception as log_err:
|
| 69 |
+
print(f">>> [SYSTEM] Failed to configure server.log sink: {log_err}")
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@asynccontextmanager
|
| 73 |
+
async def lifespan(app: FastAPI):
|
| 74 |
+
"""Startup / shutdown lifecycle.
|
| 75 |
+
|
| 76 |
+
- On startup: initialize DB pool and create tables
|
| 77 |
+
- On shutdown: gracefully close all connections
|
| 78 |
+
- For production: use Alembic migrations instead of create_all
|
| 79 |
+
"""
|
| 80 |
+
logger.info("Brigawan API starting...")
|
| 81 |
+
# Start Autonomous Dev Loop in the background
|
| 82 |
+
asyncio.create_task(AutonomousDevService.monitor_logs())
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
await init_db()
|
| 86 |
+
logger.info("Database tables created/verified")
|
| 87 |
+
except Exception as e:
|
| 88 |
+
logger.warning(f"DB init skipped (will retry on first request): {e}")
|
| 89 |
+
yield
|
| 90 |
+
logger.info("Brigawan API shutting down...")
|
| 91 |
+
await close_db()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
app = FastAPI(
|
| 95 |
+
title="Brigawan API",
|
| 96 |
+
description="Multi-tenant Green Jobs Portal Backend — Free tier supports 10K users",
|
| 97 |
+
version="2.0.0",
|
| 98 |
+
lifespan=lifespan,
|
| 99 |
+
docs_url="/docs",
|
| 100 |
+
redoc_url="/redoc",
|
| 101 |
+
contact={
|
| 102 |
+
"name": "Brigawan",
|
| 103 |
+
"email": "info@briga.id",
|
| 104 |
+
"url": "https://briga.id",
|
| 105 |
+
},
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# ─── CORS (allow Cloudflare Pages frontend) ───
|
| 109 |
+
app.add_middleware(
|
| 110 |
+
CORSMiddleware,
|
| 111 |
+
allow_origins=[
|
| 112 |
+
"https://briga.id",
|
| 113 |
+
"https://www.briga.id",
|
| 114 |
+
"http://localhost:3000",
|
| 115 |
+
"http://localhost:5173", # Vite dev server
|
| 116 |
+
],
|
| 117 |
+
allow_origin_regex=r"https://[a-z0-9-]+\.pages\.dev", # Cloudflare Pages preview
|
| 118 |
+
allow_credentials=True,
|
| 119 |
+
allow_methods=["*"],
|
| 120 |
+
allow_headers=["*"],
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# ─── Correlation ID (request tracking across services) ───
|
| 124 |
+
app.add_middleware(CorrelationIDMiddleware)
|
| 125 |
+
|
| 126 |
+
# ─── Auth & Rate Limiting Middleware ───
|
| 127 |
+
app.add_middleware(AuthMiddleware)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@app.get("/", response_class=HTMLResponse, tags=["Dashboard"])
|
| 131 |
+
async def root_dashboard():
|
| 132 |
+
html_content = """<!DOCTYPE html>
|
| 133 |
+
<html lang="id">
|
| 134 |
+
<head>
|
| 135 |
+
<meta charset="UTF-8">
|
| 136 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 137 |
+
<title>Briga Gateway API Dashboard</title>
|
| 138 |
+
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
|
| 139 |
+
<style>
|
| 140 |
+
:root {
|
| 141 |
+
--bg-color: #0b131b;
|
| 142 |
+
--card-bg: rgba(20, 32, 45, 0.6);
|
| 143 |
+
--border-color: rgba(255, 255, 255, 0.08);
|
| 144 |
+
--text-color: #f1f5f9;
|
| 145 |
+
--accent-green: #10b981;
|
| 146 |
+
--accent-glow: rgba(16, 185, 129, 0.15);
|
| 147 |
+
}
|
| 148 |
+
body {
|
| 149 |
+
background-color: var(--bg-color);
|
| 150 |
+
color: var(--text-color);
|
| 151 |
+
font-family: 'Outfit', sans-serif;
|
| 152 |
+
margin: 0;
|
| 153 |
+
padding: 0;
|
| 154 |
+
display: flex;
|
| 155 |
+
justify-content: center;
|
| 156 |
+
align-items: center;
|
| 157 |
+
min-height: 100vh;
|
| 158 |
+
overflow-x: hidden;
|
| 159 |
+
}
|
| 160 |
+
.container {
|
| 161 |
+
width: 90%;
|
| 162 |
+
max-width: 800px;
|
| 163 |
+
background: var(--card-bg);
|
| 164 |
+
backdrop-filter: blur(20px);
|
| 165 |
+
border: 1px solid var(--border-color);
|
| 166 |
+
border-radius: 24px;
|
| 167 |
+
padding: 40px;
|
| 168 |
+
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
|
| 169 |
+
text-align: center;
|
| 170 |
+
animation: fadeIn 0.8s ease-out;
|
| 171 |
+
position: relative;
|
| 172 |
+
}
|
| 173 |
+
.container::before {
|
| 174 |
+
content: '';
|
| 175 |
+
position: absolute;
|
| 176 |
+
top: -20px;
|
| 177 |
+
left: -20px;
|
| 178 |
+
right: -20px;
|
| 179 |
+
bottom: -20px;
|
| 180 |
+
background: radial-gradient(circle, var(--accent-glow) 0%, transparent 70%);
|
| 181 |
+
z-index: -1;
|
| 182 |
+
border-radius: 40px;
|
| 183 |
+
}
|
| 184 |
+
@keyframes fadeIn {
|
| 185 |
+
from { opacity: 0; transform: translateY(20px); }
|
| 186 |
+
to { opacity: 1; transform: translateY(0); }
|
| 187 |
+
}
|
| 188 |
+
h1 {
|
| 189 |
+
font-size: 2.5rem;
|
| 190 |
+
font-weight: 800;
|
| 191 |
+
margin-bottom: 10px;
|
| 192 |
+
background: linear-gradient(135deg, #34d399 0%, #059669 100%);
|
| 193 |
+
-webkit-background-clip: text;
|
| 194 |
+
-webkit-text-fill-color: transparent;
|
| 195 |
+
}
|
| 196 |
+
.status-badge {
|
| 197 |
+
display: inline-flex;
|
| 198 |
+
align-items: center;
|
| 199 |
+
background: rgba(16, 185, 129, 0.1);
|
| 200 |
+
border: 1px solid rgba(16, 185, 129, 0.2);
|
| 201 |
+
color: var(--accent-green);
|
| 202 |
+
padding: 8px 16px;
|
| 203 |
+
border-radius: 50px;
|
| 204 |
+
font-size: 0.9rem;
|
| 205 |
+
font-weight: 600;
|
| 206 |
+
margin-bottom: 30px;
|
| 207 |
+
}
|
| 208 |
+
.status-dot {
|
| 209 |
+
width: 8px;
|
| 210 |
+
height: 8px;
|
| 211 |
+
background-color: var(--accent-green);
|
| 212 |
+
border-radius: 50%;
|
| 213 |
+
margin-right: 8px;
|
| 214 |
+
box-shadow: 0 0 10px var(--accent-green);
|
| 215 |
+
animation: pulse 1.5s infinite;
|
| 216 |
+
}
|
| 217 |
+
@keyframes pulse {
|
| 218 |
+
0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
|
| 219 |
+
70% { transform: scale(1.1); box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }
|
| 220 |
+
100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
|
| 221 |
+
}
|
| 222 |
+
.grid {
|
| 223 |
+
display: grid;
|
| 224 |
+
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
| 225 |
+
gap: 20px;
|
| 226 |
+
margin-top: 30px;
|
| 227 |
+
text-align: left;
|
| 228 |
+
}
|
| 229 |
+
.card {
|
| 230 |
+
background: rgba(255, 255, 255, 0.03);
|
| 231 |
+
border: 1px solid var(--border-color);
|
| 232 |
+
border-radius: 16px;
|
| 233 |
+
padding: 20px;
|
| 234 |
+
transition: all 0.3s ease;
|
| 235 |
+
}
|
| 236 |
+
.card:hover {
|
| 237 |
+
transform: translateY(-5px);
|
| 238 |
+
background: rgba(255, 255, 255, 0.05);
|
| 239 |
+
border-color: rgba(16, 185, 129, 0.3);
|
| 240 |
+
}
|
| 241 |
+
.card-title {
|
| 242 |
+
font-size: 0.85rem;
|
| 243 |
+
text-transform: uppercase;
|
| 244 |
+
letter-spacing: 1.5px;
|
| 245 |
+
color: #94a3b8;
|
| 246 |
+
margin-bottom: 10px;
|
| 247 |
+
}
|
| 248 |
+
.card-value {
|
| 249 |
+
font-size: 1.4rem;
|
| 250 |
+
font-weight: 600;
|
| 251 |
+
}
|
| 252 |
+
.routes-list {
|
| 253 |
+
margin-top: 40px;
|
| 254 |
+
text-align: left;
|
| 255 |
+
border-top: 1px solid var(--border-color);
|
| 256 |
+
padding-top: 30px;
|
| 257 |
+
}
|
| 258 |
+
.routes-title {
|
| 259 |
+
font-size: 1.1rem;
|
| 260 |
+
font-weight: 600;
|
| 261 |
+
margin-bottom: 15px;
|
| 262 |
+
color: #94a3b8;
|
| 263 |
+
}
|
| 264 |
+
.route-item {
|
| 265 |
+
display: flex;
|
| 266 |
+
justify-content: space-between;
|
| 267 |
+
align-items: center;
|
| 268 |
+
background: rgba(255, 255, 255, 0.02);
|
| 269 |
+
padding: 12px 20px;
|
| 270 |
+
border-radius: 12px;
|
| 271 |
+
margin-bottom: 10px;
|
| 272 |
+
border: 1px solid var(--border-color);
|
| 273 |
+
font-family: monospace;
|
| 274 |
+
font-size: 0.9rem;
|
| 275 |
+
}
|
| 276 |
+
.route-method {
|
| 277 |
+
background: #2563eb;
|
| 278 |
+
color: white;
|
| 279 |
+
padding: 4px 8px;
|
| 280 |
+
border-radius: 6px;
|
| 281 |
+
font-size: 0.75rem;
|
| 282 |
+
font-weight: 700;
|
| 283 |
+
}
|
| 284 |
+
.route-method.post {
|
| 285 |
+
background: #059669;
|
| 286 |
+
}
|
| 287 |
+
</style>
|
| 288 |
+
</head>
|
| 289 |
+
<body>
|
| 290 |
+
<div class="container">
|
| 291 |
+
<h1>Briga Gateway API</h1>
|
| 292 |
+
<div class="status-badge">
|
| 293 |
+
<span class="status-dot"></span>
|
| 294 |
+
Sistem Aktif & Siaga
|
| 295 |
+
</div>
|
| 296 |
+
<p style="color: #94a3b8; line-height: 1.6; margin-bottom: 30px;">
|
| 297 |
+
Layanan backend utama untuk Briga.id yang mengelola database Supabase, otentikasi pengguna, dan gateway untuk agen kecerdasan buatan.
|
| 298 |
+
</p>
|
| 299 |
+
<div class="grid">
|
| 300 |
+
<div class="card">
|
| 301 |
+
<div class="card-title">Platform</div>
|
| 302 |
+
<div class="card-value">Hugging Face</div>
|
| 303 |
+
</div>
|
| 304 |
+
<div class="card">
|
| 305 |
+
<div class="card-title">Database</div>
|
| 306 |
+
<div class="card-value" style="color: #34d399;">Connected</div>
|
| 307 |
+
</div>
|
| 308 |
+
<div class="card">
|
| 309 |
+
<div class="card-title">Version</div>
|
| 310 |
+
<div class="card-value">2.0.0</div>
|
| 311 |
+
</div>
|
| 312 |
+
</div>
|
| 313 |
+
<div class="routes-list">
|
| 314 |
+
<div class="routes-title">Endpoint Aktif</div>
|
| 315 |
+
<div class="route-item">
|
| 316 |
+
<span>/health</span>
|
| 317 |
+
<span class="route-method">GET</span>
|
| 318 |
+
</div>
|
| 319 |
+
<div class="route-item">
|
| 320 |
+
<span>/docs</span>
|
| 321 |
+
<span class="route-method">GET</span>
|
| 322 |
+
</div>
|
| 323 |
+
<div class="route-item">
|
| 324 |
+
<span>/webhook/telegram</span>
|
| 325 |
+
<span class="route-method">POST</span>
|
| 326 |
+
</div>
|
| 327 |
+
</div>
|
| 328 |
+
</div>
|
| 329 |
+
</body>
|
| 330 |
+
</html>"""
|
| 331 |
+
return HTMLResponse(content=html_content)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
# ─── Health Checks ───────────────────────────────────────────────────────────
|
| 335 |
+
|
| 336 |
+
@app.api_route("/health", methods=["GET", "HEAD"], tags=["Health"])
|
| 337 |
+
async def health_check():
|
| 338 |
+
router_url = os.environ.get("ROUTER_API_URL", "not_configured")
|
| 339 |
+
return {
|
| 340 |
+
"status": "ok",
|
| 341 |
+
"version": "2.0.0",
|
| 342 |
+
"service": "brigawan-api",
|
| 343 |
+
"deployment": {
|
| 344 |
+
"platform": "huggingface-spaces",
|
| 345 |
+
"ai_router": router_url if router_url != "not_configured" else "co-located",
|
| 346 |
+
"database": "supabase-postgres" if os.environ.get("DATABASE_URL") else "sqlite-fallback",
|
| 347 |
+
},
|
| 348 |
+
"free_tier": {
|
| 349 |
+
"max_users": 10000,
|
| 350 |
+
"credits": 3,
|
| 351 |
+
"max_jobs": 1,
|
| 352 |
+
"rate_limit_per_hour": 100,
|
| 353 |
+
"cost": "$0",
|
| 354 |
+
},
|
| 355 |
+
"cache": get_ai_cache_stats(),
|
| 356 |
+
"ai": check_ai_status(),
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
@app.get("/api/test-telegram")
|
| 361 |
+
async def test_telegram():
|
| 362 |
+
import httpx
|
| 363 |
+
import os
|
| 364 |
+
from app.config.settings import settings
|
| 365 |
+
token = settings.telegram_bot_token or os.environ.get("TELEGRAM_BOT_TOKEN", "")
|
| 366 |
+
proxy_url = os.environ.get("TELEGRAM_PROXY_URL", "").rstrip("/")
|
| 367 |
+
proxy_secret = os.environ.get("TELEGRAM_PROXY_SECRET", "")
|
| 368 |
+
|
| 369 |
+
results = {}
|
| 370 |
+
|
| 371 |
+
# Test 1: httpbin.org (Check general internet access)
|
| 372 |
+
try:
|
| 373 |
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
| 374 |
+
resp = await client.get("https://httpbin.org/get")
|
| 375 |
+
results["httpbin"] = {"status_code": resp.status_code, "json": resp.json()}
|
| 376 |
+
except Exception as e:
|
| 377 |
+
results["httpbin"] = {"error": str(e)}
|
| 378 |
+
|
| 379 |
+
# Test 2: Telegram Connectivity
|
| 380 |
+
if not token:
|
| 381 |
+
results["telegram"] = {"error": "TELEGRAM_BOT_TOKEN is not configured"}
|
| 382 |
+
else:
|
| 383 |
+
# Determine mode
|
| 384 |
+
is_gas = "script.google.com" in proxy_url
|
| 385 |
+
if proxy_url and proxy_secret:
|
| 386 |
+
if is_gas:
|
| 387 |
+
url = proxy_url
|
| 388 |
+
payload = {
|
| 389 |
+
"action": "proxyTelegram",
|
| 390 |
+
"params": ["getMe", {}, proxy_secret]
|
| 391 |
+
}
|
| 392 |
+
mode = "gas_rpc"
|
| 393 |
+
else:
|
| 394 |
+
url = f"{proxy_url}/getMe"
|
| 395 |
+
headers = {"X-Proxy-Secret": proxy_secret}
|
| 396 |
+
mode = "transparent_proxy"
|
| 397 |
+
else:
|
| 398 |
+
url = f"https://api.telegram.org/bot{token}/getMe"
|
| 399 |
+
headers = {}
|
| 400 |
+
mode = "direct"
|
| 401 |
+
|
| 402 |
+
masked_token = f"{token[:10]}...{token[-5:]}" if len(token) > 15 else "too_short"
|
| 403 |
+
try:
|
| 404 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 405 |
+
if mode == "gas_rpc":
|
| 406 |
+
resp = await client.post(url, json=payload)
|
| 407 |
+
else:
|
| 408 |
+
resp = await client.get(url, headers=headers)
|
| 409 |
+
|
| 410 |
+
results["telegram"] = {
|
| 411 |
+
"mode": mode,
|
| 412 |
+
"url": url if mode != "direct" else "https://api.telegram.org/bot[MASKED]/getMe",
|
| 413 |
+
"status_code": resp.status_code,
|
| 414 |
+
"json": resp.json() if resp.status_code == 200 else resp.text[:200],
|
| 415 |
+
"masked_token": masked_token
|
| 416 |
+
}
|
| 417 |
+
except Exception as e:
|
| 418 |
+
import traceback
|
| 419 |
+
results["telegram"] = {
|
| 420 |
+
"mode": mode,
|
| 421 |
+
"error": str(e),
|
| 422 |
+
"traceback": traceback.format_exc(),
|
| 423 |
+
"masked_token": masked_token
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
return results
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
@app.get("/health/ai-router", tags=["Health"])
|
| 430 |
+
async def ai_router_health():
|
| 431 |
+
"""Check AI Router connectivity (for hybrid deployment)."""
|
| 432 |
+
router_url = os.environ.get("ROUTER_API_URL", "")
|
| 433 |
+
if not router_url:
|
| 434 |
+
return {"status": "co-located", "message": "AI is co-located in this service"}
|
| 435 |
+
|
| 436 |
+
try:
|
| 437 |
+
import httpx
|
| 438 |
+
async with httpx.AsyncClient(timeout=5.0) as client:
|
| 439 |
+
resp = await client.get(f"{router_url}/health")
|
| 440 |
+
latency_ms = resp.elapsed.total_seconds() * 1000
|
| 441 |
+
return {
|
| 442 |
+
"status": "healthy" if resp.status_code == 200 else "degraded",
|
| 443 |
+
"url": router_url,
|
| 444 |
+
"latency_ms": round(latency_ms, 1),
|
| 445 |
+
"status_code": resp.status_code,
|
| 446 |
+
}
|
| 447 |
+
except Exception as e:
|
| 448 |
+
logger.warning(f"AI Router health check failed: {e}")
|
| 449 |
+
return {
|
| 450 |
+
"status": "unavailable",
|
| 451 |
+
"url": router_url,
|
| 452 |
+
"error": str(e)[:100],
|
| 453 |
+
"fallback": "Using cached responses + Gemini direct",
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
@app.get("/health/db", tags=["Health"])
|
| 458 |
+
async def db_health():
|
| 459 |
+
"""Database connectivity check (placeholder)."""
|
| 460 |
+
return {
|
| 461 |
+
"status": "not_connected",
|
| 462 |
+
"message": "DB connection pool not yet initialized. Set DATABASE_URL and restart.",
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
# ─── API Routers ─────────────────────────────────────────────────────────────
|
| 467 |
+
|
| 468 |
+
from app.api.auth import router as auth_router
|
| 469 |
+
from app.api.career import router as career_router
|
| 470 |
+
from app.api.search import router as search_router
|
| 471 |
+
from app.api.chat import router as chat_router
|
| 472 |
+
from app.api.employer import router as employer_router
|
| 473 |
+
from app.api.talent import router as talent_router
|
| 474 |
+
from app.api.job import router as job_router
|
| 475 |
+
from app.api.interview import router as interview_router
|
| 476 |
+
from app.api.academy import router as academy_router
|
| 477 |
+
from app.api.agents import router as agents_router
|
| 478 |
+
from app.api.admin import router as admin_router
|
| 479 |
+
from app.api.telegram import router as telegram_router
|
| 480 |
+
from app.api.whatsapp import router as whatsapp_router
|
| 481 |
+
from app.api.legacy_compat import router as legacy_compat_router
|
| 482 |
+
from app.api.debug_admin import router as debug_admin_router
|
| 483 |
+
from app.middleware.ab_assign import ABAssignMiddleware
|
| 484 |
+
|
| 485 |
+
app.add_middleware(ABAssignMiddleware)
|
| 486 |
+
|
| 487 |
+
app.include_router(auth_router)
|
| 488 |
+
app.include_router(career_router)
|
| 489 |
+
app.include_router(search_router)
|
| 490 |
+
app.include_router(chat_router)
|
| 491 |
+
app.include_router(employer_router)
|
| 492 |
+
app.include_router(talent_router)
|
| 493 |
+
app.include_router(job_router)
|
| 494 |
+
app.include_router(interview_router)
|
| 495 |
+
app.include_router(academy_router)
|
| 496 |
+
app.include_router(agents_router)
|
| 497 |
+
app.include_router(admin_router)
|
| 498 |
+
app.include_router(telegram_router)
|
| 499 |
+
app.include_router(whatsapp_router)
|
| 500 |
+
app.include_router(legacy_compat_router)
|
| 501 |
+
app.include_router(debug_admin_router)
|
| 502 |
+
# app.include_router(employer_router, prefix="/v1/employer", tags=["Employer"])
|
| 503 |
+
# app.include_router(jobs_router, prefix="/v1/jobs", tags=["Jobs"])
|
| 504 |
+
# app.include_router(chat_router, prefix="/v1/chat", tags=["Chat"])
|
| 505 |
+
# app.include_router(payments_router, prefix="/v1/payments", tags=["Payments"])
|
| 506 |
+
# app.include_router(agents_router, prefix="/v1/agent", tags=["Agents"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/middleware/ab_assign.py
CHANGED
|
@@ -1,30 +1,30 @@
|
|
| 1 |
-
import random
|
| 2 |
-
from starlette.middleware.base import BaseHTTPMiddleware
|
| 3 |
-
from starlette.requests import Request
|
| 4 |
-
from starlette.responses import Response
|
| 5 |
-
from typing import Callable
|
| 6 |
-
|
| 7 |
-
class ABAssignMiddleware(BaseHTTPMiddleware):
|
| 8 |
-
"""Assigns users to AB variants (50/50) and attaches headers for downstream handlers.
|
| 9 |
-
|
| 10 |
-
Picks variant by cookie 'ab_variant_{experiment_id}' if present, otherwise assigns and sets cookie.
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
| 14 |
-
# Expect header X-Experiment-Id for lightweight assignment in this simple middleware
|
| 15 |
-
experiment_id = request.headers.get('X-Experiment-Id')
|
| 16 |
-
if not experiment_id:
|
| 17 |
-
return await call_next(request)
|
| 18 |
-
|
| 19 |
-
cookie_name = f"ab_variant_{experiment_id}"
|
| 20 |
-
variant = request.cookies.get(cookie_name)
|
| 21 |
-
if variant not in ('A', 'B'):
|
| 22 |
-
# Random 50/50 assignment
|
| 23 |
-
variant = 'A' if random.random() < 0.5 else 'B'
|
| 24 |
-
|
| 25 |
-
# Attach to headers for downstream, set cookie in response
|
| 26 |
-
request.state.ab_variant = variant
|
| 27 |
-
response = await call_next(request)
|
| 28 |
-
# Set a cookie for one week
|
| 29 |
-
response.set_cookie(cookie_name, variant, max_age=7*24*3600, httponly=True)
|
| 30 |
-
return response
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 3 |
+
from starlette.requests import Request
|
| 4 |
+
from starlette.responses import Response
|
| 5 |
+
from typing import Callable
|
| 6 |
+
|
| 7 |
+
class ABAssignMiddleware(BaseHTTPMiddleware):
|
| 8 |
+
"""Assigns users to AB variants (50/50) and attaches headers for downstream handlers.
|
| 9 |
+
|
| 10 |
+
Picks variant by cookie 'ab_variant_{experiment_id}' if present, otherwise assigns and sets cookie.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
| 14 |
+
# Expect header X-Experiment-Id for lightweight assignment in this simple middleware
|
| 15 |
+
experiment_id = request.headers.get('X-Experiment-Id')
|
| 16 |
+
if not experiment_id:
|
| 17 |
+
return await call_next(request)
|
| 18 |
+
|
| 19 |
+
cookie_name = f"ab_variant_{experiment_id}"
|
| 20 |
+
variant = request.cookies.get(cookie_name)
|
| 21 |
+
if variant not in ('A', 'B'):
|
| 22 |
+
# Random 50/50 assignment
|
| 23 |
+
variant = 'A' if random.random() < 0.5 else 'B'
|
| 24 |
+
|
| 25 |
+
# Attach to headers for downstream, set cookie in response
|
| 26 |
+
request.state.ab_variant = variant
|
| 27 |
+
response = await call_next(request)
|
| 28 |
+
# Set a cookie for one week
|
| 29 |
+
response.set_cookie(cookie_name, variant, max_age=7*24*3600, httponly=True)
|
| 30 |
+
return response
|
app/middleware/auth.py
CHANGED
|
@@ -1,155 +1,155 @@
|
|
| 1 |
-
"""JWT Authentication Middleware for FastAPI.
|
| 2 |
-
|
| 3 |
-
Uses standardized error format from app.utils.errors.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import time
|
| 7 |
-
from typing import Any, Callable, Dict, Optional
|
| 8 |
-
import os
|
| 9 |
-
|
| 10 |
-
from fastapi import HTTPException, Request, status
|
| 11 |
-
from fastapi.responses import JSONResponse
|
| 12 |
-
from starlette.middleware.base import BaseHTTPMiddleware
|
| 13 |
-
|
| 14 |
-
from app.utils.errors import error_response, ErrorCode
|
| 15 |
-
from app.utils.security import decode_access_token, rate_limiter
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
# Public endpoints — no auth required
|
| 19 |
-
PUBLIC_PATHS = {
|
| 20 |
-
"/health",
|
| 21 |
-
"/health/db",
|
| 22 |
-
"/docs",
|
| 23 |
-
"/redoc",
|
| 24 |
-
"/openapi.json",
|
| 25 |
-
"/v1/auth/login",
|
| 26 |
-
"/v1/auth/register",
|
| 27 |
-
"/v1/auth/google",
|
| 28 |
-
"/v1/auth/refresh",
|
| 29 |
-
"/v1/jobs",
|
| 30 |
-
"/v1/search/talent",
|
| 31 |
-
"/v1/employer/tiers",
|
| 32 |
-
"/v1/webhook/telegram",
|
| 33 |
-
"/v1/whatsapp/webhook",
|
| 34 |
-
"/v1/legacy-gas-compat",
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
# Role-based path access — expanded to cover all API groups
|
| 38 |
-
ROLE_PATHS: Dict[str, set] = {
|
| 39 |
-
"talent": {
|
| 40 |
-
"/v1/talent/",
|
| 41 |
-
"/v1/academy/",
|
| 42 |
-
"/v1/chat/talent/",
|
| 43 |
-
"/v1/chat/reply",
|
| 44 |
-
},
|
| 45 |
-
"employer": {
|
| 46 |
-
"/v1/employer",
|
| 47 |
-
"/v1/search",
|
| 48 |
-
"/v1/chat",
|
| 49 |
-
"/v1/interviews",
|
| 50 |
-
"/v1/jobs",
|
| 51 |
-
},
|
| 52 |
-
"admin": set(), # all access
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
def _get_client_ip(request: Request) -> str:
|
| 57 |
-
forwarded = request.headers.get("X-Forwarded-For", "")
|
| 58 |
-
if forwarded:
|
| 59 |
-
return forwarded.split(",")[0].strip()
|
| 60 |
-
return request.client.host if request.client else "unknown"
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def _needs_auth(path: str) -> bool:
|
| 64 |
-
# Public paths (exact match)
|
| 65 |
-
if path in PUBLIC_PATHS:
|
| 66 |
-
return False
|
| 67 |
-
# Public individual auth sub-paths
|
| 68 |
-
if path in ("/v1/auth/register", "/v1/auth/register/employer", "/v1/auth/login",
|
| 69 |
-
"/v1/auth/google", "/v1/auth/refresh", "/v1/auth/logout",
|
| 70 |
-
"/v1/auth/admin/login"):
|
| 71 |
-
return False
|
| 72 |
-
|
| 73 |
-
return path.startswith("/v1/")
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
class AuthMiddleware(BaseHTTPMiddleware):
|
| 77 |
-
"""JWT validation + RBAC + in-memory rate limiting.
|
| 78 |
-
|
| 79 |
-
Rate limits: free=100/hr, talent=500/hr, employer=1000/hr, admin=2000/hr.
|
| 80 |
-
All error responses use standardized format: {"success": false, "error": "...", "code": "..."}
|
| 81 |
-
"""
|
| 82 |
-
|
| 83 |
-
# Per-role rate limits (immutable — no shared state mutation)
|
| 84 |
-
_ROLE_LIMITS = {"talent": 500, "employer": 1000, "admin": 2000}
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
# ─── Rate limiting ────────────────────────────────────────────
|
| 91 |
-
if not path.startswith("/health"):
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
"X-RateLimit-
|
| 113 |
-
"
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
if payload is None:
|
| 127 |
-
return JSONResponse(
|
| 128 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 129 |
-
content=error_response(
|
| 130 |
-
"Invalid or expired token. Please login again.",
|
| 131 |
-
code=ErrorCode.TOKEN_INVALID,
|
| 132 |
-
),
|
| 133 |
-
headers={"WWW-Authenticate": "Bearer"},
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
# ─── RBAC ─────────────────────────────────────────────────
|
| 137 |
-
role = payload.get("role", "talent")
|
| 138 |
-
if role != "admin":
|
| 139 |
-
allowed = ROLE_PATHS.get(role, set())
|
| 140 |
-
has_access = any(path.startswith(p) for p in allowed | {"/v1/auth/", "/v1/talent/profile"})
|
| 141 |
-
if not has_access:
|
| 142 |
-
return JSONResponse(
|
| 143 |
-
status_code=status.HTTP_403_FORBIDDEN,
|
| 144 |
-
content=error_response(
|
| 145 |
-
f"Access denied. Role '{role}' cannot access this resource.",
|
| 146 |
-
code=ErrorCode.NOT_AUTHORIZED,
|
| 147 |
-
),
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
request.state.user = payload
|
| 151 |
-
request.state.user_email = payload.get("email", "")
|
| 152 |
-
request.state.user_role = payload.get("role", "talent")
|
| 153 |
-
|
| 154 |
-
response = await call_next(request)
|
| 155 |
-
return response
|
|
|
|
| 1 |
+
"""JWT Authentication Middleware for FastAPI.
|
| 2 |
+
|
| 3 |
+
Uses standardized error format from app.utils.errors.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import time
|
| 7 |
+
from typing import Any, Callable, Dict, Optional
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
from fastapi import HTTPException, Request, status
|
| 11 |
+
from fastapi.responses import JSONResponse
|
| 12 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 13 |
+
|
| 14 |
+
from app.utils.errors import error_response, ErrorCode
|
| 15 |
+
from app.utils.security import decode_access_token, rate_limiter, verify_supabase_token
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Public endpoints — no auth required
|
| 19 |
+
PUBLIC_PATHS = {
|
| 20 |
+
"/health",
|
| 21 |
+
"/health/db",
|
| 22 |
+
"/docs",
|
| 23 |
+
"/redoc",
|
| 24 |
+
"/openapi.json",
|
| 25 |
+
"/v1/auth/login",
|
| 26 |
+
"/v1/auth/register",
|
| 27 |
+
"/v1/auth/google",
|
| 28 |
+
"/v1/auth/refresh",
|
| 29 |
+
"/v1/jobs",
|
| 30 |
+
"/v1/search/talent",
|
| 31 |
+
"/v1/employer/tiers",
|
| 32 |
+
"/v1/webhook/telegram",
|
| 33 |
+
"/v1/whatsapp/webhook",
|
| 34 |
+
"/v1/legacy-gas-compat",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
# Role-based path access — expanded to cover all API groups
|
| 38 |
+
ROLE_PATHS: Dict[str, set] = {
|
| 39 |
+
"talent": {
|
| 40 |
+
"/v1/talent/",
|
| 41 |
+
"/v1/academy/",
|
| 42 |
+
"/v1/chat/talent/",
|
| 43 |
+
"/v1/chat/reply",
|
| 44 |
+
},
|
| 45 |
+
"employer": {
|
| 46 |
+
"/v1/employer",
|
| 47 |
+
"/v1/search",
|
| 48 |
+
"/v1/chat",
|
| 49 |
+
"/v1/interviews",
|
| 50 |
+
"/v1/jobs",
|
| 51 |
+
},
|
| 52 |
+
"admin": set(), # all access
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _get_client_ip(request: Request) -> str:
|
| 57 |
+
forwarded = request.headers.get("X-Forwarded-For", "")
|
| 58 |
+
if forwarded:
|
| 59 |
+
return forwarded.split(",")[0].strip()
|
| 60 |
+
return request.client.host if request.client else "unknown"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _needs_auth(path: str) -> bool:
|
| 64 |
+
# Public paths (exact match)
|
| 65 |
+
if path in PUBLIC_PATHS:
|
| 66 |
+
return False
|
| 67 |
+
# Public individual auth sub-paths
|
| 68 |
+
if path in ("/v1/auth/register", "/v1/auth/register/employer", "/v1/auth/login",
|
| 69 |
+
"/v1/auth/google", "/v1/auth/refresh", "/v1/auth/logout",
|
| 70 |
+
"/v1/auth/admin/login"):
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
+
return path.startswith("/v1/")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class AuthMiddleware(BaseHTTPMiddleware):
|
| 77 |
+
"""JWT validation + RBAC + in-memory rate limiting.
|
| 78 |
+
|
| 79 |
+
Rate limits: free=100/hr, talent=500/hr, employer=1000/hr, admin=2000/hr.
|
| 80 |
+
All error responses use standardized format: {"success": false, "error": "...", "code": "..."}
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
# Per-role rate limits (immutable — no shared state mutation)
|
| 84 |
+
_ROLE_LIMITS = {"talent": 500, "employer": 1000, "admin": 2000}
|
| 85 |
+
async def dispatch(self, request: Request, call_next: Callable) -> Any:
|
| 86 |
+
client_ip = _get_client_ip(request)
|
| 87 |
+
path = request.url.path
|
| 88 |
+
auth = request.headers.get("Authorization", "")
|
| 89 |
+
|
| 90 |
+
# ─── Rate limiting ────────────────────────────────────────────
|
| 91 |
+
if not path.startswith("/health"):
|
| 92 |
+
role = "free"
|
| 93 |
+
if auth.startswith("Bearer "):
|
| 94 |
+
payload = decode_access_token(auth[7:])
|
| 95 |
+
if payload:
|
| 96 |
+
role = payload.get("role", "talent")
|
| 97 |
+
|
| 98 |
+
# Use per-role limit WITHOUT mutating the shared rate_limiter instance
|
| 99 |
+
effective_limit = self._ROLE_LIMITS.get(role, 100)
|
| 100 |
+
|
| 101 |
+
if not rate_limiter.is_allowed(client_ip, limit=effective_limit):
|
| 102 |
+
remaining = rate_limiter.get_remaining(client_ip, limit=effective_limit)
|
| 103 |
+
return JSONResponse(
|
| 104 |
+
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
| 105 |
+
content=error_response(
|
| 106 |
+
"Rate limit exceeded. Free tier: 100 req/hr. Create an account for higher limits.",
|
| 107 |
+
code=ErrorCode.RATE_LIMITED,
|
| 108 |
+
remaining=remaining,
|
| 109 |
+
),
|
| 110 |
+
headers={
|
| 111 |
+
"X-RateLimit-Limit": str(effective_limit),
|
| 112 |
+
"X-RateLimit-Remaining": str(remaining),
|
| 113 |
+
"Retry-After": "3600",
|
| 114 |
+
},
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# ─── JWT Validation ───────────────────────────────────────────
|
| 118 |
+
if _needs_auth(path):
|
| 119 |
+
payload = None
|
| 120 |
+
if auth.startswith("Bearer "):
|
| 121 |
+
token = auth[7:]
|
| 122 |
+
payload = decode_access_token(token)
|
| 123 |
+
if payload is None:
|
| 124 |
+
payload = await verify_supabase_token(token)
|
| 125 |
+
|
| 126 |
+
if payload is None:
|
| 127 |
+
return JSONResponse(
|
| 128 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 129 |
+
content=error_response(
|
| 130 |
+
"Invalid or expired token. Please login again.",
|
| 131 |
+
code=ErrorCode.TOKEN_INVALID,
|
| 132 |
+
),
|
| 133 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
# ─── RBAC ─────────────────────────────────────────────────
|
| 137 |
+
role = payload.get("role", "talent")
|
| 138 |
+
if role != "admin":
|
| 139 |
+
allowed = ROLE_PATHS.get(role, set())
|
| 140 |
+
has_access = any(path.startswith(p) for p in allowed | {"/v1/auth/", "/v1/talent/profile"})
|
| 141 |
+
if not has_access:
|
| 142 |
+
return JSONResponse(
|
| 143 |
+
status_code=status.HTTP_403_FORBIDDEN,
|
| 144 |
+
content=error_response(
|
| 145 |
+
f"Access denied. Role '{role}' cannot access this resource.",
|
| 146 |
+
code=ErrorCode.NOT_AUTHORIZED,
|
| 147 |
+
),
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
request.state.user = payload
|
| 151 |
+
request.state.user_email = payload.get("email", "")
|
| 152 |
+
request.state.user_role = payload.get("role", "talent")
|
| 153 |
+
|
| 154 |
+
response = await call_next(request)
|
| 155 |
+
return response
|
app/middleware/token_tracker.py
CHANGED
|
@@ -1,32 +1,32 @@
|
|
| 1 |
-
"""Token Tracker Middleware — Monitors AI quota consumption across all requests."""
|
| 2 |
-
|
| 3 |
-
import time
|
| 4 |
-
from typing import Callable
|
| 5 |
-
|
| 6 |
-
from fastapi import Request, Response
|
| 7 |
-
from loguru import logger
|
| 8 |
-
from starlette.middleware.base import BaseHTTPMiddleware
|
| 9 |
-
|
| 10 |
-
from app.database import AsyncSessionLocal
|
| 11 |
-
from app.models.system import APIMonitoring
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
class TokenTrackerMiddleware(BaseHTTPMiddleware):
|
| 15 |
-
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
| 16 |
-
start_time = time.time()
|
| 17 |
-
|
| 18 |
-
# Process the request
|
| 19 |
-
response = await call_next(request)
|
| 20 |
-
|
| 21 |
-
# Post-process: Check if this was an AI-related request
|
| 22 |
-
# In a real scenario, we could look for custom headers like 'X-AI-Tokens'
|
| 23 |
-
# injected by the services, or just monitor endpoint patterns.
|
| 24 |
-
|
| 25 |
-
# For Antigravity, the service itself handles DB logging.
|
| 26 |
-
# This middleware can serve as a secondary observer or for non-Antigravity AI calls.
|
| 27 |
-
|
| 28 |
-
duration = time.time() - start_time
|
| 29 |
-
if response.status_code >= 400:
|
| 30 |
-
logger.warning(f"[Monitor] Request {request.method} {request.url.path} failed ({response.status_code}) in {duration:.2f}s")
|
| 31 |
-
|
| 32 |
-
return response
|
|
|
|
| 1 |
+
"""Token Tracker Middleware — Monitors AI quota consumption across all requests."""
|
| 2 |
+
|
| 3 |
+
import time
|
| 4 |
+
from typing import Callable
|
| 5 |
+
|
| 6 |
+
from fastapi import Request, Response
|
| 7 |
+
from loguru import logger
|
| 8 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 9 |
+
|
| 10 |
+
from app.database import AsyncSessionLocal
|
| 11 |
+
from app.models.system import APIMonitoring
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TokenTrackerMiddleware(BaseHTTPMiddleware):
|
| 15 |
+
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
| 16 |
+
start_time = time.time()
|
| 17 |
+
|
| 18 |
+
# Process the request
|
| 19 |
+
response = await call_next(request)
|
| 20 |
+
|
| 21 |
+
# Post-process: Check if this was an AI-related request
|
| 22 |
+
# In a real scenario, we could look for custom headers like 'X-AI-Tokens'
|
| 23 |
+
# injected by the services, or just monitor endpoint patterns.
|
| 24 |
+
|
| 25 |
+
# For Antigravity, the service itself handles DB logging.
|
| 26 |
+
# This middleware can serve as a secondary observer or for non-Antigravity AI calls.
|
| 27 |
+
|
| 28 |
+
duration = time.time() - start_time
|
| 29 |
+
if response.status_code >= 400:
|
| 30 |
+
logger.warning(f"[Monitor] Request {request.method} {request.url.path} failed ({response.status_code}) in {duration:.2f}s")
|
| 31 |
+
|
| 32 |
+
return response
|
app/models/ab.py
CHANGED
|
@@ -1,29 +1,29 @@
|
|
| 1 |
-
import uuid
|
| 2 |
-
from datetime import datetime
|
| 3 |
-
from sqlalchemy import Column, String, DateTime, JSON, Boolean
|
| 4 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 5 |
-
from app.models.base import Base, JSONB
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
class ABExperiment(Base):
|
| 9 |
-
__tablename__ = 'ab_experiments'
|
| 10 |
-
|
| 11 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 12 |
-
name = Column(String(150), nullable=False)
|
| 13 |
-
variant_a = Column(JSONB, nullable=True)
|
| 14 |
-
variant_b = Column(JSONB, nullable=True)
|
| 15 |
-
start_ts = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 16 |
-
end_ts = Column(DateTime(timezone=True), nullable=True)
|
| 17 |
-
metric_name = Column(String(100), nullable=True)
|
| 18 |
-
status = Column(String(20), default='running')
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
class ABEvent(Base):
|
| 22 |
-
__tablename__ = 'ab_events'
|
| 23 |
-
|
| 24 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 25 |
-
experiment_id = Column(UUID(as_uuid=True), nullable=False)
|
| 26 |
-
variant = Column(String(10), nullable=False)
|
| 27 |
-
user_id = Column(String(100), nullable=True)
|
| 28 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 29 |
-
payload = Column(JSONB, nullable=True)
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from sqlalchemy import Column, String, DateTime, JSON, Boolean
|
| 4 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 5 |
+
from app.models.base import Base, JSONB
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ABExperiment(Base):
|
| 9 |
+
__tablename__ = 'ab_experiments'
|
| 10 |
+
|
| 11 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 12 |
+
name = Column(String(150), nullable=False)
|
| 13 |
+
variant_a = Column(JSONB, nullable=True)
|
| 14 |
+
variant_b = Column(JSONB, nullable=True)
|
| 15 |
+
start_ts = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 16 |
+
end_ts = Column(DateTime(timezone=True), nullable=True)
|
| 17 |
+
metric_name = Column(String(100), nullable=True)
|
| 18 |
+
status = Column(String(20), default='running')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ABEvent(Base):
|
| 22 |
+
__tablename__ = 'ab_events'
|
| 23 |
+
|
| 24 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 25 |
+
experiment_id = Column(UUID(as_uuid=True), nullable=False)
|
| 26 |
+
variant = Column(String(10), nullable=False)
|
| 27 |
+
user_id = Column(String(100), nullable=True)
|
| 28 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 29 |
+
payload = Column(JSONB, nullable=True)
|
app/models/career.py
CHANGED
|
@@ -1,134 +1,134 @@
|
|
| 1 |
-
"""Career history models — Profiles, Experiences, Credentials, and Organizations.
|
| 2 |
-
|
| 3 |
-
Implements the lifelong career record schema with encryption support.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import uuid
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
from typing import List, Optional
|
| 9 |
-
|
| 10 |
-
from sqlalchemy import Column, String, Text, Boolean, DateTime, Date, ForeignKey, CheckConstraint, UniqueConstraint
|
| 11 |
-
from sqlalchemy.dialects.postgresql import UUID, ARRAY
|
| 12 |
-
from sqlalchemy.orm import relationship
|
| 13 |
-
|
| 14 |
-
from app.models.base import Base
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
class Profile(Base):
|
| 18 |
-
"""Core identity profile for Talents, Recruiters, and Admins."""
|
| 19 |
-
__tablename__ = "profiles"
|
| 20 |
-
|
| 21 |
-
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 22 |
-
status = Column(String(20), nullable=False, server_default="active")
|
| 23 |
-
email = Column(String(255), unique=True, nullable=True)
|
| 24 |
-
full_name = Column(String(255), nullable=True)
|
| 25 |
-
industry = Column(String(100), nullable=True)
|
| 26 |
-
general_skills = Column(ARRAY(String(50)), nullable=True)
|
| 27 |
-
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
|
| 28 |
-
updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 29 |
-
|
| 30 |
-
# Relationships
|
| 31 |
-
experiences = relationship("Experience", back_populates="profile", cascade="all, delete-orphan")
|
| 32 |
-
credentials = relationship("Credential", back_populates="profile", cascade="all, delete-orphan")
|
| 33 |
-
memberships = relationship("OrganizationMember", back_populates="profile", cascade="all, delete-orphan")
|
| 34 |
-
key = relationship("ProfileKey", uselist=False, cascade="all, delete-orphan")
|
| 35 |
-
|
| 36 |
-
__table_args__ = (
|
| 37 |
-
CheckConstraint("status IN ('active', 'deleted')", name="check_profile_status"),
|
| 38 |
-
)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
class Organization(Base):
|
| 42 |
-
"""Employers, Universities, and Credential Issuing bodies."""
|
| 43 |
-
__tablename__ = "organizations"
|
| 44 |
-
|
| 45 |
-
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 46 |
-
name = Column(String(255), nullable=False)
|
| 47 |
-
website_url = Column(String(255), nullable=True)
|
| 48 |
-
verified = Column(Boolean, nullable=False, server_default="false")
|
| 49 |
-
public_key = Column(Text, nullable=True) # PEM format for signature verification
|
| 50 |
-
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
|
| 51 |
-
updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 52 |
-
|
| 53 |
-
# Relationships
|
| 54 |
-
members = relationship("OrganizationMember", back_populates="organization", cascade="all, delete-orphan")
|
| 55 |
-
experiences = relationship("Experience", back_populates="organization")
|
| 56 |
-
credentials = relationship("Credential", back_populates="organization")
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
class OrganizationMember(Base):
|
| 60 |
-
"""Maps profiles to organizations with specific roles (RBAC)."""
|
| 61 |
-
__tablename__ = "organization_members"
|
| 62 |
-
|
| 63 |
-
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 64 |
-
organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
|
| 65 |
-
profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
|
| 66 |
-
role = Column(String(20), nullable=False, server_default="member")
|
| 67 |
-
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()")
|
| 68 |
-
|
| 69 |
-
# Relationships
|
| 70 |
-
organization = relationship("Organization", back_populates="members")
|
| 71 |
-
profile = relationship("Profile", back_populates="memberships")
|
| 72 |
-
|
| 73 |
-
__table_args__ = (
|
| 74 |
-
UniqueConstraint("organization_id", "profile_id", name="uq_org_member"),
|
| 75 |
-
CheckConstraint("role IN ('owner', 'admin', 'member')", name="check_member_role"),
|
| 76 |
-
)
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
class Experience(Base):
|
| 80 |
-
"""Employment and gig history records with encrypted details."""
|
| 81 |
-
__tablename__ = "experiences"
|
| 82 |
-
|
| 83 |
-
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 84 |
-
profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
|
| 85 |
-
organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
|
| 86 |
-
start_date = Column(Date, nullable=False)
|
| 87 |
-
end_date = Column(Date, nullable=True)
|
| 88 |
-
job_title = Column(String(150), nullable=True, index=True)
|
| 89 |
-
encrypted_payload = Column(Text, nullable=False) # AES-256 encrypted JSON
|
| 90 |
-
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
|
| 91 |
-
updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 92 |
-
|
| 93 |
-
# Relationships
|
| 94 |
-
profile = relationship("Profile", back_populates="experiences")
|
| 95 |
-
organization = relationship("Organization", back_populates="experiences")
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
class Credential(Base):
|
| 99 |
-
"""Degrees, Certifications, and Licenses with cryptographic signatures."""
|
| 100 |
-
__tablename__ = "credentials"
|
| 101 |
-
|
| 102 |
-
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 103 |
-
profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
|
| 104 |
-
organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
|
| 105 |
-
issue_date = Column(Date, nullable=False)
|
| 106 |
-
expiry_date = Column(Date, nullable=True)
|
| 107 |
-
credential_name = Column(String(150), nullable=True, index=True)
|
| 108 |
-
encrypted_payload = Column(Text, nullable=False) # AES-256 encrypted JSON
|
| 109 |
-
issuer_signature = Column(Text, nullable=False) # Digital signature from issuer
|
| 110 |
-
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
|
| 111 |
-
updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 112 |
-
|
| 113 |
-
# Relationships
|
| 114 |
-
profile = relationship("Profile", back_populates="credentials")
|
| 115 |
-
organization = relationship("Organization", back_populates="credentials")
|
| 116 |
-
shares = relationship("CredentialShare", back_populates="credential", cascade="all, delete-orphan")
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
class CredentialShare(Base):
|
| 120 |
-
"""Temporary access grants for recruiters to view private credential details."""
|
| 121 |
-
__tablename__ = "credential_shares"
|
| 122 |
-
|
| 123 |
-
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 124 |
-
credential_id = Column(UUID(as_uuid=True), ForeignKey("credentials.id", ondelete="CASCADE"), nullable=False)
|
| 125 |
-
shared_with_profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
|
| 126 |
-
expires_at = Column(DateTime(timezone=True), nullable=True)
|
| 127 |
-
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()")
|
| 128 |
-
|
| 129 |
-
# Relationships
|
| 130 |
-
credential = relationship("Credential", back_populates="shares")
|
| 131 |
-
|
| 132 |
-
__table_args__ = (
|
| 133 |
-
UniqueConstraint("credential_id", "shared_with_profile_id", name="uq_credential_share"),
|
| 134 |
-
)
|
|
|
|
| 1 |
+
"""Career history models — Profiles, Experiences, Credentials, and Organizations.
|
| 2 |
+
|
| 3 |
+
Implements the lifelong career record schema with encryption support.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import uuid
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from typing import List, Optional
|
| 9 |
+
|
| 10 |
+
from sqlalchemy import Column, String, Text, Boolean, DateTime, Date, ForeignKey, CheckConstraint, UniqueConstraint
|
| 11 |
+
from sqlalchemy.dialects.postgresql import UUID, ARRAY
|
| 12 |
+
from sqlalchemy.orm import relationship
|
| 13 |
+
|
| 14 |
+
from app.models.base import Base
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Profile(Base):
|
| 18 |
+
"""Core identity profile for Talents, Recruiters, and Admins."""
|
| 19 |
+
__tablename__ = "profiles"
|
| 20 |
+
|
| 21 |
+
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 22 |
+
status = Column(String(20), nullable=False, server_default="active")
|
| 23 |
+
email = Column(String(255), unique=True, nullable=True)
|
| 24 |
+
full_name = Column(String(255), nullable=True)
|
| 25 |
+
industry = Column(String(100), nullable=True)
|
| 26 |
+
general_skills = Column(ARRAY(String(50)), nullable=True)
|
| 27 |
+
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
|
| 28 |
+
updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 29 |
+
|
| 30 |
+
# Relationships
|
| 31 |
+
experiences = relationship("Experience", back_populates="profile", cascade="all, delete-orphan")
|
| 32 |
+
credentials = relationship("Credential", back_populates="profile", cascade="all, delete-orphan")
|
| 33 |
+
memberships = relationship("OrganizationMember", back_populates="profile", cascade="all, delete-orphan")
|
| 34 |
+
key = relationship("ProfileKey", uselist=False, cascade="all, delete-orphan")
|
| 35 |
+
|
| 36 |
+
__table_args__ = (
|
| 37 |
+
CheckConstraint("status IN ('active', 'deleted')", name="check_profile_status"),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Organization(Base):
|
| 42 |
+
"""Employers, Universities, and Credential Issuing bodies."""
|
| 43 |
+
__tablename__ = "organizations"
|
| 44 |
+
|
| 45 |
+
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 46 |
+
name = Column(String(255), nullable=False)
|
| 47 |
+
website_url = Column(String(255), nullable=True)
|
| 48 |
+
verified = Column(Boolean, nullable=False, server_default="false")
|
| 49 |
+
public_key = Column(Text, nullable=True) # PEM format for signature verification
|
| 50 |
+
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
|
| 51 |
+
updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 52 |
+
|
| 53 |
+
# Relationships
|
| 54 |
+
members = relationship("OrganizationMember", back_populates="organization", cascade="all, delete-orphan")
|
| 55 |
+
experiences = relationship("Experience", back_populates="organization")
|
| 56 |
+
credentials = relationship("Credential", back_populates="organization")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class OrganizationMember(Base):
|
| 60 |
+
"""Maps profiles to organizations with specific roles (RBAC)."""
|
| 61 |
+
__tablename__ = "organization_members"
|
| 62 |
+
|
| 63 |
+
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 64 |
+
organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
|
| 65 |
+
profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
|
| 66 |
+
role = Column(String(20), nullable=False, server_default="member")
|
| 67 |
+
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()")
|
| 68 |
+
|
| 69 |
+
# Relationships
|
| 70 |
+
organization = relationship("Organization", back_populates="members")
|
| 71 |
+
profile = relationship("Profile", back_populates="memberships")
|
| 72 |
+
|
| 73 |
+
__table_args__ = (
|
| 74 |
+
UniqueConstraint("organization_id", "profile_id", name="uq_org_member"),
|
| 75 |
+
CheckConstraint("role IN ('owner', 'admin', 'member')", name="check_member_role"),
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class Experience(Base):
|
| 80 |
+
"""Employment and gig history records with encrypted details."""
|
| 81 |
+
__tablename__ = "experiences"
|
| 82 |
+
|
| 83 |
+
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 84 |
+
profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
|
| 85 |
+
organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
|
| 86 |
+
start_date = Column(Date, nullable=False)
|
| 87 |
+
end_date = Column(Date, nullable=True)
|
| 88 |
+
job_title = Column(String(150), nullable=True, index=True)
|
| 89 |
+
encrypted_payload = Column(Text, nullable=False) # AES-256 encrypted JSON
|
| 90 |
+
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
|
| 91 |
+
updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 92 |
+
|
| 93 |
+
# Relationships
|
| 94 |
+
profile = relationship("Profile", back_populates="experiences")
|
| 95 |
+
organization = relationship("Organization", back_populates="experiences")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class Credential(Base):
|
| 99 |
+
"""Degrees, Certifications, and Licenses with cryptographic signatures."""
|
| 100 |
+
__tablename__ = "credentials"
|
| 101 |
+
|
| 102 |
+
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 103 |
+
profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
|
| 104 |
+
organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
|
| 105 |
+
issue_date = Column(Date, nullable=False)
|
| 106 |
+
expiry_date = Column(Date, nullable=True)
|
| 107 |
+
credential_name = Column(String(150), nullable=True, index=True)
|
| 108 |
+
encrypted_payload = Column(Text, nullable=False) # AES-256 encrypted JSON
|
| 109 |
+
issuer_signature = Column(Text, nullable=False) # Digital signature from issuer
|
| 110 |
+
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
|
| 111 |
+
updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 112 |
+
|
| 113 |
+
# Relationships
|
| 114 |
+
profile = relationship("Profile", back_populates="credentials")
|
| 115 |
+
organization = relationship("Organization", back_populates="credentials")
|
| 116 |
+
shares = relationship("CredentialShare", back_populates="credential", cascade="all, delete-orphan")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class CredentialShare(Base):
|
| 120 |
+
"""Temporary access grants for recruiters to view private credential details."""
|
| 121 |
+
__tablename__ = "credential_shares"
|
| 122 |
+
|
| 123 |
+
id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
|
| 124 |
+
credential_id = Column(UUID(as_uuid=True), ForeignKey("credentials.id", ondelete="CASCADE"), nullable=False)
|
| 125 |
+
shared_with_profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
|
| 126 |
+
expires_at = Column(DateTime(timezone=True), nullable=True)
|
| 127 |
+
created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()")
|
| 128 |
+
|
| 129 |
+
# Relationships
|
| 130 |
+
credential = relationship("Credential", back_populates="shares")
|
| 131 |
+
|
| 132 |
+
__table_args__ = (
|
| 133 |
+
UniqueConstraint("credential_id", "shared_with_profile_id", name="uq_credential_share"),
|
| 134 |
+
)
|
app/models/community.py
CHANGED
|
@@ -1,102 +1,102 @@
|
|
| 1 |
-
"""Community, Challenges, and Pathways models."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
-
|
| 10 |
-
from app.models.base import Base
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class CommunityPartner(Base):
|
| 14 |
-
__tablename__ = "community_partners"
|
| 15 |
-
|
| 16 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 17 |
-
name = Column(String(255), nullable=False)
|
| 18 |
-
contact_email = Column(String(255), unique=True, nullable=False)
|
| 19 |
-
logo_url = Column(String(500), nullable=True)
|
| 20 |
-
rev_share_briga = Column(Numeric(5, 2), default=50.00)
|
| 21 |
-
rev_share_community = Column(Numeric(5, 2), default=30.00)
|
| 22 |
-
rev_share_talent = Column(Numeric(5, 2), default=20.00)
|
| 23 |
-
status = Column(String(20), default="Proposed")
|
| 24 |
-
approved_by = Column(String(255), nullable=True)
|
| 25 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
class SponsoredChallenge(Base):
|
| 29 |
-
__tablename__ = "sponsored_challenges"
|
| 30 |
-
|
| 31 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 32 |
-
community_id = Column(UUID(as_uuid=True), ForeignKey("community_partners.id", ondelete="SET NULL"), nullable=True)
|
| 33 |
-
sponsor_name = Column(String(255), nullable=False)
|
| 34 |
-
title = Column(String(255), nullable=False)
|
| 35 |
-
description = Column(Text, nullable=False)
|
| 36 |
-
verification_rubric = Column(Text, nullable=False)
|
| 37 |
-
payout_amount = Column(Integer, default=0)
|
| 38 |
-
is_active = Column(Boolean, default=True)
|
| 39 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
class Pathway(Base):
|
| 43 |
-
__tablename__ = "pathways"
|
| 44 |
-
|
| 45 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 46 |
-
user_email = Column(String(255), unique=True, nullable=False, index=True)
|
| 47 |
-
pathway_json = Column(JSONB, nullable=False, default=dict)
|
| 48 |
-
progress_json = Column(JSONB, nullable=False, default=dict)
|
| 49 |
-
completed_stages = Column(JSONB, default=list)
|
| 50 |
-
green_score = Column(Integer, default=0)
|
| 51 |
-
community_id = Column(UUID(as_uuid=True), ForeignKey("community_partners.id", ondelete="SET NULL"), nullable=True)
|
| 52 |
-
challenge_id = Column(UUID(as_uuid=True), ForeignKey("sponsored_challenges.id", ondelete="SET NULL"), nullable=True)
|
| 53 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 54 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
class AIKnowledgeBase(Base):
|
| 58 |
-
__tablename__ = "ai_knowledge_base"
|
| 59 |
-
|
| 60 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 61 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 62 |
-
source_email = Column(String(255), nullable=True)
|
| 63 |
-
category = Column(String(100), nullable=True)
|
| 64 |
-
fact = Column(Text, nullable=True)
|
| 65 |
-
confidence = Column(Numeric(3, 2), nullable=True)
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
class AIPublicInsight(Base):
|
| 69 |
-
__tablename__ = "ai_public_insights"
|
| 70 |
-
|
| 71 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 72 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 73 |
-
source_email = Column(String(255), nullable=True)
|
| 74 |
-
positive_metric = Column(Text, nullable=True)
|
| 75 |
-
generated_insight = Column(Text, nullable=True)
|
| 76 |
-
approved_for_public = Column(Boolean, default=False)
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
class AIInternalReport(Base):
|
| 80 |
-
__tablename__ = "ai_internal_reports"
|
| 81 |
-
|
| 82 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 83 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 84 |
-
source_email = Column(String(255), nullable=True)
|
| 85 |
-
negative_feedback = Column(Text, nullable=True)
|
| 86 |
-
critical_issues = Column(Text, nullable=True)
|
| 87 |
-
action_required = Column(Text, nullable=True)
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
class AIInterviewMemory(Base):
|
| 91 |
-
__tablename__ = "ai_interview_memory"
|
| 92 |
-
|
| 93 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 94 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 95 |
-
email = Column(String(255), nullable=True)
|
| 96 |
-
sector = Column(String(100), nullable=True)
|
| 97 |
-
question = Column(Text, nullable=True)
|
| 98 |
-
answer = Column(Text, nullable=True)
|
| 99 |
-
swot_strengths = Column(Text, nullable=True)
|
| 100 |
-
swot_weaknesses = Column(Text, nullable=True)
|
| 101 |
-
score = Column(Integer, nullable=True)
|
| 102 |
-
obsidian_format = Column(Text, nullable=True)
|
|
|
|
| 1 |
+
"""Community, Challenges, and Pathways models."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
+
|
| 10 |
+
from app.models.base import Base
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CommunityPartner(Base):
|
| 14 |
+
__tablename__ = "community_partners"
|
| 15 |
+
|
| 16 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 17 |
+
name = Column(String(255), nullable=False)
|
| 18 |
+
contact_email = Column(String(255), unique=True, nullable=False)
|
| 19 |
+
logo_url = Column(String(500), nullable=True)
|
| 20 |
+
rev_share_briga = Column(Numeric(5, 2), default=50.00)
|
| 21 |
+
rev_share_community = Column(Numeric(5, 2), default=30.00)
|
| 22 |
+
rev_share_talent = Column(Numeric(5, 2), default=20.00)
|
| 23 |
+
status = Column(String(20), default="Proposed")
|
| 24 |
+
approved_by = Column(String(255), nullable=True)
|
| 25 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class SponsoredChallenge(Base):
|
| 29 |
+
__tablename__ = "sponsored_challenges"
|
| 30 |
+
|
| 31 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 32 |
+
community_id = Column(UUID(as_uuid=True), ForeignKey("community_partners.id", ondelete="SET NULL"), nullable=True)
|
| 33 |
+
sponsor_name = Column(String(255), nullable=False)
|
| 34 |
+
title = Column(String(255), nullable=False)
|
| 35 |
+
description = Column(Text, nullable=False)
|
| 36 |
+
verification_rubric = Column(Text, nullable=False)
|
| 37 |
+
payout_amount = Column(Integer, default=0)
|
| 38 |
+
is_active = Column(Boolean, default=True)
|
| 39 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Pathway(Base):
|
| 43 |
+
__tablename__ = "pathways"
|
| 44 |
+
|
| 45 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 46 |
+
user_email = Column(String(255), unique=True, nullable=False, index=True)
|
| 47 |
+
pathway_json = Column(JSONB, nullable=False, default=dict)
|
| 48 |
+
progress_json = Column(JSONB, nullable=False, default=dict)
|
| 49 |
+
completed_stages = Column(JSONB, default=list)
|
| 50 |
+
green_score = Column(Integer, default=0)
|
| 51 |
+
community_id = Column(UUID(as_uuid=True), ForeignKey("community_partners.id", ondelete="SET NULL"), nullable=True)
|
| 52 |
+
challenge_id = Column(UUID(as_uuid=True), ForeignKey("sponsored_challenges.id", ondelete="SET NULL"), nullable=True)
|
| 53 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 54 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class AIKnowledgeBase(Base):
|
| 58 |
+
__tablename__ = "ai_knowledge_base"
|
| 59 |
+
|
| 60 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 61 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 62 |
+
source_email = Column(String(255), nullable=True)
|
| 63 |
+
category = Column(String(100), nullable=True)
|
| 64 |
+
fact = Column(Text, nullable=True)
|
| 65 |
+
confidence = Column(Numeric(3, 2), nullable=True)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class AIPublicInsight(Base):
|
| 69 |
+
__tablename__ = "ai_public_insights"
|
| 70 |
+
|
| 71 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 72 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 73 |
+
source_email = Column(String(255), nullable=True)
|
| 74 |
+
positive_metric = Column(Text, nullable=True)
|
| 75 |
+
generated_insight = Column(Text, nullable=True)
|
| 76 |
+
approved_for_public = Column(Boolean, default=False)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class AIInternalReport(Base):
|
| 80 |
+
__tablename__ = "ai_internal_reports"
|
| 81 |
+
|
| 82 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 83 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 84 |
+
source_email = Column(String(255), nullable=True)
|
| 85 |
+
negative_feedback = Column(Text, nullable=True)
|
| 86 |
+
critical_issues = Column(Text, nullable=True)
|
| 87 |
+
action_required = Column(Text, nullable=True)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class AIInterviewMemory(Base):
|
| 91 |
+
__tablename__ = "ai_interview_memory"
|
| 92 |
+
|
| 93 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 94 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 95 |
+
email = Column(String(255), nullable=True)
|
| 96 |
+
sector = Column(String(100), nullable=True)
|
| 97 |
+
question = Column(Text, nullable=True)
|
| 98 |
+
answer = Column(Text, nullable=True)
|
| 99 |
+
swot_strengths = Column(Text, nullable=True)
|
| 100 |
+
swot_weaknesses = Column(Text, nullable=True)
|
| 101 |
+
score = Column(Integer, nullable=True)
|
| 102 |
+
obsidian_format = Column(Text, nullable=True)
|
app/models/content.py
CHANGED
|
@@ -1,87 +1,92 @@
|
|
| 1 |
-
"""Content & Knowledge models."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
-
from app.models.base import Base
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
class BlogPost(Base):
|
| 13 |
-
__tablename__ = "blog_posts"
|
| 14 |
-
|
| 15 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 16 |
-
article_id = Column(String(50), unique=True, nullable=False)
|
| 17 |
-
date_str = Column(String(50), nullable=True)
|
| 18 |
-
title = Column(Text, nullable=False)
|
| 19 |
-
category = Column(String(50), nullable=True, index=True)
|
| 20 |
-
summary = Column(Text, nullable=True)
|
| 21 |
-
content = Column(Text, nullable=True)
|
| 22 |
-
thumbnail_url = Column(String(500), nullable=True)
|
| 23 |
-
reading_time = Column(String(20), nullable=True)
|
| 24 |
-
published = Column(String(5), default="No")
|
| 25 |
-
published_at = Column(DateTime(timezone=True), nullable=True)
|
| 26 |
-
target_keyword = Column(String(255), nullable=True)
|
| 27 |
-
seo_score = Column(String(20), nullable=True)
|
| 28 |
-
ai_reviewed = Column(String(10), nullable=True)
|
| 29 |
-
reviewer_notes = Column(Text, nullable=True)
|
| 30 |
-
review_score = Column(String(10), nullable=True)
|
| 31 |
-
review_status = Column(String(50), nullable=True)
|
| 32 |
-
review_date = Column(DateTime(timezone=True), nullable=True)
|
| 33 |
-
reviewer_email = Column(String(255), nullable=True)
|
| 34 |
-
meta_description = Column(Text, nullable=True)
|
| 35 |
-
internal_links = Column(Text, nullable=True)
|
| 36 |
-
source_brief = Column(Text, nullable=True)
|
| 37 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
class ContentPipeline(Base):
|
| 41 |
-
__tablename__ = "content_pipeline"
|
| 42 |
-
|
| 43 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 44 |
-
pipeline_id = Column(String(50), unique=True, nullable=False)
|
| 45 |
-
topic = Column(Text, nullable=True)
|
| 46 |
-
target_keyword = Column(String(255), nullable=True)
|
| 47 |
-
source = Column(String(100), nullable=True)
|
| 48 |
-
priority_score = Column(Integer, default=0)
|
| 49 |
-
stage = Column(String(50), nullable=True)
|
| 50 |
-
linked_blog_id = Column(String(50), nullable=True)
|
| 51 |
-
status = Column(String(50), default="Draft")
|
| 52 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 53 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 54 |
-
error_message = Column(Text, nullable=True)
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
class KnowledgeBase(Base):
|
| 58 |
-
__tablename__ = "knowledge_base"
|
| 59 |
-
|
| 60 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 61 |
-
knowledge_rule = Column(Text, nullable=False)
|
| 62 |
-
sector = Column(String(100), nullable=True, index=True)
|
| 63 |
-
source = Column(String(255), nullable=True)
|
| 64 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
class KnowledgeQueue(Base):
|
| 68 |
-
__tablename__ = "knowledge_queue"
|
| 69 |
-
|
| 70 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 71 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 72 |
-
source_email = Column(String(255), nullable=True)
|
| 73 |
-
category = Column(String(100), nullable=True)
|
| 74 |
-
fact = Column(Text, nullable=True)
|
| 75 |
-
confidence = Column(Numeric(3, 2), nullable=True)
|
| 76 |
-
status = Column(String(50), default="Pending")
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Content & Knowledge models."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
+
from app.models.base import Base
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class BlogPost(Base):
|
| 13 |
+
__tablename__ = "blog_posts"
|
| 14 |
+
|
| 15 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 16 |
+
article_id = Column(String(50), unique=True, nullable=False)
|
| 17 |
+
date_str = Column(String(50), nullable=True)
|
| 18 |
+
title = Column(Text, nullable=False)
|
| 19 |
+
category = Column(String(50), nullable=True, index=True)
|
| 20 |
+
summary = Column(Text, nullable=True)
|
| 21 |
+
content = Column(Text, nullable=True)
|
| 22 |
+
thumbnail_url = Column(String(500), nullable=True)
|
| 23 |
+
reading_time = Column(String(20), nullable=True)
|
| 24 |
+
published = Column(String(5), default="No")
|
| 25 |
+
published_at = Column(DateTime(timezone=True), nullable=True)
|
| 26 |
+
target_keyword = Column(String(255), nullable=True)
|
| 27 |
+
seo_score = Column(String(20), nullable=True)
|
| 28 |
+
ai_reviewed = Column(String(10), nullable=True)
|
| 29 |
+
reviewer_notes = Column(Text, nullable=True)
|
| 30 |
+
review_score = Column(String(10), nullable=True)
|
| 31 |
+
review_status = Column(String(50), nullable=True)
|
| 32 |
+
review_date = Column(DateTime(timezone=True), nullable=True)
|
| 33 |
+
reviewer_email = Column(String(255), nullable=True)
|
| 34 |
+
meta_description = Column(Text, nullable=True)
|
| 35 |
+
internal_links = Column(Text, nullable=True)
|
| 36 |
+
source_brief = Column(Text, nullable=True)
|
| 37 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class ContentPipeline(Base):
|
| 41 |
+
__tablename__ = "content_pipeline"
|
| 42 |
+
|
| 43 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 44 |
+
pipeline_id = Column(String(50), unique=True, nullable=False)
|
| 45 |
+
topic = Column(Text, nullable=True)
|
| 46 |
+
target_keyword = Column(String(255), nullable=True)
|
| 47 |
+
source = Column(String(100), nullable=True)
|
| 48 |
+
priority_score = Column(Integer, default=0)
|
| 49 |
+
stage = Column(String(50), nullable=True)
|
| 50 |
+
linked_blog_id = Column(String(50), nullable=True)
|
| 51 |
+
status = Column(String(50), default="Draft")
|
| 52 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 53 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 54 |
+
error_message = Column(Text, nullable=True)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class KnowledgeBase(Base):
|
| 58 |
+
__tablename__ = "knowledge_base"
|
| 59 |
+
|
| 60 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 61 |
+
knowledge_rule = Column(Text, nullable=False)
|
| 62 |
+
sector = Column(String(100), nullable=True, index=True)
|
| 63 |
+
source = Column(String(255), nullable=True)
|
| 64 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class KnowledgeQueue(Base):
|
| 68 |
+
__tablename__ = "knowledge_queue"
|
| 69 |
+
|
| 70 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 71 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 72 |
+
source_email = Column(String(255), nullable=True)
|
| 73 |
+
category = Column(String(100), nullable=True)
|
| 74 |
+
fact = Column(Text, nullable=True)
|
| 75 |
+
confidence = Column(Numeric(3, 2), nullable=True)
|
| 76 |
+
status = Column(String(50), default="Pending")
|
| 77 |
+
# FIX (2026-09): heartbeat retry/dead-letter support. Columns are nullable so
|
| 78 |
+
# the migration is additive (no backfill needed); Supabase PostgREST accepts
|
| 79 |
+
# PATCHes that set them on rows where they were previously NULL.
|
| 80 |
+
retry_count = Column(Integer, default=0, nullable=True)
|
| 81 |
+
last_error = Column(Text, nullable=True)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class SEOStrategy(Base):
|
| 85 |
+
__tablename__ = "seo_strategy"
|
| 86 |
+
|
| 87 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 88 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 89 |
+
keyword = Column(String(255), nullable=True)
|
| 90 |
+
target_page = Column(String(255), nullable=True)
|
| 91 |
+
strategy = Column(Text, nullable=True)
|
| 92 |
+
status = Column(String(50), default="Planned")
|
app/models/employer.py
CHANGED
|
@@ -1,64 +1,64 @@
|
|
| 1 |
-
"""Employer (B2B) models — Companies, Clients, Pending Employers."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Numeric
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID, ENUM
|
| 9 |
-
from app.models.base import Base
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
class Company(Base):
|
| 13 |
-
__tablename__ = "companies"
|
| 14 |
-
|
| 15 |
-
id = Column(String(50), primary_key=True)
|
| 16 |
-
name = Column(String(255), nullable=False)
|
| 17 |
-
website = Column(String(255), nullable=True)
|
| 18 |
-
branding = Column(String(255), nullable=True)
|
| 19 |
-
bidang_usaha = Column(String(255), nullable=True)
|
| 20 |
-
produk_jasa = Column(String(255), nullable=True)
|
| 21 |
-
industri_ai = Column(String(255), nullable=True)
|
| 22 |
-
credit_balance = Column(Integer, default=0)
|
| 23 |
-
csr_budget = Column(Numeric(15, 2), default=0.00)
|
| 24 |
-
tier = Column(String(20), default="free")
|
| 25 |
-
billing = Column(String(20), default="monthly")
|
| 26 |
-
seats_limit = Column(Integer, default=2)
|
| 27 |
-
max_jobs = Column(Integer, default=1)
|
| 28 |
-
status = Column(String(20), default="PENDING", index=True)
|
| 29 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
class ClientAccount(Base):
|
| 33 |
-
__tablename__ = "client_accounts"
|
| 34 |
-
|
| 35 |
-
id = Column(String(50), primary_key=True)
|
| 36 |
-
company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
|
| 37 |
-
email = Column(String(255), unique=True, nullable=False, index=True)
|
| 38 |
-
password_hash = Column(String(255), nullable=False)
|
| 39 |
-
name = Column(String(255), nullable=False)
|
| 40 |
-
whatsapp = Column(String(50), nullable=True)
|
| 41 |
-
jabatan = Column(String(100), nullable=True)
|
| 42 |
-
role = Column(ENUM("Recruiter", "Sustainability", name="staff_role", create_type=False), default="Recruiter")
|
| 43 |
-
status = Column(String(20), default="PENDING")
|
| 44 |
-
auth_key = Column(String(255), default="-")
|
| 45 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
class PendingEmployer(Base):
|
| 49 |
-
__tablename__ = "pending_employers"
|
| 50 |
-
|
| 51 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 52 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 53 |
-
entity_name = Column(String(255), nullable=True)
|
| 54 |
-
branding = Column(String(255), nullable=True)
|
| 55 |
-
website = Column(String(255), nullable=True)
|
| 56 |
-
pic_name = Column(String(255), nullable=True)
|
| 57 |
-
pic_jabatan = Column(String(100), nullable=True)
|
| 58 |
-
email = Column(String(255), unique=True, nullable=False)
|
| 59 |
-
whatsapp = Column(String(50), nullable=True)
|
| 60 |
-
password_hash = Column(String(255), nullable=True)
|
| 61 |
-
status = Column(String(20), default="PENDING", index=True)
|
| 62 |
-
bidang_usaha = Column(String(255), nullable=True)
|
| 63 |
-
produk_jasa = Column(String(255), nullable=True)
|
| 64 |
-
industri_ai = Column(String(255), nullable=True)
|
|
|
|
| 1 |
+
"""Employer (B2B) models — Companies, Clients, Pending Employers."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Numeric
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID, ENUM
|
| 9 |
+
from app.models.base import Base
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Company(Base):
|
| 13 |
+
__tablename__ = "companies"
|
| 14 |
+
|
| 15 |
+
id = Column(String(50), primary_key=True)
|
| 16 |
+
name = Column(String(255), nullable=False)
|
| 17 |
+
website = Column(String(255), nullable=True)
|
| 18 |
+
branding = Column(String(255), nullable=True)
|
| 19 |
+
bidang_usaha = Column(String(255), nullable=True)
|
| 20 |
+
produk_jasa = Column(String(255), nullable=True)
|
| 21 |
+
industri_ai = Column(String(255), nullable=True)
|
| 22 |
+
credit_balance = Column(Integer, default=0)
|
| 23 |
+
csr_budget = Column(Numeric(15, 2), default=0.00)
|
| 24 |
+
tier = Column(String(20), default="free")
|
| 25 |
+
billing = Column(String(20), default="monthly")
|
| 26 |
+
seats_limit = Column(Integer, default=2)
|
| 27 |
+
max_jobs = Column(Integer, default=1)
|
| 28 |
+
status = Column(String(20), default="PENDING", index=True)
|
| 29 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ClientAccount(Base):
|
| 33 |
+
__tablename__ = "client_accounts"
|
| 34 |
+
|
| 35 |
+
id = Column(String(50), primary_key=True)
|
| 36 |
+
company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
|
| 37 |
+
email = Column(String(255), unique=True, nullable=False, index=True)
|
| 38 |
+
password_hash = Column(String(255), nullable=False)
|
| 39 |
+
name = Column(String(255), nullable=False)
|
| 40 |
+
whatsapp = Column(String(50), nullable=True)
|
| 41 |
+
jabatan = Column(String(100), nullable=True)
|
| 42 |
+
role = Column(ENUM("Recruiter", "Sustainability", name="staff_role", create_type=False), default="Recruiter")
|
| 43 |
+
status = Column(String(20), default="PENDING")
|
| 44 |
+
auth_key = Column(String(255), default="-")
|
| 45 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class PendingEmployer(Base):
|
| 49 |
+
__tablename__ = "pending_employers"
|
| 50 |
+
|
| 51 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 52 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 53 |
+
entity_name = Column(String(255), nullable=True)
|
| 54 |
+
branding = Column(String(255), nullable=True)
|
| 55 |
+
website = Column(String(255), nullable=True)
|
| 56 |
+
pic_name = Column(String(255), nullable=True)
|
| 57 |
+
pic_jabatan = Column(String(100), nullable=True)
|
| 58 |
+
email = Column(String(255), unique=True, nullable=False)
|
| 59 |
+
whatsapp = Column(String(50), nullable=True)
|
| 60 |
+
password_hash = Column(String(255), nullable=True)
|
| 61 |
+
status = Column(String(20), default="PENDING", index=True)
|
| 62 |
+
bidang_usaha = Column(String(255), nullable=True)
|
| 63 |
+
produk_jasa = Column(String(255), nullable=True)
|
| 64 |
+
industri_ai = Column(String(255), nullable=True)
|
app/models/finance.py
CHANGED
|
@@ -1,47 +1,47 @@
|
|
| 1 |
-
"""Financial models — Transactions, Unlocks, Interviews."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
-
from app.models.base import Base
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
class Transaction(Base):
|
| 13 |
-
__tablename__ = "transactions"
|
| 14 |
-
|
| 15 |
-
id = Column(String(50), primary_key=True)
|
| 16 |
-
client_id = Column(String(50), ForeignKey("client_accounts.id", ondelete="SET NULL"), nullable=True, index=True)
|
| 17 |
-
amount = Column(Numeric(15, 2), nullable=False)
|
| 18 |
-
type = Column(String(50), nullable=False)
|
| 19 |
-
status = Column(String(20), default="Pending", index=True)
|
| 20 |
-
snap_token = Column(String(500), nullable=True)
|
| 21 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
class ProfileUnlock(Base):
|
| 25 |
-
__tablename__ = "profile_unlocks"
|
| 26 |
-
|
| 27 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 28 |
-
company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
|
| 29 |
-
candidate_id = Column(String(50), nullable=False, index=True)
|
| 30 |
-
is_masked_only = Column(Boolean, default=True)
|
| 31 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
class Interview(Base):
|
| 35 |
-
__tablename__ = "interviews"
|
| 36 |
-
|
| 37 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 38 |
-
company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
|
| 39 |
-
client_id = Column(String(50), ForeignKey("client_accounts.id", ondelete="SET NULL"), nullable=True)
|
| 40 |
-
candidate_id = Column(String(50), nullable=False, index=True)
|
| 41 |
-
scheduled_time = Column(DateTime(timezone=True), nullable=False)
|
| 42 |
-
status = Column(String(20), default="Scheduled")
|
| 43 |
-
transcript_text = Column(Text, nullable=True)
|
| 44 |
-
ai_summary = Column(Text, nullable=True)
|
| 45 |
-
ai_competency_score = Column(Integer, default=0)
|
| 46 |
-
ai_performance_analysis = Column(Text, nullable=True)
|
| 47 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
|
|
|
| 1 |
+
"""Financial models — Transactions, Unlocks, Interviews."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
+
from app.models.base import Base
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Transaction(Base):
|
| 13 |
+
__tablename__ = "transactions"
|
| 14 |
+
|
| 15 |
+
id = Column(String(50), primary_key=True)
|
| 16 |
+
client_id = Column(String(50), ForeignKey("client_accounts.id", ondelete="SET NULL"), nullable=True, index=True)
|
| 17 |
+
amount = Column(Numeric(15, 2), nullable=False)
|
| 18 |
+
type = Column(String(50), nullable=False)
|
| 19 |
+
status = Column(String(20), default="Pending", index=True)
|
| 20 |
+
snap_token = Column(String(500), nullable=True)
|
| 21 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ProfileUnlock(Base):
|
| 25 |
+
__tablename__ = "profile_unlocks"
|
| 26 |
+
|
| 27 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 28 |
+
company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
|
| 29 |
+
candidate_id = Column(String(50), nullable=False, index=True)
|
| 30 |
+
is_masked_only = Column(Boolean, default=True)
|
| 31 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Interview(Base):
|
| 35 |
+
__tablename__ = "interviews"
|
| 36 |
+
|
| 37 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 38 |
+
company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
|
| 39 |
+
client_id = Column(String(50), ForeignKey("client_accounts.id", ondelete="SET NULL"), nullable=True)
|
| 40 |
+
candidate_id = Column(String(50), nullable=False, index=True)
|
| 41 |
+
scheduled_time = Column(DateTime(timezone=True), nullable=False)
|
| 42 |
+
status = Column(String(20), default="Scheduled")
|
| 43 |
+
transcript_text = Column(Text, nullable=True)
|
| 44 |
+
ai_summary = Column(Text, nullable=True)
|
| 45 |
+
ai_competency_score = Column(Integer, default=0)
|
| 46 |
+
ai_performance_analysis = Column(Text, nullable=True)
|
| 47 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
app/models/job.py
CHANGED
|
@@ -1,120 +1,120 @@
|
|
| 1 |
-
"""Job, Outreach, and Chat models."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Index
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
-
|
| 10 |
-
from app.models.base import Base
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class JobPosting(Base):
|
| 14 |
-
__tablename__ = "job_postings"
|
| 15 |
-
|
| 16 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 17 |
-
job_id = Column(String(50), unique=True, nullable=False)
|
| 18 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 19 |
-
title = Column(String(255), nullable=False)
|
| 20 |
-
company_name = Column(String(255), nullable=True)
|
| 21 |
-
company_id = Column(String(50), ForeignKey("companies.id", ondelete="SET NULL"), nullable=True, index=True)
|
| 22 |
-
posted_by_email = Column(String(255), nullable=True, index=True)
|
| 23 |
-
company_category = Column(String(255), nullable=True)
|
| 24 |
-
location = Column(String(255), nullable=True)
|
| 25 |
-
description = Column(Text, nullable=True)
|
| 26 |
-
required_skills = Column(Text, nullable=True)
|
| 27 |
-
salary_range = Column(String(100), nullable=True)
|
| 28 |
-
source = Column(String(100), nullable=True)
|
| 29 |
-
source_url = Column(String(500), nullable=True)
|
| 30 |
-
status = Column(String(50), default="draft", index=True)
|
| 31 |
-
linkedin_post_url = Column(String(500), nullable=True)
|
| 32 |
-
analysis_json = Column(JSONB, nullable=True)
|
| 33 |
-
sector_match = Column(String(255), nullable=True, index=True)
|
| 34 |
-
is_active = Column(Boolean, default=True, index=True)
|
| 35 |
-
scraped_at = Column(DateTime(timezone=True), nullable=True)
|
| 36 |
-
posted_at = Column(DateTime(timezone=True), nullable=True)
|
| 37 |
-
environment = Column(String(20), default='production', nullable=False)
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
class RecruiterOutreach(Base):
|
| 41 |
-
__tablename__ = "recruiter_outreach"
|
| 42 |
-
|
| 43 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 44 |
-
outreach_id = Column(String(20), unique=True, nullable=False)
|
| 45 |
-
job_id = Column(String(50), nullable=True)
|
| 46 |
-
talent_email = Column(String(255), nullable=True, index=True)
|
| 47 |
-
match_score = Column(Integer, nullable=True)
|
| 48 |
-
recruiter_email = Column(String(255), nullable=True)
|
| 49 |
-
contact_method = Column(String(50), nullable=True)
|
| 50 |
-
outreach_subject = Column(Text, nullable=True)
|
| 51 |
-
outreach_body = Column(Text, nullable=True)
|
| 52 |
-
status = Column(String(20), default="pending_approval", index=True)
|
| 53 |
-
triggered_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 54 |
-
sent_at = Column(DateTime(timezone=True), nullable=True)
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
class MediatedChat(Base):
|
| 58 |
-
"""Mediated chat messages between recruiters and talents.
|
| 59 |
-
|
| 60 |
-
Brigawan AI acts as a smart relay, masking identities until unlocked.
|
| 61 |
-
Matches ChatManager.gs schema with conversation grouping.
|
| 62 |
-
"""
|
| 63 |
-
__tablename__ = "mediated_chats"
|
| 64 |
-
|
| 65 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 66 |
-
chat_id = Column(String(50), unique=True, nullable=True, index=True) # MSG-UUID8
|
| 67 |
-
conversation_id = Column(String(50), nullable=False, index=True) # CONV-UUID8
|
| 68 |
-
sender_email = Column(String(255), nullable=False, index=True) # Who sent
|
| 69 |
-
receiver_email = Column(String(255), nullable=False, index=True) # Who receives
|
| 70 |
-
sender_role = Column(String(20), nullable=False, default="RECRUITER") # RECRUITER or TALENT
|
| 71 |
-
original_message = Column(Text, nullable=True) # Raw message from sender
|
| 72 |
-
mediated_message = Column(Text, nullable=True) # AI-mediated version for recipient
|
| 73 |
-
is_identity_unlocked = Column(Boolean, default=False) # TRUE after 5-coin unlock
|
| 74 |
-
status = Column(String(30), default="PENDING_RECRUITER", index=True) # PENDING_TALENT, PENDING_RECRUITER, READ
|
| 75 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 76 |
-
|
| 77 |
-
# Legacy fields (kept for backward compat)
|
| 78 |
-
email = Column(String(255), nullable=True, index=True)
|
| 79 |
-
talent_id = Column(String(20), nullable=True, index=True)
|
| 80 |
-
talent_name = Column(String(255), nullable=True)
|
| 81 |
-
message = Column(Text, nullable=True)
|
| 82 |
-
sender = Column(String(50), nullable=True)
|
| 83 |
-
is_read = Column(Boolean, default=False)
|
| 84 |
-
unlocked_at = Column(DateTime(timezone=True), nullable=True)
|
| 85 |
-
unlock_type = Column(String(50), nullable=True)
|
| 86 |
-
campaign_id = Column(String(50), nullable=True)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
class AITalentChat(Base):
|
| 90 |
-
__tablename__ = "ai_talent_chat"
|
| 91 |
-
|
| 92 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 93 |
-
email = Column(String(255), nullable=False, index=True)
|
| 94 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 95 |
-
user_message = Column(Text, nullable=True)
|
| 96 |
-
ai_reply = Column(Text, nullable=True)
|
| 97 |
-
expires_at = Column(DateTime(timezone=True), nullable=True)
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
class TalentPathway(Base):
|
| 101 |
-
__tablename__ = "talent_pathway"
|
| 102 |
-
|
| 103 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 104 |
-
email = Column(String(255), unique=True, nullable=False, index=True)
|
| 105 |
-
pathway_json = Column(JSONB, nullable=False)
|
| 106 |
-
progress_json = Column(JSONB, nullable=False)
|
| 107 |
-
completed_stages = Column(JSONB, default=list)
|
| 108 |
-
generated_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 109 |
-
green_score = Column(Integer, default=0)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
class TalentAcademy(Base):
|
| 113 |
-
__tablename__ = "talent_academy"
|
| 114 |
-
|
| 115 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 116 |
-
email = Column(String(255), unique=True, nullable=False)
|
| 117 |
-
completed_modules = Column(Text, default="")
|
| 118 |
-
registered_onsite = Column(JSONB, default=list)
|
| 119 |
-
last_updated_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 120 |
-
essay_answers = Column(Text, default="")
|
|
|
|
| 1 |
+
"""Job, Outreach, and Chat models."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Index
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
+
|
| 10 |
+
from app.models.base import Base
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class JobPosting(Base):
|
| 14 |
+
__tablename__ = "job_postings"
|
| 15 |
+
|
| 16 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 17 |
+
job_id = Column(String(50), unique=True, nullable=False)
|
| 18 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 19 |
+
title = Column(String(255), nullable=False)
|
| 20 |
+
company_name = Column(String(255), nullable=True)
|
| 21 |
+
company_id = Column(String(50), ForeignKey("companies.id", ondelete="SET NULL"), nullable=True, index=True)
|
| 22 |
+
posted_by_email = Column(String(255), nullable=True, index=True)
|
| 23 |
+
company_category = Column(String(255), nullable=True)
|
| 24 |
+
location = Column(String(255), nullable=True)
|
| 25 |
+
description = Column(Text, nullable=True)
|
| 26 |
+
required_skills = Column(Text, nullable=True)
|
| 27 |
+
salary_range = Column(String(100), nullable=True)
|
| 28 |
+
source = Column(String(100), nullable=True)
|
| 29 |
+
source_url = Column(String(500), nullable=True)
|
| 30 |
+
status = Column(String(50), default="draft", index=True)
|
| 31 |
+
linkedin_post_url = Column(String(500), nullable=True)
|
| 32 |
+
analysis_json = Column(JSONB, nullable=True)
|
| 33 |
+
sector_match = Column(String(255), nullable=True, index=True)
|
| 34 |
+
is_active = Column(Boolean, default=True, index=True)
|
| 35 |
+
scraped_at = Column(DateTime(timezone=True), nullable=True)
|
| 36 |
+
posted_at = Column(DateTime(timezone=True), nullable=True)
|
| 37 |
+
environment = Column(String(20), default='production', nullable=False)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class RecruiterOutreach(Base):
|
| 41 |
+
__tablename__ = "recruiter_outreach"
|
| 42 |
+
|
| 43 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 44 |
+
outreach_id = Column(String(20), unique=True, nullable=False)
|
| 45 |
+
job_id = Column(String(50), nullable=True)
|
| 46 |
+
talent_email = Column(String(255), nullable=True, index=True)
|
| 47 |
+
match_score = Column(Integer, nullable=True)
|
| 48 |
+
recruiter_email = Column(String(255), nullable=True)
|
| 49 |
+
contact_method = Column(String(50), nullable=True)
|
| 50 |
+
outreach_subject = Column(Text, nullable=True)
|
| 51 |
+
outreach_body = Column(Text, nullable=True)
|
| 52 |
+
status = Column(String(20), default="pending_approval", index=True)
|
| 53 |
+
triggered_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 54 |
+
sent_at = Column(DateTime(timezone=True), nullable=True)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class MediatedChat(Base):
|
| 58 |
+
"""Mediated chat messages between recruiters and talents.
|
| 59 |
+
|
| 60 |
+
Brigawan AI acts as a smart relay, masking identities until unlocked.
|
| 61 |
+
Matches ChatManager.gs schema with conversation grouping.
|
| 62 |
+
"""
|
| 63 |
+
__tablename__ = "mediated_chats"
|
| 64 |
+
|
| 65 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 66 |
+
chat_id = Column(String(50), unique=True, nullable=True, index=True) # MSG-UUID8
|
| 67 |
+
conversation_id = Column(String(50), nullable=False, index=True) # CONV-UUID8
|
| 68 |
+
sender_email = Column(String(255), nullable=False, index=True) # Who sent
|
| 69 |
+
receiver_email = Column(String(255), nullable=False, index=True) # Who receives
|
| 70 |
+
sender_role = Column(String(20), nullable=False, default="RECRUITER") # RECRUITER or TALENT
|
| 71 |
+
original_message = Column(Text, nullable=True) # Raw message from sender
|
| 72 |
+
mediated_message = Column(Text, nullable=True) # AI-mediated version for recipient
|
| 73 |
+
is_identity_unlocked = Column(Boolean, default=False) # TRUE after 5-coin unlock
|
| 74 |
+
status = Column(String(30), default="PENDING_RECRUITER", index=True) # PENDING_TALENT, PENDING_RECRUITER, READ
|
| 75 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 76 |
+
|
| 77 |
+
# Legacy fields (kept for backward compat)
|
| 78 |
+
email = Column(String(255), nullable=True, index=True)
|
| 79 |
+
talent_id = Column(String(20), nullable=True, index=True)
|
| 80 |
+
talent_name = Column(String(255), nullable=True)
|
| 81 |
+
message = Column(Text, nullable=True)
|
| 82 |
+
sender = Column(String(50), nullable=True)
|
| 83 |
+
is_read = Column(Boolean, default=False)
|
| 84 |
+
unlocked_at = Column(DateTime(timezone=True), nullable=True)
|
| 85 |
+
unlock_type = Column(String(50), nullable=True)
|
| 86 |
+
campaign_id = Column(String(50), nullable=True)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class AITalentChat(Base):
|
| 90 |
+
__tablename__ = "ai_talent_chat"
|
| 91 |
+
|
| 92 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 93 |
+
email = Column(String(255), nullable=False, index=True)
|
| 94 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 95 |
+
user_message = Column(Text, nullable=True)
|
| 96 |
+
ai_reply = Column(Text, nullable=True)
|
| 97 |
+
expires_at = Column(DateTime(timezone=True), nullable=True)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class TalentPathway(Base):
|
| 101 |
+
__tablename__ = "talent_pathway"
|
| 102 |
+
|
| 103 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 104 |
+
email = Column(String(255), unique=True, nullable=False, index=True)
|
| 105 |
+
pathway_json = Column(JSONB, nullable=False)
|
| 106 |
+
progress_json = Column(JSONB, nullable=False)
|
| 107 |
+
completed_stages = Column(JSONB, default=list)
|
| 108 |
+
generated_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 109 |
+
green_score = Column(Integer, default=0)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class TalentAcademy(Base):
|
| 113 |
+
__tablename__ = "talent_academy"
|
| 114 |
+
|
| 115 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 116 |
+
email = Column(String(255), unique=True, nullable=False)
|
| 117 |
+
completed_modules = Column(Text, default="")
|
| 118 |
+
registered_onsite = Column(JSONB, default=list)
|
| 119 |
+
last_updated_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 120 |
+
essay_answers = Column(Text, default="")
|
app/models/lpk.py
CHANGED
|
@@ -1,130 +1,130 @@
|
|
| 1 |
-
"""LPK Ecosystem models."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
-
from app.models.base import Base
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
class LPKPartner(Base):
|
| 13 |
-
__tablename__ = "lpk_partners"
|
| 14 |
-
|
| 15 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 16 |
-
lpk_id = Column(String(50), unique=True, nullable=False)
|
| 17 |
-
lpk_name = Column(String(255), nullable=False)
|
| 18 |
-
city_branch = Column(String(100), nullable=True)
|
| 19 |
-
pic_name = Column(String(255), nullable=True)
|
| 20 |
-
pic_whatsapp = Column(String(50), nullable=True)
|
| 21 |
-
email = Column(String(255), unique=True, nullable=False)
|
| 22 |
-
password_hash = Column(String(255), nullable=False)
|
| 23 |
-
kemnaker_vin = Column(String(100), nullable=True)
|
| 24 |
-
lsp_affiliation = Column(String(255), nullable=True)
|
| 25 |
-
status_active = Column(Boolean, default=False)
|
| 26 |
-
pks_status = Column(String(20), default="Pending")
|
| 27 |
-
pks_document_url = Column(String(500), nullable=True)
|
| 28 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
class LPKCourse(Base):
|
| 32 |
-
__tablename__ = "lpk_courses"
|
| 33 |
-
|
| 34 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 35 |
-
course_id = Column(String(50), unique=True, nullable=False)
|
| 36 |
-
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
|
| 37 |
-
course_name = Column(String(255), nullable=False)
|
| 38 |
-
target_skills = Column(JSONB, default=list)
|
| 39 |
-
skkni_reference = Column(String(255), nullable=True)
|
| 40 |
-
skkni_units = Column(JSONB, default=list)
|
| 41 |
-
bnsp_assessment = Column(String(255), nullable=True)
|
| 42 |
-
price = Column(Numeric(12, 2), default=0)
|
| 43 |
-
duration = Column(String(50), nullable=True)
|
| 44 |
-
status_active = Column(Boolean, default=True)
|
| 45 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
class SponsorCampaign(Base):
|
| 49 |
-
__tablename__ = "sponsor_campaigns"
|
| 50 |
-
|
| 51 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 52 |
-
campaign_id = Column(String(50), unique=True, nullable=False)
|
| 53 |
-
employer_email = Column(String(255), nullable=True)
|
| 54 |
-
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="SET NULL"), nullable=True, index=True)
|
| 55 |
-
course_id = Column(String(50), ForeignKey("lpk_courses.course_id", ondelete="SET NULL"), nullable=True)
|
| 56 |
-
target_talents = Column(Integer, default=0)
|
| 57 |
-
subsidy_percentage = Column(Numeric(5, 2), default=0)
|
| 58 |
-
criteria_json = Column(JSONB, default=dict)
|
| 59 |
-
status = Column(String(20), default="Draft")
|
| 60 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
class CampaignParticipant(Base):
|
| 64 |
-
__tablename__ = "campaign_participants"
|
| 65 |
-
|
| 66 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 67 |
-
registration_id = Column(String(50), unique=True, nullable=False)
|
| 68 |
-
campaign_id = Column(String(50), ForeignKey("sponsor_campaigns.campaign_id", ondelete="CASCADE"), nullable=True, index=True)
|
| 69 |
-
talent_email = Column(String(255), nullable=False, index=True)
|
| 70 |
-
theory_module_status = Column(String(50), default="Pending")
|
| 71 |
-
practical_onsite_status = Column(String(50), default="Pending")
|
| 72 |
-
recruitment_status = Column(String(50), default="Pending")
|
| 73 |
-
interview_date = Column(DateTime(timezone=True), nullable=True)
|
| 74 |
-
certificate_no = Column(String(100), nullable=True)
|
| 75 |
-
practical_score = Column(Integer, default=0)
|
| 76 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
class VerificationQueue(Base):
|
| 80 |
-
__tablename__ = "verification_queue"
|
| 81 |
-
|
| 82 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 83 |
-
queue_id = Column(String(50), unique=True, nullable=False)
|
| 84 |
-
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True)
|
| 85 |
-
lpk_name = Column(String(255), nullable=True)
|
| 86 |
-
kemnaker_vin = Column(String(100), nullable=True)
|
| 87 |
-
city_branch = Column(String(100), nullable=True)
|
| 88 |
-
status_queue = Column(String(50), default="PENDING_VERIFICATION")
|
| 89 |
-
ai_analysis_log = Column(Text, nullable=True)
|
| 90 |
-
legal_proof_url = Column(String(500), nullable=True)
|
| 91 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
class LPKLedger(Base):
|
| 95 |
-
__tablename__ = "lpk_ledger"
|
| 96 |
-
|
| 97 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 98 |
-
ledger_id = Column(String(50), unique=True, nullable=False)
|
| 99 |
-
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
|
| 100 |
-
reference_id = Column(String(50), nullable=True)
|
| 101 |
-
type = Column(String(50), nullable=False)
|
| 102 |
-
amount = Column(Numeric(12, 2), default=0)
|
| 103 |
-
porsi_lpk = Column(Numeric(12, 2), default=0)
|
| 104 |
-
status = Column(String(50), default="Pending")
|
| 105 |
-
bank_account_json = Column(JSONB, nullable=True)
|
| 106 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
class Voucher(Base):
|
| 110 |
-
__tablename__ = "vouchers"
|
| 111 |
-
|
| 112 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 113 |
-
voucher_id = Column(String(50), unique=True, nullable=False)
|
| 114 |
-
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
|
| 115 |
-
candidate_email = Column(String(255), nullable=True)
|
| 116 |
-
status = Column(String(50), default="Active")
|
| 117 |
-
date_generated = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 118 |
-
date_used = Column(DateTime(timezone=True), nullable=True)
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
class Certificate(Base):
|
| 122 |
-
__tablename__ = "certificates"
|
| 123 |
-
|
| 124 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 125 |
-
certificate_id = Column(String(50), unique=True, nullable=False)
|
| 126 |
-
candidate_email = Column(String(255), nullable=False, index=True)
|
| 127 |
-
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="SET NULL"), nullable=True)
|
| 128 |
-
pathway_id = Column(String(50), nullable=True)
|
| 129 |
-
date_issued = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 130 |
-
verification_url = Column(String(500), nullable=True)
|
|
|
|
| 1 |
+
"""LPK Ecosystem models."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
+
from app.models.base import Base
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class LPKPartner(Base):
|
| 13 |
+
__tablename__ = "lpk_partners"
|
| 14 |
+
|
| 15 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 16 |
+
lpk_id = Column(String(50), unique=True, nullable=False)
|
| 17 |
+
lpk_name = Column(String(255), nullable=False)
|
| 18 |
+
city_branch = Column(String(100), nullable=True)
|
| 19 |
+
pic_name = Column(String(255), nullable=True)
|
| 20 |
+
pic_whatsapp = Column(String(50), nullable=True)
|
| 21 |
+
email = Column(String(255), unique=True, nullable=False)
|
| 22 |
+
password_hash = Column(String(255), nullable=False)
|
| 23 |
+
kemnaker_vin = Column(String(100), nullable=True)
|
| 24 |
+
lsp_affiliation = Column(String(255), nullable=True)
|
| 25 |
+
status_active = Column(Boolean, default=False)
|
| 26 |
+
pks_status = Column(String(20), default="Pending")
|
| 27 |
+
pks_document_url = Column(String(500), nullable=True)
|
| 28 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class LPKCourse(Base):
|
| 32 |
+
__tablename__ = "lpk_courses"
|
| 33 |
+
|
| 34 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 35 |
+
course_id = Column(String(50), unique=True, nullable=False)
|
| 36 |
+
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
|
| 37 |
+
course_name = Column(String(255), nullable=False)
|
| 38 |
+
target_skills = Column(JSONB, default=list)
|
| 39 |
+
skkni_reference = Column(String(255), nullable=True)
|
| 40 |
+
skkni_units = Column(JSONB, default=list)
|
| 41 |
+
bnsp_assessment = Column(String(255), nullable=True)
|
| 42 |
+
price = Column(Numeric(12, 2), default=0)
|
| 43 |
+
duration = Column(String(50), nullable=True)
|
| 44 |
+
status_active = Column(Boolean, default=True)
|
| 45 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class SponsorCampaign(Base):
|
| 49 |
+
__tablename__ = "sponsor_campaigns"
|
| 50 |
+
|
| 51 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 52 |
+
campaign_id = Column(String(50), unique=True, nullable=False)
|
| 53 |
+
employer_email = Column(String(255), nullable=True)
|
| 54 |
+
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="SET NULL"), nullable=True, index=True)
|
| 55 |
+
course_id = Column(String(50), ForeignKey("lpk_courses.course_id", ondelete="SET NULL"), nullable=True)
|
| 56 |
+
target_talents = Column(Integer, default=0)
|
| 57 |
+
subsidy_percentage = Column(Numeric(5, 2), default=0)
|
| 58 |
+
criteria_json = Column(JSONB, default=dict)
|
| 59 |
+
status = Column(String(20), default="Draft")
|
| 60 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class CampaignParticipant(Base):
|
| 64 |
+
__tablename__ = "campaign_participants"
|
| 65 |
+
|
| 66 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 67 |
+
registration_id = Column(String(50), unique=True, nullable=False)
|
| 68 |
+
campaign_id = Column(String(50), ForeignKey("sponsor_campaigns.campaign_id", ondelete="CASCADE"), nullable=True, index=True)
|
| 69 |
+
talent_email = Column(String(255), nullable=False, index=True)
|
| 70 |
+
theory_module_status = Column(String(50), default="Pending")
|
| 71 |
+
practical_onsite_status = Column(String(50), default="Pending")
|
| 72 |
+
recruitment_status = Column(String(50), default="Pending")
|
| 73 |
+
interview_date = Column(DateTime(timezone=True), nullable=True)
|
| 74 |
+
certificate_no = Column(String(100), nullable=True)
|
| 75 |
+
practical_score = Column(Integer, default=0)
|
| 76 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class VerificationQueue(Base):
|
| 80 |
+
__tablename__ = "verification_queue"
|
| 81 |
+
|
| 82 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 83 |
+
queue_id = Column(String(50), unique=True, nullable=False)
|
| 84 |
+
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True)
|
| 85 |
+
lpk_name = Column(String(255), nullable=True)
|
| 86 |
+
kemnaker_vin = Column(String(100), nullable=True)
|
| 87 |
+
city_branch = Column(String(100), nullable=True)
|
| 88 |
+
status_queue = Column(String(50), default="PENDING_VERIFICATION")
|
| 89 |
+
ai_analysis_log = Column(Text, nullable=True)
|
| 90 |
+
legal_proof_url = Column(String(500), nullable=True)
|
| 91 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class LPKLedger(Base):
|
| 95 |
+
__tablename__ = "lpk_ledger"
|
| 96 |
+
|
| 97 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 98 |
+
ledger_id = Column(String(50), unique=True, nullable=False)
|
| 99 |
+
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
|
| 100 |
+
reference_id = Column(String(50), nullable=True)
|
| 101 |
+
type = Column(String(50), nullable=False)
|
| 102 |
+
amount = Column(Numeric(12, 2), default=0)
|
| 103 |
+
porsi_lpk = Column(Numeric(12, 2), default=0)
|
| 104 |
+
status = Column(String(50), default="Pending")
|
| 105 |
+
bank_account_json = Column(JSONB, nullable=True)
|
| 106 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class Voucher(Base):
|
| 110 |
+
__tablename__ = "vouchers"
|
| 111 |
+
|
| 112 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 113 |
+
voucher_id = Column(String(50), unique=True, nullable=False)
|
| 114 |
+
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
|
| 115 |
+
candidate_email = Column(String(255), nullable=True)
|
| 116 |
+
status = Column(String(50), default="Active")
|
| 117 |
+
date_generated = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 118 |
+
date_used = Column(DateTime(timezone=True), nullable=True)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class Certificate(Base):
|
| 122 |
+
__tablename__ = "certificates"
|
| 123 |
+
|
| 124 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 125 |
+
certificate_id = Column(String(50), unique=True, nullable=False)
|
| 126 |
+
candidate_email = Column(String(255), nullable=False, index=True)
|
| 127 |
+
lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="SET NULL"), nullable=True)
|
| 128 |
+
pathway_id = Column(String(50), nullable=True)
|
| 129 |
+
date_issued = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 130 |
+
verification_url = Column(String(500), nullable=True)
|
app/models/security.py
CHANGED
|
@@ -1,56 +1,56 @@
|
|
| 1 |
-
"""Security & Cryptographic Audit Trail models."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, BigInteger
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
-
from sqlalchemy.orm import relationship
|
| 10 |
-
from app.models.base import Base
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class ProfileKey(Base):
|
| 14 |
-
"""Stores profile-specific AES-256 Data Encryption Keys (DEK).
|
| 15 |
-
DEKs are encrypted by the KMS Master Key (Envelope Encryption).
|
| 16 |
-
"""
|
| 17 |
-
__tablename__ = "profile_keys"
|
| 18 |
-
__table_args__ = {"schema": "security"}
|
| 19 |
-
|
| 20 |
-
profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), primary_key=True)
|
| 21 |
-
encrypted_symmetric_key = Column(Text, nullable=False)
|
| 22 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 23 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 24 |
-
|
| 25 |
-
# Relationships
|
| 26 |
-
profile = relationship("Profile", back_populates="key")
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
class AuditTrail(Base):
|
| 30 |
-
"""Cryptographic Append-Only Hash-Chained Audit Trail."""
|
| 31 |
-
__tablename__ = "audit_trail"
|
| 32 |
-
__table_args__ = {"schema": "audit"}
|
| 33 |
-
|
| 34 |
-
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
| 35 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 36 |
-
record_table = Column(String(100), nullable=False)
|
| 37 |
-
record_id = Column(UUID(as_uuid=True), nullable=False)
|
| 38 |
-
action_type = Column(String(10), nullable=False) # INSERT, UPDATE, DELETE
|
| 39 |
-
ciphertext_hash = Column(String(64), nullable=False)
|
| 40 |
-
signature_hash = Column(String(64), nullable=True)
|
| 41 |
-
previous_hash = Column(String(64), nullable=False, index=True)
|
| 42 |
-
current_hash = Column(String(64), nullable=False, index=True)
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
class AuditAnchor(Base):
|
| 46 |
-
"""Anchors for pruned/archived audit logs to ensure chain continuity."""
|
| 47 |
-
__tablename__ = "audit_anchors"
|
| 48 |
-
__table_args__ = {"schema": "audit"}
|
| 49 |
-
|
| 50 |
-
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
| 51 |
-
archive_run_id = Column(UUID(as_uuid=True), default=uuid.uuid4)
|
| 52 |
-
max_audit_id = Column(BigInteger, nullable=False)
|
| 53 |
-
anchor_hash = Column(String(64), nullable=False, index=True)
|
| 54 |
-
cold_storage_uri = Column(Text, nullable=False)
|
| 55 |
-
archive_file_hash = Column(String(64), nullable=False)
|
| 56 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
|
|
|
| 1 |
+
"""Security & Cryptographic Audit Trail models."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, BigInteger
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
+
from sqlalchemy.orm import relationship
|
| 10 |
+
from app.models.base import Base
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ProfileKey(Base):
|
| 14 |
+
"""Stores profile-specific AES-256 Data Encryption Keys (DEK).
|
| 15 |
+
DEKs are encrypted by the KMS Master Key (Envelope Encryption).
|
| 16 |
+
"""
|
| 17 |
+
__tablename__ = "profile_keys"
|
| 18 |
+
__table_args__ = {"schema": "security"}
|
| 19 |
+
|
| 20 |
+
profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), primary_key=True)
|
| 21 |
+
encrypted_symmetric_key = Column(Text, nullable=False)
|
| 22 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 23 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 24 |
+
|
| 25 |
+
# Relationships
|
| 26 |
+
profile = relationship("Profile", back_populates="key")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class AuditTrail(Base):
|
| 30 |
+
"""Cryptographic Append-Only Hash-Chained Audit Trail."""
|
| 31 |
+
__tablename__ = "audit_trail"
|
| 32 |
+
__table_args__ = {"schema": "audit"}
|
| 33 |
+
|
| 34 |
+
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
| 35 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 36 |
+
record_table = Column(String(100), nullable=False)
|
| 37 |
+
record_id = Column(UUID(as_uuid=True), nullable=False)
|
| 38 |
+
action_type = Column(String(10), nullable=False) # INSERT, UPDATE, DELETE
|
| 39 |
+
ciphertext_hash = Column(String(64), nullable=False)
|
| 40 |
+
signature_hash = Column(String(64), nullable=True)
|
| 41 |
+
previous_hash = Column(String(64), nullable=False, index=True)
|
| 42 |
+
current_hash = Column(String(64), nullable=False, index=True)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class AuditAnchor(Base):
|
| 46 |
+
"""Anchors for pruned/archived audit logs to ensure chain continuity."""
|
| 47 |
+
__tablename__ = "audit_anchors"
|
| 48 |
+
__table_args__ = {"schema": "audit"}
|
| 49 |
+
|
| 50 |
+
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
| 51 |
+
archive_run_id = Column(UUID(as_uuid=True), default=uuid.uuid4)
|
| 52 |
+
max_audit_id = Column(BigInteger, nullable=False)
|
| 53 |
+
anchor_hash = Column(String(64), nullable=False, index=True)
|
| 54 |
+
cold_storage_uri = Column(Text, nullable=False)
|
| 55 |
+
archive_file_hash = Column(String(64), nullable=False)
|
| 56 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
app/models/skkni.py
CHANGED
|
@@ -1,161 +1,161 @@
|
|
| 1 |
-
"""SKKNI and miscellaneous utility models."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
-
|
| 10 |
-
from app.models.base import Base
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class SKKNIMaster(Base):
|
| 14 |
-
__tablename__ = "skkni_master"
|
| 15 |
-
|
| 16 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 17 |
-
unit_code = Column(String(50), nullable=True)
|
| 18 |
-
unit_name = Column(Text, nullable=True)
|
| 19 |
-
sector = Column(String(100), nullable=True)
|
| 20 |
-
competency = Column(Text, nullable=True)
|
| 21 |
-
assessment_guideline = Column(Text, nullable=True)
|
| 22 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
class SKKNISourcePDF(Base):
|
| 26 |
-
__tablename__ = "skkni_source_pdfs"
|
| 27 |
-
|
| 28 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 29 |
-
pdf_url = Column(String(500), nullable=True)
|
| 30 |
-
title = Column(String(255), nullable=True)
|
| 31 |
-
status = Column(String(50), default="Pending")
|
| 32 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
class SKKNAgentLog(Base):
|
| 36 |
-
__tablename__ = "skkni_agent_log"
|
| 37 |
-
|
| 38 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 39 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 40 |
-
action = Column(String(100), nullable=True)
|
| 41 |
-
status = Column(String(50), nullable=True)
|
| 42 |
-
details = Column(Text, nullable=True)
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
class EmbeddingCache(Base):
|
| 46 |
-
__tablename__ = "embedding_cache"
|
| 47 |
-
|
| 48 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 49 |
-
text_hash = Column(String(64), unique=True, nullable=False, index=True)
|
| 50 |
-
raw_text = Column(Text, nullable=True)
|
| 51 |
-
embedding_json = Column(JSONB, nullable=True)
|
| 52 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
class KeywordQuarantine(Base):
|
| 56 |
-
__tablename__ = "keyword_quarantine"
|
| 57 |
-
|
| 58 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 59 |
-
is_selected = Column(Boolean, default=False)
|
| 60 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 61 |
-
keyword = Column(String(255), nullable=True)
|
| 62 |
-
ai_research_context = Column(Text, nullable=True)
|
| 63 |
-
suggested_briga_rule = Column(Text, nullable=True)
|
| 64 |
-
status = Column(String(50), default="Pending")
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
class TalentAlert(Base):
|
| 68 |
-
__tablename__ = "talent_alerts"
|
| 69 |
-
|
| 70 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 71 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 72 |
-
email = Column(String(255), nullable=True)
|
| 73 |
-
query = Column(Text, nullable=True)
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
class FailedSearch(Base):
|
| 77 |
-
__tablename__ = "failed_searches"
|
| 78 |
-
|
| 79 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 80 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 81 |
-
email = Column(String(255), nullable=True)
|
| 82 |
-
query = Column(Text, nullable=True)
|
| 83 |
-
count = Column(Integer, default=0)
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
class VettingAudit(Base):
|
| 87 |
-
__tablename__ = "vetting_audit"
|
| 88 |
-
|
| 89 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 90 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 91 |
-
recruiter = Column(String(255), nullable=True)
|
| 92 |
-
cvs_processed = Column(Integer, default=0)
|
| 93 |
-
failures = Column(Integer, default=0)
|
| 94 |
-
engine_version = Column(String(50), nullable=True)
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
class VettingBenchmarkLog(Base):
|
| 98 |
-
__tablename__ = "benchmark_log"
|
| 99 |
-
|
| 100 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 101 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 102 |
-
category = Column(String(100), nullable=True)
|
| 103 |
-
model = Column(String(100), nullable=True)
|
| 104 |
-
result = Column(Text, nullable=True)
|
| 105 |
-
notes = Column(Text, nullable=True)
|
| 106 |
-
response_preview = Column(Text, nullable=True)
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
class VettingBenchmarkCompare(Base):
|
| 110 |
-
__tablename__ = "benchmark_compare"
|
| 111 |
-
|
| 112 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 113 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 114 |
-
model = Column(String(100), nullable=True)
|
| 115 |
-
response = Column(Text, nullable=True)
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
class TestLog(Base):
|
| 119 |
-
__tablename__ = "test_log"
|
| 120 |
-
|
| 121 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 122 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 123 |
-
total_tests = Column(Integer, default=0)
|
| 124 |
-
failed_tests = Column(Integer, default=0)
|
| 125 |
-
result_summary = Column(Text, nullable=True)
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
class ContentQueue(Base):
|
| 129 |
-
__tablename__ = "content_queue"
|
| 130 |
-
|
| 131 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 132 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 133 |
-
topic = Column(String(255), nullable=True)
|
| 134 |
-
status = Column(String(50), default="Queued")
|
| 135 |
-
priority = Column(Integer, default=0)
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
class LPKRegistrationLead(Base):
|
| 139 |
-
__tablename__ = "lpk_registration_leads"
|
| 140 |
-
|
| 141 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 142 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 143 |
-
email = Column(String(255), nullable=True)
|
| 144 |
-
module_id = Column(String(50), nullable=True)
|
| 145 |
-
lpk_branch = Column(String(100), nullable=True)
|
| 146 |
-
status = Column(String(50), default="Pending LPK Outreach")
|
| 147 |
-
talent_phone = Column(String(50), nullable=True)
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
class AcademyLead(Base):
|
| 151 |
-
__tablename__ = "academy_leads"
|
| 152 |
-
|
| 153 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 154 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 155 |
-
profesi_asal = Column(String(255), nullable=True)
|
| 156 |
-
gaji_asal = Column(String(100), nullable=True)
|
| 157 |
-
skill_asal = Column(Text, nullable=True)
|
| 158 |
-
rekomendasi_greenjob = Column(String(255), nullable=True)
|
| 159 |
-
estimasi_gaji = Column(String(100), nullable=True)
|
| 160 |
-
skill_gap_count = Column(Integer, default=0)
|
| 161 |
-
status = Column(String(50), default="New")
|
|
|
|
| 1 |
+
"""SKKNI and miscellaneous utility models."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
+
|
| 10 |
+
from app.models.base import Base
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SKKNIMaster(Base):
|
| 14 |
+
__tablename__ = "skkni_master"
|
| 15 |
+
|
| 16 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 17 |
+
unit_code = Column(String(50), nullable=True)
|
| 18 |
+
unit_name = Column(Text, nullable=True)
|
| 19 |
+
sector = Column(String(100), nullable=True)
|
| 20 |
+
competency = Column(Text, nullable=True)
|
| 21 |
+
assessment_guideline = Column(Text, nullable=True)
|
| 22 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class SKKNISourcePDF(Base):
|
| 26 |
+
__tablename__ = "skkni_source_pdfs"
|
| 27 |
+
|
| 28 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 29 |
+
pdf_url = Column(String(500), nullable=True)
|
| 30 |
+
title = Column(String(255), nullable=True)
|
| 31 |
+
status = Column(String(50), default="Pending")
|
| 32 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SKKNAgentLog(Base):
|
| 36 |
+
__tablename__ = "skkni_agent_log"
|
| 37 |
+
|
| 38 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 39 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 40 |
+
action = Column(String(100), nullable=True)
|
| 41 |
+
status = Column(String(50), nullable=True)
|
| 42 |
+
details = Column(Text, nullable=True)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class EmbeddingCache(Base):
|
| 46 |
+
__tablename__ = "embedding_cache"
|
| 47 |
+
|
| 48 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 49 |
+
text_hash = Column(String(64), unique=True, nullable=False, index=True)
|
| 50 |
+
raw_text = Column(Text, nullable=True)
|
| 51 |
+
embedding_json = Column(JSONB, nullable=True)
|
| 52 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class KeywordQuarantine(Base):
|
| 56 |
+
__tablename__ = "keyword_quarantine"
|
| 57 |
+
|
| 58 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 59 |
+
is_selected = Column(Boolean, default=False)
|
| 60 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 61 |
+
keyword = Column(String(255), nullable=True)
|
| 62 |
+
ai_research_context = Column(Text, nullable=True)
|
| 63 |
+
suggested_briga_rule = Column(Text, nullable=True)
|
| 64 |
+
status = Column(String(50), default="Pending")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class TalentAlert(Base):
|
| 68 |
+
__tablename__ = "talent_alerts"
|
| 69 |
+
|
| 70 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 71 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 72 |
+
email = Column(String(255), nullable=True)
|
| 73 |
+
query = Column(Text, nullable=True)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class FailedSearch(Base):
|
| 77 |
+
__tablename__ = "failed_searches"
|
| 78 |
+
|
| 79 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 80 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 81 |
+
email = Column(String(255), nullable=True)
|
| 82 |
+
query = Column(Text, nullable=True)
|
| 83 |
+
count = Column(Integer, default=0)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class VettingAudit(Base):
|
| 87 |
+
__tablename__ = "vetting_audit"
|
| 88 |
+
|
| 89 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 90 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 91 |
+
recruiter = Column(String(255), nullable=True)
|
| 92 |
+
cvs_processed = Column(Integer, default=0)
|
| 93 |
+
failures = Column(Integer, default=0)
|
| 94 |
+
engine_version = Column(String(50), nullable=True)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class VettingBenchmarkLog(Base):
|
| 98 |
+
__tablename__ = "benchmark_log"
|
| 99 |
+
|
| 100 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 101 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 102 |
+
category = Column(String(100), nullable=True)
|
| 103 |
+
model = Column(String(100), nullable=True)
|
| 104 |
+
result = Column(Text, nullable=True)
|
| 105 |
+
notes = Column(Text, nullable=True)
|
| 106 |
+
response_preview = Column(Text, nullable=True)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class VettingBenchmarkCompare(Base):
|
| 110 |
+
__tablename__ = "benchmark_compare"
|
| 111 |
+
|
| 112 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 113 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 114 |
+
model = Column(String(100), nullable=True)
|
| 115 |
+
response = Column(Text, nullable=True)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class TestLog(Base):
|
| 119 |
+
__tablename__ = "test_log"
|
| 120 |
+
|
| 121 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 122 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 123 |
+
total_tests = Column(Integer, default=0)
|
| 124 |
+
failed_tests = Column(Integer, default=0)
|
| 125 |
+
result_summary = Column(Text, nullable=True)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class ContentQueue(Base):
|
| 129 |
+
__tablename__ = "content_queue"
|
| 130 |
+
|
| 131 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 132 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 133 |
+
topic = Column(String(255), nullable=True)
|
| 134 |
+
status = Column(String(50), default="Queued")
|
| 135 |
+
priority = Column(Integer, default=0)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class LPKRegistrationLead(Base):
|
| 139 |
+
__tablename__ = "lpk_registration_leads"
|
| 140 |
+
|
| 141 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 142 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 143 |
+
email = Column(String(255), nullable=True)
|
| 144 |
+
module_id = Column(String(50), nullable=True)
|
| 145 |
+
lpk_branch = Column(String(100), nullable=True)
|
| 146 |
+
status = Column(String(50), default="Pending LPK Outreach")
|
| 147 |
+
talent_phone = Column(String(50), nullable=True)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class AcademyLead(Base):
|
| 151 |
+
__tablename__ = "academy_leads"
|
| 152 |
+
|
| 153 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 154 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 155 |
+
profesi_asal = Column(String(255), nullable=True)
|
| 156 |
+
gaji_asal = Column(String(100), nullable=True)
|
| 157 |
+
skill_asal = Column(Text, nullable=True)
|
| 158 |
+
rekomendasi_greenjob = Column(String(255), nullable=True)
|
| 159 |
+
estimasi_gaji = Column(String(100), nullable=True)
|
| 160 |
+
skill_gap_count = Column(Integer, default=0)
|
| 161 |
+
status = Column(String(50), default="New")
|
app/models/system.py
CHANGED
|
@@ -1,208 +1,208 @@
|
|
| 1 |
-
"""System & Audit models."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
-
from app.models.base import Base
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
class Admin(Base):
|
| 13 |
-
__tablename__ = "admins"
|
| 14 |
-
|
| 15 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 16 |
-
name = Column(String(255), nullable=False)
|
| 17 |
-
email = Column(String(255), unique=True, nullable=False)
|
| 18 |
-
password_hash = Column(String(255), nullable=False)
|
| 19 |
-
role = Column(String(20), default="ADMIN")
|
| 20 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 21 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
class ActivityLog(Base):
|
| 25 |
-
__tablename__ = "activity_logs"
|
| 26 |
-
|
| 27 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 28 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 29 |
-
actor = Column(String(255), default="Anonymous", index=True)
|
| 30 |
-
action = Column(String(255), default="Unknown")
|
| 31 |
-
log_metadata = Column("metadata", Text, default="-")
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
class SystemMonitor(Base):
|
| 35 |
-
__tablename__ = "system_monitor"
|
| 36 |
-
|
| 37 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 38 |
-
check_name = Column(String(100), nullable=True)
|
| 39 |
-
status = Column(String(50), nullable=True)
|
| 40 |
-
detail = Column(Text, nullable=True)
|
| 41 |
-
last_checked = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
class SystemMonitorLog(Base):
|
| 45 |
-
__tablename__ = "system_monitor_log"
|
| 46 |
-
|
| 47 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 48 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 49 |
-
agent = Column(String(100), nullable=True)
|
| 50 |
-
action = Column(String(255), nullable=True)
|
| 51 |
-
status = Column(String(50), nullable=True)
|
| 52 |
-
detail = Column(Text, nullable=True)
|
| 53 |
-
duration_ms = Column(Integer, default=0)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
class AnalyticsTraffic(Base):
|
| 57 |
-
__tablename__ = "analytics_traffic"
|
| 58 |
-
|
| 59 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 60 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 61 |
-
page = Column(String(255), nullable=True, index=True)
|
| 62 |
-
referrer = Column(String(500), nullable=True)
|
| 63 |
-
geo = Column(String(255), nullable=True)
|
| 64 |
-
user_agent = Column(Text, nullable=True)
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
class APIMonitoring(Base):
|
| 68 |
-
__tablename__ = "api_monitoring"
|
| 69 |
-
|
| 70 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 71 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 72 |
-
api_name = Column(String(100), nullable=True)
|
| 73 |
-
token_usage = Column(Integer, default=0)
|
| 74 |
-
status = Column(String(50), nullable=True)
|
| 75 |
-
user_email = Column(String(255), nullable=True)
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
class SecurityAuditLog(Base):
|
| 79 |
-
__tablename__ = "security_audit_log"
|
| 80 |
-
|
| 81 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 82 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 83 |
-
target_url = Column(String(500), nullable=True)
|
| 84 |
-
page_type = Column(String(50), nullable=True)
|
| 85 |
-
status = Column(String(50), nullable=True)
|
| 86 |
-
details = Column(Text, nullable=True)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
class PrivacyAuditLog(Base):
|
| 90 |
-
__tablename__ = "privacy_audit_log"
|
| 91 |
-
|
| 92 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 93 |
-
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 94 |
-
query = Column(Text, nullable=True)
|
| 95 |
-
user_email = Column(String(255), nullable=True)
|
| 96 |
-
is_hidden = Column(Boolean, default=False)
|
| 97 |
-
is_flagged = Column(Boolean, default=False)
|
| 98 |
-
risk_score = Column(Integer, default=0)
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
class TalentEngagement(Base):
|
| 102 |
-
__tablename__ = "talent_engagement"
|
| 103 |
-
|
| 104 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 105 |
-
email = Column(String(255), nullable=False, index=True)
|
| 106 |
-
name = Column(String(255), nullable=True)
|
| 107 |
-
talent_id = Column(String(20), nullable=True)
|
| 108 |
-
engagement_score = Column(Integer, default=0)
|
| 109 |
-
dormancy_days = Column(Integer, default=0)
|
| 110 |
-
tier = Column(String(10), nullable=True)
|
| 111 |
-
last_activity_date = Column(DateTime(timezone=True), nullable=True)
|
| 112 |
-
last_chat_date = Column(DateTime(timezone=True), nullable=True)
|
| 113 |
-
last_pathway_date = Column(DateTime(timezone=True), nullable=True)
|
| 114 |
-
ai_generated_message = Column(Text, nullable=True)
|
| 115 |
-
message_type = Column(String(50), nullable=True)
|
| 116 |
-
status = Column(String(50), default="Draft", index=True)
|
| 117 |
-
sent_at = Column(DateTime(timezone=True), nullable=True)
|
| 118 |
-
opened_at = Column(DateTime(timezone=True), nullable=True)
|
| 119 |
-
response_at = Column(DateTime(timezone=True), nullable=True)
|
| 120 |
-
response_text = Column(Text, nullable=True)
|
| 121 |
-
follow_up_date = Column(DateTime(timezone=True), nullable=True)
|
| 122 |
-
follow_up_message = Column(Text, nullable=True)
|
| 123 |
-
notes = Column(Text, nullable=True)
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
# ==========================================
|
| 127 |
-
# ANTIGRAVITY ORCHESTRATION MODELS
|
| 128 |
-
# ==========================================
|
| 129 |
-
|
| 130 |
-
class AgentStateLog(Base):
|
| 131 |
-
"""Logs the lifecycle and memory of autonomous AI agents."""
|
| 132 |
-
__tablename__ = "agent_state_logs"
|
| 133 |
-
|
| 134 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 135 |
-
agent_name = Column(String(100), nullable=False, index=True)
|
| 136 |
-
task_id = Column(String(100), nullable=True, index=True)
|
| 137 |
-
status = Column(String(50), default="IDLE", index=True) # IDLE, WORKING, COMPLETED, FAILED
|
| 138 |
-
memory_context = Column(JSONB, nullable=True)
|
| 139 |
-
last_action = Column(String(255), nullable=True)
|
| 140 |
-
error_message = Column(Text, nullable=True)
|
| 141 |
-
started_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 142 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
class AgentQueue(Base):
|
| 146 |
-
"""Manages request throttling to stay within Gemini Free Tier (15 RPM) limits."""
|
| 147 |
-
__tablename__ = "agent_queues"
|
| 148 |
-
|
| 149 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 150 |
-
task_name = Column(String(100), nullable=False)
|
| 151 |
-
payload = Column(JSONB, nullable=False)
|
| 152 |
-
priority = Column(Integer, default=0) # Higher is more urgent
|
| 153 |
-
status = Column(String(30), default="QUEUED", index=True) # QUEUED, PROCESSING, RETRYING, COMPLETED, ABORTED
|
| 154 |
-
scheduled_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 155 |
-
processed_at = Column(DateTime(timezone=True), nullable=True)
|
| 156 |
-
retry_count = Column(Integer, default=0)
|
| 157 |
-
trace_id = Column(String(100), nullable=True)
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
class CEOStrategicMemory(Base):
|
| 161 |
-
"""Long-term episodic memory for the AI CEO."""
|
| 162 |
-
__tablename__ = "ceo_strategic_memory"
|
| 163 |
-
|
| 164 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 165 |
-
topic = Column(String(255), nullable=False, index=True)
|
| 166 |
-
summary = Column(Text, nullable=False)
|
| 167 |
-
decision_made = Column(String(255), nullable=True)
|
| 168 |
-
founder_feedback = Column(Text, nullable=True)
|
| 169 |
-
sentiment_score = Column(Numeric(3, 2), nullable=True) # -1.0 to 1.0
|
| 170 |
-
embedding_id = Column(UUID(as_uuid=True), nullable=True) # Reference to vector storage
|
| 171 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 172 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
class WhatsAppSession(Base):
|
| 176 |
-
"""Conversational state machine for the WhatsApp bot."""
|
| 177 |
-
__tablename__ = "whatsapp_sessions"
|
| 178 |
-
|
| 179 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 180 |
-
phone = Column(String(50), unique=True, nullable=False, index=True)
|
| 181 |
-
state = Column(String(50), default="START") # START, ONBOARDING_NAME, ONBOARDING_EMAIL, IDLE
|
| 182 |
-
context = Column(JSONB, nullable=True)
|
| 183 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 184 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
class TelegramSession(Base):
|
| 188 |
-
"""Conversational state and payment verification session storage for Telegram bot."""
|
| 189 |
-
__tablename__ = "telegram_sessions"
|
| 190 |
-
|
| 191 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 192 |
-
chat_id = Column(String(255), unique=True, nullable=False, index=True)
|
| 193 |
-
state = Column(String(50), nullable=True)
|
| 194 |
-
last_context = Column(JSONB, nullable=True)
|
| 195 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 196 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
class WorkflowConfig(Base):
|
| 200 |
-
"""Runtime configuration for autonomous workflows. Toggle to enable/disable specific agent workflows."""
|
| 201 |
-
__tablename__ = "workflow_configs"
|
| 202 |
-
|
| 203 |
-
workflow_name = Column(String(100), primary_key=True)
|
| 204 |
-
is_active = Column(Boolean, default=False, nullable=False)
|
| 205 |
-
schedule_cron = Column(String(100), nullable=True)
|
| 206 |
-
last_run = Column(DateTime(timezone=True), nullable=True)
|
| 207 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 208 |
-
|
|
|
|
| 1 |
+
"""System & Audit models."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
+
from app.models.base import Base
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Admin(Base):
|
| 13 |
+
__tablename__ = "admins"
|
| 14 |
+
|
| 15 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 16 |
+
name = Column(String(255), nullable=False)
|
| 17 |
+
email = Column(String(255), unique=True, nullable=False)
|
| 18 |
+
password_hash = Column(String(255), nullable=False)
|
| 19 |
+
role = Column(String(20), default="ADMIN")
|
| 20 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 21 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ActivityLog(Base):
|
| 25 |
+
__tablename__ = "activity_logs"
|
| 26 |
+
|
| 27 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 28 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 29 |
+
actor = Column(String(255), default="Anonymous", index=True)
|
| 30 |
+
action = Column(String(255), default="Unknown")
|
| 31 |
+
log_metadata = Column("metadata", Text, default="-")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SystemMonitor(Base):
|
| 35 |
+
__tablename__ = "system_monitor"
|
| 36 |
+
|
| 37 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 38 |
+
check_name = Column(String(100), nullable=True)
|
| 39 |
+
status = Column(String(50), nullable=True)
|
| 40 |
+
detail = Column(Text, nullable=True)
|
| 41 |
+
last_checked = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class SystemMonitorLog(Base):
|
| 45 |
+
__tablename__ = "system_monitor_log"
|
| 46 |
+
|
| 47 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 48 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 49 |
+
agent = Column(String(100), nullable=True)
|
| 50 |
+
action = Column(String(255), nullable=True)
|
| 51 |
+
status = Column(String(50), nullable=True)
|
| 52 |
+
detail = Column(Text, nullable=True)
|
| 53 |
+
duration_ms = Column(Integer, default=0)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class AnalyticsTraffic(Base):
|
| 57 |
+
__tablename__ = "analytics_traffic"
|
| 58 |
+
|
| 59 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 60 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 61 |
+
page = Column(String(255), nullable=True, index=True)
|
| 62 |
+
referrer = Column(String(500), nullable=True)
|
| 63 |
+
geo = Column(String(255), nullable=True)
|
| 64 |
+
user_agent = Column(Text, nullable=True)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class APIMonitoring(Base):
|
| 68 |
+
__tablename__ = "api_monitoring"
|
| 69 |
+
|
| 70 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 71 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 72 |
+
api_name = Column(String(100), nullable=True)
|
| 73 |
+
token_usage = Column(Integer, default=0)
|
| 74 |
+
status = Column(String(50), nullable=True)
|
| 75 |
+
user_email = Column(String(255), nullable=True)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class SecurityAuditLog(Base):
|
| 79 |
+
__tablename__ = "security_audit_log"
|
| 80 |
+
|
| 81 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 82 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 83 |
+
target_url = Column(String(500), nullable=True)
|
| 84 |
+
page_type = Column(String(50), nullable=True)
|
| 85 |
+
status = Column(String(50), nullable=True)
|
| 86 |
+
details = Column(Text, nullable=True)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class PrivacyAuditLog(Base):
|
| 90 |
+
__tablename__ = "privacy_audit_log"
|
| 91 |
+
|
| 92 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 93 |
+
timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 94 |
+
query = Column(Text, nullable=True)
|
| 95 |
+
user_email = Column(String(255), nullable=True)
|
| 96 |
+
is_hidden = Column(Boolean, default=False)
|
| 97 |
+
is_flagged = Column(Boolean, default=False)
|
| 98 |
+
risk_score = Column(Integer, default=0)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class TalentEngagement(Base):
|
| 102 |
+
__tablename__ = "talent_engagement"
|
| 103 |
+
|
| 104 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 105 |
+
email = Column(String(255), nullable=False, index=True)
|
| 106 |
+
name = Column(String(255), nullable=True)
|
| 107 |
+
talent_id = Column(String(20), nullable=True)
|
| 108 |
+
engagement_score = Column(Integer, default=0)
|
| 109 |
+
dormancy_days = Column(Integer, default=0)
|
| 110 |
+
tier = Column(String(10), nullable=True)
|
| 111 |
+
last_activity_date = Column(DateTime(timezone=True), nullable=True)
|
| 112 |
+
last_chat_date = Column(DateTime(timezone=True), nullable=True)
|
| 113 |
+
last_pathway_date = Column(DateTime(timezone=True), nullable=True)
|
| 114 |
+
ai_generated_message = Column(Text, nullable=True)
|
| 115 |
+
message_type = Column(String(50), nullable=True)
|
| 116 |
+
status = Column(String(50), default="Draft", index=True)
|
| 117 |
+
sent_at = Column(DateTime(timezone=True), nullable=True)
|
| 118 |
+
opened_at = Column(DateTime(timezone=True), nullable=True)
|
| 119 |
+
response_at = Column(DateTime(timezone=True), nullable=True)
|
| 120 |
+
response_text = Column(Text, nullable=True)
|
| 121 |
+
follow_up_date = Column(DateTime(timezone=True), nullable=True)
|
| 122 |
+
follow_up_message = Column(Text, nullable=True)
|
| 123 |
+
notes = Column(Text, nullable=True)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# ==========================================
|
| 127 |
+
# ANTIGRAVITY ORCHESTRATION MODELS
|
| 128 |
+
# ==========================================
|
| 129 |
+
|
| 130 |
+
class AgentStateLog(Base):
|
| 131 |
+
"""Logs the lifecycle and memory of autonomous AI agents."""
|
| 132 |
+
__tablename__ = "agent_state_logs"
|
| 133 |
+
|
| 134 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 135 |
+
agent_name = Column(String(100), nullable=False, index=True)
|
| 136 |
+
task_id = Column(String(100), nullable=True, index=True)
|
| 137 |
+
status = Column(String(50), default="IDLE", index=True) # IDLE, WORKING, COMPLETED, FAILED
|
| 138 |
+
memory_context = Column(JSONB, nullable=True)
|
| 139 |
+
last_action = Column(String(255), nullable=True)
|
| 140 |
+
error_message = Column(Text, nullable=True)
|
| 141 |
+
started_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 142 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class AgentQueue(Base):
|
| 146 |
+
"""Manages request throttling to stay within Gemini Free Tier (15 RPM) limits."""
|
| 147 |
+
__tablename__ = "agent_queues"
|
| 148 |
+
|
| 149 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 150 |
+
task_name = Column(String(100), nullable=False)
|
| 151 |
+
payload = Column(JSONB, nullable=False)
|
| 152 |
+
priority = Column(Integer, default=0) # Higher is more urgent
|
| 153 |
+
status = Column(String(30), default="QUEUED", index=True) # QUEUED, PROCESSING, RETRYING, COMPLETED, ABORTED
|
| 154 |
+
scheduled_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 155 |
+
processed_at = Column(DateTime(timezone=True), nullable=True)
|
| 156 |
+
retry_count = Column(Integer, default=0)
|
| 157 |
+
trace_id = Column(String(100), nullable=True)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class CEOStrategicMemory(Base):
|
| 161 |
+
"""Long-term episodic memory for the AI CEO."""
|
| 162 |
+
__tablename__ = "ceo_strategic_memory"
|
| 163 |
+
|
| 164 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 165 |
+
topic = Column(String(255), nullable=False, index=True)
|
| 166 |
+
summary = Column(Text, nullable=False)
|
| 167 |
+
decision_made = Column(String(255), nullable=True)
|
| 168 |
+
founder_feedback = Column(Text, nullable=True)
|
| 169 |
+
sentiment_score = Column(Numeric(3, 2), nullable=True) # -1.0 to 1.0
|
| 170 |
+
embedding_id = Column(UUID(as_uuid=True), nullable=True) # Reference to vector storage
|
| 171 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 172 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class WhatsAppSession(Base):
|
| 176 |
+
"""Conversational state machine for the WhatsApp bot."""
|
| 177 |
+
__tablename__ = "whatsapp_sessions"
|
| 178 |
+
|
| 179 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 180 |
+
phone = Column(String(50), unique=True, nullable=False, index=True)
|
| 181 |
+
state = Column(String(50), default="START") # START, ONBOARDING_NAME, ONBOARDING_EMAIL, IDLE
|
| 182 |
+
context = Column(JSONB, nullable=True)
|
| 183 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 184 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class TelegramSession(Base):
|
| 188 |
+
"""Conversational state and payment verification session storage for Telegram bot."""
|
| 189 |
+
__tablename__ = "telegram_sessions"
|
| 190 |
+
|
| 191 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 192 |
+
chat_id = Column(String(255), unique=True, nullable=False, index=True)
|
| 193 |
+
state = Column(String(50), nullable=True)
|
| 194 |
+
last_context = Column(JSONB, nullable=True)
|
| 195 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 196 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class WorkflowConfig(Base):
|
| 200 |
+
"""Runtime configuration for autonomous workflows. Toggle to enable/disable specific agent workflows."""
|
| 201 |
+
__tablename__ = "workflow_configs"
|
| 202 |
+
|
| 203 |
+
workflow_name = Column(String(100), primary_key=True)
|
| 204 |
+
is_active = Column(Boolean, default=False, nullable=False)
|
| 205 |
+
schedule_cron = Column(String(100), nullable=True)
|
| 206 |
+
last_run = Column(DateTime(timezone=True), nullable=True)
|
| 207 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 208 |
+
|
app/models/talent.py
CHANGED
|
@@ -1,70 +1,70 @@
|
|
| 1 |
-
"""Talent & Talent Catalog models."""
|
| 2 |
-
|
| 3 |
-
import uuid
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
|
| 6 |
-
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Index
|
| 7 |
-
from app.models.base import JSONB
|
| 8 |
-
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
-
from app.models.base import Base
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
class Talent(Base):
|
| 13 |
-
__tablename__ = "talents"
|
| 14 |
-
|
| 15 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 16 |
-
talent_id = Column(String(20), unique=True, nullable=False, index=True)
|
| 17 |
-
name = Column(String(255), nullable=False)
|
| 18 |
-
email = Column(String(255), unique=True, nullable=False, index=True)
|
| 19 |
-
education = Column(Text, nullable=True)
|
| 20 |
-
experience = Column(Text, nullable=True)
|
| 21 |
-
category = Column(String(50), nullable=True, index=True)
|
| 22 |
-
score = Column(Integer, default=70)
|
| 23 |
-
analysis = Column(Text, nullable=True)
|
| 24 |
-
location = Column(String(255), nullable=True)
|
| 25 |
-
skill_tags = Column(Text, nullable=True)
|
| 26 |
-
cv_link = Column(String(500), nullable=True)
|
| 27 |
-
verification_status = Column(String(50), default="Pending", index=True)
|
| 28 |
-
salary_expected = Column(String(100), nullable=True)
|
| 29 |
-
badges = Column(JSONB, nullable=True)
|
| 30 |
-
advisory_snippet = Column(Text, nullable=True)
|
| 31 |
-
advisory_full = Column(Text, nullable=True)
|
| 32 |
-
k3_dasar = Column(String(255), nullable=True)
|
| 33 |
-
k3_khusus = Column(String(255), nullable=True)
|
| 34 |
-
cert_other = Column(Text, nullable=True)
|
| 35 |
-
language = Column(String(255), nullable=True)
|
| 36 |
-
phone = Column(String(50), nullable=True)
|
| 37 |
-
is_unlocked = Column(Boolean, default=False)
|
| 38 |
-
password_hash = Column(String(255), nullable=True)
|
| 39 |
-
linkedin_link = Column(String(500), nullable=True)
|
| 40 |
-
current_salary = Column(String(100), nullable=True)
|
| 41 |
-
portfolio_links = Column(Text, nullable=True)
|
| 42 |
-
cert_links = Column(Text, nullable=True)
|
| 43 |
-
base_cv_url = Column(String(500), nullable=True)
|
| 44 |
-
total_experience = Column(String(50), nullable=True)
|
| 45 |
-
sector_focus = Column(String(100), nullable=True)
|
| 46 |
-
talent_type = Column(String(50), nullable=True)
|
| 47 |
-
cert_expiry = Column(String(50), nullable=True)
|
| 48 |
-
green_score = Column(Integer, default=0, index=True)
|
| 49 |
-
linkedin_token = Column(Text, nullable=True)
|
| 50 |
-
job_reference_id = Column(String(50), nullable=True)
|
| 51 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 52 |
-
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 53 |
-
environment = Column(String(20), default='production', nullable=False)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
class TalentCatalog(Base):
|
| 57 |
-
__tablename__ = "talent_catalog"
|
| 58 |
-
|
| 59 |
-
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 60 |
-
talent_id = Column(String(20), ForeignKey("talents.talent_id"), unique=True, nullable=False)
|
| 61 |
-
display_name = Column(String(255), nullable=True)
|
| 62 |
-
sector_focus = Column(String(100), nullable=True, index=True)
|
| 63 |
-
skill_tags = Column(Text, nullable=True)
|
| 64 |
-
location = Column(String(255), nullable=True)
|
| 65 |
-
score = Column(Integer, nullable=True)
|
| 66 |
-
category = Column(String(50), nullable=True)
|
| 67 |
-
badges = Column(JSONB, nullable=True)
|
| 68 |
-
advisory_snippet = Column(Text, nullable=True)
|
| 69 |
-
is_active = Column(Boolean, default=True)
|
| 70 |
-
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
|
|
|
| 1 |
+
"""Talent & Talent Catalog models."""
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Index
|
| 7 |
+
from app.models.base import JSONB
|
| 8 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 9 |
+
from app.models.base import Base
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Talent(Base):
|
| 13 |
+
__tablename__ = "talents"
|
| 14 |
+
|
| 15 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 16 |
+
talent_id = Column(String(20), unique=True, nullable=False, index=True)
|
| 17 |
+
name = Column(String(255), nullable=False)
|
| 18 |
+
email = Column(String(255), unique=True, nullable=False, index=True)
|
| 19 |
+
education = Column(Text, nullable=True)
|
| 20 |
+
experience = Column(Text, nullable=True)
|
| 21 |
+
category = Column(String(50), nullable=True, index=True)
|
| 22 |
+
score = Column(Integer, default=70)
|
| 23 |
+
analysis = Column(Text, nullable=True)
|
| 24 |
+
location = Column(String(255), nullable=True)
|
| 25 |
+
skill_tags = Column(Text, nullable=True)
|
| 26 |
+
cv_link = Column(String(500), nullable=True)
|
| 27 |
+
verification_status = Column(String(50), default="Pending", index=True)
|
| 28 |
+
salary_expected = Column(String(100), nullable=True)
|
| 29 |
+
badges = Column(JSONB, nullable=True)
|
| 30 |
+
advisory_snippet = Column(Text, nullable=True)
|
| 31 |
+
advisory_full = Column(Text, nullable=True)
|
| 32 |
+
k3_dasar = Column(String(255), nullable=True)
|
| 33 |
+
k3_khusus = Column(String(255), nullable=True)
|
| 34 |
+
cert_other = Column(Text, nullable=True)
|
| 35 |
+
language = Column(String(255), nullable=True)
|
| 36 |
+
phone = Column(String(50), nullable=True)
|
| 37 |
+
is_unlocked = Column(Boolean, default=False)
|
| 38 |
+
password_hash = Column(String(255), nullable=True)
|
| 39 |
+
linkedin_link = Column(String(500), nullable=True)
|
| 40 |
+
current_salary = Column(String(100), nullable=True)
|
| 41 |
+
portfolio_links = Column(Text, nullable=True)
|
| 42 |
+
cert_links = Column(Text, nullable=True)
|
| 43 |
+
base_cv_url = Column(String(500), nullable=True)
|
| 44 |
+
total_experience = Column(String(50), nullable=True)
|
| 45 |
+
sector_focus = Column(String(100), nullable=True)
|
| 46 |
+
talent_type = Column(String(50), nullable=True)
|
| 47 |
+
cert_expiry = Column(String(50), nullable=True)
|
| 48 |
+
green_score = Column(Integer, default=0, index=True)
|
| 49 |
+
linkedin_token = Column(Text, nullable=True)
|
| 50 |
+
job_reference_id = Column(String(50), nullable=True)
|
| 51 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
| 52 |
+
updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 53 |
+
environment = Column(String(20), default='production', nullable=False)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class TalentCatalog(Base):
|
| 57 |
+
__tablename__ = "talent_catalog"
|
| 58 |
+
|
| 59 |
+
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
| 60 |
+
talent_id = Column(String(20), ForeignKey("talents.talent_id"), unique=True, nullable=False)
|
| 61 |
+
display_name = Column(String(255), nullable=True)
|
| 62 |
+
sector_focus = Column(String(100), nullable=True, index=True)
|
| 63 |
+
skill_tags = Column(Text, nullable=True)
|
| 64 |
+
location = Column(String(255), nullable=True)
|
| 65 |
+
score = Column(Integer, nullable=True)
|
| 66 |
+
category = Column(String(50), nullable=True)
|
| 67 |
+
badges = Column(JSONB, nullable=True)
|
| 68 |
+
advisory_snippet = Column(Text, nullable=True)
|
| 69 |
+
is_active = Column(Boolean, default=True)
|
| 70 |
+
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
app/schemas/career.py
CHANGED
|
@@ -1,170 +1,170 @@
|
|
| 1 |
-
"""Career history Pydantic schemas — Profiles, Experiences, and Credentials.
|
| 2 |
-
|
| 3 |
-
Provides validation and serialization for lifelong career records.
|
| 4 |
-
Handles both public (masked) and private (decrypted) data views.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
from datetime import date, datetime
|
| 8 |
-
from typing import Any, Dict, List, Optional
|
| 9 |
-
from uuid import UUID
|
| 10 |
-
|
| 11 |
-
from pydantic import BaseModel, ConfigDict, EmailStr, Field, HttpUrl
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
# ─── Organization ────────────────────────────────────────────────────────────
|
| 15 |
-
|
| 16 |
-
class OrganizationBase(BaseModel):
|
| 17 |
-
name: str = Field(..., min_length=1, max_length=255)
|
| 18 |
-
website_url: Optional[HttpUrl] = None
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
class OrganizationCreate(OrganizationBase):
|
| 22 |
-
pass
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
class OrganizationRead(OrganizationBase):
|
| 26 |
-
id: UUID
|
| 27 |
-
verified: bool
|
| 28 |
-
created_at: datetime
|
| 29 |
-
|
| 30 |
-
model_config = ConfigDict(from_attributes=True)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# ─── Profile ────────────────────────────────────────────────────────────────
|
| 34 |
-
|
| 35 |
-
class ProfileBase(BaseModel):
|
| 36 |
-
full_name: Optional[str] = Field(None, max_length=255)
|
| 37 |
-
industry: Optional[str] = Field(None, max_length=100)
|
| 38 |
-
general_skills: List[str] = Field(default_factory=list)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
class ProfileCreate(ProfileBase):
|
| 42 |
-
email: EmailStr
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
class ProfileRead(ProfileBase):
|
| 46 |
-
id: UUID
|
| 47 |
-
status: str
|
| 48 |
-
email: Optional[EmailStr] = None
|
| 49 |
-
created_at: datetime
|
| 50 |
-
updated_at: datetime
|
| 51 |
-
|
| 52 |
-
model_config = ConfigDict(from_attributes=True)
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
class ProfilePublicRead(BaseModel):
|
| 56 |
-
id: UUID
|
| 57 |
-
full_name: Optional[str]
|
| 58 |
-
industry: Optional[str]
|
| 59 |
-
general_skills: List[str]
|
| 60 |
-
masked_email: Optional[str]
|
| 61 |
-
verified_credential_count: int
|
| 62 |
-
created_at: datetime
|
| 63 |
-
|
| 64 |
-
model_config = ConfigDict(from_attributes=True)
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
# ─── Career Record Payloads (Encrypted) ──────────────────────────────────────
|
| 68 |
-
|
| 69 |
-
class ExperiencePayload(BaseModel):
|
| 70 |
-
"""Internal details of an employment record (AES-256 encrypted in DB)."""
|
| 71 |
-
responsibilities: Optional[str] = None
|
| 72 |
-
achievements: Optional[List[str]] = None
|
| 73 |
-
tools_used: Optional[List[str]] = None
|
| 74 |
-
team_size: Optional[int] = None
|
| 75 |
-
department: Optional[str] = None
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
class CredentialPayload(BaseModel):
|
| 79 |
-
"""Internal details of a certification record (AES-256 encrypted in DB)."""
|
| 80 |
-
grade: Optional[str] = None
|
| 81 |
-
serial_number: Optional[str] = None
|
| 82 |
-
skills_verified: Optional[List[str]] = None
|
| 83 |
-
metadata: Optional[Dict[str, Any]] = None
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
# ─── Experience ─────────────────────────────────────────────────────────────
|
| 87 |
-
|
| 88 |
-
class ExperienceBase(BaseModel):
|
| 89 |
-
organization_id: UUID
|
| 90 |
-
start_date: date
|
| 91 |
-
end_date: Optional[date] = None
|
| 92 |
-
job_title: str = Field(..., min_length=1, max_length=150)
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
class ExperienceCreate(ExperienceBase):
|
| 96 |
-
payload: ExperiencePayload
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
class ExperienceUpdate(BaseModel):
|
| 100 |
-
start_date: Optional[date] = None
|
| 101 |
-
end_date: Optional[date] = None
|
| 102 |
-
job_title: Optional[str] = Field(None, max_length=150)
|
| 103 |
-
payload: Optional[ExperiencePayload] = None
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
class ExperienceRead(ExperienceBase):
|
| 107 |
-
id: UUID
|
| 108 |
-
profile_id: UUID
|
| 109 |
-
created_at: datetime
|
| 110 |
-
payload: ExperiencePayload # This should be populated after decryption
|
| 111 |
-
|
| 112 |
-
model_config = ConfigDict(from_attributes=True)
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
class ExperiencePublicRead(ExperienceBase):
|
| 116 |
-
id: UUID
|
| 117 |
-
profile_id: UUID
|
| 118 |
-
organization_name: Optional[str] = None # To be joined in the view/query
|
| 119 |
-
|
| 120 |
-
model_config = ConfigDict(from_attributes=True)
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
# ─── Credential ─────────────────────────────────────────────────────────────
|
| 124 |
-
|
| 125 |
-
class CredentialBase(BaseModel):
|
| 126 |
-
organization_id: UUID
|
| 127 |
-
issue_date: date
|
| 128 |
-
expiry_date: Optional[date] = None
|
| 129 |
-
credential_name: str = Field(..., min_length=1, max_length=150)
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
class CredentialCreate(CredentialBase):
|
| 133 |
-
payload: CredentialPayload
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
class CredentialRead(CredentialBase):
|
| 137 |
-
id: UUID
|
| 138 |
-
profile_id: UUID
|
| 139 |
-
issuer_signature: str
|
| 140 |
-
created_at: datetime
|
| 141 |
-
payload: CredentialPayload # This should be populated after decryption
|
| 142 |
-
|
| 143 |
-
model_config = ConfigDict(from_attributes=True)
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
class CredentialPublicRead(CredentialBase):
|
| 147 |
-
id: UUID
|
| 148 |
-
profile_id: UUID
|
| 149 |
-
organization_name: Optional[str] = None
|
| 150 |
-
is_verified: bool = False
|
| 151 |
-
|
| 152 |
-
model_config = ConfigDict(from_attributes=True)
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
# ─── Shares ─────────────────────────────────────────────────────────────────
|
| 156 |
-
|
| 157 |
-
class CredentialShareCreate(BaseModel):
|
| 158 |
-
credential_id: UUID
|
| 159 |
-
shared_with_profile_id: UUID
|
| 160 |
-
expires_at: Optional[datetime] = None
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
class CredentialShareRead(BaseModel):
|
| 164 |
-
id: UUID
|
| 165 |
-
credential_id: UUID
|
| 166 |
-
shared_with_profile_id: UUID
|
| 167 |
-
expires_at: Optional[datetime]
|
| 168 |
-
created_at: datetime
|
| 169 |
-
|
| 170 |
-
model_config = ConfigDict(from_attributes=True)
|
|
|
|
| 1 |
+
"""Career history Pydantic schemas — Profiles, Experiences, and Credentials.
|
| 2 |
+
|
| 3 |
+
Provides validation and serialization for lifelong career records.
|
| 4 |
+
Handles both public (masked) and private (decrypted) data views.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from datetime import date, datetime
|
| 8 |
+
from typing import Any, Dict, List, Optional
|
| 9 |
+
from uuid import UUID
|
| 10 |
+
|
| 11 |
+
from pydantic import BaseModel, ConfigDict, EmailStr, Field, HttpUrl
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# ─── Organization ────────────────────────────────────────────────────────────
|
| 15 |
+
|
| 16 |
+
class OrganizationBase(BaseModel):
|
| 17 |
+
name: str = Field(..., min_length=1, max_length=255)
|
| 18 |
+
website_url: Optional[HttpUrl] = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class OrganizationCreate(OrganizationBase):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class OrganizationRead(OrganizationBase):
|
| 26 |
+
id: UUID
|
| 27 |
+
verified: bool
|
| 28 |
+
created_at: datetime
|
| 29 |
+
|
| 30 |
+
model_config = ConfigDict(from_attributes=True)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# ─── Profile ────────────────────────────────────────────────────────────────
|
| 34 |
+
|
| 35 |
+
class ProfileBase(BaseModel):
|
| 36 |
+
full_name: Optional[str] = Field(None, max_length=255)
|
| 37 |
+
industry: Optional[str] = Field(None, max_length=100)
|
| 38 |
+
general_skills: List[str] = Field(default_factory=list)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ProfileCreate(ProfileBase):
|
| 42 |
+
email: EmailStr
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ProfileRead(ProfileBase):
|
| 46 |
+
id: UUID
|
| 47 |
+
status: str
|
| 48 |
+
email: Optional[EmailStr] = None
|
| 49 |
+
created_at: datetime
|
| 50 |
+
updated_at: datetime
|
| 51 |
+
|
| 52 |
+
model_config = ConfigDict(from_attributes=True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ProfilePublicRead(BaseModel):
|
| 56 |
+
id: UUID
|
| 57 |
+
full_name: Optional[str]
|
| 58 |
+
industry: Optional[str]
|
| 59 |
+
general_skills: List[str]
|
| 60 |
+
masked_email: Optional[str]
|
| 61 |
+
verified_credential_count: int
|
| 62 |
+
created_at: datetime
|
| 63 |
+
|
| 64 |
+
model_config = ConfigDict(from_attributes=True)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ─── Career Record Payloads (Encrypted) ──────────────────────────────────────
|
| 68 |
+
|
| 69 |
+
class ExperiencePayload(BaseModel):
|
| 70 |
+
"""Internal details of an employment record (AES-256 encrypted in DB)."""
|
| 71 |
+
responsibilities: Optional[str] = None
|
| 72 |
+
achievements: Optional[List[str]] = None
|
| 73 |
+
tools_used: Optional[List[str]] = None
|
| 74 |
+
team_size: Optional[int] = None
|
| 75 |
+
department: Optional[str] = None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class CredentialPayload(BaseModel):
|
| 79 |
+
"""Internal details of a certification record (AES-256 encrypted in DB)."""
|
| 80 |
+
grade: Optional[str] = None
|
| 81 |
+
serial_number: Optional[str] = None
|
| 82 |
+
skills_verified: Optional[List[str]] = None
|
| 83 |
+
metadata: Optional[Dict[str, Any]] = None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# ─── Experience ─────────────────────────────────────────────────────────────
|
| 87 |
+
|
| 88 |
+
class ExperienceBase(BaseModel):
|
| 89 |
+
organization_id: UUID
|
| 90 |
+
start_date: date
|
| 91 |
+
end_date: Optional[date] = None
|
| 92 |
+
job_title: str = Field(..., min_length=1, max_length=150)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class ExperienceCreate(ExperienceBase):
|
| 96 |
+
payload: ExperiencePayload
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class ExperienceUpdate(BaseModel):
|
| 100 |
+
start_date: Optional[date] = None
|
| 101 |
+
end_date: Optional[date] = None
|
| 102 |
+
job_title: Optional[str] = Field(None, max_length=150)
|
| 103 |
+
payload: Optional[ExperiencePayload] = None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class ExperienceRead(ExperienceBase):
|
| 107 |
+
id: UUID
|
| 108 |
+
profile_id: UUID
|
| 109 |
+
created_at: datetime
|
| 110 |
+
payload: ExperiencePayload # This should be populated after decryption
|
| 111 |
+
|
| 112 |
+
model_config = ConfigDict(from_attributes=True)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class ExperiencePublicRead(ExperienceBase):
|
| 116 |
+
id: UUID
|
| 117 |
+
profile_id: UUID
|
| 118 |
+
organization_name: Optional[str] = None # To be joined in the view/query
|
| 119 |
+
|
| 120 |
+
model_config = ConfigDict(from_attributes=True)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# ─── Credential ─────────────────────────────────────────────────────────────
|
| 124 |
+
|
| 125 |
+
class CredentialBase(BaseModel):
|
| 126 |
+
organization_id: UUID
|
| 127 |
+
issue_date: date
|
| 128 |
+
expiry_date: Optional[date] = None
|
| 129 |
+
credential_name: str = Field(..., min_length=1, max_length=150)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class CredentialCreate(CredentialBase):
|
| 133 |
+
payload: CredentialPayload
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class CredentialRead(CredentialBase):
|
| 137 |
+
id: UUID
|
| 138 |
+
profile_id: UUID
|
| 139 |
+
issuer_signature: str
|
| 140 |
+
created_at: datetime
|
| 141 |
+
payload: CredentialPayload # This should be populated after decryption
|
| 142 |
+
|
| 143 |
+
model_config = ConfigDict(from_attributes=True)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class CredentialPublicRead(CredentialBase):
|
| 147 |
+
id: UUID
|
| 148 |
+
profile_id: UUID
|
| 149 |
+
organization_name: Optional[str] = None
|
| 150 |
+
is_verified: bool = False
|
| 151 |
+
|
| 152 |
+
model_config = ConfigDict(from_attributes=True)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# ─── Shares ─────────────────────────────────────────────────────────────────
|
| 156 |
+
|
| 157 |
+
class CredentialShareCreate(BaseModel):
|
| 158 |
+
credential_id: UUID
|
| 159 |
+
shared_with_profile_id: UUID
|
| 160 |
+
expires_at: Optional[datetime] = None
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class CredentialShareRead(BaseModel):
|
| 164 |
+
id: UUID
|
| 165 |
+
credential_id: UUID
|
| 166 |
+
shared_with_profile_id: UUID
|
| 167 |
+
expires_at: Optional[datetime]
|
| 168 |
+
created_at: datetime
|
| 169 |
+
|
| 170 |
+
model_config = ConfigDict(from_attributes=True)
|
app/schemas/interview.py
CHANGED
|
@@ -1,117 +1,117 @@
|
|
| 1 |
-
"""Interview & AI Notulen Pydantic schemas.
|
| 2 |
-
|
| 3 |
-
Business model:
|
| 4 |
-
- Schedule interview costs 5 coins (Enterprise = free)
|
| 5 |
-
- AI Notulen generates meeting summaries
|
| 6 |
-
- Competency analysis via Gemini MEDIUM tier
|
| 7 |
-
- Multi-candidate comparison via Gemini HIGH tier
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
from datetime import datetime
|
| 11 |
-
from typing import Any, Dict, List, Optional
|
| 12 |
-
|
| 13 |
-
from pydantic import BaseModel, Field
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
class ScheduleInterviewRequest(BaseModel):
|
| 17 |
-
candidate_id: str = Field(..., description="Talent ID to interview")
|
| 18 |
-
scheduled_time: str = Field(..., description="ISO datetime string for interview time")
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
class ScheduleInterviewResponse(BaseModel):
|
| 22 |
-
success: bool = True
|
| 23 |
-
interview_id: str = ""
|
| 24 |
-
candidate_name: str = ""
|
| 25 |
-
candidate_id: str = ""
|
| 26 |
-
scheduled_time: Optional[str] = None
|
| 27 |
-
credits_deducted: int = 0
|
| 28 |
-
credits_remaining: int = 0
|
| 29 |
-
message: str = ""
|
| 30 |
-
error: Optional[str] = None
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
class SaveTranscriptRequest(BaseModel):
|
| 34 |
-
transcript_text: str = Field(..., min_length=10, max_length=50000)
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
class SaveTranscriptResponse(BaseModel):
|
| 38 |
-
success: bool = True
|
| 39 |
-
interview_id: str = ""
|
| 40 |
-
message: str = ""
|
| 41 |
-
error: Optional[str] = None
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
class NotulenResponse(BaseModel):
|
| 45 |
-
success: bool = True
|
| 46 |
-
interview_id: str = ""
|
| 47 |
-
summary: str = ""
|
| 48 |
-
ai_used: bool = False
|
| 49 |
-
error: Optional[str] = None
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
class CompetencyItem(BaseModel):
|
| 53 |
-
name: str = ""
|
| 54 |
-
score: int = 0
|
| 55 |
-
notes: str = ""
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
class CompetencyAnalysisResponse(BaseModel):
|
| 59 |
-
success: bool = True
|
| 60 |
-
interview_id: str = ""
|
| 61 |
-
overall_score: int = 0
|
| 62 |
-
competencies: List[CompetencyItem] = Field(default_factory=list)
|
| 63 |
-
strengths: str = ""
|
| 64 |
-
weaknesses: str = ""
|
| 65 |
-
recommendation: str = ""
|
| 66 |
-
ai_used: bool = False
|
| 67 |
-
error: Optional[str] = None
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
class CandidateComparisonItem(BaseModel):
|
| 71 |
-
candidate_id: str = ""
|
| 72 |
-
candidate_name: str = ""
|
| 73 |
-
overall_score: int = 0
|
| 74 |
-
competency_scores: Dict[str, int] = Field(default_factory=dict)
|
| 75 |
-
strengths: str = ""
|
| 76 |
-
weaknesses: str = ""
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
class ComparisonRequest(BaseModel):
|
| 80 |
-
interview_ids: List[str] = Field(..., min_length=2, max_length=10)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
class ComparisonResponse(BaseModel):
|
| 84 |
-
success: bool = True
|
| 85 |
-
candidates: List[CandidateComparisonItem] = Field(default_factory=list)
|
| 86 |
-
recommendation: str = ""
|
| 87 |
-
matrix_summary: str = ""
|
| 88 |
-
ai_used: bool = False
|
| 89 |
-
error: Optional[str] = None
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
class InterviewItem(BaseModel):
|
| 93 |
-
interview_id: str = ""
|
| 94 |
-
candidate_id: str = ""
|
| 95 |
-
candidate_name: str = ""
|
| 96 |
-
scheduled_time: Optional[str] = None
|
| 97 |
-
status: str = "Scheduled"
|
| 98 |
-
has_transcript: bool = False
|
| 99 |
-
has_ai_summary: bool = False
|
| 100 |
-
competency_score: int = 0
|
| 101 |
-
created_at: Optional[str] = None
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
class InterviewDetailResponse(BaseModel):
|
| 105 |
-
success: bool = True
|
| 106 |
-
data: Optional[InterviewItem] = None
|
| 107 |
-
transcript: str = ""
|
| 108 |
-
ai_summary: str = ""
|
| 109 |
-
competency_analysis: Optional[Dict[str, Any]] = None
|
| 110 |
-
error: Optional[str] = None
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
class InterviewListResponse(BaseModel):
|
| 114 |
-
success: bool = True
|
| 115 |
-
data: List[InterviewItem] = Field(default_factory=list)
|
| 116 |
-
total: int = 0
|
| 117 |
-
error: Optional[str] = None
|
|
|
|
| 1 |
+
"""Interview & AI Notulen Pydantic schemas.
|
| 2 |
+
|
| 3 |
+
Business model:
|
| 4 |
+
- Schedule interview costs 5 coins (Enterprise = free)
|
| 5 |
+
- AI Notulen generates meeting summaries
|
| 6 |
+
- Competency analysis via Gemini MEDIUM tier
|
| 7 |
+
- Multi-candidate comparison via Gemini HIGH tier
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from typing import Any, Dict, List, Optional
|
| 12 |
+
|
| 13 |
+
from pydantic import BaseModel, Field
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ScheduleInterviewRequest(BaseModel):
|
| 17 |
+
candidate_id: str = Field(..., description="Talent ID to interview")
|
| 18 |
+
scheduled_time: str = Field(..., description="ISO datetime string for interview time")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ScheduleInterviewResponse(BaseModel):
|
| 22 |
+
success: bool = True
|
| 23 |
+
interview_id: str = ""
|
| 24 |
+
candidate_name: str = ""
|
| 25 |
+
candidate_id: str = ""
|
| 26 |
+
scheduled_time: Optional[str] = None
|
| 27 |
+
credits_deducted: int = 0
|
| 28 |
+
credits_remaining: int = 0
|
| 29 |
+
message: str = ""
|
| 30 |
+
error: Optional[str] = None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class SaveTranscriptRequest(BaseModel):
|
| 34 |
+
transcript_text: str = Field(..., min_length=10, max_length=50000)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class SaveTranscriptResponse(BaseModel):
|
| 38 |
+
success: bool = True
|
| 39 |
+
interview_id: str = ""
|
| 40 |
+
message: str = ""
|
| 41 |
+
error: Optional[str] = None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class NotulenResponse(BaseModel):
|
| 45 |
+
success: bool = True
|
| 46 |
+
interview_id: str = ""
|
| 47 |
+
summary: str = ""
|
| 48 |
+
ai_used: bool = False
|
| 49 |
+
error: Optional[str] = None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class CompetencyItem(BaseModel):
|
| 53 |
+
name: str = ""
|
| 54 |
+
score: int = 0
|
| 55 |
+
notes: str = ""
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class CompetencyAnalysisResponse(BaseModel):
|
| 59 |
+
success: bool = True
|
| 60 |
+
interview_id: str = ""
|
| 61 |
+
overall_score: int = 0
|
| 62 |
+
competencies: List[CompetencyItem] = Field(default_factory=list)
|
| 63 |
+
strengths: str = ""
|
| 64 |
+
weaknesses: str = ""
|
| 65 |
+
recommendation: str = ""
|
| 66 |
+
ai_used: bool = False
|
| 67 |
+
error: Optional[str] = None
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class CandidateComparisonItem(BaseModel):
|
| 71 |
+
candidate_id: str = ""
|
| 72 |
+
candidate_name: str = ""
|
| 73 |
+
overall_score: int = 0
|
| 74 |
+
competency_scores: Dict[str, int] = Field(default_factory=dict)
|
| 75 |
+
strengths: str = ""
|
| 76 |
+
weaknesses: str = ""
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class ComparisonRequest(BaseModel):
|
| 80 |
+
interview_ids: List[str] = Field(..., min_length=2, max_length=10)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class ComparisonResponse(BaseModel):
|
| 84 |
+
success: bool = True
|
| 85 |
+
candidates: List[CandidateComparisonItem] = Field(default_factory=list)
|
| 86 |
+
recommendation: str = ""
|
| 87 |
+
matrix_summary: str = ""
|
| 88 |
+
ai_used: bool = False
|
| 89 |
+
error: Optional[str] = None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class InterviewItem(BaseModel):
|
| 93 |
+
interview_id: str = ""
|
| 94 |
+
candidate_id: str = ""
|
| 95 |
+
candidate_name: str = ""
|
| 96 |
+
scheduled_time: Optional[str] = None
|
| 97 |
+
status: str = "Scheduled"
|
| 98 |
+
has_transcript: bool = False
|
| 99 |
+
has_ai_summary: bool = False
|
| 100 |
+
competency_score: int = 0
|
| 101 |
+
created_at: Optional[str] = None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class InterviewDetailResponse(BaseModel):
|
| 105 |
+
success: bool = True
|
| 106 |
+
data: Optional[InterviewItem] = None
|
| 107 |
+
transcript: str = ""
|
| 108 |
+
ai_summary: str = ""
|
| 109 |
+
competency_analysis: Optional[Dict[str, Any]] = None
|
| 110 |
+
error: Optional[str] = None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class InterviewListResponse(BaseModel):
|
| 114 |
+
success: bool = True
|
| 115 |
+
data: List[InterviewItem] = Field(default_factory=list)
|
| 116 |
+
total: int = 0
|
| 117 |
+
error: Optional[str] = None
|
app/schemas/job.py
CHANGED
|
@@ -1,156 +1,156 @@
|
|
| 1 |
-
"""Job Pydantic schemas - Posting, Outreach, Compatibility, Vouchers."""
|
| 2 |
-
|
| 3 |
-
from datetime import datetime
|
| 4 |
-
from typing import Any, Dict, List, Optional
|
| 5 |
-
|
| 6 |
-
from pydantic import BaseModel, Field
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
# ─── Job Posting ────────────────────────────────────────────────────────────
|
| 10 |
-
|
| 11 |
-
class JobPostingResponse(BaseModel):
|
| 12 |
-
job_id: str = ""
|
| 13 |
-
title: str = ""
|
| 14 |
-
company_category: str = ""
|
| 15 |
-
location: str = ""
|
| 16 |
-
description: str = ""
|
| 17 |
-
required_skills: List[str] = Field(default_factory=list)
|
| 18 |
-
salary_range: str = "Negotiable"
|
| 19 |
-
source: str = ""
|
| 20 |
-
status: str = ""
|
| 21 |
-
sector_match: str = ""
|
| 22 |
-
linkedin_post_url: str = ""
|
| 23 |
-
timestamp: Optional[str] = None
|
| 24 |
-
posted_at: Optional[str] = None
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
class JobListResponse(BaseModel):
|
| 28 |
-
success: bool = True
|
| 29 |
-
page: int = 1
|
| 30 |
-
limit: int = 10
|
| 31 |
-
total: int = 0
|
| 32 |
-
data: List[JobPostingResponse] = Field(default_factory=list)
|
| 33 |
-
error: Optional[str] = None
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
class CreateJobRequest(BaseModel):
|
| 37 |
-
title: str = Field(..., min_length=3, max_length=255)
|
| 38 |
-
company_category: str = Field(..., max_length=255)
|
| 39 |
-
location: str = Field(..., max_length=255)
|
| 40 |
-
description: str = Field(..., min_length=20, max_length=10000)
|
| 41 |
-
required_skills: str = Field(..., description="Comma-separated skills")
|
| 42 |
-
salary_range: str = Field("Negotiable", max_length=100)
|
| 43 |
-
sector_match: str = Field("", max_length=255)
|
| 44 |
-
linkedin_post_url: str = Field("", max_length=500)
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
class UpdateJobStatusRequest(BaseModel):
|
| 48 |
-
job_id: str = Field(...)
|
| 49 |
-
status: str = Field(..., pattern='^(draft|posted|closed|archived)$')
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
# ─── Job Compatibility ──────────────────────────────────────────────────────
|
| 53 |
-
|
| 54 |
-
class AnalyzeCompatibilityRequest(BaseModel):
|
| 55 |
-
job_id: str = Field(...)
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
class SkillMatchItem(BaseModel):
|
| 59 |
-
skill: str = ""
|
| 60 |
-
status: str = "matched"
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
class CompatibilityResult(BaseModel):
|
| 64 |
-
matchScore: int = 0
|
| 65 |
-
matchedSkills: List[SkillMatchItem] = Field(default_factory=list)
|
| 66 |
-
gapSkills: List[SkillMatchItem] = Field(default_factory=list)
|
| 67 |
-
strategy: str = ""
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
class AnalyzeCompatibilityResponse(BaseModel):
|
| 71 |
-
success: bool = True
|
| 72 |
-
data: Optional[CompatibilityResult] = None
|
| 73 |
-
error: Optional[str] = None
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# ─── Job Limit ──────────────────────────────────────────────────────────────
|
| 77 |
-
|
| 78 |
-
class CheckJobLimitResponse(BaseModel):
|
| 79 |
-
allowed: bool = True
|
| 80 |
-
tier: str = "free"
|
| 81 |
-
active_count: int = 0
|
| 82 |
-
limit: int = 1
|
| 83 |
-
error: Optional[str] = None
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
# ─── Recruiter Outreach ─────────────────────────────────────────────────────
|
| 87 |
-
|
| 88 |
-
class OutreachRecordResponse(BaseModel):
|
| 89 |
-
success: bool = True
|
| 90 |
-
outreach_id: str = ""
|
| 91 |
-
error: Optional[str] = None
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
class SendOutreachRequest(BaseModel):
|
| 95 |
-
job_id: str = Field(...)
|
| 96 |
-
talent_email: str = Field(...)
|
| 97 |
-
match_score: int = Field(0, ge=0, le=100)
|
| 98 |
-
subject: str = Field(..., max_length=200)
|
| 99 |
-
body: str = Field(..., max_length=5000)
|
| 100 |
-
method: str = Field("email", pattern='^(email|whatsapp)$')
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
class SendOutreachResponse(BaseModel):
|
| 104 |
-
success: bool = True
|
| 105 |
-
outreach_id: str = ""
|
| 106 |
-
remaining: int = 0
|
| 107 |
-
error: Optional[str] = None
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
# ─── Voucher System ─────────────────────────────────────────────────────────
|
| 111 |
-
|
| 112 |
-
class VoucherItem(BaseModel):
|
| 113 |
-
voucher_id: str = ""
|
| 114 |
-
lpk_id: str = ""
|
| 115 |
-
candidate_email: str = ""
|
| 116 |
-
status: str = "Available"
|
| 117 |
-
date_generated: Optional[str] = None
|
| 118 |
-
date_used: Optional[str] = None
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
class VoucherCounts(BaseModel):
|
| 122 |
-
Available: int = 0
|
| 123 |
-
Used: int = 0
|
| 124 |
-
Total: int = 0
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
class VoucherGenerateRequest(BaseModel):
|
| 128 |
-
lpk_id: str = Field(...)
|
| 129 |
-
quantity: int = Field(1, ge=1, le=100)
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
class VoucherGenerateResponse(BaseModel):
|
| 133 |
-
success: bool = True
|
| 134 |
-
message: str = ""
|
| 135 |
-
vouchers: List[str] = Field(default_factory=list)
|
| 136 |
-
count: int = 0
|
| 137 |
-
error: Optional[str] = None
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
class VoucherRedeemRequest(BaseModel):
|
| 141 |
-
voucher_code: str = Field(..., pattern='^BRG-LPK-[A-Z0-9]{8}$')
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
class VoucherRedeemResponse(BaseModel):
|
| 145 |
-
success: bool = True
|
| 146 |
-
message: str = ""
|
| 147 |
-
lpk_id: str = ""
|
| 148 |
-
voucher_code: str = ""
|
| 149 |
-
error: Optional[str] = None
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
class VoucherListResponse(BaseModel):
|
| 153 |
-
success: bool = True
|
| 154 |
-
vouchers: List[VoucherItem] = Field(default_factory=list)
|
| 155 |
-
counts: VoucherCounts = Field(default_factory=VoucherCounts)
|
| 156 |
-
error: Optional[str] = None
|
|
|
|
| 1 |
+
"""Job Pydantic schemas - Posting, Outreach, Compatibility, Vouchers."""
|
| 2 |
+
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from typing import Any, Dict, List, Optional
|
| 5 |
+
|
| 6 |
+
from pydantic import BaseModel, Field
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# ─── Job Posting ────────────────────────────────────────────────────────────
|
| 10 |
+
|
| 11 |
+
class JobPostingResponse(BaseModel):
|
| 12 |
+
job_id: str = ""
|
| 13 |
+
title: str = ""
|
| 14 |
+
company_category: str = ""
|
| 15 |
+
location: str = ""
|
| 16 |
+
description: str = ""
|
| 17 |
+
required_skills: List[str] = Field(default_factory=list)
|
| 18 |
+
salary_range: str = "Negotiable"
|
| 19 |
+
source: str = ""
|
| 20 |
+
status: str = ""
|
| 21 |
+
sector_match: str = ""
|
| 22 |
+
linkedin_post_url: str = ""
|
| 23 |
+
timestamp: Optional[str] = None
|
| 24 |
+
posted_at: Optional[str] = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class JobListResponse(BaseModel):
|
| 28 |
+
success: bool = True
|
| 29 |
+
page: int = 1
|
| 30 |
+
limit: int = 10
|
| 31 |
+
total: int = 0
|
| 32 |
+
data: List[JobPostingResponse] = Field(default_factory=list)
|
| 33 |
+
error: Optional[str] = None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CreateJobRequest(BaseModel):
|
| 37 |
+
title: str = Field(..., min_length=3, max_length=255)
|
| 38 |
+
company_category: str = Field(..., max_length=255)
|
| 39 |
+
location: str = Field(..., max_length=255)
|
| 40 |
+
description: str = Field(..., min_length=20, max_length=10000)
|
| 41 |
+
required_skills: str = Field(..., description="Comma-separated skills")
|
| 42 |
+
salary_range: str = Field("Negotiable", max_length=100)
|
| 43 |
+
sector_match: str = Field("", max_length=255)
|
| 44 |
+
linkedin_post_url: str = Field("", max_length=500)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class UpdateJobStatusRequest(BaseModel):
|
| 48 |
+
job_id: str = Field(...)
|
| 49 |
+
status: str = Field(..., pattern='^(draft|posted|closed|archived)$')
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ─── Job Compatibility ──────────────────────────────────────────────────────
|
| 53 |
+
|
| 54 |
+
class AnalyzeCompatibilityRequest(BaseModel):
|
| 55 |
+
job_id: str = Field(...)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class SkillMatchItem(BaseModel):
|
| 59 |
+
skill: str = ""
|
| 60 |
+
status: str = "matched"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class CompatibilityResult(BaseModel):
|
| 64 |
+
matchScore: int = 0
|
| 65 |
+
matchedSkills: List[SkillMatchItem] = Field(default_factory=list)
|
| 66 |
+
gapSkills: List[SkillMatchItem] = Field(default_factory=list)
|
| 67 |
+
strategy: str = ""
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class AnalyzeCompatibilityResponse(BaseModel):
|
| 71 |
+
success: bool = True
|
| 72 |
+
data: Optional[CompatibilityResult] = None
|
| 73 |
+
error: Optional[str] = None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# ─── Job Limit ──────────────────────────────────────────────────────────────
|
| 77 |
+
|
| 78 |
+
class CheckJobLimitResponse(BaseModel):
|
| 79 |
+
allowed: bool = True
|
| 80 |
+
tier: str = "free"
|
| 81 |
+
active_count: int = 0
|
| 82 |
+
limit: int = 1
|
| 83 |
+
error: Optional[str] = None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# ─── Recruiter Outreach ─────────────────────────────────────────────────────
|
| 87 |
+
|
| 88 |
+
class OutreachRecordResponse(BaseModel):
|
| 89 |
+
success: bool = True
|
| 90 |
+
outreach_id: str = ""
|
| 91 |
+
error: Optional[str] = None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class SendOutreachRequest(BaseModel):
|
| 95 |
+
job_id: str = Field(...)
|
| 96 |
+
talent_email: str = Field(...)
|
| 97 |
+
match_score: int = Field(0, ge=0, le=100)
|
| 98 |
+
subject: str = Field(..., max_length=200)
|
| 99 |
+
body: str = Field(..., max_length=5000)
|
| 100 |
+
method: str = Field("email", pattern='^(email|whatsapp)$')
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class SendOutreachResponse(BaseModel):
|
| 104 |
+
success: bool = True
|
| 105 |
+
outreach_id: str = ""
|
| 106 |
+
remaining: int = 0
|
| 107 |
+
error: Optional[str] = None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# ─── Voucher System ─────────────────────────────────────────────────────────
|
| 111 |
+
|
| 112 |
+
class VoucherItem(BaseModel):
|
| 113 |
+
voucher_id: str = ""
|
| 114 |
+
lpk_id: str = ""
|
| 115 |
+
candidate_email: str = ""
|
| 116 |
+
status: str = "Available"
|
| 117 |
+
date_generated: Optional[str] = None
|
| 118 |
+
date_used: Optional[str] = None
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class VoucherCounts(BaseModel):
|
| 122 |
+
Available: int = 0
|
| 123 |
+
Used: int = 0
|
| 124 |
+
Total: int = 0
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class VoucherGenerateRequest(BaseModel):
|
| 128 |
+
lpk_id: str = Field(...)
|
| 129 |
+
quantity: int = Field(1, ge=1, le=100)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class VoucherGenerateResponse(BaseModel):
|
| 133 |
+
success: bool = True
|
| 134 |
+
message: str = ""
|
| 135 |
+
vouchers: List[str] = Field(default_factory=list)
|
| 136 |
+
count: int = 0
|
| 137 |
+
error: Optional[str] = None
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class VoucherRedeemRequest(BaseModel):
|
| 141 |
+
voucher_code: str = Field(..., pattern='^BRG-LPK-[A-Z0-9]{8}$')
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class VoucherRedeemResponse(BaseModel):
|
| 145 |
+
success: bool = True
|
| 146 |
+
message: str = ""
|
| 147 |
+
lpk_id: str = ""
|
| 148 |
+
voucher_code: str = ""
|
| 149 |
+
error: Optional[str] = None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class VoucherListResponse(BaseModel):
|
| 153 |
+
success: bool = True
|
| 154 |
+
vouchers: List[VoucherItem] = Field(default_factory=list)
|
| 155 |
+
counts: VoucherCounts = Field(default_factory=VoucherCounts)
|
| 156 |
+
error: Optional[str] = None
|
app/services/academy_email_service.py
CHANGED
|
@@ -1,169 +1,170 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Academy Email Service — AI-powered essay feedback & email outreach.
|
| 3 |
-
|
| 4 |
-
Generates personalized feedback on academy essay answers using Gemini,
|
| 5 |
-
then sends it via email through the Apps Script deployment gateway.
|
| 6 |
-
|
| 7 |
-
Uses app.services.ai_service.call_gemini_json() instead of a private _call_gemini.
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
import os
|
| 11 |
-
import asyncio
|
| 12 |
-
from datetime import datetime
|
| 13 |
-
from zoneinfo import ZoneInfo
|
| 14 |
-
|
| 15 |
-
from loguru import logger
|
| 16 |
-
from sqlalchemy import func, select
|
| 17 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 18 |
-
|
| 19 |
-
from app.models.job import TalentAcademy
|
| 20 |
-
from app.services.ai_service import call_gemini_json
|
| 21 |
-
from app.services.email_service import email_service
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
class AcademyEmailService:
|
| 25 |
-
"""Generates AI feedback on academy essays and sends via email."""
|
| 26 |
-
|
| 27 |
-
def __init__(self):
|
| 28 |
-
self.tz = ZoneInfo(os.getenv("TIMEZONE", "Asia/Jakarta"))
|
| 29 |
-
|
| 30 |
-
async def generate_feedback(self, email, completed_modules, essay_answers):
|
| 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 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
<div style="
|
| 79 |
-
<
|
| 80 |
-
<
|
| 81 |
-
</
|
| 82 |
-
<div
|
| 83 |
-
<
|
| 84 |
-
<
|
| 85 |
-
<
|
| 86 |
-
<
|
| 87 |
-
</
|
| 88 |
-
<div
|
| 89 |
-
<
|
| 90 |
-
<
|
| 91 |
-
</
|
| 92 |
-
<div
|
| 93 |
-
<
|
| 94 |
-
<
|
| 95 |
-
</
|
| 96 |
-
<div
|
| 97 |
-
<
|
| 98 |
-
<
|
| 99 |
-
</
|
| 100 |
-
<
|
| 101 |
-
<
|
| 102 |
-
<
|
| 103 |
-
</
|
| 104 |
-
</div>
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
"
|
| 143 |
-
"
|
| 144 |
-
"
|
| 145 |
-
"
|
| 146 |
-
"
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
"
|
| 166 |
-
"
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Academy Email Service — AI-powered essay feedback & email outreach.
|
| 3 |
+
|
| 4 |
+
Generates personalized feedback on academy essay answers using Gemini,
|
| 5 |
+
then sends it via email through the Apps Script deployment gateway.
|
| 6 |
+
|
| 7 |
+
Uses app.services.ai_service.call_gemini_json() instead of a private _call_gemini.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
import asyncio
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from zoneinfo import ZoneInfo
|
| 14 |
+
|
| 15 |
+
from loguru import logger
|
| 16 |
+
from sqlalchemy import func, select
|
| 17 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 18 |
+
|
| 19 |
+
from app.models.job import TalentAcademy
|
| 20 |
+
from app.services.ai_service import call_gemini_json
|
| 21 |
+
from app.services.email_service import email_service
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class AcademyEmailService:
|
| 25 |
+
"""Generates AI feedback on academy essays and sends via email."""
|
| 26 |
+
|
| 27 |
+
def __init__(self):
|
| 28 |
+
self.tz = ZoneInfo(os.getenv("TIMEZONE", "Asia/Jakarta"))
|
| 29 |
+
|
| 30 |
+
async def generate_feedback(self, email, completed_modules, essay_answers):
|
| 31 |
+
# ... existing code ...
|
| 32 |
+
modules_str = ", ".join(completed_modules) if completed_modules else "Belum ada modul selesai"
|
| 33 |
+
|
| 34 |
+
prompt = f"""Kamu adalah Brigawan Academy Mentor — mentor karir hijau yang hangat dan profesional di Indonesia.
|
| 35 |
+
|
| 36 |
+
TUGAS: Berikan feedback personal atas jawaban essay talenta Akademi Brigawan.
|
| 37 |
+
|
| 38 |
+
DATA TALENT:
|
| 39 |
+
- Email: {email}
|
| 40 |
+
- Modul Selesai: {modules_str}
|
| 41 |
+
|
| 42 |
+
JAWABAN ESSAY TALENT:
|
| 43 |
+
{essay_answers if essay_answers else "Belum mengirimkan essay."}
|
| 44 |
+
|
| 45 |
+
INSTRUKSI:
|
| 46 |
+
1. Analisis jawaban essay dengan mendalam (kekuatan, area pengembangan)
|
| 47 |
+
2. Berikan 2-3 saran konkret untuk meningkatkan pemahaman mereka
|
| 48 |
+
3. Jika belum ada essay, berikan motivasi untuk memulai modul pertama
|
| 49 |
+
4. Bahasa Indonesia profesional dan hangat
|
| 50 |
+
|
| 51 |
+
Format JSON:
|
| 52 |
+
{{
|
| 53 |
+
"feedback_intro": "1-2 kalimat pembuka personal",
|
| 54 |
+
"strengths": "Apa yang sudah baik dari jawaban mereka",
|
| 55 |
+
"areas_for_improvement": "Area yang bisa dikembangkan",
|
| 56 |
+
"concrete_tips": ["saran 1", "saran 2", "saran 3"],
|
| 57 |
+
"next_steps": "Rekomendasi modul atau langkah selanjutnya",
|
| 58 |
+
"closing": "Kalimat penutup yang memotivasi"
|
| 59 |
+
}}
|
| 60 |
+
"""
|
| 61 |
+
return await call_gemini_json(prompt, temperature=0.4, max_output_tokens=2048)
|
| 62 |
+
|
| 63 |
+
async def send_feedback_email(self, recipient_email, feedback_data):
|
| 64 |
+
"""Send the feedback via python-native SMTP service."""
|
| 65 |
+
subject = "Umpan Balik Akademi Brigawan — Personalisasi AI"
|
| 66 |
+
|
| 67 |
+
intro = feedback_data.get("feedback_intro", "Halo,")
|
| 68 |
+
strengths = feedback_data.get("strengths", "")
|
| 69 |
+
areas = feedback_data.get("areas_for_improvement", "")
|
| 70 |
+
tips = feedback_data.get("concrete_tips", [])
|
| 71 |
+
next_steps = feedback_data.get("next_steps", "")
|
| 72 |
+
closing = feedback_data.get("closing", "Semangat terus!")
|
| 73 |
+
|
| 74 |
+
tips_html = ""
|
| 75 |
+
for t in tips:
|
| 76 |
+
tips_html += f"<li>{t}</li>"
|
| 77 |
+
|
| 78 |
+
body_html = f"""<div style="font-family: 'Segoe UI', Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 30px; background: #f9fafb; border-radius: 16px;">
|
| 79 |
+
<div style="background: linear-gradient(135deg, #059669, #10b981); padding: 30px; border-radius: 12px 12px 0 0; text-align: center;">
|
| 80 |
+
<h1 style="color: white; margin: 0; font-size: 24px;">🎓 Umpan Balik Akademi</h1>
|
| 81 |
+
<p style="color: #d1fae5; margin: 8px 0 0;">Brigawan AI — Personalisasi untuk Perjalanan Belajarmu</p>
|
| 82 |
+
</div>
|
| 83 |
+
<div style="background: white; padding: 30px; border-radius: 0 0 12px 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
|
| 84 |
+
<p style="font-size: 16px; color: #374151;">{intro}</p>
|
| 85 |
+
<div style="background: #ecfdf5; padding: 20px; border-radius: 8px; margin: 16px 0; border-left: 4px solid #10b981;">
|
| 86 |
+
<h3 style="color: #059669; margin: 0 0 8px;">✅ Kekuatan</h3>
|
| 87 |
+
<p style="color: #374151; margin: 0;">{strengths}</p>
|
| 88 |
+
</div>
|
| 89 |
+
<div style="background: #fffbeb; padding: 20px; border-radius: 8px; margin: 16px 0; border-left: 4px solid #f59e0b;">
|
| 90 |
+
<h3 style="color: #d97706; margin: 0 0 8px;">📈 Area Pengembangan</h3>
|
| 91 |
+
<p style="color: #374151; margin: 0;">{areas}</p>
|
| 92 |
+
</div>
|
| 93 |
+
<div style="background: #eff6ff; padding: 20px; border-radius: 8px; margin: 16px 0; border-left: 4px solid #3b82f6;">
|
| 94 |
+
<h3 style="color: #2563eb; margin: 0 0 8px;">💡 Saran Konkret</h3>
|
| 95 |
+
<ul style="color: #374151; margin: 0; padding-left: 20px;">{tips_html}</ul>
|
| 96 |
+
</div>
|
| 97 |
+
<div style="background: #f0f9ff; padding: 20px; border-radius: 8px; margin: 16px 0;">
|
| 98 |
+
<h3 style="color: #0284c7; margin: 0 0 8px;">🎯 Langkah Selanjutnya</h3>
|
| 99 |
+
<p style="color: #374151; margin: 0;">{next_steps}</p>
|
| 100 |
+
</div>
|
| 101 |
+
<p style="color: #6b7280; font-style: italic; text-align: center; margin-top: 24px;">{closing}</p>
|
| 102 |
+
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 24px 0;">
|
| 103 |
+
<p style="color: #9ca3af; font-size: 12px; text-align: center;">© Brigawan.id — Platform Karir Hijau Indonesia<br>Email ini dikirim secara otomatis oleh AI Academy Mentor.</p>
|
| 104 |
+
</div>
|
| 105 |
+
</div>"""
|
| 106 |
+
|
| 107 |
+
success = await asyncio.to_thread(
|
| 108 |
+
email_service.send_html_email, recipient_email, subject, body_html
|
| 109 |
+
)
|
| 110 |
+
if success:
|
| 111 |
+
return {"success": True, "message": "Email feedback terkirim"}
|
| 112 |
+
return {"success": False, "error": "Failed to send email via SMTP service"}
|
| 113 |
+
|
| 114 |
+
async def process_academy_feedback(self, db: AsyncSession, email: str):
|
| 115 |
+
"""Full pipeline: fetch academy data -> generate AI feedback -> send email."""
|
| 116 |
+
try:
|
| 117 |
+
e = email.lower().strip()
|
| 118 |
+
result = await db.execute(
|
| 119 |
+
select(TalentAcademy).where(func.lower(TalentAcademy.email) == e).limit(1)
|
| 120 |
+
)
|
| 121 |
+
acad = result.scalar_one_or_none()
|
| 122 |
+
if not acad:
|
| 123 |
+
return {"success": False, "error": "Data akademi tidak ditemukan"}
|
| 124 |
+
|
| 125 |
+
completed_modules = [m.strip() for m in (acad.completed_modules or "").split(",") if m.strip()]
|
| 126 |
+
essay_answers = acad.essay_answers or ""
|
| 127 |
+
|
| 128 |
+
if not completed_modules and not essay_answers:
|
| 129 |
+
return {"success": False, "error": "Belum ada aktivitas akademi"}
|
| 130 |
+
|
| 131 |
+
# Generate feedback
|
| 132 |
+
logger.info(f"[AcademyEmail] Generating feedback for {e}")
|
| 133 |
+
feedback = await self.generate_feedback(e, completed_modules, essay_answers)
|
| 134 |
+
if "error" in feedback:
|
| 135 |
+
return {"success": False, "error": feedback["error"]}
|
| 136 |
+
|
| 137 |
+
# Send email
|
| 138 |
+
logger.info(f"[AcademyEmail] Sending feedback to {e}")
|
| 139 |
+
send_result = await self.send_feedback_email(e, feedback)
|
| 140 |
+
|
| 141 |
+
return {
|
| 142 |
+
"success": send_result.get("success", False),
|
| 143 |
+
"email": e,
|
| 144 |
+
"modules_completed": len(completed_modules),
|
| 145 |
+
"feedback_generated": True,
|
| 146 |
+
"email_sent": send_result.get("success", False),
|
| 147 |
+
"error": send_result.get("error"),
|
| 148 |
+
}
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logger.error(f"[AcademyEmail] Error: {e}")
|
| 151 |
+
return {"success": False, "error": str(e)}
|
| 152 |
+
|
| 153 |
+
async def process_bulk_academy_feedback(self, db: AsyncSession, limit=20):
|
| 154 |
+
"""Process academy feedback for all talents with completed modules."""
|
| 155 |
+
try:
|
| 156 |
+
result = await db.execute(
|
| 157 |
+
select(TalentAcademy).limit(limit)
|
| 158 |
+
)
|
| 159 |
+
records = result.scalars().all()
|
| 160 |
+
results = []
|
| 161 |
+
for acad in records:
|
| 162 |
+
res = await self.process_academy_feedback(db, acad.email)
|
| 163 |
+
results.append(res)
|
| 164 |
+
return {
|
| 165 |
+
"success": True,
|
| 166 |
+
"total": len(records),
|
| 167 |
+
"results": results,
|
| 168 |
+
}
|
| 169 |
+
except Exception as e:
|
| 170 |
+
return {"success": False, "error": str(e)}
|
app/services/agent_activity_service.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent Activity Service — Tracking and Intervention Manager.
|
| 2 |
+
|
| 3 |
+
Provides the database tracking logic for the Interactive Command Center,
|
| 4 |
+
allowing tasks to be monitored and paused for Board intervention.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import uuid
|
| 8 |
+
import asyncio
|
| 9 |
+
from typing import Dict, Any, Optional
|
| 10 |
+
from loguru import logger
|
| 11 |
+
from sqlalchemy import text
|
| 12 |
+
from app.database import get_db_session
|
| 13 |
+
|
| 14 |
+
class AgentActivityService:
|
| 15 |
+
"""Manages the lifecycle and state of agent tasks in the database."""
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
async def log_activity(cls, agent_id: str, task: str) -> str:
|
| 19 |
+
"""Creates a new activity log and returns its ID."""
|
| 20 |
+
activity_id = str(uuid.uuid4())
|
| 21 |
+
try:
|
| 22 |
+
async for db in get_db_session():
|
| 23 |
+
query = text("""
|
| 24 |
+
INSERT INTO agent_activities (id, agent_id, task_description, status)
|
| 25 |
+
VALUES (:id, :agent_id, :task, 'IN_PROGRESS')
|
| 26 |
+
""")
|
| 27 |
+
await db.execute(query, {"id": activity_id, "agent_id": agent_id, "task": task})
|
| 28 |
+
await db.commit()
|
| 29 |
+
break
|
| 30 |
+
except Exception as e:
|
| 31 |
+
logger.error(f"[ActivityLog] Failed to log start for {agent_id}: {e}")
|
| 32 |
+
return activity_id
|
| 33 |
+
|
| 34 |
+
@classmethod
|
| 35 |
+
async def update_status(cls, activity_id: str, status: str, payload: Optional[Dict] = None, next_action: str = None):
|
| 36 |
+
"""Updates the status of an ongoing activity."""
|
| 37 |
+
try:
|
| 38 |
+
async for db in get_db_session():
|
| 39 |
+
import json
|
| 40 |
+
query = text("""
|
| 41 |
+
UPDATE agent_activities
|
| 42 |
+
SET status = :status,
|
| 43 |
+
result_payload = :payload,
|
| 44 |
+
next_action = :next_action,
|
| 45 |
+
updated_at = NOW()
|
| 46 |
+
WHERE id = :id
|
| 47 |
+
""")
|
| 48 |
+
await db.execute(query, {
|
| 49 |
+
"id": activity_id,
|
| 50 |
+
"status": status,
|
| 51 |
+
"payload": json.dumps(payload) if payload else None,
|
| 52 |
+
"next_action": next_action
|
| 53 |
+
})
|
| 54 |
+
await db.commit()
|
| 55 |
+
break
|
| 56 |
+
except Exception as e:
|
| 57 |
+
logger.error(f"[ActivityLog] Failed to update {activity_id}: {e}")
|
| 58 |
+
|
| 59 |
+
@classmethod
|
| 60 |
+
async def request_intervention(cls, activity_id: str, agent_id: str, issue: str, telegram_msg: str):
|
| 61 |
+
"""Pauses a workflow and sends a ping to the Board."""
|
| 62 |
+
logger.warning(f"[Intervention] Agent {agent_id} requesting Board intervention: {issue}")
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
async for db in get_db_session():
|
| 66 |
+
query = text("""
|
| 67 |
+
UPDATE agent_activities
|
| 68 |
+
SET status = 'BLOCKED',
|
| 69 |
+
requires_intervention = TRUE,
|
| 70 |
+
intervention_type = 'APPROVAL_REQUIRED',
|
| 71 |
+
next_action = :issue,
|
| 72 |
+
updated_at = NOW()
|
| 73 |
+
WHERE id = :id
|
| 74 |
+
""")
|
| 75 |
+
await db.execute(query, {"id": activity_id, "issue": issue})
|
| 76 |
+
await db.commit()
|
| 77 |
+
break
|
| 78 |
+
|
| 79 |
+
# Send Notification to Telegram
|
| 80 |
+
from app.services.telegram_ceo_service import telegram_service
|
| 81 |
+
# We wrap the message with instructions on how to reply
|
| 82 |
+
full_msg = f"⚠️ *INTERVENTION REQUIRED*\n\nAgent: `{agent_id}`\nIssue: {issue}\n\n{telegram_msg}\n\nReply with `/approve {activity_id[:8]}` or `/reject {activity_id[:8]}`."
|
| 83 |
+
await telegram_service.send_ceo_message(full_msg)
|
| 84 |
+
|
| 85 |
+
except Exception as e:
|
| 86 |
+
logger.error(f"[Intervention] Failed to request intervention: {e}")
|
| 87 |
+
|
| 88 |
+
@classmethod
|
| 89 |
+
async def wait_for_approval(cls, activity_id: str, timeout_seconds: int = 3600) -> bool:
|
| 90 |
+
"""Polls the database waiting for the Board to change status to APPROVED."""
|
| 91 |
+
logger.info(f"[Intervention] Waiting for Board approval on {activity_id}...")
|
| 92 |
+
|
| 93 |
+
waited = 0
|
| 94 |
+
while waited < timeout_seconds:
|
| 95 |
+
try:
|
| 96 |
+
async for db in get_db_session():
|
| 97 |
+
query = text("SELECT status FROM agent_activities WHERE id = :id")
|
| 98 |
+
res = await db.execute(query, {"id": activity_id})
|
| 99 |
+
row = res.fetchone()
|
| 100 |
+
if row:
|
| 101 |
+
status = row[0]
|
| 102 |
+
if status == 'APPROVED':
|
| 103 |
+
logger.success(f"[Intervention] Board APPROVED {activity_id}. Resuming...")
|
| 104 |
+
return True
|
| 105 |
+
elif status in ('REJECTED', 'FAILED'):
|
| 106 |
+
logger.warning(f"[Intervention] Board REJECTED {activity_id}. Halting.")
|
| 107 |
+
return False
|
| 108 |
+
break
|
| 109 |
+
except Exception:
|
| 110 |
+
pass
|
| 111 |
+
|
| 112 |
+
await asyncio.sleep(10) # Poll every 10 seconds
|
| 113 |
+
waited += 10
|
| 114 |
+
|
| 115 |
+
logger.error(f"[Intervention] Timed out waiting for Board approval on {activity_id}.")
|
| 116 |
+
return False
|
app/services/agent_memory_service.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent Memory Service — Obsidian-like Vector RAG Memory.
|
| 2 |
+
|
| 3 |
+
This service implements the "Second Brain" for the AI Organization.
|
| 4 |
+
Instead of saving to a flat JSON file, it generates mathematical vectors (embeddings)
|
| 5 |
+
for every lesson learned and stores them in Supabase (pgvector).
|
| 6 |
+
When an agent needs context, it retrieves only the semantically relevant memories.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import List
|
| 10 |
+
import uuid
|
| 11 |
+
from loguru import logger
|
| 12 |
+
from sqlalchemy import text
|
| 13 |
+
from app.database import AsyncSessionLocal
|
| 14 |
+
from app.services.ai_service import generate_embedding
|
| 15 |
+
|
| 16 |
+
class AgentMemoryService:
|
| 17 |
+
"""Manages vector-based long-term memory for agents using pgvector."""
|
| 18 |
+
|
| 19 |
+
@classmethod
|
| 20 |
+
async def store_learning(cls, agent_id: str, task_context: str, outcome: str, is_success: bool, key_takeaway: str):
|
| 21 |
+
"""Embeds and stores a new learning experience in the database."""
|
| 22 |
+
logger.info(f"[ObsidianMemory] Storing new memory for {agent_id}...")
|
| 23 |
+
|
| 24 |
+
# 1. Prepare the memory content
|
| 25 |
+
icon = "✅ SUCCESS" if is_success else "❌ FAILURE"
|
| 26 |
+
memory_text = f"[{icon}] Task: {task_context}. Outcome: {outcome}. Key Takeaway: {key_takeaway}"
|
| 27 |
+
|
| 28 |
+
# 2. Generate Embedding Vector (768 dimensions)
|
| 29 |
+
embedding = await generate_embedding(memory_text)
|
| 30 |
+
|
| 31 |
+
if sum(embedding) == 0.0:
|
| 32 |
+
logger.warning("[ObsidianMemory] Embedding generation failed. Skipping memory save.")
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
# 3. Save to Supabase via SQLAlchemy
|
| 36 |
+
try:
|
| 37 |
+
async with AsyncSessionLocal() as db:
|
| 38 |
+
query = text("""
|
| 39 |
+
INSERT INTO agent_memories (id, agent_id, content, embedding, task_context, success)
|
| 40 |
+
VALUES (:id, :agent_id, :content, :embedding, :task_context, :success)
|
| 41 |
+
""")
|
| 42 |
+
await db.execute(query, {
|
| 43 |
+
"id": str(uuid.uuid4()),
|
| 44 |
+
"agent_id": agent_id,
|
| 45 |
+
"content": memory_text,
|
| 46 |
+
"embedding": str(embedding), # pgvector accepts string representation of list
|
| 47 |
+
"task_context": task_context[:500],
|
| 48 |
+
"success": is_success
|
| 49 |
+
})
|
| 50 |
+
await db.commit()
|
| 51 |
+
logger.success(f"[ObsidianMemory] Memory successfully crystallized for {agent_id}.")
|
| 52 |
+
except Exception as e:
|
| 53 |
+
logger.error(f"[ObsidianMemory] Database insertion failed: {e}")
|
| 54 |
+
|
| 55 |
+
@classmethod
|
| 56 |
+
async def get_learnings(cls, agent_id: str, current_task_prompt: str, limit: int = 3, query_embedding: List[float] = None) -> str:
|
| 57 |
+
"""Retrieves semantically relevant past learnings (RAG)."""
|
| 58 |
+
# If the task is empty, we can't do semantic search
|
| 59 |
+
if not current_task_prompt:
|
| 60 |
+
return ""
|
| 61 |
+
|
| 62 |
+
logger.debug(f"[ObsidianMemory] Searching Second Brain for {agent_id} relevant to current task...")
|
| 63 |
+
|
| 64 |
+
# 1. Embed the current task to find its math vector
|
| 65 |
+
if query_embedding is None:
|
| 66 |
+
query_embedding = await generate_embedding(current_task_prompt)
|
| 67 |
+
if sum(query_embedding) == 0.0:
|
| 68 |
+
return ""
|
| 69 |
+
|
| 70 |
+
# 2. Semantic Search (Cosine Distance) in Supabase
|
| 71 |
+
relevant_memories = []
|
| 72 |
+
try:
|
| 73 |
+
async with AsyncSessionLocal() as db:
|
| 74 |
+
# <=> is the pgvector operator for Cosine Distance. Lower is more similar.
|
| 75 |
+
query = text("""
|
| 76 |
+
SELECT content
|
| 77 |
+
FROM agent_memories
|
| 78 |
+
WHERE agent_id = :agent_id
|
| 79 |
+
ORDER BY embedding <=> :query_embedding
|
| 80 |
+
LIMIT :limit
|
| 81 |
+
""")
|
| 82 |
+
result = await db.execute(query, {
|
| 83 |
+
"agent_id": agent_id,
|
| 84 |
+
"query_embedding": str(query_embedding),
|
| 85 |
+
"limit": limit
|
| 86 |
+
})
|
| 87 |
+
|
| 88 |
+
rows = result.fetchall()
|
| 89 |
+
relevant_memories = [row[0] for row in rows]
|
| 90 |
+
except Exception as e:
|
| 91 |
+
logger.error(f"[ObsidianMemory] Semantic search failed: {e}")
|
| 92 |
+
return ""
|
| 93 |
+
|
| 94 |
+
# 3. Format the retrieved knowledge
|
| 95 |
+
if not relevant_memories:
|
| 96 |
+
return ""
|
| 97 |
+
|
| 98 |
+
learning_text = "PENGALAMAN & PEMBELAJARAN MASA LALU (SANGAT RELEVAN DENGAN TUGAS INI):\n"
|
| 99 |
+
for mem in relevant_memories:
|
| 100 |
+
learning_text += f"- {mem}\n"
|
| 101 |
+
|
| 102 |
+
return learning_text
|
app/services/agent_service.py
ADDED
|
@@ -0,0 +1,764 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent Organization Service — Defining the 74-Agent Hierarchy.
|
| 2 |
+
|
| 3 |
+
This service manages the system prompts, tiers, and roles for the full
|
| 4 |
+
Brigawan AI Agent Organization (C-Level, VP, Manager, Specialist, Tech).
|
| 5 |
+
|
| 6 |
+
FIX (2026-09): docstring previously said 68 — actual registry count is 74.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
from typing import Any, Dict, List, Optional
|
| 11 |
+
from app.services.ai_service import call_high, call_medium, call_low, call_gemini_json, generate_embedding
|
| 12 |
+
from app.services.agent_memory_service import AgentMemoryService
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# =============================================================================
|
| 16 |
+
# PER-AGENT TIER ROUTING (2026-09)
|
| 17 |
+
# =============================================================================
|
| 18 |
+
# Override tier untuk agent tertentu tanpa menyentuh definisi registry.
|
| 19 |
+
# Tier mapping ke provider (lihat ai_service.py TIERS + fallback chain):
|
| 20 |
+
# HIGH -> Gemini Pro key (free tier ~5 RPM / ~100 req/day — hemat utk strategis)
|
| 21 |
+
# MEDIUM -> Gemini Flash multi-key (kapasitas harian terbesar)
|
| 22 |
+
# LOW -> Gemini Flash light; Groq/OpenRouter :free menangani overflow
|
| 23 |
+
AGENT_TIER_OVERRIDES: Dict[str, str] = {
|
| 24 |
+
# Strategis & jarang dipanggil -> HIGH (kualitas maksimal)
|
| 25 |
+
"programmatic-seo-agent": "HIGH",
|
| 26 |
+
"competitor-spy-agent": "HIGH",
|
| 27 |
+
# JSON-heavy & sering dipanggil -> MEDIUM (lebih murah & cepat)
|
| 28 |
+
"test-writer": "MEDIUM",
|
| 29 |
+
"api-tester": "MEDIUM",
|
| 30 |
+
"seed-generator": "MEDIUM",
|
| 31 |
+
# Utility trivial -> LOW
|
| 32 |
+
"changelog-generator": "LOW",
|
| 33 |
+
"i18n-translator": "LOW",
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
# Runtime overrides via env (JSON): AGENT_TIER_OVERRIDES_JSON='{"ceo-agent":"MEDIUM"}'
|
| 37 |
+
_env_overrides_raw = os.getenv("AGENT_TIER_OVERRIDES_JSON", "")
|
| 38 |
+
if _env_overrides_raw:
|
| 39 |
+
try:
|
| 40 |
+
import json as _json
|
| 41 |
+
_parsed = _json.loads(_env_overrides_raw)
|
| 42 |
+
if isinstance(_parsed, dict):
|
| 43 |
+
AGENT_TIER_OVERRIDES.update({str(k): str(v).upper() for k, v in _parsed.items()})
|
| 44 |
+
except Exception:
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _resolve_tier(agent_id: str, default_tier: str) -> str:
|
| 49 |
+
"""Return the effective tier for an agent, honoring per-agent overrides."""
|
| 50 |
+
return AGENT_TIER_OVERRIDES.get(agent_id, default_tier).upper()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class AgentRegistry:
|
| 54 |
+
"""Registry of system prompts and configurations for all agents."""
|
| 55 |
+
|
| 56 |
+
AGENTS = {
|
| 57 |
+
# 🏛️ C-LEVEL (Level 1) - HIGH TIER
|
| 58 |
+
"ceo-agent": {
|
| 59 |
+
"tier": "HIGH",
|
| 60 |
+
"role": "Chief Executive Officer",
|
| 61 |
+
"prompt": (
|
| 62 |
+
"IDENTITAS: Anda adalah BUFFY, CEO & Orchestrator-in-Chief Brigawan AI Organization.\n"
|
| 63 |
+
"MISI: Menetapkan visi, strategi pertumbuhan, dan mengambil keputusan tingkat tinggi untuk portal green jobs Brigawan.\n"
|
| 64 |
+
"TANGGUNG JAWAB: Strategi bisnis, prioritas utama, persetujuan roadmap, dan delegasi ke jajaran C-Level & VP.\n"
|
| 65 |
+
"GAYA: Visioner, tegas, berwibawa, namun berorientasi pada data."
|
| 66 |
+
)
|
| 67 |
+
},
|
| 68 |
+
"cto-agent": {
|
| 69 |
+
"tier": "HIGH",
|
| 70 |
+
"role": "Chief Technology Officer",
|
| 71 |
+
"prompt": (
|
| 72 |
+
"IDENTITAS: Anda adalah CTO Brigawan AI Organization.\n"
|
| 73 |
+
"MISI: Menetapkan strategi teknologi, arsitektur sistem, dan inovasi teknis.\n"
|
| 74 |
+
"TANGGUNG JAWAB: Keputusan arsitektur, standar keamanan, skalabilitas, dan pengawasan pipeline engineering.\n"
|
| 75 |
+
"GAYA: Analitis, inovatif, fokus pada efisiensi dan keamanan."
|
| 76 |
+
)
|
| 77 |
+
},
|
| 78 |
+
"coo-agent": {
|
| 79 |
+
"tier": "HIGH",
|
| 80 |
+
"role": "Chief Operating Officer",
|
| 81 |
+
"prompt": (
|
| 82 |
+
"IDENTITAS: Anda adalah COO Brigawan AI Organization.\n"
|
| 83 |
+
"MISI: Mengoptimalkan resource allocation dan efisiensi operasional.\n"
|
| 84 |
+
"TANGGUNG JAWAB: Alokasi budget token, optimalisasi workflow, dan koordinasi antar departemen.\n"
|
| 85 |
+
"GAYA: Terperinci, efisien, berorientasi pada hasil."
|
| 86 |
+
)
|
| 87 |
+
},
|
| 88 |
+
"cmo-agent": {
|
| 89 |
+
"tier": "HIGH",
|
| 90 |
+
"role": "Chief Marketing Officer",
|
| 91 |
+
"prompt": (
|
| 92 |
+
"IDENTITAS: Anda adalah CMO Brigawan AI Organization.\n"
|
| 93 |
+
"MISI: Menetapkan strategi pemasaran dan brand positioning.\n"
|
| 94 |
+
"TANGGUNG JAWAB: Strategi SEO, kalender konten, kampanye marketing, dan riset pasar.\n"
|
| 95 |
+
"GAYA: Kreatif, strategis, persuasif."
|
| 96 |
+
)
|
| 97 |
+
},
|
| 98 |
+
"cfo-agent": {
|
| 99 |
+
"tier": "HIGH",
|
| 100 |
+
"role": "Chief Financial Officer",
|
| 101 |
+
"prompt": (
|
| 102 |
+
"IDENTITAS: Anda adalah CFO Brigawan AI Organization.\n"
|
| 103 |
+
"MISI: Mengelola anggaran dan optimalisasi biaya operasional AI (Token Economics).\n"
|
| 104 |
+
"TANGGUNG JAWAB: Analisis ROI, pemantauan pengeluaran token API, dan strategi penetapan harga.\n"
|
| 105 |
+
"GAYA: Kalkulatif, hemat, berpusat pada profitabilitas."
|
| 106 |
+
)
|
| 107 |
+
},
|
| 108 |
+
"cio-agent": {
|
| 109 |
+
"tier": "HIGH",
|
| 110 |
+
"role": "Chief Information Officer",
|
| 111 |
+
"prompt": (
|
| 112 |
+
"IDENTITAS: Anda adalah CIO Brigawan AI Organization.\n"
|
| 113 |
+
"MISI: Mengelola tata kelola data (Data Governance) dan intelijen bisnis.\n"
|
| 114 |
+
"TANGGUNG JAWAB: Strategi retensi data, arsitektur informasi, dan kolaborasi dengan Compliance Officer.\n"
|
| 115 |
+
"GAYA: Terstruktur, berpusat pada data, strategis."
|
| 116 |
+
)
|
| 117 |
+
},
|
| 118 |
+
|
| 119 |
+
# 👔 VP / DIRECTOR (Level 2) - MEDIUM TIER
|
| 120 |
+
"vp-engineering": {
|
| 121 |
+
"tier": "MEDIUM",
|
| 122 |
+
"role": "VP of Engineering",
|
| 123 |
+
"prompt": (
|
| 124 |
+
"IDENTITAS: Anda adalah VP of Engineering Brigawan.\n"
|
| 125 |
+
"MISI: Mengawasi pelaksanaan teknis dan kualitas kode di seluruh platform.\n"
|
| 126 |
+
"TANGGUNG JAWAB: Sprint planning, evaluasi audit kode, koordinasi frontend/backend, dan release management.\n"
|
| 127 |
+
"GAYA: Pragmatis, terorganisir, fokus pada pengiriman hasil (delivery)."
|
| 128 |
+
)
|
| 129 |
+
},
|
| 130 |
+
"vp-product": {
|
| 131 |
+
"tier": "MEDIUM",
|
| 132 |
+
"role": "VP of Product",
|
| 133 |
+
"prompt": (
|
| 134 |
+
"IDENTITAS: Anda adalah VP of Product Brigawan.\n"
|
| 135 |
+
"MISI: Menentukan roadmap produk dan prioritas fitur.\n"
|
| 136 |
+
"TANGGUNG JAWAB: Strategi roadmap, prioritasi fitur berdasarkan user impact, dan validasi ide produk.\n"
|
| 137 |
+
"GAYA: Berfokus pada data, visioner."
|
| 138 |
+
)
|
| 139 |
+
},
|
| 140 |
+
"vp-talent": {
|
| 141 |
+
"tier": "MEDIUM",
|
| 142 |
+
"role": "VP of Talent",
|
| 143 |
+
"prompt": (
|
| 144 |
+
"IDENTITAS: Anda adalah VP of Talent Brigawan.\n"
|
| 145 |
+
"MISI: Mengelola strategi akuisisi dan retensi talenta green jobs.\n"
|
| 146 |
+
"TANGGUNG JAWAB: Mengevaluasi kualitas talent database, strategi re-engagement, dan operasional HR.\n"
|
| 147 |
+
"GAYA: Empatis, strategis, berpusat pada manusia (people-centric)."
|
| 148 |
+
)
|
| 149 |
+
},
|
| 150 |
+
"vp-marketing": {
|
| 151 |
+
"tier": "MEDIUM",
|
| 152 |
+
"role": "VP of Marketing",
|
| 153 |
+
"prompt": (
|
| 154 |
+
"IDENTITAS: Anda adalah VP of Marketing Brigawan.\n"
|
| 155 |
+
"MISI: Merancang strategi kampanye pemasaran dan SEO.\n"
|
| 156 |
+
"TANGGUNG JAWAB: Mengelola eksekusi kalender konten, mengevaluasi target audiens, dan menganalisis performa kampanye.\n"
|
| 157 |
+
"GAYA: Kreatif, analitis, berorientasi target."
|
| 158 |
+
)
|
| 159 |
+
},
|
| 160 |
+
"vp-sales": {
|
| 161 |
+
"tier": "MEDIUM",
|
| 162 |
+
"role": "VP of Sales",
|
| 163 |
+
"prompt": (
|
| 164 |
+
"IDENTITAS: Anda adalah VP of Sales Brigawan.\n"
|
| 165 |
+
"MISI: Mengelola strategi pendapatan (revenue) dan pengembangan kemitraan B2B.\n"
|
| 166 |
+
"TANGGUNG JAWAB: Analisis conversion funnel, strategi penawaran talenta, dan manajemen hubungan klien.\n"
|
| 167 |
+
"GAYA: Persuasif, agresif dalam target, profesional."
|
| 168 |
+
)
|
| 169 |
+
},
|
| 170 |
+
|
| 171 |
+
# 📋 MANAGER (Level 3) - MEDIUM TIER
|
| 172 |
+
"product-manager": {
|
| 173 |
+
"tier": "MEDIUM",
|
| 174 |
+
"role": "Product Manager",
|
| 175 |
+
"prompt": (
|
| 176 |
+
"IDENTITAS: Anda adalah Product Manager Brigawan.\n"
|
| 177 |
+
"MISI: Menerjemahkan visi produk ke dalam fitur konkret dan backlog.\n"
|
| 178 |
+
"TANGGUNG JAWAB: Menulis user stories, prioritas backlog, koordinasi dengan Engineering Manager, dan validasi fitur.\n"
|
| 179 |
+
"GAYA: Berorientasi pada pengguna, kolaboratif."
|
| 180 |
+
)
|
| 181 |
+
},
|
| 182 |
+
"engineering-manager": {
|
| 183 |
+
"tier": "MEDIUM",
|
| 184 |
+
"role": "Engineering Manager",
|
| 185 |
+
"prompt": (
|
| 186 |
+
"IDENTITAS: Anda adalah Engineering Manager Brigawan.\n"
|
| 187 |
+
"MISI: Mengkoordinasikan tim teknis dan menjaga standar kode.\n"
|
| 188 |
+
"TANGGUNG JAWAB: Mengatur task assignment, mereview hasil code-fixer, dan memastikan sprint berjalan lancar.\n"
|
| 189 |
+
"GAYA: Teknis, sistematis, memecahkan masalah (problem-solver)."
|
| 190 |
+
)
|
| 191 |
+
},
|
| 192 |
+
"hr-manager": {
|
| 193 |
+
"tier": "MEDIUM",
|
| 194 |
+
"role": "HR Manager",
|
| 195 |
+
"prompt": (
|
| 196 |
+
"IDENTITAS: Anda adalah HR Manager Brigawan.\n"
|
| 197 |
+
"MISI: Mengelola pipeline rekrutmen dan interaksi talenta.\n"
|
| 198 |
+
"TANGGUNG JAWAB: Proses screening talenta, mengelola pesan re-engagement, dan memantau kepuasan talenta.\n"
|
| 199 |
+
"GAYA: Ramah, terstruktur, suportif."
|
| 200 |
+
)
|
| 201 |
+
},
|
| 202 |
+
"marketing-manager": {
|
| 203 |
+
"tier": "MEDIUM",
|
| 204 |
+
"role": "Marketing Manager",
|
| 205 |
+
"prompt": (
|
| 206 |
+
"IDENTITAS: Anda adalah Marketing Manager Brigawan.\n"
|
| 207 |
+
"MISI: Mengeksekusi kampanye pemasaran harian.\n"
|
| 208 |
+
"TANGGUNG JAWAB: Mengelola jadwal rilis konten, memantau engagement sosial media, dan berkoordinasi dengan agen pembuat konten.\n"
|
| 209 |
+
"GAYA: Gesit, kreatif, responsif terhadap tren."
|
| 210 |
+
)
|
| 211 |
+
},
|
| 212 |
+
"community-manager": {
|
| 213 |
+
"tier": "MEDIUM",
|
| 214 |
+
"role": "Community Manager",
|
| 215 |
+
"prompt": (
|
| 216 |
+
"IDENTITAS: Anda adalah Community Manager Brigawan.\n"
|
| 217 |
+
"MISI: Membangun dan menjaga interaksi positif di dalam komunitas talenta dan rekruter.\n"
|
| 218 |
+
"TANGGUNG JAWAB: Merespons feedback pengguna, mengelola program referral, dan menjaga sentimen positif brand.\n"
|
| 219 |
+
"GAYA: Ramah, empatik, komunikator ulung."
|
| 220 |
+
)
|
| 221 |
+
},
|
| 222 |
+
|
| 223 |
+
# 📊 BUSINESS SPECIALIST (Level 4) - MEDIUM TIER
|
| 224 |
+
"market-researcher": {
|
| 225 |
+
"tier": "MEDIUM",
|
| 226 |
+
"role": "Market Researcher",
|
| 227 |
+
"prompt": (
|
| 228 |
+
"IDENTITAS: Anda adalah Market Researcher Brigawan.\n"
|
| 229 |
+
"MISI: Menganalisis tren industri green jobs dan kompetitor.\n"
|
| 230 |
+
"TANGGUNG JAWAB: Riset tren pasar, analisis kompetitor, dan identifikasi peluang pasar baru.\n"
|
| 231 |
+
"GAYA: Penasaran, analitis, objektif."
|
| 232 |
+
)
|
| 233 |
+
},
|
| 234 |
+
"business-analyst": {
|
| 235 |
+
"tier": "MEDIUM",
|
| 236 |
+
"role": "Business Analyst",
|
| 237 |
+
"prompt": (
|
| 238 |
+
"IDENTITAS: Anda adalah Business Analyst Brigawan.\n"
|
| 239 |
+
"MISI: Mengoptimalkan proses bisnis dan menyusun kebutuhan sistem.\n"
|
| 240 |
+
"TANGGUNG JAWAB: Menganalisis bottleneck proses, menyusun Business Requirements Document (BRD), dan mengusulkan efisiensi.\n"
|
| 241 |
+
"GAYA: Logis, detail, berorientasi proses."
|
| 242 |
+
)
|
| 243 |
+
},
|
| 244 |
+
"data-analyst": {
|
| 245 |
+
"tier": "MEDIUM",
|
| 246 |
+
"role": "Data Analyst",
|
| 247 |
+
"prompt": (
|
| 248 |
+
"IDENTITAS: Anda adalah Data Analyst Brigawan.\n"
|
| 249 |
+
"MISI: Menghasilkan insight bisnis dari data mentah.\n"
|
| 250 |
+
"TANGGUNG JAWAB: Menganalisis pola pengguna, conversion funnel, mendeteksi anomali data, dan membuat laporan/dashboard.\n"
|
| 251 |
+
"GAYA: Berbasis data (data-driven), numerik, analitis."
|
| 252 |
+
)
|
| 253 |
+
},
|
| 254 |
+
"compliance-officer": {
|
| 255 |
+
"tier": "HIGH",
|
| 256 |
+
"role": "Compliance Officer",
|
| 257 |
+
"prompt": (
|
| 258 |
+
"IDENTITAS: Anda adalah Compliance Officer Brigawan.\n"
|
| 259 |
+
"MISI: Memastikan operasional Brigawan mematuhi regulasi privasi data (GDPR, UU ITE).\n"
|
| 260 |
+
"TANGGUNG JAWAB: Mengaudit penanganan data, mengamankan PII (Personally Identifiable Information), dan menyusun kebijakan privasi.\n"
|
| 261 |
+
"GAYA: Kaku pada aturan, protektif, detail."
|
| 262 |
+
)
|
| 263 |
+
},
|
| 264 |
+
"qa-manager": {
|
| 265 |
+
"tier": "MEDIUM",
|
| 266 |
+
"role": "QA Manager",
|
| 267 |
+
"prompt": (
|
| 268 |
+
"IDENTITAS: Anda adalah QA Manager Brigawan.\n"
|
| 269 |
+
"MISI: Menjaga standar kualitas (Quality Assurance) sebelum produk dirilis.\n"
|
| 270 |
+
"TANGGUNG JAWAB: Menetapkan acceptance criteria, mengevaluasi hasil test-runner, dan memberikan sign-off untuk rilis.\n"
|
| 271 |
+
"GAYA: Kritis, perfeksionis, tidak kenal kompromi terhadap kualitas."
|
| 272 |
+
)
|
| 273 |
+
},
|
| 274 |
+
"risk-manager": {
|
| 275 |
+
"tier": "MEDIUM",
|
| 276 |
+
"role": "Risk Manager",
|
| 277 |
+
"prompt": (
|
| 278 |
+
"IDENTITAS: Anda adalah Risk Manager Brigawan.\n"
|
| 279 |
+
"MISI: Mengidentifikasi dan memitigasi risiko bisnis maupun operasional.\n"
|
| 280 |
+
"TANGGUNG JAWAB: Menilai potensi masalah keamanan, stabilitas, atau regulasi sebelum menjadi krisis nyata.\n"
|
| 281 |
+
"GAYA: Antisipatif, analitis, penuh kehati-hatian."
|
| 282 |
+
)
|
| 283 |
+
},
|
| 284 |
+
"partnership-manager": {
|
| 285 |
+
"tier": "MEDIUM",
|
| 286 |
+
"role": "Partnership Manager & B2B Sales",
|
| 287 |
+
"prompt": (
|
| 288 |
+
"IDENTITAS: Anda adalah Partnership Manager Brigawan yang handal dalam B2B Sales.\n"
|
| 289 |
+
"MISI: Menjalin kerjasama dengan perusahaan (Employer) dan menjual layanan kurasi talenta Brigawan.\n"
|
| 290 |
+
"TANGGUNG JAWAB: Menulis cold email penawaran talenta yang sangat personal (hyper-personalized), menarik minat HRD/Recruiter, dan fokus pada konversi tanpa terkesan seperti spam bot.\n"
|
| 291 |
+
"GAYA: Profesional, persuasif, to-the-point, dan berorientasi nilai (value-driven)."
|
| 292 |
+
)
|
| 293 |
+
},
|
| 294 |
+
"customer-support": {
|
| 295 |
+
"tier": "MEDIUM",
|
| 296 |
+
"role": "Customer Support Specialist",
|
| 297 |
+
"prompt": (
|
| 298 |
+
"IDENTITAS: Anda adalah Customer Support Brigawan.\n"
|
| 299 |
+
"MISI: Memberikan bantuan kepada pengguna dan menjaga kepuasan pelanggan.\n"
|
| 300 |
+
"TANGGUNG JAWAB: Menangani keluhan, membuat FAQ, dan memberikan solusi bagi masalah pengguna.\n"
|
| 301 |
+
"GAYA: Empati, solutif, komunikatif."
|
| 302 |
+
)
|
| 303 |
+
},
|
| 304 |
+
"social-media-agent": {
|
| 305 |
+
"tier": "MEDIUM",
|
| 306 |
+
"role": "Social Media Manager",
|
| 307 |
+
"prompt": (
|
| 308 |
+
"IDENTITAS: Anda adalah Social Media Manager Brigawan.\n"
|
| 309 |
+
"MISI: Mengelola kehadiran Brigawan di Instagram, LinkedIn, dan TikTok.\n"
|
| 310 |
+
"TANGGUNG JAWAB: Membuat caption yang viral, menentukan jadwal posting, dan menyusun narasi untuk Reels/Carousel.\n"
|
| 311 |
+
"GAYA: Trendy, interaktif, dan informatif."
|
| 312 |
+
)
|
| 313 |
+
},
|
| 314 |
+
"fact-checker": {
|
| 315 |
+
"tier": "HIGH",
|
| 316 |
+
"role": "Content Editor & Fact Checker",
|
| 317 |
+
"prompt": (
|
| 318 |
+
"IDENTITAS: Anda adalah Editor-in-Chief dan Fact Checker Brigawan.\n"
|
| 319 |
+
"MISI: Memastikan semua konten yang diproduksi akurat, relevan, tidak bias, dan sesuai dengan standar brand green jobs Brigawan.\n"
|
| 320 |
+
"TANGGUNG JAWAB: Mengkurasi draf konten, memverifikasi klaim (greenwashing detection), memastikan ejaan yang benar, dan menyetujui (Approve) atau menolak (Reject) konten.\n"
|
| 321 |
+
"GAYA: Kritis, objektif, teliti."
|
| 322 |
+
)
|
| 323 |
+
},
|
| 324 |
+
"style-designer": {
|
| 325 |
+
"tier": "MEDIUM",
|
| 326 |
+
"role": "Visual Style Designer",
|
| 327 |
+
"prompt": (
|
| 328 |
+
"IDENTITAS: Anda adalah Visual Style Designer Brigawan.\n"
|
| 329 |
+
"MISI: Menentukan estetika visual konten Brigawan.\n"
|
| 330 |
+
"TANGGUNG JAWAB: Memberikan brief visual, menentukan skema warna, dan membuat prompt gambar (untuk Pollinations/Flux) yang estetik untuk slide Carousel atau aset Reels.\n"
|
| 331 |
+
"GAYA: Artistik, modern, minimalis."
|
| 332 |
+
)
|
| 333 |
+
},
|
| 334 |
+
|
| 335 |
+
# 🛠️ TECHNICAL AGENTS (Level 5) - LOW TIER
|
| 336 |
+
"code-auditor": {
|
| 337 |
+
"tier": "LOW",
|
| 338 |
+
"role": "Code Quality Auditor",
|
| 339 |
+
"prompt": (
|
| 340 |
+
"IDENTITAS: Anda adalah Code Auditor Brigawan.\n"
|
| 341 |
+
"MISI: Memastikan kualitas, kompleksitas, dan pemeliharaan kode (maintainability).\n"
|
| 342 |
+
"TANGGUNG JAWAB: Mengukur LOC, mendeteksi dead code, review naming convention, dan maintainability score.\n"
|
| 343 |
+
"GAYA: Detail, teknis, objektif."
|
| 344 |
+
)
|
| 345 |
+
},
|
| 346 |
+
"security-auditor": {
|
| 347 |
+
"tier": "LOW",
|
| 348 |
+
"role": "Security Auditor",
|
| 349 |
+
"prompt": (
|
| 350 |
+
"IDENTITAS: Anda adalah Security Auditor Brigawan.\n"
|
| 351 |
+
"MISI: Menjaga keamanan aplikasi dari kerentanan.\n"
|
| 352 |
+
"TANGGUNG JAWAB: Deteksi XSS, SQL Injection, audit otentikasi, dan pengecekan hardcoded secrets.\n"
|
| 353 |
+
"GAYA: Waspada, metodis."
|
| 354 |
+
)
|
| 355 |
+
},
|
| 356 |
+
"code-fixer": {
|
| 357 |
+
"tier": "LOW",
|
| 358 |
+
"role": "Code Fixer",
|
| 359 |
+
"prompt": (
|
| 360 |
+
"IDENTITAS: Anda adalah Code Fixer Brigawan.\n"
|
| 361 |
+
"MISI: Memperbaiki bug dan mengimplementasikan rekomendasi dari auditor.\n"
|
| 362 |
+
"TANGGUNG JAWAB: Menulis perbaikan kode berdasarkan file FIXES.md atau instruksi Error Handler tanpa merusak fungsi yang ada.\n"
|
| 363 |
+
"GAYA: Efisien, patuh pada standar kode."
|
| 364 |
+
)
|
| 365 |
+
},
|
| 366 |
+
"error-handler": {
|
| 367 |
+
"tier": "LOW",
|
| 368 |
+
"role": "Error Handler",
|
| 369 |
+
"prompt": (
|
| 370 |
+
"IDENTITAS: Anda adalah Error Handler Brigawan.\n"
|
| 371 |
+
"MISI: Menganalisis log error dan menentukan akar masalah (root cause).\n"
|
| 372 |
+
"TANGGUNG JAWAB: Membaca trace log, mengidentifikasi file dan baris yang bermasalah, serta memberikan instruksi perbaikan konkret untuk Code Fixer.\n"
|
| 373 |
+
"GAYA: Diagnostik, cepat, akurat."
|
| 374 |
+
)
|
| 375 |
+
},
|
| 376 |
+
"frontend-builder": {
|
| 377 |
+
"tier": "MEDIUM",
|
| 378 |
+
"role": "Frontend Developer Agent",
|
| 379 |
+
"prompt": (
|
| 380 |
+
"IDENTITAS: Anda adalah Frontend Builder Brigawan.\n"
|
| 381 |
+
"MISI: Membangun dan memelihara komponen UI (HTML/CSS/JS).\n"
|
| 382 |
+
"TANGGUNG JAWAB: Menulis kode frontend yang responsif, mengintegrasikan API backend, dan memastikan kompatibilitas browser.\n"
|
| 383 |
+
"GAYA: Praktis, berorientasi desain, rapi."
|
| 384 |
+
)
|
| 385 |
+
},
|
| 386 |
+
"backend-builder": {
|
| 387 |
+
"tier": "MEDIUM",
|
| 388 |
+
"role": "Backend Developer Agent",
|
| 389 |
+
"prompt": (
|
| 390 |
+
"IDENTITAS: Anda adalah Backend Builder Brigawan.\n"
|
| 391 |
+
"MISI: Membangun dan memelihara logika server, API, dan integrasi database (Python/FastAPI).\n"
|
| 392 |
+
"TANGGUNG JAWAB: Menulis kode backend yang efisien, aman, dan dapat diskalakan.\n"
|
| 393 |
+
"GAYA: Logis, arsitektural, aman."
|
| 394 |
+
)
|
| 395 |
+
},
|
| 396 |
+
"test-runner": {
|
| 397 |
+
"tier": "LOW",
|
| 398 |
+
"role": "Test Automation Agent",
|
| 399 |
+
"prompt": (
|
| 400 |
+
"IDENTITAS: Anda adalah Test Runner Brigawan.\n"
|
| 401 |
+
"MISI: Memvalidasi bahwa perubahan kode tidak merusak sistem.\n"
|
| 402 |
+
"TANGGUNG JAWAB: Mengeksekusi test suite, melaporkan hasil pass/fail, dan mengidentifikasi edge case yang belum teruji.\n"
|
| 403 |
+
"GAYA: Metodis, tanpa kompromi, detail."
|
| 404 |
+
)
|
| 405 |
+
},
|
| 406 |
+
"deploy-checker": {
|
| 407 |
+
"tier": "LOW",
|
| 408 |
+
"role": "Pre-Deployment Validator",
|
| 409 |
+
"prompt": (
|
| 410 |
+
"IDENTITAS: Anda adalah Deploy Checker Brigawan.\n"
|
| 411 |
+
"MISI: Memastikan semua komponen siap untuk dirilis ke production.\n"
|
| 412 |
+
"TANGGUNG JAWAB: Memvalidasi environment variables, mengecek konfigurasi server, dan memastikan tidak ada dead links sebelum deploy.\n"
|
| 413 |
+
"GAYA: Hati-hati, menyeluruh."
|
| 414 |
+
)
|
| 415 |
+
},
|
| 416 |
+
"pr-writer": {
|
| 417 |
+
"tier": "LOW",
|
| 418 |
+
"role": "Pull Request Generator",
|
| 419 |
+
"prompt": (
|
| 420 |
+
"IDENTITAS: Anda adalah PR Writer Brigawan.\n"
|
| 421 |
+
"MISI: Mendokumentasikan perubahan kode ke dalam bentuk changelog dan Pull Request.\n"
|
| 422 |
+
"TANGGUNG JAWAB: Menganalisis git diff, menyusun deskripsi perubahan yang jelas, dan men-tag reviewer yang relevan.\n"
|
| 423 |
+
"GAYA: Komunikatif, terstruktur, ringkas."
|
| 424 |
+
)
|
| 425 |
+
},
|
| 426 |
+
# 🛡️ AUDITORS (Level 5)
|
| 427 |
+
"bug-auditor": {
|
| 428 |
+
"tier": "LOW",
|
| 429 |
+
"role": "Runtime Bug Auditor",
|
| 430 |
+
"prompt": "IDENTITAS: Bug Auditor. TUGAS: Menganalisis potensi runtime error, edge cases, dan logic flaws di kode. Output format: AUDIT_BUGS.md"
|
| 431 |
+
},
|
| 432 |
+
"perf-auditor": {
|
| 433 |
+
"tier": "LOW",
|
| 434 |
+
"role": "Performance Auditor",
|
| 435 |
+
"prompt": "IDENTITAS: Performance Auditor. TUGAS: Mengevaluasi bundle size, memory leaks, dan render-blocking resources. Output format: AUDIT_PERF.md"
|
| 436 |
+
},
|
| 437 |
+
"db-auditor": {
|
| 438 |
+
"tier": "LOW",
|
| 439 |
+
"role": "Database Auditor",
|
| 440 |
+
"prompt": "IDENTITAS: Database Auditor. TUGAS: Menganalisis N+1 query, missing indexes, dan validasi skema. Output format: AUDIT_DB.md"
|
| 441 |
+
},
|
| 442 |
+
"dep-auditor": {
|
| 443 |
+
"tier": "LOW",
|
| 444 |
+
"role": "Dependency Auditor",
|
| 445 |
+
"prompt": "IDENTITAS: Dependency Auditor. TUGAS: Mendeteksi dependensi yang usang, rentan (vulnerable), atau tidak terpakai. Output format: AUDIT_DEPS.md"
|
| 446 |
+
},
|
| 447 |
+
"doc-auditor": {
|
| 448 |
+
"tier": "LOW",
|
| 449 |
+
"role": "Documentation Auditor",
|
| 450 |
+
"prompt": "IDENTITAS: Documentation Auditor. TUGAS: Memastikan kode memiliki komentar/JSDoc yang memadai dan mendeteksi stale docs. Output format: AUDIT_DOCS.md"
|
| 451 |
+
},
|
| 452 |
+
"infra-auditor": {
|
| 453 |
+
"tier": "LOW",
|
| 454 |
+
"role": "Infrastructure Auditor",
|
| 455 |
+
"prompt": "IDENTITAS: Infrastructure Auditor. TUGAS: Mengecek konfigurasi CI/CD, wrangler.json, Dockerfile, dan _redirects. Output format: AUDIT_INFRA.md"
|
| 456 |
+
},
|
| 457 |
+
"seo-auditor": {
|
| 458 |
+
"tier": "LOW",
|
| 459 |
+
"role": "SEO Auditor",
|
| 460 |
+
"prompt": "IDENTITAS: SEO Auditor. TUGAS: Memvalidasi meta tags, JSON-LD, OG tags, dan aksesibilitas robots.txt. Output format: AUDIT_SEO.md"
|
| 461 |
+
},
|
| 462 |
+
"ui-auditor": {
|
| 463 |
+
"tier": "LOW",
|
| 464 |
+
"role": "UI/UX & Accessibility Auditor",
|
| 465 |
+
"prompt": "IDENTITAS: UI/UX Auditor. TUGAS: Mengecek WCAG compliance, kontras warna, dan konsistensi pola desain. Output format: AUDIT_UI.md"
|
| 466 |
+
},
|
| 467 |
+
"architect-reviewer": {
|
| 468 |
+
"tier": "MEDIUM",
|
| 469 |
+
"role": "Architecture Reviewer",
|
| 470 |
+
"prompt": "IDENTITAS: Architect Reviewer. TUGAS: Mengulas keputusan desain tingkat tinggi, coupling antar modul, dan pattern. Bertindak sebagai penasihat untuk VP Engineering."
|
| 471 |
+
},
|
| 472 |
+
"api-tester": {
|
| 473 |
+
"tier": "LOW",
|
| 474 |
+
"role": "API Contract Tester",
|
| 475 |
+
"prompt": "IDENTITAS: API Tester. TUGAS: Memvalidasi endpoint REST, error handling, dan skema payload. Output format: AUDIT_API.md"
|
| 476 |
+
},
|
| 477 |
+
# 🧪 TESTERS (Level 5)
|
| 478 |
+
"test-writer": {
|
| 479 |
+
"tier": "LOW",
|
| 480 |
+
"role": "Unit Test Writer",
|
| 481 |
+
"prompt": "IDENTITAS: Test Writer. TUGAS: Menulis unit test untuk fungsi yang belum memiliki coverage. Pastikan pengujian mencakup edge cases."
|
| 482 |
+
},
|
| 483 |
+
"browser-qa-agent": {
|
| 484 |
+
"tier": "LOW",
|
| 485 |
+
"role": "E2E Browser QA",
|
| 486 |
+
"prompt": "IDENTITAS: Browser QA Agent. TUGAS: Mensimulasikan navigasi pengguna akhir dan interaksi form. Gunakan Playwright context."
|
| 487 |
+
},
|
| 488 |
+
"console-monitor": {
|
| 489 |
+
"tier": "LOW",
|
| 490 |
+
"role": "Console Error Monitor",
|
| 491 |
+
"prompt": "IDENTITAS: Console Monitor. TUGAS: Menganalisis log console browser untuk mendeteksi warning dan uncaught exceptions."
|
| 492 |
+
},
|
| 493 |
+
"visual-diff": {
|
| 494 |
+
"tier": "LOW",
|
| 495 |
+
"role": "Visual Regression Tester",
|
| 496 |
+
"prompt": "IDENTITAS: Visual Diff Agent. TUGAS: Membandingkan screenshot sebelum dan sesudah perubahan untuk memastikan tidak ada UI yang bergeser."
|
| 497 |
+
},
|
| 498 |
+
# ⚙️ OPERATIONS & BUILDERS
|
| 499 |
+
"fix-planner": {
|
| 500 |
+
"tier": "MEDIUM",
|
| 501 |
+
"role": "Fix Orchestrator",
|
| 502 |
+
"prompt": "IDENTITAS: Fix Planner. TUGAS: Menggabungkan laporan dari semua Auditor menjadi satu dokumen prioritas (FIXES.md) untuk dikerjakan Code Fixer."
|
| 503 |
+
},
|
| 504 |
+
"env-validator": {
|
| 505 |
+
"tier": "LOW",
|
| 506 |
+
"role": "Environment Validator",
|
| 507 |
+
"prompt": "IDENTITAS: Environment Validator. TUGAS: Mengecek .env vs .env.example untuk memastikan tidak ada rahasia yang bocor atau missing keys."
|
| 508 |
+
},
|
| 509 |
+
"seed-generator": {
|
| 510 |
+
"tier": "LOW",
|
| 511 |
+
"role": "Test Data Generator",
|
| 512 |
+
"prompt": "IDENTITAS: Seed Generator. TUGAS: Membuat data dummy yang sangat realistis untuk menguji database atau fungsi pencarian."
|
| 513 |
+
},
|
| 514 |
+
"fullstack-qa-orchestrator": {
|
| 515 |
+
"tier": "MEDIUM",
|
| 516 |
+
"role": "QA Pipeline Orchestrator",
|
| 517 |
+
"prompt": "IDENTITAS: QA Orchestrator. TUGAS: Mengatur siklus audit -> fix -> test. Memberikan persetujuan akhir sebelum kode dikirim ke PR."
|
| 518 |
+
},
|
| 519 |
+
"content-agent": {
|
| 520 |
+
"tier": "MEDIUM",
|
| 521 |
+
"role": "Blog Content Writer",
|
| 522 |
+
"prompt": "IDENTITAS: Content Agent. TUGAS: Menulis artikel panjang (blog) yang SEO-friendly, berbasis riset, dan engaging."
|
| 523 |
+
},
|
| 524 |
+
"system-monitor": {
|
| 525 |
+
"tier": "LOW",
|
| 526 |
+
"role": "System Health Monitor",
|
| 527 |
+
"prompt": "IDENTITAS: System Monitor. TUGAS: Mengecek endpoint kesehatan sistem secara periodik dan melaporkan jika ada downtime."
|
| 528 |
+
},
|
| 529 |
+
"talent-engagement": {
|
| 530 |
+
"tier": "MEDIUM",
|
| 531 |
+
"role": "Talent Re-engagement Bot",
|
| 532 |
+
"prompt": "IDENTITAS: Talent Engagement. TUGAS: Menulis pesan empati untuk talenta yang sudah tidak aktif (dormant) agar kembali ke platform."
|
| 533 |
+
},
|
| 534 |
+
"code-reviewer": {
|
| 535 |
+
"tier": "MEDIUM",
|
| 536 |
+
"role": "Code Reviewer",
|
| 537 |
+
"prompt": "IDENTITAS: Code Reviewer. TUGAS: Mengulas Pull Request secara kritis. Fokus pada keamanan, performa, dan DRY principles."
|
| 538 |
+
},
|
| 539 |
+
"auth-manager": {
|
| 540 |
+
"tier": "MEDIUM",
|
| 541 |
+
"role": "Auth Manager",
|
| 542 |
+
"prompt": "IDENTITAS: Auth Manager. TUGAS: Mengelola integrasi otentikasi (JWT, OAuth) dan logika RBAC (Role-Based Access Control)."
|
| 543 |
+
},
|
| 544 |
+
"sheet-manager": {
|
| 545 |
+
"tier": "LOW",
|
| 546 |
+
"role": "Google Sheets Schema Manager",
|
| 547 |
+
"prompt": "IDENTITAS: Sheet Manager. TUGAS: Mengelola pemetaan kolom dan skema jika berhadapan dengan legacy data Sheets."
|
| 548 |
+
},
|
| 549 |
+
"gemini-orchestrator": {
|
| 550 |
+
"tier": "HIGH",
|
| 551 |
+
"role": "AI Model Orchestrator",
|
| 552 |
+
"prompt": "IDENTITAS: Gemini Orchestrator. TUGAS: Memantau penggunaan token, merutekan panggilan AI, dan mengatur sistem fallback."
|
| 553 |
+
},
|
| 554 |
+
"trigger-scheduler": {
|
| 555 |
+
"tier": "LOW",
|
| 556 |
+
"role": "Cron/Trigger Manager",
|
| 557 |
+
"prompt": "IDENTITAS: Trigger Scheduler. TUGAS: Mengatur jadwal task background (CRON) dan memastikan tidak ada tabrakan waktu."
|
| 558 |
+
},
|
| 559 |
+
"migration-agent": {
|
| 560 |
+
"tier": "MEDIUM",
|
| 561 |
+
"role": "Migration Agent",
|
| 562 |
+
"prompt": "IDENTITAS: Migration Agent. TUGAS: Menulis skrip Alembic untuk migrasi database atau migrasi data massal tanpa downtime."
|
| 563 |
+
},
|
| 564 |
+
"backup-restorer": {
|
| 565 |
+
"tier": "LOW",
|
| 566 |
+
"role": "Backup & Restore Agent",
|
| 567 |
+
"prompt": "IDENTITAS: Backup Restorer. TUGAS: Menjalankan dump database secara periodik dan menguji proses restorasi (disaster recovery)."
|
| 568 |
+
},
|
| 569 |
+
"i18n-translator": {
|
| 570 |
+
"tier": "LOW",
|
| 571 |
+
"role": "Localization Agent",
|
| 572 |
+
"prompt": "IDENTITAS: I18N Translator. TUGAS: Menerjemahkan string UI ke dalam berbagai bahasa tanpa merusak konteks teknis atau tata letak (layout)."
|
| 573 |
+
},
|
| 574 |
+
"payment-manager": {
|
| 575 |
+
"tier": "MEDIUM",
|
| 576 |
+
"role": "Payment Manager",
|
| 577 |
+
"prompt": "IDENTITAS: Payment Manager. TUGAS: Mengelola integrasi Midtrans, webhooks pembayaran, dan pemotongan saldo (Coin deduction)."
|
| 578 |
+
},
|
| 579 |
+
"recruiter-agent": {
|
| 580 |
+
"tier": "MEDIUM",
|
| 581 |
+
"role": "Recruiter Portal Automator",
|
| 582 |
+
"prompt": "IDENTITAS: Recruiter Agent. TUGAS: Mengotomatiskan proses vetting CV masal dan mencocokkan talenta berdasarkan input pencarian rekruter."
|
| 583 |
+
},
|
| 584 |
+
"build-deployer": {
|
| 585 |
+
"tier": "LOW",
|
| 586 |
+
"role": "CI/CD Build Deployer",
|
| 587 |
+
"prompt": "IDENTITAS: Build Deployer. TUGAS: Menjalankan skrip build CSS/JS dan mengorkestrasi pengiriman kode ke Cloudflare Pages atau Docker registry."
|
| 588 |
+
},
|
| 589 |
+
"changelog-generator": {
|
| 590 |
+
"tier": "LOW",
|
| 591 |
+
"role": "Changelog Generator",
|
| 592 |
+
"prompt": "IDENTITAS: Changelog Generator. TUGAS: Mengubah daftar commit menjadi dokumen CHANGELOG.md yang ramah manusia (user-facing release notes)."
|
| 593 |
+
},
|
| 594 |
+
"onboarding-agent": {
|
| 595 |
+
"tier": "LOW",
|
| 596 |
+
"role": "Onboarding Documentation Agent",
|
| 597 |
+
"prompt": "IDENTITAS: Onboarding Agent. TUGAS: Menyusun dokumen panduan (setup guide) agar developer manusia yang baru bergabung bisa langsung bekerja dalam 10 menit."
|
| 598 |
+
},
|
| 599 |
+
# 🚀 ADVANCED GROWTH & AUTOMATION AGENTS (Level 4/5)
|
| 600 |
+
"programmatic-seo-agent": {
|
| 601 |
+
"tier": "HIGH",
|
| 602 |
+
"role": "Programmatic SEO Architect",
|
| 603 |
+
"prompt": (
|
| 604 |
+
"IDENTITAS: Anda adalah Programmatic SEO Agent Brigawan.\n"
|
| 605 |
+
"MISI: Mendominasi hasil pencarian Google untuk niche green jobs melalui pembuatan halaman secara massal dan otomatis.\n"
|
| 606 |
+
"TANGGUNG JAWAB: Mengidentifikasi long-tail keywords (misal: 'Gaji ESG Manager Jakarta'), mengumpulkan data dari database, dan menginstruksikan Frontend Builder untuk membuat ratusan/ribuan landing page yang sangat spesifik dan SEO-optimized secara terprogram.\n"
|
| 607 |
+
"GAYA: Sangat analitis, fokus pada search volume, agresif dalam akuisisi trafik organik."
|
| 608 |
+
)
|
| 609 |
+
},
|
| 610 |
+
"ab-test-optimizer": {
|
| 611 |
+
"tier": "MEDIUM",
|
| 612 |
+
"role": "A/B Testing & Conversion Optimizer",
|
| 613 |
+
"prompt": (
|
| 614 |
+
"IDENTITAS: Anda adalah A/B Testing Optimizer Brigawan.\n"
|
| 615 |
+
"MISI: Meningkatkan rasio konversi (pendaftaran talenta/perusahaan) secara berkesinambungan tanpa intervensi manusia.\n"
|
| 616 |
+
"TANGGUNG JAWAB: Merancang eksperimen UI/UX (A/B Test), memantau metrik klik (CTR) selama periode waktu tertentu, menganalisis hasilnya, dan secara otomatis menetapkan varian pemenang sebagai standar aplikasi baru.\n"
|
| 617 |
+
"GAYA: Eksperimental, berbasis probabilitas, tidak bias."
|
| 618 |
+
)
|
| 619 |
+
},
|
| 620 |
+
"competitor-spy-agent": {
|
| 621 |
+
"tier": "HIGH",
|
| 622 |
+
"role": "Competitor Intelligence Spy",
|
| 623 |
+
"prompt": (
|
| 624 |
+
"IDENTITAS: Anda adalah Competitor Spy Agent Brigawan.\n"
|
| 625 |
+
"MISI: Memantau dan menganalisis pergerakan portal kompetitor (job boards konvensional & green niche) secara real-time.\n"
|
| 626 |
+
"TANGGUNG JAWAB: Menggunakan scraper untuk mendeteksi fitur baru kompetitor, perubahan harga, atau klien besar yang mereka dapatkan. Melaporkan temuan ini secara instan ke CEO Agent untuk merumuskan counter-strategy.\n"
|
| 627 |
+
"GAYA: Waspada, taktis, seperti agen intelijen bisnis."
|
| 628 |
+
)
|
| 629 |
+
},
|
| 630 |
+
"api-arbitrage-agent": {
|
| 631 |
+
"tier": "MEDIUM",
|
| 632 |
+
"role": "API Cost Arbitrage Manager",
|
| 633 |
+
"prompt": (
|
| 634 |
+
"IDENTITAS: Anda adalah API Arbitrage Agent Brigawan.\n"
|
| 635 |
+
"MISI: Menekan biaya operasional AI (Token Costs) mendekati $0/bulan.\n"
|
| 636 |
+
"TANGGUNG JAWAB: Secara real-time memantau harga dan latensi di berbagai bursa AI (OpenRouter, Groq, 9Router, DeepSeek API langsung). Jika mendeteksi kenaikan harga atau limitasi, otomatis mengubah rute (routing) ke provider termurah/gratis yang memiliki kualitas setara untuk model yang diminta.\n"
|
| 637 |
+
"GAYA: Oportunis (dalam arti positif), super efisien, berorientasi pada penghematan ekstrem."
|
| 638 |
+
)
|
| 639 |
+
}
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
@classmethod
|
| 643 |
+
def get_agent(cls, agent_id: str) -> Optional[Dict[str, Any]]:
|
| 644 |
+
return cls.AGENTS.get(agent_id)
|
| 645 |
+
|
| 646 |
+
async def call_agent(agent_id: str, user_input: str, context: str = "") -> Dict[str, Any]:
|
| 647 |
+
"""Execute a task using a specific agent from the registry."""
|
| 648 |
+
import os
|
| 649 |
+
from loguru import logger
|
| 650 |
+
|
| 651 |
+
agent_info = AgentRegistry.get_agent(agent_id)
|
| 652 |
+
if not agent_info:
|
| 653 |
+
return {"success": False, "error": f"Agent {agent_id} not found."}
|
| 654 |
+
|
| 655 |
+
tier = agent_info["tier"]
|
| 656 |
+
system_prompt = agent_info["prompt"]
|
| 657 |
+
|
| 658 |
+
# Inject DESIGN.md tokens and voice guidance when available (best-effort)
|
| 659 |
+
try:
|
| 660 |
+
# Path is repo-root/DESIGN.md; adjust relative path from service folder
|
| 661 |
+
design_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "DESIGN.md")
|
| 662 |
+
with open(design_path, "r", encoding="utf-8") as f:
|
| 663 |
+
design_md = f.read()
|
| 664 |
+
system_prompt += f"\n\nDESIGN_GUIDELINES:\n{design_md[:4000]}"
|
| 665 |
+
except Exception:
|
| 666 |
+
pass
|
| 667 |
+
|
| 668 |
+
# Inject Context
|
| 669 |
+
if context:
|
| 670 |
+
system_prompt += f"\n\nKONTEKS OPERASIONAL:\n{context}"
|
| 671 |
+
|
| 672 |
+
# Retrieve memories/learnings
|
| 673 |
+
past_learnings = ""
|
| 674 |
+
obsidian_learnings = ""
|
| 675 |
+
try:
|
| 676 |
+
query_embedding = await generate_embedding(user_input)
|
| 677 |
+
if agent_id == "obsidian-vault":
|
| 678 |
+
obsidian_learnings = await AgentMemoryService.get_learnings("obsidian-vault", user_input, query_embedding=query_embedding)
|
| 679 |
+
else:
|
| 680 |
+
past_learnings = await AgentMemoryService.get_learnings(agent_id, user_input, query_embedding=query_embedding)
|
| 681 |
+
obsidian_learnings = await AgentMemoryService.get_learnings("obsidian-vault", user_input, query_embedding=query_embedding)
|
| 682 |
+
except Exception as e:
|
| 683 |
+
logger.error(f"[AgentService] Error retrieving memories for agent {agent_id}: {e}")
|
| 684 |
+
|
| 685 |
+
# Append to system_prompt
|
| 686 |
+
if past_learnings:
|
| 687 |
+
system_prompt += f"\n\n{past_learnings}"
|
| 688 |
+
if obsidian_learnings:
|
| 689 |
+
system_prompt += f"\n\n{obsidian_learnings}"
|
| 690 |
+
|
| 691 |
+
# Choose call method based on effective tier (per-agent override aware)
|
| 692 |
+
effective_tier = _resolve_tier(agent_id, tier)
|
| 693 |
+
if effective_tier == "HIGH":
|
| 694 |
+
text, tokens = await call_high(prompt=user_input, system_instruction=system_prompt)
|
| 695 |
+
elif effective_tier == "MEDIUM":
|
| 696 |
+
text, tokens = await call_medium(prompt=user_input, system_instruction=system_prompt)
|
| 697 |
+
else:
|
| 698 |
+
text, tokens = await call_low(prompt=user_input, system_instruction=system_prompt)
|
| 699 |
+
|
| 700 |
+
return {
|
| 701 |
+
"success": True,
|
| 702 |
+
"agent": agent_id,
|
| 703 |
+
"role": agent_info["role"],
|
| 704 |
+
"reply": text,
|
| 705 |
+
"tokens": tokens
|
| 706 |
+
}
|
| 707 |
+
|
| 708 |
+
async def call_agent_json(agent_id: str, user_input: str, context: str = "") -> Dict[str, Any]:
|
| 709 |
+
"""Execute a task using a specific agent and expect JSON output."""
|
| 710 |
+
import os
|
| 711 |
+
from loguru import logger
|
| 712 |
+
|
| 713 |
+
agent_info = AgentRegistry.get_agent(agent_id)
|
| 714 |
+
if not agent_info:
|
| 715 |
+
return {"success": False, "error": f"Agent {agent_id} not found."}
|
| 716 |
+
|
| 717 |
+
tier = agent_info["tier"]
|
| 718 |
+
system_prompt = agent_info["prompt"]
|
| 719 |
+
|
| 720 |
+
# Inject DESIGN.md tokens and voice guidance when available (best-effort)
|
| 721 |
+
try:
|
| 722 |
+
design_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "DESIGN.md")
|
| 723 |
+
with open(design_path, "r", encoding="utf-8") as f:
|
| 724 |
+
design_md = f.read()
|
| 725 |
+
system_prompt += f"\n\nDESIGN_GUIDELINES:\n{design_md[:4000]}"
|
| 726 |
+
except Exception:
|
| 727 |
+
pass
|
| 728 |
+
|
| 729 |
+
if context:
|
| 730 |
+
system_prompt += f"\n\nKONTEKS OPERASIONAL:\n{context}"
|
| 731 |
+
|
| 732 |
+
# Retrieve memories/learnings
|
| 733 |
+
past_learnings = ""
|
| 734 |
+
obsidian_learnings = ""
|
| 735 |
+
try:
|
| 736 |
+
query_embedding = await generate_embedding(user_input)
|
| 737 |
+
if agent_id == "obsidian-vault":
|
| 738 |
+
obsidian_learnings = await AgentMemoryService.get_learnings("obsidian-vault", user_input, query_embedding=query_embedding)
|
| 739 |
+
else:
|
| 740 |
+
past_learnings = await AgentMemoryService.get_learnings(agent_id, user_input, query_embedding=query_embedding)
|
| 741 |
+
obsidian_learnings = await AgentMemoryService.get_learnings("obsidian-vault", user_input, query_embedding=query_embedding)
|
| 742 |
+
except Exception as e:
|
| 743 |
+
logger.error(f"[AgentService] Error retrieving memories in JSON for agent {agent_id}: {e}")
|
| 744 |
+
|
| 745 |
+
# Append to system_prompt
|
| 746 |
+
if past_learnings:
|
| 747 |
+
system_prompt += f"\n\n{past_learnings}"
|
| 748 |
+
if obsidian_learnings:
|
| 749 |
+
system_prompt += f"\n\n{obsidian_learnings}"
|
| 750 |
+
|
| 751 |
+
system_prompt += "\n\nPENTING: Respon HARUS dalam format JSON valid."
|
| 752 |
+
|
| 753 |
+
parsed, tokens = await call_gemini_json(
|
| 754 |
+
prompt=user_input,
|
| 755 |
+
tier=_resolve_tier(agent_id, tier),
|
| 756 |
+
system_instruction=system_prompt
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
return {
|
| 760 |
+
"success": "error" not in parsed,
|
| 761 |
+
"agent": agent_id,
|
| 762 |
+
"data": parsed,
|
| 763 |
+
"tokens": tokens
|
| 764 |
+
}
|
app/services/ai_service.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
app/services/antigravity.py
CHANGED
|
@@ -1,460 +1,460 @@
|
|
| 1 |
-
"""Antigravity Agent Orchestrator — The "Digital Workforce" CEO.
|
| 2 |
-
|
| 3 |
-
Orchestrates multi-agent workflows, manages token quotas (Free Tier 15 RPM),
|
| 4 |
-
and ensures graceful degradation during AI exhaustion.
|
| 5 |
-
|
| 6 |
-
Architecture:
|
| 7 |
-
- Antigravity Service (CEO)
|
| 8 |
-
- AgentQueue (Traffic Controller)
|
| 9 |
-
- AI Service (Operational Workers)
|
| 10 |
-
- Long-Term Memory (LTM)
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
import asyncio
|
| 14 |
-
import json
|
| 15 |
-
import uuid
|
| 16 |
-
from datetime import datetime, timedelta, timezone
|
| 17 |
-
from typing import Any, Dict, List, Optional
|
| 18 |
-
|
| 19 |
-
from loguru import logger
|
| 20 |
-
from sqlalchemy import select, update, func
|
| 21 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 22 |
-
|
| 23 |
-
from app.models.system import AgentStateLog, AgentQueue, APIMonitoring, CEOStrategicMemory, AnalyticsTraffic, ActivityLog
|
| 24 |
-
from app.models.job import AITalentChat
|
| 25 |
-
from app.models.skkni import FailedSearch
|
| 26 |
-
from app.models.finance import Transaction
|
| 27 |
-
from app.models.lpk import LPKLedger
|
| 28 |
-
from app.services import ai_service
|
| 29 |
-
from app.services.academy_email_service import AcademyEmailService
|
| 30 |
-
from app.services.google_workspace_service import spark_agent
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
class AntigravityOrchestrator:
|
| 34 |
-
"""The central orchestrator for all AI agent activities in Briga.id."""
|
| 35 |
-
|
| 36 |
-
def __init__(self, db: AsyncSession):
|
| 37 |
-
self.db = db
|
| 38 |
-
self.email_service = AcademyEmailService()
|
| 39 |
-
# Multi-Key Capacity (5 keys * 15 RPM = 75 RPM)
|
| 40 |
-
self.MAX_RPM = 70
|
| 41 |
-
self.MAX_RPD = 7500
|
| 42 |
-
self.SAFE_THRESHOLD = 0.80 # Enter Triage L1 at 80% (6,000 RPD)
|
| 43 |
-
self.CRITICAL_THRESHOLD = 0.95 # Enter Triage L2 at 95% (7,125 RPD)
|
| 44 |
-
|
| 45 |
-
async def execute_task(
|
| 46 |
-
self,
|
| 47 |
-
agent_name: str,
|
| 48 |
-
task_name: str,
|
| 49 |
-
payload: Dict[str, Any],
|
| 50 |
-
priority: int = 0,
|
| 51 |
-
user_email: Optional[str] = None
|
| 52 |
-
) -> Dict[str, Any]:
|
| 53 |
-
"""Execute an AI task through the Antigravity gateway."""
|
| 54 |
-
trace_id = str(uuid.uuid4())
|
| 55 |
-
logger.info(f"[Antigravity] Task Received: {task_name} (Agent: {agent_name}, Trace: {trace_id})")
|
| 56 |
-
|
| 57 |
-
# 1. Log Initial State
|
| 58 |
-
state_log = AgentStateLog(
|
| 59 |
-
agent_name=agent_name,
|
| 60 |
-
task_id=trace_id,
|
| 61 |
-
status="WORKING",
|
| 62 |
-
memory_context={"task_name": task_name, "initial_payload": payload},
|
| 63 |
-
last_action="INITIATED"
|
| 64 |
-
)
|
| 65 |
-
self.db.add(state_log)
|
| 66 |
-
await self.db.flush()
|
| 67 |
-
|
| 68 |
-
# 2. Quota & Triage Check
|
| 69 |
-
quota_status = await self._check_quota_status()
|
| 70 |
-
|
| 71 |
-
if quota_status["rpd_percent"] >= 1.0:
|
| 72 |
-
return await self._handle_fallback(trace_id, agent_name, task_name, payload, "EXHAUSTED")
|
| 73 |
-
|
| 74 |
-
if quota_status["rpd_percent"] >= self.CRITICAL_THRESHOLD:
|
| 75 |
-
return await self._handle_fallback(trace_id, agent_name, task_name, payload, "TRIAGE_L2")
|
| 76 |
-
|
| 77 |
-
if quota_status["rpd_percent"] >= self.SAFE_THRESHOLD and priority < 1:
|
| 78 |
-
if agent_name in ["ContentPipeline", "EngagementBot"]:
|
| 79 |
-
return await self._handle_fallback(trace_id, agent_name, task_name, payload, "TRIAGE_L1")
|
| 80 |
-
|
| 81 |
-
# 3. RPM Throttling
|
| 82 |
-
await self._wait_for_slot()
|
| 83 |
-
|
| 84 |
-
# 4. Model Delegation & Execution
|
| 85 |
-
try:
|
| 86 |
-
result = await self._delegate_and_run(agent_name, task_name, payload)
|
| 87 |
-
|
| 88 |
-
# Log usage
|
| 89 |
-
await self._log_usage(task_name, result.get("tokens", 0), user_email)
|
| 90 |
-
|
| 91 |
-
# Update State
|
| 92 |
-
state_log.status = "COMPLETED"
|
| 93 |
-
state_log.last_action = "EXECUTION_SUCCESS"
|
| 94 |
-
state_log.memory_context["result_summary"] = str(result)[:200]
|
| 95 |
-
|
| 96 |
-
# 5. ASYNC NOTIFICATION (EMAIL RESPONSE)
|
| 97 |
-
if user_email and task_name in ["career_advice", "cv_analysis", "academy_feedback", "bulk_vetting"]:
|
| 98 |
-
logger.info(f"[Antigravity] Sending asynchronous email result to {user_email}")
|
| 99 |
-
await self._notify_user_via_email(user_email, task_name, result)
|
| 100 |
-
|
| 101 |
-
await self.db.commit()
|
| 102 |
-
return {"status": "success", "trace_id": trace_id, "data": result}
|
| 103 |
-
|
| 104 |
-
except Exception as e:
|
| 105 |
-
logger.error(f"[Antigravity] Execution Failed: {e}")
|
| 106 |
-
return await self._handle_fallback(trace_id, agent_name, task_name, payload, "ERROR", str(e))
|
| 107 |
-
|
| 108 |
-
async def _check_quota_status(self) -> Dict[str, float]:
|
| 109 |
-
"""Calculates current RPD usage percent."""
|
| 110 |
-
today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
|
| 111 |
-
query = select(func.count(APIMonitoring.id)).where(APIMonitoring.timestamp >= today)
|
| 112 |
-
res = await self.db.execute(query)
|
| 113 |
-
daily_count = res.scalar() or 0
|
| 114 |
-
return {"daily_count": daily_count, "rpd_percent": daily_count / self.MAX_RPD}
|
| 115 |
-
|
| 116 |
-
async def _wait_for_slot(self):
|
| 117 |
-
"""Simple RPM throttle."""
|
| 118 |
-
while True:
|
| 119 |
-
one_min_ago = datetime.now(timezone.utc) - timedelta(minutes=1)
|
| 120 |
-
query = select(func.count(APIMonitoring.id)).where(APIMonitoring.timestamp >= one_min_ago)
|
| 121 |
-
res = await self.db.execute(query)
|
| 122 |
-
if (res.scalar() or 0) < self.MAX_RPM: break
|
| 123 |
-
await asyncio.sleep(2)
|
| 124 |
-
|
| 125 |
-
async def _delegate_and_run(self, agent, task, payload) -> Dict[str, Any]:
|
| 126 |
-
"""Delegates task to the appropriate Gemini model tier."""
|
| 127 |
-
|
| 128 |
-
if task == "semantic_matching":
|
| 129 |
-
return await ai_service.analyze_semantic_match(payload["query"], payload["talent_data"])
|
| 130 |
-
|
| 131 |
-
if task == "cv_extraction":
|
| 132 |
-
cv_text, tokens = await ai_service.generate_cv_text(payload["talent_data"])
|
| 133 |
-
return {"cv_text": cv_text, "tokens": tokens}
|
| 134 |
-
|
| 135 |
-
if task == "chat_mediation":
|
| 136 |
-
reply, tokens = await ai_service.chat_mediation(payload["message"], payload.get("context", ""))
|
| 137 |
-
return {"reply": reply, "tokens": tokens}
|
| 138 |
-
|
| 139 |
-
if task == "bulk_vetting":
|
| 140 |
-
# 1. Parse cv_payloads from payload
|
| 141 |
-
cv_payloads = payload.get("cv_payloads", [])
|
| 142 |
-
if isinstance(cv_payloads, str):
|
| 143 |
-
try:
|
| 144 |
-
cv_payloads = json.loads(cv_payloads)
|
| 145 |
-
except Exception as e:
|
| 146 |
-
logger.error(f"[Antigravity] Failed to parse cv_payloads JSON string: {e}")
|
| 147 |
-
return {
|
| 148 |
-
"success": False,
|
| 149 |
-
"error": f"Format payload CV tidak valid: {str(e)}",
|
| 150 |
-
"tokens": 0
|
| 151 |
-
}
|
| 152 |
-
|
| 153 |
-
# If payload is in raw legacy GAS format where key is 'payloads'
|
| 154 |
-
if not cv_payloads and "payloads" in payload:
|
| 155 |
-
cv_payloads = payload.get("payloads", [])
|
| 156 |
-
if isinstance(cv_payloads, str):
|
| 157 |
-
try:
|
| 158 |
-
cv_payloads = json.loads(cv_payloads)
|
| 159 |
-
except:
|
| 160 |
-
pass
|
| 161 |
-
|
| 162 |
-
if not isinstance(cv_payloads, list) or len(cv_payloads) == 0:
|
| 163 |
-
# Fallback: if they sent raw 'cv_text' instead of payloads list, wrap it
|
| 164 |
-
if "cv_text" in payload:
|
| 165 |
-
cv_payloads = [{
|
| 166 |
-
"filename": "CV_Input.txt",
|
| 167 |
-
"content": payload["cv_text"],
|
| 168 |
-
"isBase64": False,
|
| 169 |
-
"mimeType": "text/plain"
|
| 170 |
-
}]
|
| 171 |
-
else:
|
| 172 |
-
return {
|
| 173 |
-
"success": False,
|
| 174 |
-
"error": "Tidak ada berkas CV yang dikirim.",
|
| 175 |
-
"tokens": 0
|
| 176 |
-
}
|
| 177 |
-
|
| 178 |
-
recruiter_context = payload.get("context", "")
|
| 179 |
-
|
| 180 |
-
# Limit to 10 CVs per batch (matching GAS limit)
|
| 181 |
-
MAX_BATCH = 10
|
| 182 |
-
if len(cv_payloads) > MAX_BATCH:
|
| 183 |
-
return {
|
| 184 |
-
"success": False,
|
| 185 |
-
"error": f"Maksimum {MAX_BATCH} CV per batch. Anda mengirim {len(cv_payloads)}.",
|
| 186 |
-
"tokens": 0
|
| 187 |
-
}
|
| 188 |
-
|
| 189 |
-
results = []
|
| 190 |
-
errors = []
|
| 191 |
-
total_tokens = 0
|
| 192 |
-
|
| 193 |
-
from app.utils.cv_parser import cv_parser
|
| 194 |
-
import base64
|
| 195 |
-
|
| 196 |
-
for idx, cv in enumerate(cv_payloads):
|
| 197 |
-
filename = cv.get("filename", f"CV_{idx + 1}")
|
| 198 |
-
try:
|
| 199 |
-
# Extract text or convert from base64
|
| 200 |
-
content = cv.get("content", "")
|
| 201 |
-
is_base64 = cv.get("isBase64", False)
|
| 202 |
-
|
| 203 |
-
if not content:
|
| 204 |
-
errors.append({"filename": filename, "error": "Konten CV kosong."})
|
| 205 |
-
continue
|
| 206 |
-
|
| 207 |
-
cv_markdown = ""
|
| 208 |
-
if is_base64:
|
| 209 |
-
# Decode base64 bytes
|
| 210 |
-
file_bytes = base64.b64decode(content)
|
| 211 |
-
# Local conversion using MarkItDown
|
| 212 |
-
cv_markdown = await cv_parser.parse_to_markdown(file_bytes, filename)
|
| 213 |
-
else:
|
| 214 |
-
cv_markdown = content
|
| 215 |
-
|
| 216 |
-
if not cv_markdown or len(cv_markdown.strip()) < 50:
|
| 217 |
-
errors.append({"filename": filename, "error": "Gagal mengekstrak teks (teks terlalu pendek)."})
|
| 218 |
-
continue
|
| 219 |
-
|
| 220 |
-
# Run vetting analysis on this CV
|
| 221 |
-
vet_data, tokens = await ai_service.bulk_vetting_analysis(cv_markdown, recruiter_context)
|
| 222 |
-
total_tokens += tokens
|
| 223 |
-
|
| 224 |
-
if "error" in vet_data:
|
| 225 |
-
errors.append({"filename": filename, "error": vet_data["error"]})
|
| 226 |
-
else:
|
| 227 |
-
# Inject filename and index for frontend sorting/display
|
| 228 |
-
vet_data["_filename"] = filename
|
| 229 |
-
vet_data["_index"] = idx
|
| 230 |
-
results.append(vet_data)
|
| 231 |
-
|
| 232 |
-
except Exception as ex:
|
| 233 |
-
logger.error(f"[Antigravity] Error processing CV {filename}: {ex}")
|
| 234 |
-
errors.append({"filename": filename, "error": str(ex)})
|
| 235 |
-
|
| 236 |
-
# Sort results by score (skor) descending, matching legacy GAS
|
| 237 |
-
results.sort(key=lambda x: x.get("skor", 0), reverse=True)
|
| 238 |
-
|
| 239 |
-
# Generate summary dictionary matching legacy GAS BulkVettingEngine.gs
|
| 240 |
-
summary = None
|
| 241 |
-
if results:
|
| 242 |
-
skilled = len([r for r in results if r.get("kategori") == "Skilled"])
|
| 243 |
-
semi_skilled = len([r for r in results if r.get("kategori") == "Semi-Skilled"])
|
| 244 |
-
unskilled = len([r for r in results if r.get("kategori") == "Unskilled"])
|
| 245 |
-
|
| 246 |
-
scores = [r.get("skor", 0) for r in results]
|
| 247 |
-
avg_score = round(sum(scores) / len(scores)) if scores else 0
|
| 248 |
-
|
| 249 |
-
# Sektor counts
|
| 250 |
-
sector_counts = {}
|
| 251 |
-
for r in results:
|
| 252 |
-
for s in r.get("sektor_cocok", []):
|
| 253 |
-
sector_counts[s] = sector_counts.get(s, 0) + 1
|
| 254 |
-
top_sectors = sorted(sector_counts.keys(), key=lambda x: sector_counts[x], reverse=True)[:3]
|
| 255 |
-
|
| 256 |
-
summary = {
|
| 257 |
-
"total_candidates": len(results),
|
| 258 |
-
"avg_score": avg_score,
|
| 259 |
-
"distribution": {
|
| 260 |
-
"skilled": skilled,
|
| 261 |
-
"semi_skilled": semi_skilled,
|
| 262 |
-
"unskilled": unskilled
|
| 263 |
-
},
|
| 264 |
-
"top_sectors": top_sectors,
|
| 265 |
-
"top_candidate": {
|
| 266 |
-
"filename": results[0]["_filename"],
|
| 267 |
-
"skor": results[0].get("skor", 0),
|
| 268 |
-
"highlight": results[0].get("highlight", "")
|
| 269 |
-
}
|
| 270 |
-
}
|
| 271 |
-
|
| 272 |
-
# Return full output compatible with startBulkVetting JS expect
|
| 273 |
-
return {
|
| 274 |
-
"success": True,
|
| 275 |
-
"total": len(cv_payloads),
|
| 276 |
-
"processed": len(results),
|
| 277 |
-
"failed": len(errors),
|
| 278 |
-
"results": results,
|
| 279 |
-
"errors": errors,
|
| 280 |
-
"summary": summary,
|
| 281 |
-
"tokens": total_tokens
|
| 282 |
-
}
|
| 283 |
-
|
| 284 |
-
if task == "generate_resume":
|
| 285 |
-
link = await spark_agent.generate_standardized_resume(payload["talent_data"], payload["doc_name"])
|
| 286 |
-
return {"resume_link": link, "tokens": 0}
|
| 287 |
-
|
| 288 |
-
if task == "store_cv":
|
| 289 |
-
fid = await spark_agent.get_or_create_folder(payload["employer_name"])
|
| 290 |
-
link = await spark_agent.upload_cv(payload["file_content"], payload["file_name"], fid)
|
| 291 |
-
return {"cv_drive_link": link, "tokens": 0}
|
| 292 |
-
|
| 293 |
-
if task == "check_founder_availability":
|
| 294 |
-
slots = await spark_agent.get_founder_availability(payload["start_time"], payload["end_time"])
|
| 295 |
-
return {"busy_slots": slots, "tokens": 0}
|
| 296 |
-
|
| 297 |
-
if task == "schedule_meeting":
|
| 298 |
-
link = await spark_agent.schedule_ceo_meeting(payload["summary"], payload["start_iso"], payload["end_iso"], payload["email"])
|
| 299 |
-
return {"meeting_link": link, "tokens": 0}
|
| 300 |
-
|
| 301 |
-
if task == "strategic_growth_report":
|
| 302 |
-
prompt = f"Analyze this week's growth data and SROI. Provide a strategic summary for the Founder.\nData: {payload['stats']}"
|
| 303 |
-
res, tokens = await ai_service.call_high(prompt=prompt)
|
| 304 |
-
return {"report": res, "tokens": tokens}
|
| 305 |
-
|
| 306 |
-
if task == "strategic_debate":
|
| 307 |
-
# 1. Memory Recall
|
| 308 |
-
past_memories = await self._recall_memories(payload['idea'])
|
| 309 |
-
mem_ctx = "\n".join([f"- Topic: {m.topic}\n Summary: {m.summary}" for m in past_memories])
|
| 310 |
-
|
| 311 |
-
system_prompt = (
|
| 312 |
-
"You are the AI CEO of Briga.id with Long-Term Memory. "
|
| 313 |
-
"You are data-driven, honest, and slightly provocative. "
|
| 314 |
-
"You must reference past decisions if they are relevant."
|
| 315 |
-
)
|
| 316 |
-
user_prompt = (
|
| 317 |
-
f"Founder's Idea: {payload['idea']}\n\n"
|
| 318 |
-
f"Relevant Past Memories:\n{mem_ctx or 'None found.'}\n\n"
|
| 319 |
-
f"Market Data: {payload.get('market_context', 'N/A')}\n"
|
| 320 |
-
"Bedah ide ini secara jujur dan hubungkan dengan memori masa lalu jika ada."
|
| 321 |
-
)
|
| 322 |
-
res, tokens = await ai_service.call_high(prompt=user_prompt, system_instruction=system_prompt)
|
| 323 |
-
|
| 324 |
-
# 2. Persist to Memory
|
| 325 |
-
if res: await self._persist_memory(payload['idea'], res)
|
| 326 |
-
return {"debate_result": res, "tokens": tokens}
|
| 327 |
-
|
| 328 |
-
if task == "analyze_user_behavior":
|
| 329 |
-
# CEO Behavioral & FINANCIAL Intelligence Task
|
| 330 |
-
data = await self._fetch_behavioral_data()
|
| 331 |
-
system_prompt = (
|
| 332 |
-
"You are the AI CEO of Briga.id. Analyze user behavior, financial transactions, and market gaps. "
|
| 333 |
-
"Identify: 1. Revenue hotspots, 2. Top 3 User friction points, 3. OPPORTUNITY LOSS (Revenue missed due to failed searches or abandoned checkouts), "
|
| 334 |
-
"4. Emerging market trends. Provide high-level executive recommendations."
|
| 335 |
-
)
|
| 336 |
-
user_prompt = f"Comprehensive Business Data (Last 7 Days):\n{json.dumps(data, indent=2, default=str)}"
|
| 337 |
-
res, tokens = await ai_service.call_high(prompt=user_prompt, system_instruction=system_prompt)
|
| 338 |
-
if res: await self._persist_memory("Weekly Business Intelligence Analysis", res)
|
| 339 |
-
return {"business_insight": res, "tokens": tokens}
|
| 340 |
-
|
| 341 |
-
res, tokens = await ai_service.call_medium(payload.get("prompt", ""))
|
| 342 |
-
return {"text": res, "tokens": tokens}
|
| 343 |
-
|
| 344 |
-
async def _fetch_behavioral_data(self) -> Dict[str, Any]:
|
| 345 |
-
"""Aggregates behavioral and financial signals."""
|
| 346 |
-
seven_days_ago = datetime.now(timezone.utc) - timedelta(days=7)
|
| 347 |
-
|
| 348 |
-
# 1. Traffic & Behaviour
|
| 349 |
-
traffic_stmt = select(AnalyticsTraffic.page, func.count(AnalyticsTraffic.id)).where(AnalyticsTraffic.timestamp >= seven_days_ago).group_by(AnalyticsTraffic.page).order_by(func.count(AnalyticsTraffic.id).desc()).limit(10)
|
| 350 |
-
|
| 351 |
-
# 2. Financials (Revenue)
|
| 352 |
-
revenue_stmt = select(func.sum(Transaction.amount)).where(Transaction.created_at >= seven_days_ago, Transaction.status == 'Settled')
|
| 353 |
-
pending_stmt = select(func.count(Transaction.id), func.sum(Transaction.amount)).where(Transaction.created_at >= seven_days_ago, Transaction.status == 'Pending')
|
| 354 |
-
|
| 355 |
-
# 3. Market Gaps (Opportunity Loss)
|
| 356 |
-
search_stmt = select(FailedSearch.query, func.sum(FailedSearch.count)).where(FailedSearch.timestamp >= seven_days_ago).group_by(FailedSearch.query).order_by(func.sum(FailedSearch.count).desc()).limit(10)
|
| 357 |
-
|
| 358 |
-
# 4. Talent Interaction
|
| 359 |
-
chat_stmt = select(AITalentChat.user_message).where(AITalentChat.timestamp >= seven_days_ago).limit(20)
|
| 360 |
-
|
| 361 |
-
traffic_res = await self.db.execute(traffic_stmt)
|
| 362 |
-
rev_res = await self.db.execute(revenue_stmt)
|
| 363 |
-
pend_res = await self.db.execute(pending_stmt)
|
| 364 |
-
search_res = await self.db.execute(search_stmt)
|
| 365 |
-
chat_res = await self.db.execute(chat_stmt)
|
| 366 |
-
|
| 367 |
-
rev_val = rev_res.scalar() or 0
|
| 368 |
-
pend_row = pend_res.fetchone() or (0, 0)
|
| 369 |
-
pend_count = pend_row[0]
|
| 370 |
-
pend_val = pend_row[1] or 0
|
| 371 |
-
|
| 372 |
-
return {
|
| 373 |
-
"traffic": [{"page": r[0], "hits": r[1]} for r in traffic_res.all()],
|
| 374 |
-
"revenue": {
|
| 375 |
-
"settled_idr": float(rev_val),
|
| 376 |
-
"pending_idr": float(pend_val),
|
| 377 |
-
"abandoned_count": pend_count
|
| 378 |
-
},
|
| 379 |
-
"opportunity_loss": {
|
| 380 |
-
"failed_searches": [{"query": r[0], "volume": r[1]} for r in search_res.all()],
|
| 381 |
-
"potential_match_revenue_idr": sum([r[1] for r in search_res.all()]) * 50000 # Estimated Rp 50k per missed search lead
|
| 382 |
-
},
|
| 383 |
-
"chat_sentiment_samples": [r[0] for r in chat_res.all()]
|
| 384 |
-
}
|
| 385 |
-
|
| 386 |
-
async def _recall_memories(self, query: str) -> List[CEOStrategicMemory]:
|
| 387 |
-
stmt = select(CEOStrategicMemory).order_by(CEOStrategicMemory.created_at.desc()).limit(5)
|
| 388 |
-
res = await self.db.execute(stmt)
|
| 389 |
-
return res.scalars().all()
|
| 390 |
-
|
| 391 |
-
async def _persist_memory(self, topic: str, res_text: str):
|
| 392 |
-
self.db.add(CEOStrategicMemory(topic=topic[:255], summary=res_text[:2000], decision_made="PENDING"))
|
| 393 |
-
|
| 394 |
-
async def _handle_fallback(self, tid, agent, task, payload, reason, err=None) -> Dict[str, Any]:
|
| 395 |
-
query = update(AgentStateLog).where(AgentStateLog.task_id == tid).values(
|
| 396 |
-
status="FAILED" if reason == "ERROR" else "ABORTED",
|
| 397 |
-
last_action=f"FALLBACK_{reason}",
|
| 398 |
-
error_message=err or f"Fallback triggered due to {reason}"
|
| 399 |
-
)
|
| 400 |
-
await self.db.execute(query)
|
| 401 |
-
await self.db.commit()
|
| 402 |
-
if task == "semantic_matching":
|
| 403 |
-
s, m = ai_service._algorithmic_match_score(payload["query"], payload["talent_data"])
|
| 404 |
-
return {"status": "fallback", "data": {"score": s, "summary": m, "tier": "algorithmic"}}
|
| 405 |
-
return {"status": "error", "reason": reason, "message": "AI service unavailable. Fallback executed."}
|
| 406 |
-
|
| 407 |
-
async def get_command_center_stats(self) -> Dict[str, Any]:
|
| 408 |
-
"""Provides a holistic view of the AI workforce status."""
|
| 409 |
-
today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
|
| 410 |
-
|
| 411 |
-
# 1. Quota Stats
|
| 412 |
-
quota = await self._check_quota_status()
|
| 413 |
-
|
| 414 |
-
# 2. Task Queue Stats
|
| 415 |
-
queue_stmt = select(AgentQueue.status, func.count(AgentQueue.id)).group_by(AgentQueue.status)
|
| 416 |
-
queue_res = await self.db.execute(queue_stmt)
|
| 417 |
-
queue_stats = {r[0]: r[1] for r in queue_res.all()}
|
| 418 |
-
|
| 419 |
-
# 3. Recent Agent Activity
|
| 420 |
-
activity_stmt = select(AgentStateLog).order_by(AgentStateLog.updated_at.desc()).limit(10)
|
| 421 |
-
activity_res = await self.db.execute(activity_stmt)
|
| 422 |
-
recent_activity = [
|
| 423 |
-
{
|
| 424 |
-
"agent": a.agent_name,
|
| 425 |
-
"task": a.memory_context.get("task_name", "Unknown"),
|
| 426 |
-
"status": a.status,
|
| 427 |
-
"last_action": a.last_action,
|
| 428 |
-
"timestamp": a.updated_at
|
| 429 |
-
} for a in activity_res.scalars().all()
|
| 430 |
-
]
|
| 431 |
-
|
| 432 |
-
return {
|
| 433 |
-
"quota": quota,
|
| 434 |
-
"queue": queue_stats,
|
| 435 |
-
"activity": recent_activity,
|
| 436 |
-
"status": "HEALTHY" if quota["rpd_percent"] < self.CRITICAL_THRESHOLD else "TRIAGE_MODE"
|
| 437 |
-
}
|
| 438 |
-
|
| 439 |
-
async def _notify_user_via_email(self, email, task, data):
|
| 440 |
-
try:
|
| 441 |
-
if task == "academy_feedback": await self.email_service.send_feedback_email(email, data)
|
| 442 |
-
elif task in ["cv_analysis", "bulk_vetting"]:
|
| 443 |
-
await self.email_service.send_feedback_email(email, {
|
| 444 |
-
"feedback_intro": "Halo! Brigawan telah selesai menganalisis dokumen Anda secara mendalam. Berikut adalah hasil review dan link aktivasi akun Anda.",
|
| 445 |
-
"strengths": data.get("category", "Talenta Hijau Potensial"),
|
| 446 |
-
"areas_for_improvement": ", ".join(data.get("skill_gaps", []) or ["Terus tingkatkan sertifikasi K3"]),
|
| 447 |
-
"concrete_tips": [data.get("transition_path", "Lanjutkan eksplorasi di sektor EBT.")],
|
| 448 |
-
"next_steps": "Klik tombol di bawah ini untuk mengaktivasi akun Anda.",
|
| 449 |
-
"closing": "Selamat bergabung di ekosistem hijau Indonesia! 🌿"
|
| 450 |
-
})
|
| 451 |
-
elif task == "career_advice":
|
| 452 |
-
await self.email_service.send_feedback_email(email, {
|
| 453 |
-
"feedback_intro": "Halo! Ini adalah saran karir strategis yang dirancang khusus untuk Anda oleh Brigawan AI.",
|
| 454 |
-
"strengths": "Visi Karir Hijau Anda",
|
| 455 |
-
"areas_for_improvement": data.get("advice_snippet", "Fokus pada pengembangan spesialisasi sektor."),
|
| 456 |
-
"concrete_tips": data.get("next_steps", ["Ikuti pelatihan SKKNI terkait"]),
|
| 457 |
-
"next_steps": data.get("full_recommendation", "Cek dashboard."),
|
| 458 |
-
"closing": "Ingat, keahlian Anda adalah kunci transisi energi Indonesia. Semangat!"
|
| 459 |
-
})
|
| 460 |
-
except Exception as e: logger.error(f"[Antigravity] Email notification failed: {e}")
|
|
|
|
| 1 |
+
"""Antigravity Agent Orchestrator — The "Digital Workforce" CEO.
|
| 2 |
+
|
| 3 |
+
Orchestrates multi-agent workflows, manages token quotas (Free Tier 15 RPM),
|
| 4 |
+
and ensures graceful degradation during AI exhaustion.
|
| 5 |
+
|
| 6 |
+
Architecture:
|
| 7 |
+
- Antigravity Service (CEO)
|
| 8 |
+
- AgentQueue (Traffic Controller)
|
| 9 |
+
- AI Service (Operational Workers)
|
| 10 |
+
- Long-Term Memory (LTM)
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import asyncio
|
| 14 |
+
import json
|
| 15 |
+
import uuid
|
| 16 |
+
from datetime import datetime, timedelta, timezone
|
| 17 |
+
from typing import Any, Dict, List, Optional
|
| 18 |
+
|
| 19 |
+
from loguru import logger
|
| 20 |
+
from sqlalchemy import select, update, func
|
| 21 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 22 |
+
|
| 23 |
+
from app.models.system import AgentStateLog, AgentQueue, APIMonitoring, CEOStrategicMemory, AnalyticsTraffic, ActivityLog
|
| 24 |
+
from app.models.job import AITalentChat
|
| 25 |
+
from app.models.skkni import FailedSearch
|
| 26 |
+
from app.models.finance import Transaction
|
| 27 |
+
from app.models.lpk import LPKLedger
|
| 28 |
+
from app.services import ai_service
|
| 29 |
+
from app.services.academy_email_service import AcademyEmailService
|
| 30 |
+
from app.services.google_workspace_service import spark_agent
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class AntigravityOrchestrator:
|
| 34 |
+
"""The central orchestrator for all AI agent activities in Briga.id."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, db: AsyncSession):
|
| 37 |
+
self.db = db
|
| 38 |
+
self.email_service = AcademyEmailService()
|
| 39 |
+
# Multi-Key Capacity (5 keys * 15 RPM = 75 RPM)
|
| 40 |
+
self.MAX_RPM = 70
|
| 41 |
+
self.MAX_RPD = 7500
|
| 42 |
+
self.SAFE_THRESHOLD = 0.80 # Enter Triage L1 at 80% (6,000 RPD)
|
| 43 |
+
self.CRITICAL_THRESHOLD = 0.95 # Enter Triage L2 at 95% (7,125 RPD)
|
| 44 |
+
|
| 45 |
+
async def execute_task(
|
| 46 |
+
self,
|
| 47 |
+
agent_name: str,
|
| 48 |
+
task_name: str,
|
| 49 |
+
payload: Dict[str, Any],
|
| 50 |
+
priority: int = 0,
|
| 51 |
+
user_email: Optional[str] = None
|
| 52 |
+
) -> Dict[str, Any]:
|
| 53 |
+
"""Execute an AI task through the Antigravity gateway."""
|
| 54 |
+
trace_id = str(uuid.uuid4())
|
| 55 |
+
logger.info(f"[Antigravity] Task Received: {task_name} (Agent: {agent_name}, Trace: {trace_id})")
|
| 56 |
+
|
| 57 |
+
# 1. Log Initial State
|
| 58 |
+
state_log = AgentStateLog(
|
| 59 |
+
agent_name=agent_name,
|
| 60 |
+
task_id=trace_id,
|
| 61 |
+
status="WORKING",
|
| 62 |
+
memory_context={"task_name": task_name, "initial_payload": payload},
|
| 63 |
+
last_action="INITIATED"
|
| 64 |
+
)
|
| 65 |
+
self.db.add(state_log)
|
| 66 |
+
await self.db.flush()
|
| 67 |
+
|
| 68 |
+
# 2. Quota & Triage Check
|
| 69 |
+
quota_status = await self._check_quota_status()
|
| 70 |
+
|
| 71 |
+
if quota_status["rpd_percent"] >= 1.0:
|
| 72 |
+
return await self._handle_fallback(trace_id, agent_name, task_name, payload, "EXHAUSTED")
|
| 73 |
+
|
| 74 |
+
if quota_status["rpd_percent"] >= self.CRITICAL_THRESHOLD:
|
| 75 |
+
return await self._handle_fallback(trace_id, agent_name, task_name, payload, "TRIAGE_L2")
|
| 76 |
+
|
| 77 |
+
if quota_status["rpd_percent"] >= self.SAFE_THRESHOLD and priority < 1:
|
| 78 |
+
if agent_name in ["ContentPipeline", "EngagementBot"]:
|
| 79 |
+
return await self._handle_fallback(trace_id, agent_name, task_name, payload, "TRIAGE_L1")
|
| 80 |
+
|
| 81 |
+
# 3. RPM Throttling
|
| 82 |
+
await self._wait_for_slot()
|
| 83 |
+
|
| 84 |
+
# 4. Model Delegation & Execution
|
| 85 |
+
try:
|
| 86 |
+
result = await self._delegate_and_run(agent_name, task_name, payload)
|
| 87 |
+
|
| 88 |
+
# Log usage
|
| 89 |
+
await self._log_usage(task_name, result.get("tokens", 0), user_email)
|
| 90 |
+
|
| 91 |
+
# Update State
|
| 92 |
+
state_log.status = "COMPLETED"
|
| 93 |
+
state_log.last_action = "EXECUTION_SUCCESS"
|
| 94 |
+
state_log.memory_context["result_summary"] = str(result)[:200]
|
| 95 |
+
|
| 96 |
+
# 5. ASYNC NOTIFICATION (EMAIL RESPONSE)
|
| 97 |
+
if user_email and task_name in ["career_advice", "cv_analysis", "academy_feedback", "bulk_vetting"]:
|
| 98 |
+
logger.info(f"[Antigravity] Sending asynchronous email result to {user_email}")
|
| 99 |
+
await self._notify_user_via_email(user_email, task_name, result)
|
| 100 |
+
|
| 101 |
+
await self.db.commit()
|
| 102 |
+
return {"status": "success", "trace_id": trace_id, "data": result}
|
| 103 |
+
|
| 104 |
+
except Exception as e:
|
| 105 |
+
logger.error(f"[Antigravity] Execution Failed: {e}")
|
| 106 |
+
return await self._handle_fallback(trace_id, agent_name, task_name, payload, "ERROR", str(e))
|
| 107 |
+
|
| 108 |
+
async def _check_quota_status(self) -> Dict[str, float]:
|
| 109 |
+
"""Calculates current RPD usage percent."""
|
| 110 |
+
today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
|
| 111 |
+
query = select(func.count(APIMonitoring.id)).where(APIMonitoring.timestamp >= today)
|
| 112 |
+
res = await self.db.execute(query)
|
| 113 |
+
daily_count = res.scalar() or 0
|
| 114 |
+
return {"daily_count": daily_count, "rpd_percent": daily_count / self.MAX_RPD}
|
| 115 |
+
|
| 116 |
+
async def _wait_for_slot(self):
|
| 117 |
+
"""Simple RPM throttle."""
|
| 118 |
+
while True:
|
| 119 |
+
one_min_ago = datetime.now(timezone.utc) - timedelta(minutes=1)
|
| 120 |
+
query = select(func.count(APIMonitoring.id)).where(APIMonitoring.timestamp >= one_min_ago)
|
| 121 |
+
res = await self.db.execute(query)
|
| 122 |
+
if (res.scalar() or 0) < self.MAX_RPM: break
|
| 123 |
+
await asyncio.sleep(2)
|
| 124 |
+
|
| 125 |
+
async def _delegate_and_run(self, agent, task, payload) -> Dict[str, Any]:
|
| 126 |
+
"""Delegates task to the appropriate Gemini model tier."""
|
| 127 |
+
|
| 128 |
+
if task == "semantic_matching":
|
| 129 |
+
return await ai_service.analyze_semantic_match(payload["query"], payload["talent_data"])
|
| 130 |
+
|
| 131 |
+
if task == "cv_extraction":
|
| 132 |
+
cv_text, tokens = await ai_service.generate_cv_text(payload["talent_data"])
|
| 133 |
+
return {"cv_text": cv_text, "tokens": tokens}
|
| 134 |
+
|
| 135 |
+
if task == "chat_mediation":
|
| 136 |
+
reply, tokens = await ai_service.chat_mediation(payload["message"], payload.get("context", ""))
|
| 137 |
+
return {"reply": reply, "tokens": tokens}
|
| 138 |
+
|
| 139 |
+
if task == "bulk_vetting":
|
| 140 |
+
# 1. Parse cv_payloads from payload
|
| 141 |
+
cv_payloads = payload.get("cv_payloads", [])
|
| 142 |
+
if isinstance(cv_payloads, str):
|
| 143 |
+
try:
|
| 144 |
+
cv_payloads = json.loads(cv_payloads)
|
| 145 |
+
except Exception as e:
|
| 146 |
+
logger.error(f"[Antigravity] Failed to parse cv_payloads JSON string: {e}")
|
| 147 |
+
return {
|
| 148 |
+
"success": False,
|
| 149 |
+
"error": f"Format payload CV tidak valid: {str(e)}",
|
| 150 |
+
"tokens": 0
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
# If payload is in raw legacy GAS format where key is 'payloads'
|
| 154 |
+
if not cv_payloads and "payloads" in payload:
|
| 155 |
+
cv_payloads = payload.get("payloads", [])
|
| 156 |
+
if isinstance(cv_payloads, str):
|
| 157 |
+
try:
|
| 158 |
+
cv_payloads = json.loads(cv_payloads)
|
| 159 |
+
except:
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
if not isinstance(cv_payloads, list) or len(cv_payloads) == 0:
|
| 163 |
+
# Fallback: if they sent raw 'cv_text' instead of payloads list, wrap it
|
| 164 |
+
if "cv_text" in payload:
|
| 165 |
+
cv_payloads = [{
|
| 166 |
+
"filename": "CV_Input.txt",
|
| 167 |
+
"content": payload["cv_text"],
|
| 168 |
+
"isBase64": False,
|
| 169 |
+
"mimeType": "text/plain"
|
| 170 |
+
}]
|
| 171 |
+
else:
|
| 172 |
+
return {
|
| 173 |
+
"success": False,
|
| 174 |
+
"error": "Tidak ada berkas CV yang dikirim.",
|
| 175 |
+
"tokens": 0
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
recruiter_context = payload.get("context", "")
|
| 179 |
+
|
| 180 |
+
# Limit to 10 CVs per batch (matching GAS limit)
|
| 181 |
+
MAX_BATCH = 10
|
| 182 |
+
if len(cv_payloads) > MAX_BATCH:
|
| 183 |
+
return {
|
| 184 |
+
"success": False,
|
| 185 |
+
"error": f"Maksimum {MAX_BATCH} CV per batch. Anda mengirim {len(cv_payloads)}.",
|
| 186 |
+
"tokens": 0
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
results = []
|
| 190 |
+
errors = []
|
| 191 |
+
total_tokens = 0
|
| 192 |
+
|
| 193 |
+
from app.utils.cv_parser import cv_parser
|
| 194 |
+
import base64
|
| 195 |
+
|
| 196 |
+
for idx, cv in enumerate(cv_payloads):
|
| 197 |
+
filename = cv.get("filename", f"CV_{idx + 1}")
|
| 198 |
+
try:
|
| 199 |
+
# Extract text or convert from base64
|
| 200 |
+
content = cv.get("content", "")
|
| 201 |
+
is_base64 = cv.get("isBase64", False)
|
| 202 |
+
|
| 203 |
+
if not content:
|
| 204 |
+
errors.append({"filename": filename, "error": "Konten CV kosong."})
|
| 205 |
+
continue
|
| 206 |
+
|
| 207 |
+
cv_markdown = ""
|
| 208 |
+
if is_base64:
|
| 209 |
+
# Decode base64 bytes
|
| 210 |
+
file_bytes = base64.b64decode(content)
|
| 211 |
+
# Local conversion using MarkItDown
|
| 212 |
+
cv_markdown = await cv_parser.parse_to_markdown(file_bytes, filename)
|
| 213 |
+
else:
|
| 214 |
+
cv_markdown = content
|
| 215 |
+
|
| 216 |
+
if not cv_markdown or len(cv_markdown.strip()) < 50:
|
| 217 |
+
errors.append({"filename": filename, "error": "Gagal mengekstrak teks (teks terlalu pendek)."})
|
| 218 |
+
continue
|
| 219 |
+
|
| 220 |
+
# Run vetting analysis on this CV
|
| 221 |
+
vet_data, tokens = await ai_service.bulk_vetting_analysis(cv_markdown, recruiter_context)
|
| 222 |
+
total_tokens += tokens
|
| 223 |
+
|
| 224 |
+
if "error" in vet_data:
|
| 225 |
+
errors.append({"filename": filename, "error": vet_data["error"]})
|
| 226 |
+
else:
|
| 227 |
+
# Inject filename and index for frontend sorting/display
|
| 228 |
+
vet_data["_filename"] = filename
|
| 229 |
+
vet_data["_index"] = idx
|
| 230 |
+
results.append(vet_data)
|
| 231 |
+
|
| 232 |
+
except Exception as ex:
|
| 233 |
+
logger.error(f"[Antigravity] Error processing CV {filename}: {ex}")
|
| 234 |
+
errors.append({"filename": filename, "error": str(ex)})
|
| 235 |
+
|
| 236 |
+
# Sort results by score (skor) descending, matching legacy GAS
|
| 237 |
+
results.sort(key=lambda x: x.get("skor", 0), reverse=True)
|
| 238 |
+
|
| 239 |
+
# Generate summary dictionary matching legacy GAS BulkVettingEngine.gs
|
| 240 |
+
summary = None
|
| 241 |
+
if results:
|
| 242 |
+
skilled = len([r for r in results if r.get("kategori") == "Skilled"])
|
| 243 |
+
semi_skilled = len([r for r in results if r.get("kategori") == "Semi-Skilled"])
|
| 244 |
+
unskilled = len([r for r in results if r.get("kategori") == "Unskilled"])
|
| 245 |
+
|
| 246 |
+
scores = [r.get("skor", 0) for r in results]
|
| 247 |
+
avg_score = round(sum(scores) / len(scores)) if scores else 0
|
| 248 |
+
|
| 249 |
+
# Sektor counts
|
| 250 |
+
sector_counts = {}
|
| 251 |
+
for r in results:
|
| 252 |
+
for s in r.get("sektor_cocok", []):
|
| 253 |
+
sector_counts[s] = sector_counts.get(s, 0) + 1
|
| 254 |
+
top_sectors = sorted(sector_counts.keys(), key=lambda x: sector_counts[x], reverse=True)[:3]
|
| 255 |
+
|
| 256 |
+
summary = {
|
| 257 |
+
"total_candidates": len(results),
|
| 258 |
+
"avg_score": avg_score,
|
| 259 |
+
"distribution": {
|
| 260 |
+
"skilled": skilled,
|
| 261 |
+
"semi_skilled": semi_skilled,
|
| 262 |
+
"unskilled": unskilled
|
| 263 |
+
},
|
| 264 |
+
"top_sectors": top_sectors,
|
| 265 |
+
"top_candidate": {
|
| 266 |
+
"filename": results[0]["_filename"],
|
| 267 |
+
"skor": results[0].get("skor", 0),
|
| 268 |
+
"highlight": results[0].get("highlight", "")
|
| 269 |
+
}
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
# Return full output compatible with startBulkVetting JS expect
|
| 273 |
+
return {
|
| 274 |
+
"success": True,
|
| 275 |
+
"total": len(cv_payloads),
|
| 276 |
+
"processed": len(results),
|
| 277 |
+
"failed": len(errors),
|
| 278 |
+
"results": results,
|
| 279 |
+
"errors": errors,
|
| 280 |
+
"summary": summary,
|
| 281 |
+
"tokens": total_tokens
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
if task == "generate_resume":
|
| 285 |
+
link = await spark_agent.generate_standardized_resume(payload["talent_data"], payload["doc_name"])
|
| 286 |
+
return {"resume_link": link, "tokens": 0}
|
| 287 |
+
|
| 288 |
+
if task == "store_cv":
|
| 289 |
+
fid = await spark_agent.get_or_create_folder(payload["employer_name"])
|
| 290 |
+
link = await spark_agent.upload_cv(payload["file_content"], payload["file_name"], fid)
|
| 291 |
+
return {"cv_drive_link": link, "tokens": 0}
|
| 292 |
+
|
| 293 |
+
if task == "check_founder_availability":
|
| 294 |
+
slots = await spark_agent.get_founder_availability(payload["start_time"], payload["end_time"])
|
| 295 |
+
return {"busy_slots": slots, "tokens": 0}
|
| 296 |
+
|
| 297 |
+
if task == "schedule_meeting":
|
| 298 |
+
link = await spark_agent.schedule_ceo_meeting(payload["summary"], payload["start_iso"], payload["end_iso"], payload["email"])
|
| 299 |
+
return {"meeting_link": link, "tokens": 0}
|
| 300 |
+
|
| 301 |
+
if task == "strategic_growth_report":
|
| 302 |
+
prompt = f"Analyze this week's growth data and SROI. Provide a strategic summary for the Founder.\nData: {payload['stats']}"
|
| 303 |
+
res, tokens = await ai_service.call_high(prompt=prompt)
|
| 304 |
+
return {"report": res, "tokens": tokens}
|
| 305 |
+
|
| 306 |
+
if task == "strategic_debate":
|
| 307 |
+
# 1. Memory Recall
|
| 308 |
+
past_memories = await self._recall_memories(payload['idea'])
|
| 309 |
+
mem_ctx = "\n".join([f"- Topic: {m.topic}\n Summary: {m.summary}" for m in past_memories])
|
| 310 |
+
|
| 311 |
+
system_prompt = (
|
| 312 |
+
"You are the AI CEO of Briga.id with Long-Term Memory. "
|
| 313 |
+
"You are data-driven, honest, and slightly provocative. "
|
| 314 |
+
"You must reference past decisions if they are relevant."
|
| 315 |
+
)
|
| 316 |
+
user_prompt = (
|
| 317 |
+
f"Founder's Idea: {payload['idea']}\n\n"
|
| 318 |
+
f"Relevant Past Memories:\n{mem_ctx or 'None found.'}\n\n"
|
| 319 |
+
f"Market Data: {payload.get('market_context', 'N/A')}\n"
|
| 320 |
+
"Bedah ide ini secara jujur dan hubungkan dengan memori masa lalu jika ada."
|
| 321 |
+
)
|
| 322 |
+
res, tokens = await ai_service.call_high(prompt=user_prompt, system_instruction=system_prompt)
|
| 323 |
+
|
| 324 |
+
# 2. Persist to Memory
|
| 325 |
+
if res: await self._persist_memory(payload['idea'], res)
|
| 326 |
+
return {"debate_result": res, "tokens": tokens}
|
| 327 |
+
|
| 328 |
+
if task == "analyze_user_behavior":
|
| 329 |
+
# CEO Behavioral & FINANCIAL Intelligence Task
|
| 330 |
+
data = await self._fetch_behavioral_data()
|
| 331 |
+
system_prompt = (
|
| 332 |
+
"You are the AI CEO of Briga.id. Analyze user behavior, financial transactions, and market gaps. "
|
| 333 |
+
"Identify: 1. Revenue hotspots, 2. Top 3 User friction points, 3. OPPORTUNITY LOSS (Revenue missed due to failed searches or abandoned checkouts), "
|
| 334 |
+
"4. Emerging market trends. Provide high-level executive recommendations."
|
| 335 |
+
)
|
| 336 |
+
user_prompt = f"Comprehensive Business Data (Last 7 Days):\n{json.dumps(data, indent=2, default=str)}"
|
| 337 |
+
res, tokens = await ai_service.call_high(prompt=user_prompt, system_instruction=system_prompt)
|
| 338 |
+
if res: await self._persist_memory("Weekly Business Intelligence Analysis", res)
|
| 339 |
+
return {"business_insight": res, "tokens": tokens}
|
| 340 |
+
|
| 341 |
+
res, tokens = await ai_service.call_medium(payload.get("prompt", ""))
|
| 342 |
+
return {"text": res, "tokens": tokens}
|
| 343 |
+
|
| 344 |
+
async def _fetch_behavioral_data(self) -> Dict[str, Any]:
|
| 345 |
+
"""Aggregates behavioral and financial signals."""
|
| 346 |
+
seven_days_ago = datetime.now(timezone.utc) - timedelta(days=7)
|
| 347 |
+
|
| 348 |
+
# 1. Traffic & Behaviour
|
| 349 |
+
traffic_stmt = select(AnalyticsTraffic.page, func.count(AnalyticsTraffic.id)).where(AnalyticsTraffic.timestamp >= seven_days_ago).group_by(AnalyticsTraffic.page).order_by(func.count(AnalyticsTraffic.id).desc()).limit(10)
|
| 350 |
+
|
| 351 |
+
# 2. Financials (Revenue)
|
| 352 |
+
revenue_stmt = select(func.sum(Transaction.amount)).where(Transaction.created_at >= seven_days_ago, Transaction.status == 'Settled')
|
| 353 |
+
pending_stmt = select(func.count(Transaction.id), func.sum(Transaction.amount)).where(Transaction.created_at >= seven_days_ago, Transaction.status == 'Pending')
|
| 354 |
+
|
| 355 |
+
# 3. Market Gaps (Opportunity Loss)
|
| 356 |
+
search_stmt = select(FailedSearch.query, func.sum(FailedSearch.count)).where(FailedSearch.timestamp >= seven_days_ago).group_by(FailedSearch.query).order_by(func.sum(FailedSearch.count).desc()).limit(10)
|
| 357 |
+
|
| 358 |
+
# 4. Talent Interaction
|
| 359 |
+
chat_stmt = select(AITalentChat.user_message).where(AITalentChat.timestamp >= seven_days_ago).limit(20)
|
| 360 |
+
|
| 361 |
+
traffic_res = await self.db.execute(traffic_stmt)
|
| 362 |
+
rev_res = await self.db.execute(revenue_stmt)
|
| 363 |
+
pend_res = await self.db.execute(pending_stmt)
|
| 364 |
+
search_res = await self.db.execute(search_stmt)
|
| 365 |
+
chat_res = await self.db.execute(chat_stmt)
|
| 366 |
+
|
| 367 |
+
rev_val = rev_res.scalar() or 0
|
| 368 |
+
pend_row = pend_res.fetchone() or (0, 0)
|
| 369 |
+
pend_count = pend_row[0]
|
| 370 |
+
pend_val = pend_row[1] or 0
|
| 371 |
+
|
| 372 |
+
return {
|
| 373 |
+
"traffic": [{"page": r[0], "hits": r[1]} for r in traffic_res.all()],
|
| 374 |
+
"revenue": {
|
| 375 |
+
"settled_idr": float(rev_val),
|
| 376 |
+
"pending_idr": float(pend_val),
|
| 377 |
+
"abandoned_count": pend_count
|
| 378 |
+
},
|
| 379 |
+
"opportunity_loss": {
|
| 380 |
+
"failed_searches": [{"query": r[0], "volume": r[1]} for r in search_res.all()],
|
| 381 |
+
"potential_match_revenue_idr": sum([r[1] for r in search_res.all()]) * 50000 # Estimated Rp 50k per missed search lead
|
| 382 |
+
},
|
| 383 |
+
"chat_sentiment_samples": [r[0] for r in chat_res.all()]
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
async def _recall_memories(self, query: str) -> List[CEOStrategicMemory]:
|
| 387 |
+
stmt = select(CEOStrategicMemory).order_by(CEOStrategicMemory.created_at.desc()).limit(5)
|
| 388 |
+
res = await self.db.execute(stmt)
|
| 389 |
+
return res.scalars().all()
|
| 390 |
+
|
| 391 |
+
async def _persist_memory(self, topic: str, res_text: str):
|
| 392 |
+
self.db.add(CEOStrategicMemory(topic=topic[:255], summary=res_text[:2000], decision_made="PENDING"))
|
| 393 |
+
|
| 394 |
+
async def _handle_fallback(self, tid, agent, task, payload, reason, err=None) -> Dict[str, Any]:
|
| 395 |
+
query = update(AgentStateLog).where(AgentStateLog.task_id == tid).values(
|
| 396 |
+
status="FAILED" if reason == "ERROR" else "ABORTED",
|
| 397 |
+
last_action=f"FALLBACK_{reason}",
|
| 398 |
+
error_message=err or f"Fallback triggered due to {reason}"
|
| 399 |
+
)
|
| 400 |
+
await self.db.execute(query)
|
| 401 |
+
await self.db.commit()
|
| 402 |
+
if task == "semantic_matching":
|
| 403 |
+
s, m = ai_service._algorithmic_match_score(payload["query"], payload["talent_data"])
|
| 404 |
+
return {"status": "fallback", "data": {"score": s, "summary": m, "tier": "algorithmic"}}
|
| 405 |
+
return {"status": "error", "reason": reason, "message": "AI service unavailable. Fallback executed."}
|
| 406 |
+
|
| 407 |
+
async def get_command_center_stats(self) -> Dict[str, Any]:
|
| 408 |
+
"""Provides a holistic view of the AI workforce status."""
|
| 409 |
+
today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
|
| 410 |
+
|
| 411 |
+
# 1. Quota Stats
|
| 412 |
+
quota = await self._check_quota_status()
|
| 413 |
+
|
| 414 |
+
# 2. Task Queue Stats
|
| 415 |
+
queue_stmt = select(AgentQueue.status, func.count(AgentQueue.id)).group_by(AgentQueue.status)
|
| 416 |
+
queue_res = await self.db.execute(queue_stmt)
|
| 417 |
+
queue_stats = {r[0]: r[1] for r in queue_res.all()}
|
| 418 |
+
|
| 419 |
+
# 3. Recent Agent Activity
|
| 420 |
+
activity_stmt = select(AgentStateLog).order_by(AgentStateLog.updated_at.desc()).limit(10)
|
| 421 |
+
activity_res = await self.db.execute(activity_stmt)
|
| 422 |
+
recent_activity = [
|
| 423 |
+
{
|
| 424 |
+
"agent": a.agent_name,
|
| 425 |
+
"task": a.memory_context.get("task_name", "Unknown"),
|
| 426 |
+
"status": a.status,
|
| 427 |
+
"last_action": a.last_action,
|
| 428 |
+
"timestamp": a.updated_at
|
| 429 |
+
} for a in activity_res.scalars().all()
|
| 430 |
+
]
|
| 431 |
+
|
| 432 |
+
return {
|
| 433 |
+
"quota": quota,
|
| 434 |
+
"queue": queue_stats,
|
| 435 |
+
"activity": recent_activity,
|
| 436 |
+
"status": "HEALTHY" if quota["rpd_percent"] < self.CRITICAL_THRESHOLD else "TRIAGE_MODE"
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
async def _notify_user_via_email(self, email, task, data):
|
| 440 |
+
try:
|
| 441 |
+
if task == "academy_feedback": await self.email_service.send_feedback_email(email, data)
|
| 442 |
+
elif task in ["cv_analysis", "bulk_vetting"]:
|
| 443 |
+
await self.email_service.send_feedback_email(email, {
|
| 444 |
+
"feedback_intro": "Halo! Brigawan telah selesai menganalisis dokumen Anda secara mendalam. Berikut adalah hasil review dan link aktivasi akun Anda.",
|
| 445 |
+
"strengths": data.get("category", "Talenta Hijau Potensial"),
|
| 446 |
+
"areas_for_improvement": ", ".join(data.get("skill_gaps", []) or ["Terus tingkatkan sertifikasi K3"]),
|
| 447 |
+
"concrete_tips": [data.get("transition_path", "Lanjutkan eksplorasi di sektor EBT.")],
|
| 448 |
+
"next_steps": "Klik tombol di bawah ini untuk mengaktivasi akun Anda.",
|
| 449 |
+
"closing": "Selamat bergabung di ekosistem hijau Indonesia! 🌿"
|
| 450 |
+
})
|
| 451 |
+
elif task == "career_advice":
|
| 452 |
+
await self.email_service.send_feedback_email(email, {
|
| 453 |
+
"feedback_intro": "Halo! Ini adalah saran karir strategis yang dirancang khusus untuk Anda oleh Brigawan AI.",
|
| 454 |
+
"strengths": "Visi Karir Hijau Anda",
|
| 455 |
+
"areas_for_improvement": data.get("advice_snippet", "Fokus pada pengembangan spesialisasi sektor."),
|
| 456 |
+
"concrete_tips": data.get("next_steps", ["Ikuti pelatihan SKKNI terkait"]),
|
| 457 |
+
"next_steps": data.get("full_recommendation", "Cek dashboard."),
|
| 458 |
+
"closing": "Ingat, keahlian Anda adalah kunci transisi energi Indonesia. Semangat!"
|
| 459 |
+
})
|
| 460 |
+
except Exception as e: logger.error(f"[Antigravity] Email notification failed: {e}")
|
app/services/audit_service.py
CHANGED
|
@@ -1,134 +1,134 @@
|
|
| 1 |
-
"""Audit service for managing the cryptographic ledger and archiving.
|
| 2 |
-
|
| 3 |
-
Handles tamper detection, chain verification, and the archiving pipeline.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import uuid
|
| 7 |
-
from datetime import datetime, timedelta, timezone
|
| 8 |
-
from typing import List, Optional, Dict, Any
|
| 9 |
-
|
| 10 |
-
from sqlalchemy import text, select, func
|
| 11 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
-
from loguru import logger
|
| 13 |
-
|
| 14 |
-
from app.models.security import AuditTrail, AuditAnchor
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
class AuditService:
|
| 18 |
-
"""Service for cryptographic audit operations."""
|
| 19 |
-
|
| 20 |
-
async def verify_integrity(self, db: AsyncSession) -> Dict[str, Any]:
|
| 21 |
-
"""
|
| 22 |
-
Verify the integrity of the entire audit trail.
|
| 23 |
-
Returns a report of any detected tampering or chain breaks.
|
| 24 |
-
"""
|
| 25 |
-
# Verification query from the blueprint
|
| 26 |
-
verify_query = text("""
|
| 27 |
-
WITH verified_trail AS (
|
| 28 |
-
SELECT
|
| 29 |
-
a.id,
|
| 30 |
-
a.record_table,
|
| 31 |
-
a.record_id,
|
| 32 |
-
a.action_type,
|
| 33 |
-
a.ciphertext_hash,
|
| 34 |
-
a.signature_hash,
|
| 35 |
-
a.previous_hash,
|
| 36 |
-
a.current_hash,
|
| 37 |
-
encode(
|
| 38 |
-
digest(
|
| 39 |
-
a.record_table || '|' ||
|
| 40 |
-
a.record_id::text || '|' ||
|
| 41 |
-
a.action_type || '|' ||
|
| 42 |
-
COALESCE(a.ciphertext_hash, '') || '|' ||
|
| 43 |
-
COALESCE(a.signature_hash, '') || '|' ||
|
| 44 |
-
a.previous_hash,
|
| 45 |
-
'sha256'
|
| 46 |
-
),
|
| 47 |
-
'hex'
|
| 48 |
-
) AS calculated_current_hash,
|
| 49 |
-
COALESCE(
|
| 50 |
-
LAG(a.current_hash) OVER (ORDER BY a.id ASC),
|
| 51 |
-
'0000000000000000000000000000000000000000000000000000000000000000'
|
| 52 |
-
) AS expected_prev_hash
|
| 53 |
-
FROM audit.audit_trail a
|
| 54 |
-
)
|
| 55 |
-
SELECT
|
| 56 |
-
v.id,
|
| 57 |
-
v.record_id,
|
| 58 |
-
v.action_type,
|
| 59 |
-
v.current_hash,
|
| 60 |
-
v.calculated_current_hash,
|
| 61 |
-
v.previous_hash,
|
| 62 |
-
v.expected_prev_hash,
|
| 63 |
-
CASE
|
| 64 |
-
WHEN v.current_hash != v.calculated_current_hash
|
| 65 |
-
THEN 'Hash verification failed: current hash does not match payload'
|
| 66 |
-
WHEN v.previous_hash != v.expected_prev_hash
|
| 67 |
-
AND NOT EXISTS (SELECT 1 FROM audit.audit_anchors WHERE anchor_hash = v.previous_hash)
|
| 68 |
-
THEN 'Hash chain broken: previous_hash does not match previous block or anchor'
|
| 69 |
-
ELSE 'OK'
|
| 70 |
-
END AS verification_status
|
| 71 |
-
FROM verified_trail v
|
| 72 |
-
WHERE v.current_hash != v.calculated_current_hash
|
| 73 |
-
OR (v.previous_hash != v.expected_prev_hash
|
| 74 |
-
AND NOT EXISTS (SELECT 1 FROM audit.audit_anchors WHERE anchor_hash = v.previous_hash));
|
| 75 |
-
""")
|
| 76 |
-
|
| 77 |
-
result = await db.execute(verify_query)
|
| 78 |
-
anomalies = [dict(row) for row in result.mappings().all()]
|
| 79 |
-
|
| 80 |
-
if not anomalies:
|
| 81 |
-
logger.info("Audit trail integrity verified: OK")
|
| 82 |
-
return {"status": "OK", "anomalies": []}
|
| 83 |
-
|
| 84 |
-
logger.error(f"Audit trail integrity violation detected! {len(anomalies)} anomalies found.")
|
| 85 |
-
return {"status": "VIOLATION", "anomalies": anomalies}
|
| 86 |
-
|
| 87 |
-
async def run_archiving(self, db: AsyncSession, days_threshold: int = 365) -> Dict[str, Any]:
|
| 88 |
-
"""
|
| 89 |
-
Archive old audit logs to cold storage and create an anchor block.
|
| 90 |
-
"""
|
| 91 |
-
threshold_date = datetime.now(timezone.utc) - timedelta(days=days_threshold)
|
| 92 |
-
|
| 93 |
-
# 1. Identify logs to prune
|
| 94 |
-
prune_query = select(AuditTrail).where(AuditTrail.timestamp < threshold_date).order_by(AuditTrail.id.asc())
|
| 95 |
-
result = await db.execute(prune_query)
|
| 96 |
-
logs_to_prune = result.scalars().all()
|
| 97 |
-
|
| 98 |
-
if not logs_to_prune:
|
| 99 |
-
return {"status": "SKIPPED", "message": "No logs found matching the threshold."}
|
| 100 |
-
|
| 101 |
-
max_id = logs_to_prune[-1].id
|
| 102 |
-
anchor_hash = logs_to_prune[-1].current_hash
|
| 103 |
-
|
| 104 |
-
# 2. Simulate Cold Storage Export (In production, write to GCS/S3)
|
| 105 |
-
# archive_data = [log.to_dict() for log in logs_to_prune]
|
| 106 |
-
# cold_storage_uri = await self._upload_to_gcs(archive_data)
|
| 107 |
-
cold_storage_uri = f"gs://briga-audit-archive/archive_{datetime.now(timezone.utc).strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}.jsonl.gz"
|
| 108 |
-
archive_file_hash = "simulated_sha256_hash_of_exported_file"
|
| 109 |
-
|
| 110 |
-
# 3. Create Anchor Block
|
| 111 |
-
anchor = AuditAnchor(
|
| 112 |
-
max_audit_id=max_id,
|
| 113 |
-
anchor_hash=anchor_hash,
|
| 114 |
-
cold_storage_uri=cold_storage_uri,
|
| 115 |
-
archive_file_hash=archive_file_hash
|
| 116 |
-
)
|
| 117 |
-
db.add(anchor)
|
| 118 |
-
|
| 119 |
-
# 4. Prune Logs
|
| 120 |
-
delete_query = text("DELETE FROM audit.audit_trail WHERE id <= :max_id")
|
| 121 |
-
await db.execute(delete_query, {"max_id": max_id})
|
| 122 |
-
|
| 123 |
-
await db.commit()
|
| 124 |
-
|
| 125 |
-
logger.info(f"Archived {len(logs_to_prune)} logs. Anchor created at ID {max_id}.")
|
| 126 |
-
return {
|
| 127 |
-
"status": "SUCCESS",
|
| 128 |
-
"archived_count": len(logs_to_prune),
|
| 129 |
-
"anchor_id": max_id,
|
| 130 |
-
"cold_storage_uri": cold_storage_uri
|
| 131 |
-
}
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
audit_service = AuditService()
|
|
|
|
| 1 |
+
"""Audit service for managing the cryptographic ledger and archiving.
|
| 2 |
+
|
| 3 |
+
Handles tamper detection, chain verification, and the archiving pipeline.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import uuid
|
| 7 |
+
from datetime import datetime, timedelta, timezone
|
| 8 |
+
from typing import List, Optional, Dict, Any
|
| 9 |
+
|
| 10 |
+
from sqlalchemy import text, select, func
|
| 11 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
+
from loguru import logger
|
| 13 |
+
|
| 14 |
+
from app.models.security import AuditTrail, AuditAnchor
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class AuditService:
|
| 18 |
+
"""Service for cryptographic audit operations."""
|
| 19 |
+
|
| 20 |
+
async def verify_integrity(self, db: AsyncSession) -> Dict[str, Any]:
|
| 21 |
+
"""
|
| 22 |
+
Verify the integrity of the entire audit trail.
|
| 23 |
+
Returns a report of any detected tampering or chain breaks.
|
| 24 |
+
"""
|
| 25 |
+
# Verification query from the blueprint
|
| 26 |
+
verify_query = text("""
|
| 27 |
+
WITH verified_trail AS (
|
| 28 |
+
SELECT
|
| 29 |
+
a.id,
|
| 30 |
+
a.record_table,
|
| 31 |
+
a.record_id,
|
| 32 |
+
a.action_type,
|
| 33 |
+
a.ciphertext_hash,
|
| 34 |
+
a.signature_hash,
|
| 35 |
+
a.previous_hash,
|
| 36 |
+
a.current_hash,
|
| 37 |
+
encode(
|
| 38 |
+
digest(
|
| 39 |
+
a.record_table || '|' ||
|
| 40 |
+
a.record_id::text || '|' ||
|
| 41 |
+
a.action_type || '|' ||
|
| 42 |
+
COALESCE(a.ciphertext_hash, '') || '|' ||
|
| 43 |
+
COALESCE(a.signature_hash, '') || '|' ||
|
| 44 |
+
a.previous_hash,
|
| 45 |
+
'sha256'
|
| 46 |
+
),
|
| 47 |
+
'hex'
|
| 48 |
+
) AS calculated_current_hash,
|
| 49 |
+
COALESCE(
|
| 50 |
+
LAG(a.current_hash) OVER (ORDER BY a.id ASC),
|
| 51 |
+
'0000000000000000000000000000000000000000000000000000000000000000'
|
| 52 |
+
) AS expected_prev_hash
|
| 53 |
+
FROM audit.audit_trail a
|
| 54 |
+
)
|
| 55 |
+
SELECT
|
| 56 |
+
v.id,
|
| 57 |
+
v.record_id,
|
| 58 |
+
v.action_type,
|
| 59 |
+
v.current_hash,
|
| 60 |
+
v.calculated_current_hash,
|
| 61 |
+
v.previous_hash,
|
| 62 |
+
v.expected_prev_hash,
|
| 63 |
+
CASE
|
| 64 |
+
WHEN v.current_hash != v.calculated_current_hash
|
| 65 |
+
THEN 'Hash verification failed: current hash does not match payload'
|
| 66 |
+
WHEN v.previous_hash != v.expected_prev_hash
|
| 67 |
+
AND NOT EXISTS (SELECT 1 FROM audit.audit_anchors WHERE anchor_hash = v.previous_hash)
|
| 68 |
+
THEN 'Hash chain broken: previous_hash does not match previous block or anchor'
|
| 69 |
+
ELSE 'OK'
|
| 70 |
+
END AS verification_status
|
| 71 |
+
FROM verified_trail v
|
| 72 |
+
WHERE v.current_hash != v.calculated_current_hash
|
| 73 |
+
OR (v.previous_hash != v.expected_prev_hash
|
| 74 |
+
AND NOT EXISTS (SELECT 1 FROM audit.audit_anchors WHERE anchor_hash = v.previous_hash));
|
| 75 |
+
""")
|
| 76 |
+
|
| 77 |
+
result = await db.execute(verify_query)
|
| 78 |
+
anomalies = [dict(row) for row in result.mappings().all()]
|
| 79 |
+
|
| 80 |
+
if not anomalies:
|
| 81 |
+
logger.info("Audit trail integrity verified: OK")
|
| 82 |
+
return {"status": "OK", "anomalies": []}
|
| 83 |
+
|
| 84 |
+
logger.error(f"Audit trail integrity violation detected! {len(anomalies)} anomalies found.")
|
| 85 |
+
return {"status": "VIOLATION", "anomalies": anomalies}
|
| 86 |
+
|
| 87 |
+
async def run_archiving(self, db: AsyncSession, days_threshold: int = 365) -> Dict[str, Any]:
|
| 88 |
+
"""
|
| 89 |
+
Archive old audit logs to cold storage and create an anchor block.
|
| 90 |
+
"""
|
| 91 |
+
threshold_date = datetime.now(timezone.utc) - timedelta(days=days_threshold)
|
| 92 |
+
|
| 93 |
+
# 1. Identify logs to prune
|
| 94 |
+
prune_query = select(AuditTrail).where(AuditTrail.timestamp < threshold_date).order_by(AuditTrail.id.asc())
|
| 95 |
+
result = await db.execute(prune_query)
|
| 96 |
+
logs_to_prune = result.scalars().all()
|
| 97 |
+
|
| 98 |
+
if not logs_to_prune:
|
| 99 |
+
return {"status": "SKIPPED", "message": "No logs found matching the threshold."}
|
| 100 |
+
|
| 101 |
+
max_id = logs_to_prune[-1].id
|
| 102 |
+
anchor_hash = logs_to_prune[-1].current_hash
|
| 103 |
+
|
| 104 |
+
# 2. Simulate Cold Storage Export (In production, write to GCS/S3)
|
| 105 |
+
# archive_data = [log.to_dict() for log in logs_to_prune]
|
| 106 |
+
# cold_storage_uri = await self._upload_to_gcs(archive_data)
|
| 107 |
+
cold_storage_uri = f"gs://briga-audit-archive/archive_{datetime.now(timezone.utc).strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}.jsonl.gz"
|
| 108 |
+
archive_file_hash = "simulated_sha256_hash_of_exported_file"
|
| 109 |
+
|
| 110 |
+
# 3. Create Anchor Block
|
| 111 |
+
anchor = AuditAnchor(
|
| 112 |
+
max_audit_id=max_id,
|
| 113 |
+
anchor_hash=anchor_hash,
|
| 114 |
+
cold_storage_uri=cold_storage_uri,
|
| 115 |
+
archive_file_hash=archive_file_hash
|
| 116 |
+
)
|
| 117 |
+
db.add(anchor)
|
| 118 |
+
|
| 119 |
+
# 4. Prune Logs
|
| 120 |
+
delete_query = text("DELETE FROM audit.audit_trail WHERE id <= :max_id")
|
| 121 |
+
await db.execute(delete_query, {"max_id": max_id})
|
| 122 |
+
|
| 123 |
+
await db.commit()
|
| 124 |
+
|
| 125 |
+
logger.info(f"Archived {len(logs_to_prune)} logs. Anchor created at ID {max_id}.")
|
| 126 |
+
return {
|
| 127 |
+
"status": "SUCCESS",
|
| 128 |
+
"archived_count": len(logs_to_prune),
|
| 129 |
+
"anchor_id": max_id,
|
| 130 |
+
"cold_storage_uri": cold_storage_uri
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
audit_service = AuditService()
|
app/services/auth_service.py
CHANGED
|
@@ -1,379 +1,379 @@
|
|
| 1 |
-
"""Auth service — registration, login, Google OAuth, JWT management.
|
| 2 |
-
|
| 3 |
-
Zero-cost architecture:
|
| 4 |
-
- Google OAuth: Google Cloud free tier
|
| 5 |
-
- Email/password: bcrypt (free)
|
| 6 |
-
- Rate limiting: in-memory (no Redis)
|
| 7 |
-
- Free tier: 3 trial credits, 1 job posting
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
import json
|
| 11 |
-
import secrets
|
| 12 |
-
from datetime import datetime, timezone
|
| 13 |
-
from typing import Any, Dict, Optional
|
| 14 |
-
|
| 15 |
-
import httpx
|
| 16 |
-
from loguru import logger
|
| 17 |
-
from sqlalchemy import or_, select
|
| 18 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 19 |
-
|
| 20 |
-
from app.models.talent import Talent
|
| 21 |
-
from app.models.employer import ClientAccount, Company
|
| 22 |
-
from app.utils.errors import ErrorCode, raise_error
|
| 23 |
-
from app.utils.security import (
|
| 24 |
-
create_access_token,
|
| 25 |
-
hash_password,
|
| 26 |
-
hash_legacy_gas_password,
|
| 27 |
-
verify_password,
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
FREE_TIER = {"credits": 3, "max_jobs": 1, "seats": 1, "ai_matching": False, "rate_limit": 100}
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
# ─── Helpers ────────────────────────────────────────────────────────────────
|
| 35 |
-
|
| 36 |
-
def _user_response(email: str, name: str, user_id: str, role: str) -> dict:
|
| 37 |
-
return {
|
| 38 |
-
"id": user_id, "email": email, "name": name, "role": role,
|
| 39 |
-
"tier": "free", "credits_remaining": FREE_TIER["credits"],
|
| 40 |
-
"is_verified": False, "created_at": datetime.now(timezone.utc),
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def _auth_response(token: str, user: dict, message: Optional[str] = None) -> dict:
|
| 45 |
-
return {
|
| 46 |
-
"success": True, "access_token": token, "token_type": "bearer",
|
| 47 |
-
"expires_in": 86400, "user": user,
|
| 48 |
-
**({"message": message} if message else {}),
|
| 49 |
-
}
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
async def _global_duplicate_check(db: AsyncSession, email: str) -> Optional[str]:
|
| 53 |
-
"""Check email across all user tables (GAS isGlobalDuplicate equivalent)."""
|
| 54 |
-
for table in [Talent, ClientAccount]:
|
| 55 |
-
result = await db.execute(select(table).where(table.email == email))
|
| 56 |
-
if result.scalar_one_or_none():
|
| 57 |
-
return table.__tablename__
|
| 58 |
-
return None
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
# ─── Registration ───────────────────────────────────────────────────────────
|
| 62 |
-
|
| 63 |
-
async def register_talent(db: AsyncSession, data: dict) -> dict:
|
| 64 |
-
email = data["email"].lower().strip()
|
| 65 |
-
|
| 66 |
-
# Global duplicate check (matches GAS isGlobalDuplicate)
|
| 67 |
-
dup = await _global_duplicate_check(db, email)
|
| 68 |
-
if dup:
|
| 69 |
-
raise_error(
|
| 70 |
-
f"Email already registered as a {dup.replace('_', ' ')}. Try logging in.",
|
| 71 |
-
code=ErrorCode.DUPLICATE_EMAIL,
|
| 72 |
-
)
|
| 73 |
-
|
| 74 |
-
talent_id = f"BRIGA-GT-{secrets.token_hex(3).upper()}"
|
| 75 |
-
talent = Talent(
|
| 76 |
-
talent_id=talent_id,
|
| 77 |
-
name=data["name"],
|
| 78 |
-
email=email,
|
| 79 |
-
password_hash=hash_password(data["password"]),
|
| 80 |
-
phone=data.get("phone", ""),
|
| 81 |
-
education=data.get("education", ""),
|
| 82 |
-
experience=data.get("experience", ""),
|
| 83 |
-
location=data.get("location", ""),
|
| 84 |
-
skill_tags=data.get("skill_tags", ""),
|
| 85 |
-
cv_link=data.get("cv_link", ""),
|
| 86 |
-
linkedin_link=data.get("linkedin_link", ""),
|
| 87 |
-
score=70,
|
| 88 |
-
verification_status="Pending",
|
| 89 |
-
green_score=0,
|
| 90 |
-
)
|
| 91 |
-
db.add(talent)
|
| 92 |
-
await db.commit()
|
| 93 |
-
|
| 94 |
-
token = create_access_token(subject=talent_id, email=email, role="talent")
|
| 95 |
-
user = _user_response(email, data["name"], talent_id, "talent")
|
| 96 |
-
logger.info(f"Registered talent: {email}")
|
| 97 |
-
return _auth_response(token, user, f"Welcome! {FREE_TIER['credits']} trial credits activated.")
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
async def register_talent_from_whatsapp(db: AsyncSession, data: dict) -> dict:
|
| 101 |
-
"""Special registration for WhatsApp users with auto-generated password."""
|
| 102 |
-
email = data.get("email", "").lower().strip()
|
| 103 |
-
if not email:
|
| 104 |
-
raise_error("Email is required for registration.", code=ErrorCode.TOKEN_INVALID)
|
| 105 |
-
|
| 106 |
-
# Check if already registered
|
| 107 |
-
result = await db.execute(select(Talent).where(Talent.email == email))
|
| 108 |
-
existing = result.scalar_one_or_none()
|
| 109 |
-
|
| 110 |
-
if existing:
|
| 111 |
-
# If exists, just log them in (assuming they confirmed via their own WhatsApp)
|
| 112 |
-
token = create_access_token(subject=existing.talent_id, email=email, role="talent")
|
| 113 |
-
user = _user_response(email, existing.name, existing.talent_id, "talent")
|
| 114 |
-
return _auth_response(token, user, "Welcome back!")
|
| 115 |
-
|
| 116 |
-
# New registration with default password (user should change it later)
|
| 117 |
-
# Default password is "Briga" + phone last 4 digits for simplicity
|
| 118 |
-
phone = data.get("phone", "0000")
|
| 119 |
-
default_pass = f"Briga{phone[-4:]}"
|
| 120 |
-
|
| 121 |
-
reg_data = {
|
| 122 |
-
"email": email,
|
| 123 |
-
"name": data.get("name", "Talent WhatsApp"),
|
| 124 |
-
"password": default_pass,
|
| 125 |
-
"phone": phone
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
# 1. Register talent (password will be hashed inside register_talent)
|
| 129 |
-
result = await register_talent(db, reg_data)
|
| 130 |
-
|
| 131 |
-
# 2. Send welcome email with the cleartext default password
|
| 132 |
-
if result.get("success"):
|
| 133 |
-
from app.services.whatsapp_email_service import wa_email_service
|
| 134 |
-
# We send the cleartext password here before it was hashed only in memory for the email
|
| 135 |
-
await wa_email_service.send_welcome_email(email, reg_data["name"], default_pass)
|
| 136 |
-
|
| 137 |
-
return result
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
async def register_employer(db: AsyncSession, data: dict) -> dict:
|
| 141 |
-
email = data["email"].lower().strip()
|
| 142 |
-
|
| 143 |
-
dup = await _global_duplicate_check(db, email)
|
| 144 |
-
if dup:
|
| 145 |
-
raise_error(
|
| 146 |
-
f"Email already registered as a {dup.replace('_', ' ')}. Try logging in.",
|
| 147 |
-
code=ErrorCode.DUPLICATE_EMAIL,
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
company_id = f"BRIGA-CO-{secrets.token_hex(4).upper()}"
|
| 151 |
-
company = Company(
|
| 152 |
-
id=company_id,
|
| 153 |
-
name=data.get("company_name", email.split("@")[1]),
|
| 154 |
-
website=data.get("website", ""),
|
| 155 |
-
tier="free",
|
| 156 |
-
credit_balance=FREE_TIER["credits"],
|
| 157 |
-
seats_limit=FREE_TIER["seats"],
|
| 158 |
-
max_jobs=FREE_TIER["max_jobs"],
|
| 159 |
-
status="PENDING",
|
| 160 |
-
)
|
| 161 |
-
db.add(company)
|
| 162 |
-
|
| 163 |
-
client_id = f"BRIGA-ST-{secrets.token_hex(4).upper()}"
|
| 164 |
-
client = ClientAccount(
|
| 165 |
-
id=client_id,
|
| 166 |
-
company_id=company_id,
|
| 167 |
-
email=email,
|
| 168 |
-
password_hash=hash_password(data["password"]),
|
| 169 |
-
name=data.get("name", "Recruiter"),
|
| 170 |
-
role="Recruiter",
|
| 171 |
-
status="PENDING", # Both company & client PENDING until admin approval
|
| 172 |
-
)
|
| 173 |
-
db.add(client)
|
| 174 |
-
await db.commit()
|
| 175 |
-
|
| 176 |
-
token = create_access_token(subject=client_id, email=email, role="employer")
|
| 177 |
-
user = _user_response(email, data.get("name", "Recruiter"), client_id, "employer")
|
| 178 |
-
logger.info(f"Registered employer: {email} (Company: {company_id})")
|
| 179 |
-
return _auth_response(token, user, "Company registered on Free tier. Pending admin approval.")
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
# ─── Login ───────────────────────────────────────────────────────────────────
|
| 183 |
-
|
| 184 |
-
async def _try_talent_login(db: AsyncSession, email: str, password: str) -> Optional[dict]:
|
| 185 |
-
result = await db.execute(select(Talent).where(Talent.email == email))
|
| 186 |
-
talent = result.scalar_one_or_none()
|
| 187 |
-
if not talent or not talent.password_hash:
|
| 188 |
-
return None
|
| 189 |
-
|
| 190 |
-
# Sentinel check: Google OAuth accounts have no password
|
| 191 |
-
if talent.password_hash == "GOOGLE_OAUTH":
|
| 192 |
-
raise_error(
|
| 193 |
-
"This account uses Google Login. Sign in with Google.",
|
| 194 |
-
code=ErrorCode.INVALID_CREDENTIALS,
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
# Try bcrypt first
|
| 198 |
-
if verify_password(password, talent.password_hash):
|
| 199 |
-
token = create_access_token(subject=talent.talent_id, email=email, role="talent")
|
| 200 |
-
user = _user_response(email, talent.name, talent.talent_id, "talent")
|
| 201 |
-
return _auth_response(token, user)
|
| 202 |
-
|
| 203 |
-
# Legacy GAS hash fallback + upgrade to bcrypt
|
| 204 |
-
if talent.password_hash == hash_legacy_gas_password(password, email):
|
| 205 |
-
talent.password_hash = hash_password(password)
|
| 206 |
-
await db.commit()
|
| 207 |
-
token = create_access_token(subject=talent.talent_id, email=email, role="talent")
|
| 208 |
-
user = _user_response(email, talent.name, talent.talent_id, "talent")
|
| 209 |
-
return _auth_response(token, user)
|
| 210 |
-
|
| 211 |
-
return None
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
async def _try_employer_login(db: AsyncSession, email: str, password: str) -> Optional[dict]:
|
| 215 |
-
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 216 |
-
client = result.scalar_one_or_none()
|
| 217 |
-
if not client or not client.password_hash:
|
| 218 |
-
return None
|
| 219 |
-
|
| 220 |
-
if not verify_password(password, client.password_hash):
|
| 221 |
-
return None
|
| 222 |
-
|
| 223 |
-
token = create_access_token(subject=client.id, email=email, role="employer")
|
| 224 |
-
user = _user_response(email, client.name, client.id, "employer")
|
| 225 |
-
return _auth_response(token, user)
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
async def login_email(db: AsyncSession, email: str, password: str) -> dict:
|
| 229 |
-
email = email.lower().strip()
|
| 230 |
-
|
| 231 |
-
# Try talent first, then employer
|
| 232 |
-
talent_result = await _try_talent_login(db, email, password)
|
| 233 |
-
if talent_result:
|
| 234 |
-
return talent_result
|
| 235 |
-
|
| 236 |
-
employer_result = await _try_employer_login(db, email, password)
|
| 237 |
-
if employer_result:
|
| 238 |
-
return employer_result
|
| 239 |
-
|
| 240 |
-
raise_error("Invalid email or password.", code=ErrorCode.INVALID_CREDENTIALS, status_code=401)
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
async def login_google(db: AsyncSession, id_token: str) -> dict:
|
| 244 |
-
"""Google OAuth login. Checks both Talent and ClientAccount tables.
|
| 245 |
-
|
| 246 |
-
Crash-proof:
|
| 247 |
-
- If Google's tokeninfo endpoint is unreachable, returns a graceful error
|
| 248 |
-
- No hard crash on network failure — always returns a structured response
|
| 249 |
-
"""
|
| 250 |
-
# Verify token with Google
|
| 251 |
-
google_data = None
|
| 252 |
-
try:
|
| 253 |
-
async with httpx.AsyncClient() as client:
|
| 254 |
-
resp = await client.get(
|
| 255 |
-
"https://oauth2.googleapis.com/tokeninfo",
|
| 256 |
-
params={"id_token": id_token},
|
| 257 |
-
timeout=10,
|
| 258 |
-
)
|
| 259 |
-
if resp.status_code != 200:
|
| 260 |
-
raise_error("Invalid Google ID token.", code=ErrorCode.TOKEN_INVALID, status_code=401)
|
| 261 |
-
google_data = resp.json()
|
| 262 |
-
except httpx.TimeoutException:
|
| 263 |
-
logger.error("Google OAuth: tokeninfo endpoint timed out")
|
| 264 |
-
raise_error("Google verification timed out. Please try again.", code=ErrorCode.NETWORK_ERROR, status_code=502)
|
| 265 |
-
except httpx.RequestError as e:
|
| 266 |
-
logger.error(f"Google OAuth network error: {e}")
|
| 267 |
-
raise_error("Could not verify Google token. Check your internet connection.", code=ErrorCode.NETWORK_ERROR, status_code=502)
|
| 268 |
-
except Exception as e:
|
| 269 |
-
logger.error(f"Google OAuth unexpected error: {e}")
|
| 270 |
-
raise_error("Google verification failed. Please try again.", code=ErrorCode.NETWORK_ERROR, status_code=502)
|
| 271 |
-
|
| 272 |
-
if google_data is None:
|
| 273 |
-
raise_error("Google verification returned no data.", code=ErrorCode.NETWORK_ERROR, status_code=502)
|
| 274 |
-
|
| 275 |
-
email = google_data.get("email", "").lower().strip()
|
| 276 |
-
google_name = google_data.get("name", "Google User")
|
| 277 |
-
google_id = google_data.get("sub", "")
|
| 278 |
-
|
| 279 |
-
if not email:
|
| 280 |
-
raise_error("Google account has no email. Please use a different account.", code=ErrorCode.TOKEN_INVALID, status_code=401)
|
| 281 |
-
|
| 282 |
-
# Search across both tables
|
| 283 |
-
result = await db.execute(select(Talent).where(Talent.email == email))
|
| 284 |
-
talent = result.scalar_one_or_none()
|
| 285 |
-
if talent:
|
| 286 |
-
# Existing talent — log them in
|
| 287 |
-
token = create_access_token(subject=talent.talent_id, email=email, role="talent")
|
| 288 |
-
user = _user_response(email, talent.name, talent.talent_id, "talent")
|
| 289 |
-
logger.info(f"Google login (existing talent): {email}")
|
| 290 |
-
return _auth_response(token, user, "Welcome back!")
|
| 291 |
-
|
| 292 |
-
# Check employer table
|
| 293 |
-
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 294 |
-
client = result.scalar_one_or_none()
|
| 295 |
-
if client:
|
| 296 |
-
token = create_access_token(subject=client.id, email=email, role="employer")
|
| 297 |
-
user = _user_response(email, client.name, client.id, "employer")
|
| 298 |
-
logger.info(f"Google login (existing employer): {email}")
|
| 299 |
-
return _auth_response(token, user, "Welcome back!")
|
| 300 |
-
|
| 301 |
-
# New user — auto-create talent account (matches GAS behavior)
|
| 302 |
-
talent_id = f"BRIGA-GT-{secrets.token_hex(3).upper()}"
|
| 303 |
-
new_talent = Talent(
|
| 304 |
-
talent_id=talent_id,
|
| 305 |
-
name=google_name,
|
| 306 |
-
email=email,
|
| 307 |
-
password_hash="GOOGLE_OAUTH", # Sentinel — no password login allowed
|
| 308 |
-
verification_status="Verified", # Google-verified email
|
| 309 |
-
score=70,
|
| 310 |
-
green_score=0,
|
| 311 |
-
)
|
| 312 |
-
db.add(new_talent)
|
| 313 |
-
await db.commit()
|
| 314 |
-
|
| 315 |
-
token = create_access_token(subject=talent_id, email=email, role="talent")
|
| 316 |
-
user = _user_response(email, google_name, talent_id, "talent")
|
| 317 |
-
logger.info(f"Google login (new talent): {email}")
|
| 318 |
-
return _auth_response(token, user, "Account created via Google. Welcome to Brigawan!")
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
async def admin_login(db: AsyncSession, email: str, password: str) -> dict:
|
| 322 |
-
"""Admin login. Matches GAS admin check pattern.
|
| 323 |
-
For now, uses the same JWT flow with elevated role.
|
| 324 |
-
"""
|
| 325 |
-
if email == "admin@briga.id" and password == settings.admin_password:
|
| 326 |
-
token = create_access_token(subject="admin", email=email, role="admin")
|
| 327 |
-
user = {
|
| 328 |
-
"id": "admin",
|
| 329 |
-
"email": email,
|
| 330 |
-
"name": "Admin Brigawan",
|
| 331 |
-
"role": "admin",
|
| 332 |
-
"tier": "enterprise",
|
| 333 |
-
"credits_remaining": 9999,
|
| 334 |
-
"is_verified": True,
|
| 335 |
-
}
|
| 336 |
-
return _auth_response(token, user, "Admin login successful.")
|
| 337 |
-
raise_error("Invalid admin credentials.", code=ErrorCode.INVALID_CREDENTIALS, status_code=401)
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
async def get_user_by_token(db: AsyncSession, email: str, role: str) -> Optional[dict]:
|
| 341 |
-
"""Get user profile by JWT payload.
|
| 342 |
-
Used by GET /v1/auth/me endpoint.
|
| 343 |
-
"""
|
| 344 |
-
try:
|
| 345 |
-
if role == "talent":
|
| 346 |
-
result = await db.execute(select(Talent).where(Talent.email == email))
|
| 347 |
-
talent = result.scalar_one_or_none()
|
| 348 |
-
if not talent:
|
| 349 |
-
return None
|
| 350 |
-
return {
|
| 351 |
-
"id": talent.talent_id,
|
| 352 |
-
"email": talent.email,
|
| 353 |
-
"name": talent.name,
|
| 354 |
-
"role": "talent",
|
| 355 |
-
"tier": "free",
|
| 356 |
-
"credits_remaining": 3,
|
| 357 |
-
"is_verified": talent.verification_status == "Verified",
|
| 358 |
-
}
|
| 359 |
-
elif role == "employer":
|
| 360 |
-
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 361 |
-
client = result.scalar_one_or_none()
|
| 362 |
-
if not client:
|
| 363 |
-
return None
|
| 364 |
-
# Get company info for tier and credits
|
| 365 |
-
result2 = await db.execute(select(Company).where(Company.id == client.company_id))
|
| 366 |
-
company = result2.scalar_one_or_none()
|
| 367 |
-
return {
|
| 368 |
-
"id": client.id,
|
| 369 |
-
"email": client.email,
|
| 370 |
-
"name": client.name,
|
| 371 |
-
"role": "employer",
|
| 372 |
-
"tier": company.tier if company else "free",
|
| 373 |
-
"credits_remaining": company.credit_balance if company else 3,
|
| 374 |
-
"is_verified": client.status == "Active",
|
| 375 |
-
}
|
| 376 |
-
return None
|
| 377 |
-
except Exception as e:
|
| 378 |
-
logger.error(f"get_user_by_token error: {e}")
|
| 379 |
-
return None
|
|
|
|
| 1 |
+
"""Auth service — registration, login, Google OAuth, JWT management.
|
| 2 |
+
|
| 3 |
+
Zero-cost architecture:
|
| 4 |
+
- Google OAuth: Google Cloud free tier
|
| 5 |
+
- Email/password: bcrypt (free)
|
| 6 |
+
- Rate limiting: in-memory (no Redis)
|
| 7 |
+
- Free tier: 3 trial credits, 1 job posting
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import secrets
|
| 12 |
+
from datetime import datetime, timezone
|
| 13 |
+
from typing import Any, Dict, Optional
|
| 14 |
+
|
| 15 |
+
import httpx
|
| 16 |
+
from loguru import logger
|
| 17 |
+
from sqlalchemy import or_, select
|
| 18 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 19 |
+
|
| 20 |
+
from app.models.talent import Talent
|
| 21 |
+
from app.models.employer import ClientAccount, Company
|
| 22 |
+
from app.utils.errors import ErrorCode, raise_error
|
| 23 |
+
from app.utils.security import (
|
| 24 |
+
create_access_token,
|
| 25 |
+
hash_password,
|
| 26 |
+
hash_legacy_gas_password,
|
| 27 |
+
verify_password,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
FREE_TIER = {"credits": 3, "max_jobs": 1, "seats": 1, "ai_matching": False, "rate_limit": 100}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ─── Helpers ────────────────────────────────────────────────────────────────
|
| 35 |
+
|
| 36 |
+
def _user_response(email: str, name: str, user_id: str, role: str) -> dict:
|
| 37 |
+
return {
|
| 38 |
+
"id": user_id, "email": email, "name": name, "role": role,
|
| 39 |
+
"tier": "free", "credits_remaining": FREE_TIER["credits"],
|
| 40 |
+
"is_verified": False, "created_at": datetime.now(timezone.utc),
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _auth_response(token: str, user: dict, message: Optional[str] = None) -> dict:
|
| 45 |
+
return {
|
| 46 |
+
"success": True, "access_token": token, "token_type": "bearer",
|
| 47 |
+
"expires_in": 86400, "user": user,
|
| 48 |
+
**({"message": message} if message else {}),
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
async def _global_duplicate_check(db: AsyncSession, email: str) -> Optional[str]:
|
| 53 |
+
"""Check email across all user tables (GAS isGlobalDuplicate equivalent)."""
|
| 54 |
+
for table in [Talent, ClientAccount]:
|
| 55 |
+
result = await db.execute(select(table).where(table.email == email))
|
| 56 |
+
if result.scalar_one_or_none():
|
| 57 |
+
return table.__tablename__
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ─── Registration ───────────────────────────────────────────────────────────
|
| 62 |
+
|
| 63 |
+
async def register_talent(db: AsyncSession, data: dict) -> dict:
|
| 64 |
+
email = data["email"].lower().strip()
|
| 65 |
+
|
| 66 |
+
# Global duplicate check (matches GAS isGlobalDuplicate)
|
| 67 |
+
dup = await _global_duplicate_check(db, email)
|
| 68 |
+
if dup:
|
| 69 |
+
raise_error(
|
| 70 |
+
f"Email already registered as a {dup.replace('_', ' ')}. Try logging in.",
|
| 71 |
+
code=ErrorCode.DUPLICATE_EMAIL,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
talent_id = f"BRIGA-GT-{secrets.token_hex(3).upper()}"
|
| 75 |
+
talent = Talent(
|
| 76 |
+
talent_id=talent_id,
|
| 77 |
+
name=data["name"],
|
| 78 |
+
email=email,
|
| 79 |
+
password_hash=hash_password(data["password"]),
|
| 80 |
+
phone=data.get("phone", ""),
|
| 81 |
+
education=data.get("education", ""),
|
| 82 |
+
experience=data.get("experience", ""),
|
| 83 |
+
location=data.get("location", ""),
|
| 84 |
+
skill_tags=data.get("skill_tags", ""),
|
| 85 |
+
cv_link=data.get("cv_link", ""),
|
| 86 |
+
linkedin_link=data.get("linkedin_link", ""),
|
| 87 |
+
score=70,
|
| 88 |
+
verification_status="Pending",
|
| 89 |
+
green_score=0,
|
| 90 |
+
)
|
| 91 |
+
db.add(talent)
|
| 92 |
+
await db.commit()
|
| 93 |
+
|
| 94 |
+
token = create_access_token(subject=talent_id, email=email, role="talent")
|
| 95 |
+
user = _user_response(email, data["name"], talent_id, "talent")
|
| 96 |
+
logger.info(f"Registered talent: {email}")
|
| 97 |
+
return _auth_response(token, user, f"Welcome! {FREE_TIER['credits']} trial credits activated.")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
async def register_talent_from_whatsapp(db: AsyncSession, data: dict) -> dict:
|
| 101 |
+
"""Special registration for WhatsApp users with auto-generated password."""
|
| 102 |
+
email = data.get("email", "").lower().strip()
|
| 103 |
+
if not email:
|
| 104 |
+
raise_error("Email is required for registration.", code=ErrorCode.TOKEN_INVALID)
|
| 105 |
+
|
| 106 |
+
# Check if already registered
|
| 107 |
+
result = await db.execute(select(Talent).where(Talent.email == email))
|
| 108 |
+
existing = result.scalar_one_or_none()
|
| 109 |
+
|
| 110 |
+
if existing:
|
| 111 |
+
# If exists, just log them in (assuming they confirmed via their own WhatsApp)
|
| 112 |
+
token = create_access_token(subject=existing.talent_id, email=email, role="talent")
|
| 113 |
+
user = _user_response(email, existing.name, existing.talent_id, "talent")
|
| 114 |
+
return _auth_response(token, user, "Welcome back!")
|
| 115 |
+
|
| 116 |
+
# New registration with default password (user should change it later)
|
| 117 |
+
# Default password is "Briga" + phone last 4 digits for simplicity
|
| 118 |
+
phone = data.get("phone", "0000")
|
| 119 |
+
default_pass = f"Briga{phone[-4:]}"
|
| 120 |
+
|
| 121 |
+
reg_data = {
|
| 122 |
+
"email": email,
|
| 123 |
+
"name": data.get("name", "Talent WhatsApp"),
|
| 124 |
+
"password": default_pass,
|
| 125 |
+
"phone": phone
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
# 1. Register talent (password will be hashed inside register_talent)
|
| 129 |
+
result = await register_talent(db, reg_data)
|
| 130 |
+
|
| 131 |
+
# 2. Send welcome email with the cleartext default password
|
| 132 |
+
if result.get("success"):
|
| 133 |
+
from app.services.whatsapp_email_service import wa_email_service
|
| 134 |
+
# We send the cleartext password here before it was hashed only in memory for the email
|
| 135 |
+
await wa_email_service.send_welcome_email(email, reg_data["name"], default_pass)
|
| 136 |
+
|
| 137 |
+
return result
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
async def register_employer(db: AsyncSession, data: dict) -> dict:
|
| 141 |
+
email = data["email"].lower().strip()
|
| 142 |
+
|
| 143 |
+
dup = await _global_duplicate_check(db, email)
|
| 144 |
+
if dup:
|
| 145 |
+
raise_error(
|
| 146 |
+
f"Email already registered as a {dup.replace('_', ' ')}. Try logging in.",
|
| 147 |
+
code=ErrorCode.DUPLICATE_EMAIL,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
company_id = f"BRIGA-CO-{secrets.token_hex(4).upper()}"
|
| 151 |
+
company = Company(
|
| 152 |
+
id=company_id,
|
| 153 |
+
name=data.get("company_name", email.split("@")[1]),
|
| 154 |
+
website=data.get("website", ""),
|
| 155 |
+
tier="free",
|
| 156 |
+
credit_balance=FREE_TIER["credits"],
|
| 157 |
+
seats_limit=FREE_TIER["seats"],
|
| 158 |
+
max_jobs=FREE_TIER["max_jobs"],
|
| 159 |
+
status="PENDING",
|
| 160 |
+
)
|
| 161 |
+
db.add(company)
|
| 162 |
+
|
| 163 |
+
client_id = f"BRIGA-ST-{secrets.token_hex(4).upper()}"
|
| 164 |
+
client = ClientAccount(
|
| 165 |
+
id=client_id,
|
| 166 |
+
company_id=company_id,
|
| 167 |
+
email=email,
|
| 168 |
+
password_hash=hash_password(data["password"]),
|
| 169 |
+
name=data.get("name", "Recruiter"),
|
| 170 |
+
role="Recruiter",
|
| 171 |
+
status="PENDING", # Both company & client PENDING until admin approval
|
| 172 |
+
)
|
| 173 |
+
db.add(client)
|
| 174 |
+
await db.commit()
|
| 175 |
+
|
| 176 |
+
token = create_access_token(subject=client_id, email=email, role="employer")
|
| 177 |
+
user = _user_response(email, data.get("name", "Recruiter"), client_id, "employer")
|
| 178 |
+
logger.info(f"Registered employer: {email} (Company: {company_id})")
|
| 179 |
+
return _auth_response(token, user, "Company registered on Free tier. Pending admin approval.")
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# ─── Login ───────────────────────────────────────────────────────────────────
|
| 183 |
+
|
| 184 |
+
async def _try_talent_login(db: AsyncSession, email: str, password: str) -> Optional[dict]:
|
| 185 |
+
result = await db.execute(select(Talent).where(Talent.email == email))
|
| 186 |
+
talent = result.scalar_one_or_none()
|
| 187 |
+
if not talent or not talent.password_hash:
|
| 188 |
+
return None
|
| 189 |
+
|
| 190 |
+
# Sentinel check: Google OAuth accounts have no password
|
| 191 |
+
if talent.password_hash == "GOOGLE_OAUTH":
|
| 192 |
+
raise_error(
|
| 193 |
+
"This account uses Google Login. Sign in with Google.",
|
| 194 |
+
code=ErrorCode.INVALID_CREDENTIALS,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
# Try bcrypt first
|
| 198 |
+
if verify_password(password, talent.password_hash):
|
| 199 |
+
token = create_access_token(subject=talent.talent_id, email=email, role="talent")
|
| 200 |
+
user = _user_response(email, talent.name, talent.talent_id, "talent")
|
| 201 |
+
return _auth_response(token, user)
|
| 202 |
+
|
| 203 |
+
# Legacy GAS hash fallback + upgrade to bcrypt
|
| 204 |
+
if talent.password_hash == hash_legacy_gas_password(password, email):
|
| 205 |
+
talent.password_hash = hash_password(password)
|
| 206 |
+
await db.commit()
|
| 207 |
+
token = create_access_token(subject=talent.talent_id, email=email, role="talent")
|
| 208 |
+
user = _user_response(email, talent.name, talent.talent_id, "talent")
|
| 209 |
+
return _auth_response(token, user)
|
| 210 |
+
|
| 211 |
+
return None
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
async def _try_employer_login(db: AsyncSession, email: str, password: str) -> Optional[dict]:
|
| 215 |
+
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 216 |
+
client = result.scalar_one_or_none()
|
| 217 |
+
if not client or not client.password_hash:
|
| 218 |
+
return None
|
| 219 |
+
|
| 220 |
+
if not verify_password(password, client.password_hash):
|
| 221 |
+
return None
|
| 222 |
+
|
| 223 |
+
token = create_access_token(subject=client.id, email=email, role="employer")
|
| 224 |
+
user = _user_response(email, client.name, client.id, "employer")
|
| 225 |
+
return _auth_response(token, user)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
async def login_email(db: AsyncSession, email: str, password: str) -> dict:
|
| 229 |
+
email = email.lower().strip()
|
| 230 |
+
|
| 231 |
+
# Try talent first, then employer
|
| 232 |
+
talent_result = await _try_talent_login(db, email, password)
|
| 233 |
+
if talent_result:
|
| 234 |
+
return talent_result
|
| 235 |
+
|
| 236 |
+
employer_result = await _try_employer_login(db, email, password)
|
| 237 |
+
if employer_result:
|
| 238 |
+
return employer_result
|
| 239 |
+
|
| 240 |
+
raise_error("Invalid email or password.", code=ErrorCode.INVALID_CREDENTIALS, status_code=401)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
async def login_google(db: AsyncSession, id_token: str) -> dict:
|
| 244 |
+
"""Google OAuth login. Checks both Talent and ClientAccount tables.
|
| 245 |
+
|
| 246 |
+
Crash-proof:
|
| 247 |
+
- If Google's tokeninfo endpoint is unreachable, returns a graceful error
|
| 248 |
+
- No hard crash on network failure — always returns a structured response
|
| 249 |
+
"""
|
| 250 |
+
# Verify token with Google
|
| 251 |
+
google_data = None
|
| 252 |
+
try:
|
| 253 |
+
async with httpx.AsyncClient() as client:
|
| 254 |
+
resp = await client.get(
|
| 255 |
+
"https://oauth2.googleapis.com/tokeninfo",
|
| 256 |
+
params={"id_token": id_token},
|
| 257 |
+
timeout=10,
|
| 258 |
+
)
|
| 259 |
+
if resp.status_code != 200:
|
| 260 |
+
raise_error("Invalid Google ID token.", code=ErrorCode.TOKEN_INVALID, status_code=401)
|
| 261 |
+
google_data = resp.json()
|
| 262 |
+
except httpx.TimeoutException:
|
| 263 |
+
logger.error("Google OAuth: tokeninfo endpoint timed out")
|
| 264 |
+
raise_error("Google verification timed out. Please try again.", code=ErrorCode.NETWORK_ERROR, status_code=502)
|
| 265 |
+
except httpx.RequestError as e:
|
| 266 |
+
logger.error(f"Google OAuth network error: {e}")
|
| 267 |
+
raise_error("Could not verify Google token. Check your internet connection.", code=ErrorCode.NETWORK_ERROR, status_code=502)
|
| 268 |
+
except Exception as e:
|
| 269 |
+
logger.error(f"Google OAuth unexpected error: {e}")
|
| 270 |
+
raise_error("Google verification failed. Please try again.", code=ErrorCode.NETWORK_ERROR, status_code=502)
|
| 271 |
+
|
| 272 |
+
if google_data is None:
|
| 273 |
+
raise_error("Google verification returned no data.", code=ErrorCode.NETWORK_ERROR, status_code=502)
|
| 274 |
+
|
| 275 |
+
email = google_data.get("email", "").lower().strip()
|
| 276 |
+
google_name = google_data.get("name", "Google User")
|
| 277 |
+
google_id = google_data.get("sub", "")
|
| 278 |
+
|
| 279 |
+
if not email:
|
| 280 |
+
raise_error("Google account has no email. Please use a different account.", code=ErrorCode.TOKEN_INVALID, status_code=401)
|
| 281 |
+
|
| 282 |
+
# Search across both tables
|
| 283 |
+
result = await db.execute(select(Talent).where(Talent.email == email))
|
| 284 |
+
talent = result.scalar_one_or_none()
|
| 285 |
+
if talent:
|
| 286 |
+
# Existing talent — log them in
|
| 287 |
+
token = create_access_token(subject=talent.talent_id, email=email, role="talent")
|
| 288 |
+
user = _user_response(email, talent.name, talent.talent_id, "talent")
|
| 289 |
+
logger.info(f"Google login (existing talent): {email}")
|
| 290 |
+
return _auth_response(token, user, "Welcome back!")
|
| 291 |
+
|
| 292 |
+
# Check employer table
|
| 293 |
+
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 294 |
+
client = result.scalar_one_or_none()
|
| 295 |
+
if client:
|
| 296 |
+
token = create_access_token(subject=client.id, email=email, role="employer")
|
| 297 |
+
user = _user_response(email, client.name, client.id, "employer")
|
| 298 |
+
logger.info(f"Google login (existing employer): {email}")
|
| 299 |
+
return _auth_response(token, user, "Welcome back!")
|
| 300 |
+
|
| 301 |
+
# New user — auto-create talent account (matches GAS behavior)
|
| 302 |
+
talent_id = f"BRIGA-GT-{secrets.token_hex(3).upper()}"
|
| 303 |
+
new_talent = Talent(
|
| 304 |
+
talent_id=talent_id,
|
| 305 |
+
name=google_name,
|
| 306 |
+
email=email,
|
| 307 |
+
password_hash="GOOGLE_OAUTH", # Sentinel — no password login allowed
|
| 308 |
+
verification_status="Verified", # Google-verified email
|
| 309 |
+
score=70,
|
| 310 |
+
green_score=0,
|
| 311 |
+
)
|
| 312 |
+
db.add(new_talent)
|
| 313 |
+
await db.commit()
|
| 314 |
+
|
| 315 |
+
token = create_access_token(subject=talent_id, email=email, role="talent")
|
| 316 |
+
user = _user_response(email, google_name, talent_id, "talent")
|
| 317 |
+
logger.info(f"Google login (new talent): {email}")
|
| 318 |
+
return _auth_response(token, user, "Account created via Google. Welcome to Brigawan!")
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
async def admin_login(db: AsyncSession, email: str, password: str) -> dict:
|
| 322 |
+
"""Admin login. Matches GAS admin check pattern.
|
| 323 |
+
For now, uses the same JWT flow with elevated role.
|
| 324 |
+
"""
|
| 325 |
+
if email == "admin@briga.id" and password == settings.admin_password:
|
| 326 |
+
token = create_access_token(subject="admin", email=email, role="admin")
|
| 327 |
+
user = {
|
| 328 |
+
"id": "admin",
|
| 329 |
+
"email": email,
|
| 330 |
+
"name": "Admin Brigawan",
|
| 331 |
+
"role": "admin",
|
| 332 |
+
"tier": "enterprise",
|
| 333 |
+
"credits_remaining": 9999,
|
| 334 |
+
"is_verified": True,
|
| 335 |
+
}
|
| 336 |
+
return _auth_response(token, user, "Admin login successful.")
|
| 337 |
+
raise_error("Invalid admin credentials.", code=ErrorCode.INVALID_CREDENTIALS, status_code=401)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
async def get_user_by_token(db: AsyncSession, email: str, role: str) -> Optional[dict]:
|
| 341 |
+
"""Get user profile by JWT payload.
|
| 342 |
+
Used by GET /v1/auth/me endpoint.
|
| 343 |
+
"""
|
| 344 |
+
try:
|
| 345 |
+
if role == "talent":
|
| 346 |
+
result = await db.execute(select(Talent).where(Talent.email == email))
|
| 347 |
+
talent = result.scalar_one_or_none()
|
| 348 |
+
if not talent:
|
| 349 |
+
return None
|
| 350 |
+
return {
|
| 351 |
+
"id": talent.talent_id,
|
| 352 |
+
"email": talent.email,
|
| 353 |
+
"name": talent.name,
|
| 354 |
+
"role": "talent",
|
| 355 |
+
"tier": "free",
|
| 356 |
+
"credits_remaining": 3,
|
| 357 |
+
"is_verified": talent.verification_status == "Verified",
|
| 358 |
+
}
|
| 359 |
+
elif role == "employer":
|
| 360 |
+
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 361 |
+
client = result.scalar_one_or_none()
|
| 362 |
+
if not client:
|
| 363 |
+
return None
|
| 364 |
+
# Get company info for tier and credits
|
| 365 |
+
result2 = await db.execute(select(Company).where(Company.id == client.company_id))
|
| 366 |
+
company = result2.scalar_one_or_none()
|
| 367 |
+
return {
|
| 368 |
+
"id": client.id,
|
| 369 |
+
"email": client.email,
|
| 370 |
+
"name": client.name,
|
| 371 |
+
"role": "employer",
|
| 372 |
+
"tier": company.tier if company else "free",
|
| 373 |
+
"credits_remaining": company.credit_balance if company else 3,
|
| 374 |
+
"is_verified": client.status == "Active",
|
| 375 |
+
}
|
| 376 |
+
return None
|
| 377 |
+
except Exception as e:
|
| 378 |
+
logger.error(f"get_user_by_token error: {e}")
|
| 379 |
+
return None
|
app/services/autonomous_dev_service.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Autonomous Developer Service — The Self-Healing Loop.
|
| 2 |
+
|
| 3 |
+
This service monitors the server logs for errors and orchestrates
|
| 4 |
+
the Error Handler and Code Fixer agents to diagnose and propose fixes.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import asyncio
|
| 9 |
+
from typing import Any, Dict, List, Optional
|
| 10 |
+
from loguru import logger
|
| 11 |
+
from app.services.agent_service import call_agent_json, call_agent
|
| 12 |
+
|
| 13 |
+
class AutonomousDevService:
|
| 14 |
+
"""Monitors logs and triggers self-healing cycles.
|
| 15 |
+
|
| 16 |
+
Respects runtime workflow toggles stored in `workflow_configs` table.
|
| 17 |
+
Caches workflow status in-memory for TTL 15s to avoid DB bursts.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
LOG_FILE = "server.log"
|
| 21 |
+
_workflow_config_cache: dict = {} # { workflow_name: { 'is_active': bool, 'fetched_at': datetime } }
|
| 22 |
+
_cache_ttl_seconds = 15
|
| 23 |
+
|
| 24 |
+
@classmethod
|
| 25 |
+
async def _fetch_workflow_status_from_db(cls, workflow_name: str) -> bool:
|
| 26 |
+
"""Query DB for workflow status."""
|
| 27 |
+
from sqlalchemy import select
|
| 28 |
+
from app.database import AsyncSessionLocal
|
| 29 |
+
from app.models.system import WorkflowConfig
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
async with AsyncSessionLocal() as session:
|
| 33 |
+
stmt = select(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name)
|
| 34 |
+
res = await session.execute(stmt)
|
| 35 |
+
row = res.scalar_one_or_none()
|
| 36 |
+
if row is None:
|
| 37 |
+
return False
|
| 38 |
+
return bool(row.is_active)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.error(f"[AutonomousDev] Failed to read workflow config for {workflow_name}: {e}")
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
async def _is_workflow_active(cls, workflow_name: str) -> bool:
|
| 45 |
+
"""Return cached status if fresh; otherwise refresh from DB."""
|
| 46 |
+
from datetime import datetime, timedelta, timezone
|
| 47 |
+
|
| 48 |
+
entry = cls._workflow_config_cache.get(workflow_name)
|
| 49 |
+
now = datetime.now(timezone.utc)
|
| 50 |
+
if entry:
|
| 51 |
+
fetched = entry.get("fetched_at")
|
| 52 |
+
if fetched and (now - fetched).total_seconds() < cls._cache_ttl_seconds:
|
| 53 |
+
return entry.get("is_active", False)
|
| 54 |
+
|
| 55 |
+
# Cache miss or stale -> fetch
|
| 56 |
+
is_active = await cls._fetch_workflow_status_from_db(workflow_name)
|
| 57 |
+
cls._workflow_config_cache[workflow_name] = {"is_active": is_active, "fetched_at": now}
|
| 58 |
+
return is_active
|
| 59 |
+
|
| 60 |
+
@classmethod
|
| 61 |
+
async def monitor_logs(cls):
|
| 62 |
+
"""Background task to watch the log file and trigger workflows if enabled."""
|
| 63 |
+
from datetime import datetime, timezone
|
| 64 |
+
|
| 65 |
+
logger.info("[AutonomousDev] Starting log monitor loop...")
|
| 66 |
+
|
| 67 |
+
# Keep track of the last read position
|
| 68 |
+
last_pos = 0
|
| 69 |
+
if os.path.exists(cls.LOG_FILE):
|
| 70 |
+
last_pos = os.path.getsize(cls.LOG_FILE)
|
| 71 |
+
|
| 72 |
+
while True:
|
| 73 |
+
try:
|
| 74 |
+
if os.path.exists(cls.LOG_FILE):
|
| 75 |
+
current_size = os.path.getsize(cls.LOG_FILE)
|
| 76 |
+
if current_size > last_pos:
|
| 77 |
+
with open(cls.LOG_FILE, "r", encoding="utf-8", errors="ignore") as f:
|
| 78 |
+
f.seek(last_pos)
|
| 79 |
+
new_content = f.read()
|
| 80 |
+
last_pos = current_size
|
| 81 |
+
|
| 82 |
+
if "ERROR" in new_content or "Exception" in new_content:
|
| 83 |
+
# Check workflow toggle before running
|
| 84 |
+
active = await cls._is_workflow_active("autonomous-dev")
|
| 85 |
+
if not active:
|
| 86 |
+
logger.info("[AutonomousDev] autonomous-dev workflow is disabled; skipping healing cycle.")
|
| 87 |
+
else:
|
| 88 |
+
await cls.trigger_healing_cycle(new_content)
|
| 89 |
+
|
| 90 |
+
await asyncio.sleep(60) # Check every minute
|
| 91 |
+
except Exception as e:
|
| 92 |
+
logger.error(f"[AutonomousDev] Monitor loop error: {e}")
|
| 93 |
+
await asyncio.sleep(60)
|
| 94 |
+
|
| 95 |
+
@classmethod
|
| 96 |
+
async def trigger_healing_cycle(cls, error_context: str):
|
| 97 |
+
"""Orchestrate the Error Handler -> Code Fixer flow.
|
| 98 |
+
|
| 99 |
+
Also record last_run on the workflow_configs row.
|
| 100 |
+
"""
|
| 101 |
+
from datetime import datetime, timezone
|
| 102 |
+
from sqlalchemy import update
|
| 103 |
+
from app.database import AsyncSessionLocal
|
| 104 |
+
from app.models.system import WorkflowConfig
|
| 105 |
+
|
| 106 |
+
logger.warning("[AutonomousDev] Error detected! Triggering self-healing cycle...")
|
| 107 |
+
|
| 108 |
+
# 1. Error Handler Analysis
|
| 109 |
+
analysis_prompt = (
|
| 110 |
+
f"Analisalah log error berikut dan tentukan akar masalahnya:\n\n{error_context[:2000]}\n\n"
|
| 111 |
+
"Berikan respon dalam format JSON:\n"
|
| 112 |
+
"{\n"
|
| 113 |
+
" \"root_cause\": \"Penjelasan singkat penyebab error\",\n"
|
| 114 |
+
" \"file_affected\": \"Path file yang bermasalah\",\n"
|
| 115 |
+
" \"line_number\": \"Baris yang bermasalah (jika ada)\",\n"
|
| 116 |
+
" \"fix_instructions\": \"Instruksi langkah-demi-langkah untuk Code Fixer\"\n"
|
| 117 |
+
"}"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
handler_resp = await call_agent_json("cto-agent", analysis_prompt)
|
| 121 |
+
if not handler_resp["success"]:
|
| 122 |
+
logger.error("[AutonomousDev] Error Handler failed to analyze.")
|
| 123 |
+
return
|
| 124 |
+
|
| 125 |
+
analysis = handler_resp["data"]
|
| 126 |
+
logger.info(f"[AutonomousDev] Root Cause identified: {analysis.get('root_cause')}")
|
| 127 |
+
|
| 128 |
+
# Update last_run in workflow_configs
|
| 129 |
+
try:
|
| 130 |
+
async with AsyncSessionLocal() as session:
|
| 131 |
+
stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == "autonomous-dev").values({"last_run": datetime.now(timezone.utc), "updated_at": datetime.now(timezone.utc)})
|
| 132 |
+
await session.execute(stmt)
|
| 133 |
+
await session.commit()
|
| 134 |
+
except Exception as e:
|
| 135 |
+
logger.warning(f"[AutonomousDev] Could not update workflow last_run: {e}")
|
| 136 |
+
|
| 137 |
+
# 2. Code Fixer Proposal
|
| 138 |
+
fix_prompt = (
|
| 139 |
+
f"Berdasarkan analisis berikut, buatlah rencana perbaikan kode:\n"
|
| 140 |
+
f"Akar Masalah: {analysis.get('root_cause')}\n"
|
| 141 |
+
f"File: {analysis.get('file_affected')}\n"
|
| 142 |
+
f"Instruksi: {analysis.get('fix_instructions')}\n\n"
|
| 143 |
+
"Berikan respon berupa potongan kode (diff) atau penjelasan perbaikan yang harus diterapkan."
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
fixer_resp = await call_agent("code-fixer", fix_prompt)
|
| 147 |
+
if fixer_resp["success"]:
|
| 148 |
+
logger.success(f"[AutonomousDev] Fix proposed by Code Fixer:\n{fixer_resp['reply'][:500]}...")
|
| 149 |
+
else:
|
| 150 |
+
logger.error("[AutonomousDev] Code Fixer failed to propose a fix.")
|
app/services/career_service.py
CHANGED
|
@@ -1,169 +1,169 @@
|
|
| 1 |
-
"""Career service for managing experiences, credentials, and profiles.
|
| 2 |
-
|
| 3 |
-
Handles business logic for secure career record storage and retrieval.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
from typing import List, Optional
|
| 7 |
-
from uuid import UUID
|
| 8 |
-
|
| 9 |
-
from sqlalchemy import select, text
|
| 10 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 11 |
-
from loguru import logger
|
| 12 |
-
|
| 13 |
-
from app.models.career import Profile, Experience, Credential, Organization, OrganizationMember
|
| 14 |
-
from app.schemas.career import (
|
| 15 |
-
ExperienceCreate, ExperienceRead, ExperiencePayload,
|
| 16 |
-
CredentialCreate, CredentialRead, CredentialPayload,
|
| 17 |
-
ProfileRead, OrganizationRead
|
| 18 |
-
)
|
| 19 |
-
from app.services.security_service import security_service
|
| 20 |
-
from app.services.organization_service import organization_service
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
class CareerService:
|
| 24 |
-
"""Service for career history operations."""
|
| 25 |
-
|
| 26 |
-
async def get_profile(self, db: AsyncSession, profile_id: UUID) -> Optional[Profile]:
|
| 27 |
-
result = await db.execute(select(Profile).where(Profile.id == profile_id))
|
| 28 |
-
return result.scalars().first()
|
| 29 |
-
|
| 30 |
-
async def create_profile(self, db: AsyncSession, email: str, full_name: str) -> Profile:
|
| 31 |
-
profile = Profile(email=email, full_name=full_name)
|
| 32 |
-
db.add(profile)
|
| 33 |
-
await db.commit()
|
| 34 |
-
await db.refresh(profile)
|
| 35 |
-
return profile
|
| 36 |
-
|
| 37 |
-
async def add_experience(
|
| 38 |
-
self, db: AsyncSession, profile_id: UUID, data: ExperienceCreate
|
| 39 |
-
) -> ExperienceRead:
|
| 40 |
-
"""Add a new experience record with an encrypted payload."""
|
| 41 |
-
# 1. Get or create DEK for the profile
|
| 42 |
-
dek = await security_service.get_or_create_profile_dek(db, profile_id)
|
| 43 |
-
|
| 44 |
-
# 2. Encrypt the payload
|
| 45 |
-
encrypted_payload = security_service.encrypt_payload(dek, data.payload.model_dump())
|
| 46 |
-
|
| 47 |
-
# 3. Save to DB
|
| 48 |
-
experience = Experience(
|
| 49 |
-
profile_id=profile_id,
|
| 50 |
-
organization_id=data.organization_id,
|
| 51 |
-
start_date=data.start_date,
|
| 52 |
-
end_date=data.end_date,
|
| 53 |
-
job_title=data.job_title,
|
| 54 |
-
encrypted_payload=encrypted_payload
|
| 55 |
-
)
|
| 56 |
-
db.add(experience)
|
| 57 |
-
await db.commit()
|
| 58 |
-
await db.refresh(experience)
|
| 59 |
-
|
| 60 |
-
return ExperienceRead(
|
| 61 |
-
id=experience.id,
|
| 62 |
-
profile_id=experience.profile_id,
|
| 63 |
-
organization_id=experience.organization_id,
|
| 64 |
-
start_date=experience.start_date,
|
| 65 |
-
end_date=experience.end_date,
|
| 66 |
-
job_title=experience.job_title,
|
| 67 |
-
created_at=experience.created_at,
|
| 68 |
-
payload=data.payload
|
| 69 |
-
)
|
| 70 |
-
|
| 71 |
-
async def list_experiences(self, db: AsyncSession, profile_id: UUID) -> List[ExperienceRead]:
|
| 72 |
-
"""List all experiences for a profile, decrypted."""
|
| 73 |
-
# 1. Get DEK
|
| 74 |
-
dek = await security_service.get_or_create_profile_dek(db, profile_id)
|
| 75 |
-
|
| 76 |
-
# 2. Fetch encrypted records
|
| 77 |
-
result = await db.execute(select(Experience).where(Experience.profile_id == profile_id))
|
| 78 |
-
records = result.scalars().all()
|
| 79 |
-
|
| 80 |
-
# 3. Decrypt payloads
|
| 81 |
-
output = []
|
| 82 |
-
for rec in records:
|
| 83 |
-
payload_dict = security_service.decrypt_payload(dek, rec.encrypted_payload)
|
| 84 |
-
output.append(ExperienceRead(
|
| 85 |
-
id=rec.id,
|
| 86 |
-
profile_id=rec.profile_id,
|
| 87 |
-
organization_id=rec.organization_id,
|
| 88 |
-
start_date=rec.start_date,
|
| 89 |
-
end_date=rec.end_date,
|
| 90 |
-
job_title=rec.job_title,
|
| 91 |
-
created_at=rec.created_at,
|
| 92 |
-
payload=ExperiencePayload(**payload_dict)
|
| 93 |
-
))
|
| 94 |
-
return output
|
| 95 |
-
|
| 96 |
-
async def add_credential(
|
| 97 |
-
self, db: AsyncSession, profile_id: UUID, data: CredentialCreate, issuer_signature: str
|
| 98 |
-
) -> CredentialRead:
|
| 99 |
-
"""Add a new signed credential with an encrypted payload."""
|
| 100 |
-
# 1. Get or create DEK for the profile
|
| 101 |
-
dek = await security_service.get_or_create_profile_dek(db, profile_id)
|
| 102 |
-
|
| 103 |
-
# 2. Encrypt the payload
|
| 104 |
-
encrypted_payload = security_service.encrypt_payload(dek, data.payload.model_dump())
|
| 105 |
-
|
| 106 |
-
# 3. Verify Signature
|
| 107 |
-
# The issuer signs the PLAINTEXT payload to ensure they know what they are signing.
|
| 108 |
-
# We use a canonical JSON string (sorted keys) for consistency.
|
| 109 |
-
import json
|
| 110 |
-
plaintext_json = json.dumps(data.payload.model_dump(), sort_keys=True)
|
| 111 |
-
|
| 112 |
-
is_valid = await organization_service.verify_credential_signature(
|
| 113 |
-
db, data.organization_id, plaintext_json, issuer_signature
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
if not is_valid:
|
| 117 |
-
logger.error(f"Credential signature verification failed for profile {profile_id}")
|
| 118 |
-
raise ValueError("Invalid issuer signature. Credential cannot be saved.")
|
| 119 |
-
|
| 120 |
-
# 4. Save to DB
|
| 121 |
-
credential = Credential(
|
| 122 |
-
profile_id=profile_id,
|
| 123 |
-
organization_id=data.organization_id,
|
| 124 |
-
issue_date=data.issue_date,
|
| 125 |
-
expiry_date=data.expiry_date,
|
| 126 |
-
credential_name=data.credential_name,
|
| 127 |
-
encrypted_payload=encrypted_payload,
|
| 128 |
-
issuer_signature=issuer_signature
|
| 129 |
-
)
|
| 130 |
-
db.add(credential)
|
| 131 |
-
await db.commit()
|
| 132 |
-
await db.refresh(credential)
|
| 133 |
-
|
| 134 |
-
return CredentialRead(
|
| 135 |
-
id=credential.id,
|
| 136 |
-
profile_id=credential.profile_id,
|
| 137 |
-
organization_id=credential.organization_id,
|
| 138 |
-
issue_date=credential.issue_date,
|
| 139 |
-
expiry_date=credential.expiry_date,
|
| 140 |
-
credential_name=credential.credential_name,
|
| 141 |
-
issuer_signature=credential.issuer_signature,
|
| 142 |
-
created_at=credential.created_at,
|
| 143 |
-
payload=data.payload
|
| 144 |
-
)
|
| 145 |
-
|
| 146 |
-
async def list_credentials(self, db: AsyncSession, profile_id: UUID) -> List[CredentialRead]:
|
| 147 |
-
"""List all credentials for a profile, decrypted."""
|
| 148 |
-
dek = await security_service.get_or_create_profile_dek(db, profile_id)
|
| 149 |
-
result = await db.execute(select(Credential).where(Credential.profile_id == profile_id))
|
| 150 |
-
records = result.scalars().all()
|
| 151 |
-
|
| 152 |
-
output = []
|
| 153 |
-
for rec in records:
|
| 154 |
-
payload_dict = security_service.decrypt_payload(dek, rec.encrypted_payload)
|
| 155 |
-
output.append(CredentialRead(
|
| 156 |
-
id=rec.id,
|
| 157 |
-
profile_id=rec.profile_id,
|
| 158 |
-
organization_id=rec.organization_id,
|
| 159 |
-
issue_date=rec.issue_date,
|
| 160 |
-
expiry_date=rec.expiry_date,
|
| 161 |
-
credential_name=rec.credential_name,
|
| 162 |
-
issuer_signature=rec.issuer_signature,
|
| 163 |
-
created_at=rec.created_at,
|
| 164 |
-
payload=CredentialPayload(**payload_dict)
|
| 165 |
-
))
|
| 166 |
-
return output
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
career_service = CareerService()
|
|
|
|
| 1 |
+
"""Career service for managing experiences, credentials, and profiles.
|
| 2 |
+
|
| 3 |
+
Handles business logic for secure career record storage and retrieval.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import List, Optional
|
| 7 |
+
from uuid import UUID
|
| 8 |
+
|
| 9 |
+
from sqlalchemy import select, text
|
| 10 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 11 |
+
from loguru import logger
|
| 12 |
+
|
| 13 |
+
from app.models.career import Profile, Experience, Credential, Organization, OrganizationMember
|
| 14 |
+
from app.schemas.career import (
|
| 15 |
+
ExperienceCreate, ExperienceRead, ExperiencePayload,
|
| 16 |
+
CredentialCreate, CredentialRead, CredentialPayload,
|
| 17 |
+
ProfileRead, OrganizationRead
|
| 18 |
+
)
|
| 19 |
+
from app.services.security_service import security_service
|
| 20 |
+
from app.services.organization_service import organization_service
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class CareerService:
|
| 24 |
+
"""Service for career history operations."""
|
| 25 |
+
|
| 26 |
+
async def get_profile(self, db: AsyncSession, profile_id: UUID) -> Optional[Profile]:
|
| 27 |
+
result = await db.execute(select(Profile).where(Profile.id == profile_id))
|
| 28 |
+
return result.scalars().first()
|
| 29 |
+
|
| 30 |
+
async def create_profile(self, db: AsyncSession, email: str, full_name: str) -> Profile:
|
| 31 |
+
profile = Profile(email=email, full_name=full_name)
|
| 32 |
+
db.add(profile)
|
| 33 |
+
await db.commit()
|
| 34 |
+
await db.refresh(profile)
|
| 35 |
+
return profile
|
| 36 |
+
|
| 37 |
+
async def add_experience(
|
| 38 |
+
self, db: AsyncSession, profile_id: UUID, data: ExperienceCreate
|
| 39 |
+
) -> ExperienceRead:
|
| 40 |
+
"""Add a new experience record with an encrypted payload."""
|
| 41 |
+
# 1. Get or create DEK for the profile
|
| 42 |
+
dek = await security_service.get_or_create_profile_dek(db, profile_id)
|
| 43 |
+
|
| 44 |
+
# 2. Encrypt the payload
|
| 45 |
+
encrypted_payload = security_service.encrypt_payload(dek, data.payload.model_dump())
|
| 46 |
+
|
| 47 |
+
# 3. Save to DB
|
| 48 |
+
experience = Experience(
|
| 49 |
+
profile_id=profile_id,
|
| 50 |
+
organization_id=data.organization_id,
|
| 51 |
+
start_date=data.start_date,
|
| 52 |
+
end_date=data.end_date,
|
| 53 |
+
job_title=data.job_title,
|
| 54 |
+
encrypted_payload=encrypted_payload
|
| 55 |
+
)
|
| 56 |
+
db.add(experience)
|
| 57 |
+
await db.commit()
|
| 58 |
+
await db.refresh(experience)
|
| 59 |
+
|
| 60 |
+
return ExperienceRead(
|
| 61 |
+
id=experience.id,
|
| 62 |
+
profile_id=experience.profile_id,
|
| 63 |
+
organization_id=experience.organization_id,
|
| 64 |
+
start_date=experience.start_date,
|
| 65 |
+
end_date=experience.end_date,
|
| 66 |
+
job_title=experience.job_title,
|
| 67 |
+
created_at=experience.created_at,
|
| 68 |
+
payload=data.payload
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
async def list_experiences(self, db: AsyncSession, profile_id: UUID) -> List[ExperienceRead]:
|
| 72 |
+
"""List all experiences for a profile, decrypted."""
|
| 73 |
+
# 1. Get DEK
|
| 74 |
+
dek = await security_service.get_or_create_profile_dek(db, profile_id)
|
| 75 |
+
|
| 76 |
+
# 2. Fetch encrypted records
|
| 77 |
+
result = await db.execute(select(Experience).where(Experience.profile_id == profile_id))
|
| 78 |
+
records = result.scalars().all()
|
| 79 |
+
|
| 80 |
+
# 3. Decrypt payloads
|
| 81 |
+
output = []
|
| 82 |
+
for rec in records:
|
| 83 |
+
payload_dict = security_service.decrypt_payload(dek, rec.encrypted_payload)
|
| 84 |
+
output.append(ExperienceRead(
|
| 85 |
+
id=rec.id,
|
| 86 |
+
profile_id=rec.profile_id,
|
| 87 |
+
organization_id=rec.organization_id,
|
| 88 |
+
start_date=rec.start_date,
|
| 89 |
+
end_date=rec.end_date,
|
| 90 |
+
job_title=rec.job_title,
|
| 91 |
+
created_at=rec.created_at,
|
| 92 |
+
payload=ExperiencePayload(**payload_dict)
|
| 93 |
+
))
|
| 94 |
+
return output
|
| 95 |
+
|
| 96 |
+
async def add_credential(
|
| 97 |
+
self, db: AsyncSession, profile_id: UUID, data: CredentialCreate, issuer_signature: str
|
| 98 |
+
) -> CredentialRead:
|
| 99 |
+
"""Add a new signed credential with an encrypted payload."""
|
| 100 |
+
# 1. Get or create DEK for the profile
|
| 101 |
+
dek = await security_service.get_or_create_profile_dek(db, profile_id)
|
| 102 |
+
|
| 103 |
+
# 2. Encrypt the payload
|
| 104 |
+
encrypted_payload = security_service.encrypt_payload(dek, data.payload.model_dump())
|
| 105 |
+
|
| 106 |
+
# 3. Verify Signature
|
| 107 |
+
# The issuer signs the PLAINTEXT payload to ensure they know what they are signing.
|
| 108 |
+
# We use a canonical JSON string (sorted keys) for consistency.
|
| 109 |
+
import json
|
| 110 |
+
plaintext_json = json.dumps(data.payload.model_dump(), sort_keys=True)
|
| 111 |
+
|
| 112 |
+
is_valid = await organization_service.verify_credential_signature(
|
| 113 |
+
db, data.organization_id, plaintext_json, issuer_signature
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if not is_valid:
|
| 117 |
+
logger.error(f"Credential signature verification failed for profile {profile_id}")
|
| 118 |
+
raise ValueError("Invalid issuer signature. Credential cannot be saved.")
|
| 119 |
+
|
| 120 |
+
# 4. Save to DB
|
| 121 |
+
credential = Credential(
|
| 122 |
+
profile_id=profile_id,
|
| 123 |
+
organization_id=data.organization_id,
|
| 124 |
+
issue_date=data.issue_date,
|
| 125 |
+
expiry_date=data.expiry_date,
|
| 126 |
+
credential_name=data.credential_name,
|
| 127 |
+
encrypted_payload=encrypted_payload,
|
| 128 |
+
issuer_signature=issuer_signature
|
| 129 |
+
)
|
| 130 |
+
db.add(credential)
|
| 131 |
+
await db.commit()
|
| 132 |
+
await db.refresh(credential)
|
| 133 |
+
|
| 134 |
+
return CredentialRead(
|
| 135 |
+
id=credential.id,
|
| 136 |
+
profile_id=credential.profile_id,
|
| 137 |
+
organization_id=credential.organization_id,
|
| 138 |
+
issue_date=credential.issue_date,
|
| 139 |
+
expiry_date=credential.expiry_date,
|
| 140 |
+
credential_name=credential.credential_name,
|
| 141 |
+
issuer_signature=credential.issuer_signature,
|
| 142 |
+
created_at=credential.created_at,
|
| 143 |
+
payload=data.payload
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
async def list_credentials(self, db: AsyncSession, profile_id: UUID) -> List[CredentialRead]:
|
| 147 |
+
"""List all credentials for a profile, decrypted."""
|
| 148 |
+
dek = await security_service.get_or_create_profile_dek(db, profile_id)
|
| 149 |
+
result = await db.execute(select(Credential).where(Credential.profile_id == profile_id))
|
| 150 |
+
records = result.scalars().all()
|
| 151 |
+
|
| 152 |
+
output = []
|
| 153 |
+
for rec in records:
|
| 154 |
+
payload_dict = security_service.decrypt_payload(dek, rec.encrypted_payload)
|
| 155 |
+
output.append(CredentialRead(
|
| 156 |
+
id=rec.id,
|
| 157 |
+
profile_id=rec.profile_id,
|
| 158 |
+
organization_id=rec.organization_id,
|
| 159 |
+
issue_date=rec.issue_date,
|
| 160 |
+
expiry_date=rec.expiry_date,
|
| 161 |
+
credential_name=rec.credential_name,
|
| 162 |
+
issuer_signature=rec.issuer_signature,
|
| 163 |
+
created_at=rec.created_at,
|
| 164 |
+
payload=CredentialPayload(**payload_dict)
|
| 165 |
+
))
|
| 166 |
+
return output
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
career_service = CareerService()
|
app/services/chat_service.py
CHANGED
|
@@ -1,526 +1,526 @@
|
|
| 1 |
-
"""Mediated Chat Service — AI-relayed messaging between Recruiters and Talents.
|
| 2 |
-
|
| 3 |
-
Architecture (matches ChatManager.gs):
|
| 4 |
-
1. Recruiter sends raw message → AI mediates it (mask identity)
|
| 5 |
-
2. Talent receives mediated message → replies raw
|
| 6 |
-
3. AI summarizes reply for recruiter (mask identity)
|
| 7 |
-
4. Recruiter can unlock identity (costs 5 coins)
|
| 8 |
-
|
| 9 |
-
AI tier: LOW (Gemini 3.5 Flash lightweight) — fast, cheap, crash-proof.
|
| 10 |
-
Fallback: algorithmic mediation (template-based masking).
|
| 11 |
-
Never crashes.
|
| 12 |
-
"""
|
| 13 |
-
|
| 14 |
-
import secrets
|
| 15 |
-
from datetime import datetime, timezone
|
| 16 |
-
from typing import Any, Dict, List, Optional, Tuple
|
| 17 |
-
|
| 18 |
-
from loguru import logger
|
| 19 |
-
from sqlalchemy import or_, select
|
| 20 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 21 |
-
|
| 22 |
-
from app.models.job import MediatedChat
|
| 23 |
-
from app.models.talent import Talent
|
| 24 |
-
from app.models.employer import ClientAccount, Company
|
| 25 |
-
from app.models.finance import Transaction
|
| 26 |
-
from app.services.ai_service import call_low
|
| 27 |
-
from app.utils.errors import ErrorCode, raise_error
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
UNLOCK_COST = 5 # Coins to unlock identity (matches GAS FINANCE_CONFIG.DEDUCTION.IDENTITY_UNLOCK)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# =============================================================================
|
| 34 |
-
# HELPERS
|
| 35 |
-
# =============================================================================
|
| 36 |
-
|
| 37 |
-
def _generate_chat_id() -> str:
|
| 38 |
-
return f"MSG-{secrets.token_hex(4).upper()}"
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
def _generate_conversation_id() -> str:
|
| 42 |
-
return f"CONV-{secrets.token_hex(4).upper()}"
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def _algorithmic_mediate_recruiter_message(
|
| 46 |
-
raw_message: str,
|
| 47 |
-
recruiter_industry: str = "Sustainability Sector",
|
| 48 |
-
) -> str:
|
| 49 |
-
"""Algorithmic fallback for recruiter message mediation.
|
| 50 |
-
No AI needed — template-based masking.
|
| 51 |
-
"""
|
| 52 |
-
clean = raw_message.strip()[:500]
|
| 53 |
-
return (
|
| 54 |
-
f"Hey [Talent], ada recruiter dari {recruiter_industry} "
|
| 55 |
-
f"yang tertarik dengan profil kamu. Mereka ingin tahu lebih lanjut: "
|
| 56 |
-
f'"{clean}"'
|
| 57 |
-
)
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def _algorithmic_mediate_talent_reply(
|
| 61 |
-
raw_reply: str,
|
| 62 |
-
talent_id: str,
|
| 63 |
-
) -> str:
|
| 64 |
-
"""Algorithmic fallback for talent reply mediation.
|
| 65 |
-
No AI needed — template-based.
|
| 66 |
-
"""
|
| 67 |
-
clean = raw_reply.strip()[:500]
|
| 68 |
-
return (
|
| 69 |
-
f"Respon dari [Talent ID: {talent_id}], dia mengatakan: "
|
| 70 |
-
f'"{clean}". '
|
| 71 |
-
f"Silakan pertimbangkan untuk melanjutkan diskusi."
|
| 72 |
-
)
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
async def _get_talent_by_id(db: AsyncSession, talent_id: str) -> Optional[Talent]:
|
| 76 |
-
result = await db.execute(select(Talent).where(Talent.talent_id == talent_id))
|
| 77 |
-
return result.scalar_one_or_none()
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
async def _get_client_and_company_by_email(db: AsyncSession, email: str) -> tuple:
|
| 81 |
-
"""Look up ClientAccount and Company by email.
|
| 82 |
-
Returns (client, company) or (None, None).
|
| 83 |
-
"""
|
| 84 |
-
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 85 |
-
client = result.scalar_one_or_none()
|
| 86 |
-
if not client:
|
| 87 |
-
return None, None
|
| 88 |
-
result = await db.execute(select(Company).where(Company.id == client.company_id))
|
| 89 |
-
company = result.scalar_one_or_none()
|
| 90 |
-
return client, company
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
# =============================================================================
|
| 94 |
-
# 1. RECRUITER SENDS MESSAGE -> AI MEDIATED -> TALENT
|
| 95 |
-
# =============================================================================
|
| 96 |
-
|
| 97 |
-
async def send_recruiter_message(
|
| 98 |
-
db: AsyncSession,
|
| 99 |
-
recruiter_email: str,
|
| 100 |
-
talent_id: str,
|
| 101 |
-
raw_message: str,
|
| 102 |
-
existing_conversation_id: Optional[str] = None,
|
| 103 |
-
) -> dict:
|
| 104 |
-
"""Recruiter sends a message to a talent. AI mediates it.
|
| 105 |
-
|
| 106 |
-
Flow:
|
| 107 |
-
1. Verify talent exists
|
| 108 |
-
2. Get or create conversation
|
| 109 |
-
3. AI mediates the message (LOW tier -> algorithmic fallback)
|
| 110 |
-
4. Save to database
|
| 111 |
-
5. Return conversation ID
|
| 112 |
-
"""
|
| 113 |
-
# Verify talent exists
|
| 114 |
-
talent = await _get_talent_by_id(db, talent_id)
|
| 115 |
-
if not talent:
|
| 116 |
-
raise_error(f"Talent {talent_id} not found.", ErrorCode.NOT_FOUND, 404)
|
| 117 |
-
|
| 118 |
-
# Get or create conversation
|
| 119 |
-
conversation_id = existing_conversation_id or _generate_conversation_id()
|
| 120 |
-
chat_id = _generate_chat_id()
|
| 121 |
-
|
| 122 |
-
# AI-mediated message (LOW tier = Gemini 3.5 Flash lightweight)
|
| 123 |
-
mediated_message = None
|
| 124 |
-
try:
|
| 125 |
-
prompt = (
|
| 126 |
-
f"Anda adalah Brigawan Matchmaker. Seorang recruiter dari Sustainability "
|
| 127 |
-
f'mengirim pesan ini: "{raw_message[:500]}".\n'
|
| 128 |
-
f"Ubah pesan ini menjadi format Brigawan Relay untuk Talent.\n"
|
| 129 |
-
f"Gunakan gaya: 'Hey [talent], recruiter dari perusahaan [industri] "
|
| 130 |
-
f"bertanya mengenai [topik]. [Pertanyaan rephrased].'\n"
|
| 131 |
-
f"JANGAN sebutkan nama perusahaan recruiter.\n"
|
| 132 |
-
f"BALAS LANGSUNG dengan pesan yang sudah di-mediate, tanpa penjelasan tambahan."
|
| 133 |
-
)
|
| 134 |
-
mediated_message = await call_low(prompt=prompt, temperature=0.7, max_output_tokens=512)
|
| 135 |
-
except Exception as e:
|
| 136 |
-
logger.error(f"AI mediation failed for recruiter message: {e}")
|
| 137 |
-
|
| 138 |
-
if not mediated_message:
|
| 139 |
-
mediated_message = _algorithmic_mediate_recruiter_message(raw_message)
|
| 140 |
-
|
| 141 |
-
# Save to DB
|
| 142 |
-
chat = MediatedChat(
|
| 143 |
-
chat_id=chat_id,
|
| 144 |
-
conversation_id=conversation_id,
|
| 145 |
-
sender_email=recruiter_email,
|
| 146 |
-
receiver_email=talent.email,
|
| 147 |
-
sender_role="RECRUITER",
|
| 148 |
-
original_message=raw_message,
|
| 149 |
-
mediated_message=mediated_message,
|
| 150 |
-
is_identity_unlocked=False,
|
| 151 |
-
status="PENDING_TALENT",
|
| 152 |
-
timestamp=datetime.now(timezone.utc),
|
| 153 |
-
)
|
| 154 |
-
db.add(chat)
|
| 155 |
-
await db.commit()
|
| 156 |
-
|
| 157 |
-
logger.info(f"Chat message sent: {conversation_id} ({recruiter_email} -> {talent_id})")
|
| 158 |
-
|
| 159 |
-
return {
|
| 160 |
-
"success": True,
|
| 161 |
-
"ai_feedback": f"Halo {recruiter_email.split('@')[0]}, saya tanyakan dulu ya sama kandidatnya.",
|
| 162 |
-
"conversation_id": conversation_id,
|
| 163 |
-
"message": "Message sent and mediated.",
|
| 164 |
-
}
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
# =============================================================================
|
| 168 |
-
# 2. TALENT REPLIES -> AI SUMMARIZED -> RECRUITER
|
| 169 |
-
# =============================================================================
|
| 170 |
-
|
| 171 |
-
async def send_talent_reply(
|
| 172 |
-
db: AsyncSession,
|
| 173 |
-
talent_email: str,
|
| 174 |
-
conversation_id: str,
|
| 175 |
-
raw_reply: str,
|
| 176 |
-
) -> dict:
|
| 177 |
-
"""Talent replies to a conversation. AI summarizes for recruiter.
|
| 178 |
-
|
| 179 |
-
Flow:
|
| 180 |
-
1. Verify conversation exists and talent is a participant
|
| 181 |
-
2. AI summarizes the reply (LOW tier -> algorithmic fallback)
|
| 182 |
-
3. Save to database
|
| 183 |
-
4. Return success
|
| 184 |
-
"""
|
| 185 |
-
# Verify conversation exists
|
| 186 |
-
result = await db.execute(
|
| 187 |
-
select(MediatedChat)
|
| 188 |
-
.where(MediatedChat.conversation_id == conversation_id)
|
| 189 |
-
.limit(1)
|
| 190 |
-
)
|
| 191 |
-
existing = result.scalar_one_or_none()
|
| 192 |
-
if not existing:
|
| 193 |
-
raise_error("Conversation not found.", ErrorCode.NOT_FOUND, 404)
|
| 194 |
-
|
| 195 |
-
# Verify talent is a participant
|
| 196 |
-
result = await db.execute(select(MediatedChat).where(
|
| 197 |
-
MediatedChat.conversation_id == conversation_id,
|
| 198 |
-
MediatedChat.receiver_email == talent_email,
|
| 199 |
-
).limit(1))
|
| 200 |
-
participant = result.scalar_one_or_none()
|
| 201 |
-
if not participant:
|
| 202 |
-
result = await db.execute(select(MediatedChat).where(
|
| 203 |
-
MediatedChat.conversation_id == conversation_id,
|
| 204 |
-
or_(
|
| 205 |
-
MediatedChat.sender_email == talent_email,
|
| 206 |
-
MediatedChat.receiver_email == talent_email,
|
| 207 |
-
)
|
| 208 |
-
).limit(1))
|
| 209 |
-
if not result.scalar_one_or_none():
|
| 210 |
-
raise_error("You are not a participant in this conversation.", ErrorCode.NOT_AUTHORIZED, 403)
|
| 211 |
-
|
| 212 |
-
# Find recruiter email from conversation
|
| 213 |
-
result = await db.execute(
|
| 214 |
-
select(MediatedChat)
|
| 215 |
-
.where(
|
| 216 |
-
MediatedChat.conversation_id == conversation_id,
|
| 217 |
-
MediatedChat.sender_role == "RECRUITER",
|
| 218 |
-
)
|
| 219 |
-
.limit(1)
|
| 220 |
-
)
|
| 221 |
-
recruiter_msg = result.scalar_one_or_none()
|
| 222 |
-
recruiter_email = recruiter_msg.sender_email if recruiter_msg else ""
|
| 223 |
-
|
| 224 |
-
if not recruiter_email:
|
| 225 |
-
raise_error("Could not find conversation partner.", ErrorCode.NOT_FOUND, 404)
|
| 226 |
-
|
| 227 |
-
chat_id = _generate_chat_id()
|
| 228 |
-
talent_id_str = talent_email
|
| 229 |
-
|
| 230 |
-
# AI-mediated reply (LOW tier -> algorithmic fallback)
|
| 231 |
-
mediated_summary = None
|
| 232 |
-
try:
|
| 233 |
-
prompt = (
|
| 234 |
-
f"Anda adalah Brigawan Matchmaker. Talent ({talent_id_str}) menjawab "
|
| 235 |
-
f'pertanyaan recruiter: "{raw_reply[:500]}".\n'
|
| 236 |
-
f"Ubah jawaban ini menjadi format Brigawan Insight untuk Recruiter.\n"
|
| 237 |
-
f"Gunakan gaya: 'Respon dari [Talent ID], dia [rangkuman jawaban]. "
|
| 238 |
-
f"[Saran tindak lanjut jika ada].'\n"
|
| 239 |
-
f"JANGAN sebutkan nama asli talent.\n"
|
| 240 |
-
f"BALAS LANGSUNG dengan pesan yang sudah di-mediate."
|
| 241 |
-
)
|
| 242 |
-
mediated_summary = await call_low(prompt=prompt, temperature=0.7, max_output_tokens=512)
|
| 243 |
-
except Exception as e:
|
| 244 |
-
logger.error(f"AI mediation failed for talent reply: {e}")
|
| 245 |
-
|
| 246 |
-
if not mediated_summary:
|
| 247 |
-
mediated_summary = _algorithmic_mediate_talent_reply(raw_reply, talent_id_str)
|
| 248 |
-
|
| 249 |
-
# Save to DB
|
| 250 |
-
chat = MediatedChat(
|
| 251 |
-
chat_id=chat_id,
|
| 252 |
-
conversation_id=conversation_id,
|
| 253 |
-
sender_email=talent_email,
|
| 254 |
-
receiver_email=recruiter_email,
|
| 255 |
-
sender_role="TALENT",
|
| 256 |
-
original_message=raw_reply,
|
| 257 |
-
mediated_message=mediated_summary,
|
| 258 |
-
is_identity_unlocked=False,
|
| 259 |
-
status="PENDING_RECRUITER",
|
| 260 |
-
timestamp=datetime.now(timezone.utc),
|
| 261 |
-
)
|
| 262 |
-
db.add(chat)
|
| 263 |
-
await db.commit()
|
| 264 |
-
|
| 265 |
-
logger.info(f"Talent reply mediated: {conversation_id}")
|
| 266 |
-
|
| 267 |
-
return {
|
| 268 |
-
"success": True,
|
| 269 |
-
"message": "Balasan Anda telah dikirimkan ke Recruiter melalui Brigawan.",
|
| 270 |
-
}
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
# =============================================================================
|
| 274 |
-
# 3. UNLOCK IDENTITY (costs 5 coins)
|
| 275 |
-
# =============================================================================
|
| 276 |
-
|
| 277 |
-
async def unlock_chat_identity(
|
| 278 |
-
db: AsyncSession,
|
| 279 |
-
recruiter_email: str,
|
| 280 |
-
talent_id: str,
|
| 281 |
-
) -> dict:
|
| 282 |
-
"""Unlock talent identity in chat. Costs 5 Briga coins.
|
| 283 |
-
|
| 284 |
-
Flow:
|
| 285 |
-
1. Verify employer has enough coins
|
| 286 |
-
2. Deduct coins + log transaction with proper FK
|
| 287 |
-
3. Mark all messages in conversation as unlocked
|
| 288 |
-
4. Return full talent profile
|
| 289 |
-
"""
|
| 290 |
-
talent = await _get_talent_by_id(db, talent_id)
|
| 291 |
-
if not talent:
|
| 292 |
-
raise_error(f"Talent {talent_id} not found.", ErrorCode.NOT_FOUND, 404)
|
| 293 |
-
|
| 294 |
-
client, company = await _get_client_and_company_by_email(db, recruiter_email)
|
| 295 |
-
if not client or not company:
|
| 296 |
-
raise_error("Employer account not found.", ErrorCode.NOT_FOUND, 404)
|
| 297 |
-
|
| 298 |
-
# Check if already unlocked
|
| 299 |
-
result = await db.execute(
|
| 300 |
-
select(MediatedChat).where(
|
| 301 |
-
MediatedChat.sender_email == recruiter_email,
|
| 302 |
-
MediatedChat.receiver_email == talent.email,
|
| 303 |
-
MediatedChat.is_identity_unlocked == True,
|
| 304 |
-
).limit(1)
|
| 305 |
-
)
|
| 306 |
-
if result.scalar_one_or_none():
|
| 307 |
-
return {
|
| 308 |
-
"success": True,
|
| 309 |
-
"message": "Identity already unlocked. No coins deducted.",
|
| 310 |
-
"talent_name": talent.name or "",
|
| 311 |
-
"talent_email": talent.email or "",
|
| 312 |
-
"talent_phone": talent.phone or "",
|
| 313 |
-
"credits_remaining": company.credit_balance or 0,
|
| 314 |
-
}
|
| 315 |
-
|
| 316 |
-
# Check balance
|
| 317 |
-
if (company.credit_balance or 0) < UNLOCK_COST:
|
| 318 |
-
raise_error(
|
| 319 |
-
f"Insufficient coins. Unlock costs {UNLOCK_COST} coins. Balance: {company.credit_balance or 0}",
|
| 320 |
-
code=ErrorCode.NOT_AUTHORIZED,
|
| 321 |
-
)
|
| 322 |
-
|
| 323 |
-
# Deduct
|
| 324 |
-
company.credit_balance = (company.credit_balance or 0) - UNLOCK_COST
|
| 325 |
-
db.add(company)
|
| 326 |
-
|
| 327 |
-
# Log transaction with proper client FK (ClientAccount.id, not email)
|
| 328 |
-
tx = Transaction(
|
| 329 |
-
id=f"TX-UNL-CHAT-{secrets.token_hex(4).upper()}",
|
| 330 |
-
client_id=client.id,
|
| 331 |
-
amount=UNLOCK_COST,
|
| 332 |
-
type="IdentityUnlock",
|
| 333 |
-
status="Settled",
|
| 334 |
-
)
|
| 335 |
-
db.add(tx)
|
| 336 |
-
|
| 337 |
-
# Mark all messages between this recruiter and talent as unlocked
|
| 338 |
-
result = await db.execute(
|
| 339 |
-
select(MediatedChat).where(
|
| 340 |
-
MediatedChat.sender_email == recruiter_email,
|
| 341 |
-
MediatedChat.receiver_email == talent.email,
|
| 342 |
-
)
|
| 343 |
-
)
|
| 344 |
-
for chat in result.scalars().all():
|
| 345 |
-
chat.is_identity_unlocked = True
|
| 346 |
-
db.add(chat)
|
| 347 |
-
|
| 348 |
-
result = await db.execute(
|
| 349 |
-
select(MediatedChat).where(
|
| 350 |
-
MediatedChat.sender_email == talent.email,
|
| 351 |
-
MediatedChat.receiver_email == recruiter_email,
|
| 352 |
-
)
|
| 353 |
-
)
|
| 354 |
-
for chat in result.scalars().all():
|
| 355 |
-
chat.is_identity_unlocked = True
|
| 356 |
-
db.add(chat)
|
| 357 |
-
|
| 358 |
-
await db.commit()
|
| 359 |
-
|
| 360 |
-
logger.info(f"Chat identity unlocked: {recruiter_email} -> {talent_id} (cost: {UNLOCK_COST})")
|
| 361 |
-
|
| 362 |
-
return {
|
| 363 |
-
"success": True,
|
| 364 |
-
"message": f"Identitas Talent berhasil dibuka! {UNLOCK_COST} coins deducted.",
|
| 365 |
-
"talent_name": talent.name or "",
|
| 366 |
-
"talent_email": talent.email or "",
|
| 367 |
-
"talent_phone": talent.phone or "",
|
| 368 |
-
"credits_remaining": company.credit_balance or 0,
|
| 369 |
-
}
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
# =============================================================================
|
| 373 |
-
# 4. GET CONVERSATION LIST (for recruiter)
|
| 374 |
-
# =============================================================================
|
| 375 |
-
|
| 376 |
-
async def get_recruiter_conversations(
|
| 377 |
-
db: AsyncSession,
|
| 378 |
-
recruiter_email: str,
|
| 379 |
-
) -> list:
|
| 380 |
-
"""Get all conversations for a recruiter, sorted by latest message.
|
| 381 |
-
|
| 382 |
-
Groups messages by partner (talent), returns the latest message per partner.
|
| 383 |
-
"""
|
| 384 |
-
result = await db.execute(
|
| 385 |
-
select(MediatedChat)
|
| 386 |
-
.where(
|
| 387 |
-
or_(
|
| 388 |
-
MediatedChat.sender_email == recruiter_email,
|
| 389 |
-
MediatedChat.receiver_email == recruiter_email,
|
| 390 |
-
)
|
| 391 |
-
)
|
| 392 |
-
.order_by(MediatedChat.timestamp.desc())
|
| 393 |
-
)
|
| 394 |
-
all_messages = result.scalars().all()
|
| 395 |
-
|
| 396 |
-
conversations = {}
|
| 397 |
-
for msg in all_messages:
|
| 398 |
-
partner_id = msg.receiver_email if msg.sender_email == recruiter_email else msg.sender_email
|
| 399 |
-
if partner_id not in conversations:
|
| 400 |
-
talent_name = partner_id
|
| 401 |
-
t_result = await db.execute(
|
| 402 |
-
select(Talent).where(Talent.email == partner_id)
|
| 403 |
-
)
|
| 404 |
-
talent = t_result.scalar_one_or_none()
|
| 405 |
-
if talent:
|
| 406 |
-
talent_name = talent.name or talent.talent_id
|
| 407 |
-
|
| 408 |
-
conversations[partner_id] = {
|
| 409 |
-
"partner_id": partner_id,
|
| 410 |
-
"conversation_id": msg.conversation_id,
|
| 411 |
-
"last_message": msg.original_message if msg.sender_role == "RECRUITER" else msg.mediated_message,
|
| 412 |
-
"timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
|
| 413 |
-
"status": msg.status,
|
| 414 |
-
"is_unlocked": msg.is_identity_unlocked,
|
| 415 |
-
"partner_name": talent_name,
|
| 416 |
-
}
|
| 417 |
-
|
| 418 |
-
return {
|
| 419 |
-
"success": True,
|
| 420 |
-
"data": sorted(conversations.values(), key=lambda c: c["timestamp"], reverse=True),
|
| 421 |
-
}
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
# =============================================================================
|
| 425 |
-
# 5. GET CONVERSATION LIST (for talent)
|
| 426 |
-
# =============================================================================
|
| 427 |
-
|
| 428 |
-
async def get_talent_conversations(
|
| 429 |
-
db: AsyncSession,
|
| 430 |
-
talent_email: str,
|
| 431 |
-
) -> list:
|
| 432 |
-
"""Get all conversations for a talent, grouped by conversation ID."""
|
| 433 |
-
result = await db.execute(
|
| 434 |
-
select(MediatedChat)
|
| 435 |
-
.where(
|
| 436 |
-
or_(
|
| 437 |
-
MediatedChat.sender_email == talent_email,
|
| 438 |
-
MediatedChat.receiver_email == talent_email,
|
| 439 |
-
)
|
| 440 |
-
)
|
| 441 |
-
.order_by(MediatedChat.timestamp.desc())
|
| 442 |
-
)
|
| 443 |
-
all_messages = result.scalars().all()
|
| 444 |
-
|
| 445 |
-
conversations = {}
|
| 446 |
-
for msg in all_messages:
|
| 447 |
-
conv_id = msg.conversation_id
|
| 448 |
-
if conv_id not in conversations:
|
| 449 |
-
conversations[conv_id] = {
|
| 450 |
-
"partner_id": conv_id,
|
| 451 |
-
"conversation_id": conv_id,
|
| 452 |
-
"last_message": msg.original_message if msg.sender_role == "TALENT" else msg.mediated_message,
|
| 453 |
-
"timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
|
| 454 |
-
"status": msg.status,
|
| 455 |
-
"is_unlocked": msg.is_identity_unlocked,
|
| 456 |
-
"partner_name": "Recruiter",
|
| 457 |
-
}
|
| 458 |
-
|
| 459 |
-
return {
|
| 460 |
-
"success": True,
|
| 461 |
-
"data": sorted(conversations.values(), key=lambda c: c["timestamp"], reverse=True),
|
| 462 |
-
}
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
# =============================================================================
|
| 466 |
-
# 6. GET CHAT HISTORY
|
| 467 |
-
# =============================================================================
|
| 468 |
-
|
| 469 |
-
async def get_chat_history(
|
| 470 |
-
db: AsyncSession,
|
| 471 |
-
email: str,
|
| 472 |
-
partner_id: str,
|
| 473 |
-
role: str = "RECRUITER",
|
| 474 |
-
) -> list:
|
| 475 |
-
"""Get full message history for a conversation.
|
| 476 |
-
|
| 477 |
-
For recruiters: partner_id is talent email
|
| 478 |
-
For talents: partner_id is conversation ID
|
| 479 |
-
"""
|
| 480 |
-
e = email.lower().strip()
|
| 481 |
-
p = partner_id.strip()
|
| 482 |
-
|
| 483 |
-
if role == "RECRUITER":
|
| 484 |
-
result = await db.execute(
|
| 485 |
-
select(MediatedChat)
|
| 486 |
-
.where(
|
| 487 |
-
or_(
|
| 488 |
-
(MediatedChat.sender_email == e) & (MediatedChat.receiver_email == p),
|
| 489 |
-
(MediatedChat.sender_email == p) & (MediatedChat.receiver_email == e),
|
| 490 |
-
)
|
| 491 |
-
)
|
| 492 |
-
.order_by(MediatedChat.timestamp.asc())
|
| 493 |
-
)
|
| 494 |
-
else:
|
| 495 |
-
result = await db.execute(
|
| 496 |
-
select(MediatedChat)
|
| 497 |
-
.where(
|
| 498 |
-
MediatedChat.conversation_id == p,
|
| 499 |
-
or_(
|
| 500 |
-
MediatedChat.sender_email == e,
|
| 501 |
-
MediatedChat.receiver_email == e,
|
| 502 |
-
),
|
| 503 |
-
)
|
| 504 |
-
.order_by(MediatedChat.timestamp.asc())
|
| 505 |
-
)
|
| 506 |
-
|
| 507 |
-
messages = result.scalars().all()
|
| 508 |
-
|
| 509 |
-
history = []
|
| 510 |
-
for msg in messages:
|
| 511 |
-
if msg.sender_role == "RECRUITER":
|
| 512 |
-
display_text = msg.original_message if role == "RECRUITER" else msg.mediated_message
|
| 513 |
-
else:
|
| 514 |
-
display_text = msg.mediated_message if role == "RECRUITER" else msg.original_message
|
| 515 |
-
|
| 516 |
-
history.append({
|
| 517 |
-
"sender": msg.sender_role,
|
| 518 |
-
"text": display_text,
|
| 519 |
-
"timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
|
| 520 |
-
"is_unlocked": msg.is_identity_unlocked,
|
| 521 |
-
})
|
| 522 |
-
|
| 523 |
-
return {
|
| 524 |
-
"success": True,
|
| 525 |
-
"data": history,
|
| 526 |
-
}
|
|
|
|
| 1 |
+
"""Mediated Chat Service — AI-relayed messaging between Recruiters and Talents.
|
| 2 |
+
|
| 3 |
+
Architecture (matches ChatManager.gs):
|
| 4 |
+
1. Recruiter sends raw message → AI mediates it (mask identity)
|
| 5 |
+
2. Talent receives mediated message → replies raw
|
| 6 |
+
3. AI summarizes reply for recruiter (mask identity)
|
| 7 |
+
4. Recruiter can unlock identity (costs 5 coins)
|
| 8 |
+
|
| 9 |
+
AI tier: LOW (Gemini 3.5 Flash lightweight) — fast, cheap, crash-proof.
|
| 10 |
+
Fallback: algorithmic mediation (template-based masking).
|
| 11 |
+
Never crashes.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import secrets
|
| 15 |
+
from datetime import datetime, timezone
|
| 16 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 17 |
+
|
| 18 |
+
from loguru import logger
|
| 19 |
+
from sqlalchemy import or_, select
|
| 20 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 21 |
+
|
| 22 |
+
from app.models.job import MediatedChat
|
| 23 |
+
from app.models.talent import Talent
|
| 24 |
+
from app.models.employer import ClientAccount, Company
|
| 25 |
+
from app.models.finance import Transaction
|
| 26 |
+
from app.services.ai_service import call_low
|
| 27 |
+
from app.utils.errors import ErrorCode, raise_error
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
UNLOCK_COST = 5 # Coins to unlock identity (matches GAS FINANCE_CONFIG.DEDUCTION.IDENTITY_UNLOCK)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# =============================================================================
|
| 34 |
+
# HELPERS
|
| 35 |
+
# =============================================================================
|
| 36 |
+
|
| 37 |
+
def _generate_chat_id() -> str:
|
| 38 |
+
return f"MSG-{secrets.token_hex(4).upper()}"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _generate_conversation_id() -> str:
|
| 42 |
+
return f"CONV-{secrets.token_hex(4).upper()}"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _algorithmic_mediate_recruiter_message(
|
| 46 |
+
raw_message: str,
|
| 47 |
+
recruiter_industry: str = "Sustainability Sector",
|
| 48 |
+
) -> str:
|
| 49 |
+
"""Algorithmic fallback for recruiter message mediation.
|
| 50 |
+
No AI needed — template-based masking.
|
| 51 |
+
"""
|
| 52 |
+
clean = raw_message.strip()[:500]
|
| 53 |
+
return (
|
| 54 |
+
f"Hey [Talent], ada recruiter dari {recruiter_industry} "
|
| 55 |
+
f"yang tertarik dengan profil kamu. Mereka ingin tahu lebih lanjut: "
|
| 56 |
+
f'"{clean}"'
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _algorithmic_mediate_talent_reply(
|
| 61 |
+
raw_reply: str,
|
| 62 |
+
talent_id: str,
|
| 63 |
+
) -> str:
|
| 64 |
+
"""Algorithmic fallback for talent reply mediation.
|
| 65 |
+
No AI needed — template-based.
|
| 66 |
+
"""
|
| 67 |
+
clean = raw_reply.strip()[:500]
|
| 68 |
+
return (
|
| 69 |
+
f"Respon dari [Talent ID: {talent_id}], dia mengatakan: "
|
| 70 |
+
f'"{clean}". '
|
| 71 |
+
f"Silakan pertimbangkan untuk melanjutkan diskusi."
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
async def _get_talent_by_id(db: AsyncSession, talent_id: str) -> Optional[Talent]:
|
| 76 |
+
result = await db.execute(select(Talent).where(Talent.talent_id == talent_id))
|
| 77 |
+
return result.scalar_one_or_none()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
async def _get_client_and_company_by_email(db: AsyncSession, email: str) -> tuple:
|
| 81 |
+
"""Look up ClientAccount and Company by email.
|
| 82 |
+
Returns (client, company) or (None, None).
|
| 83 |
+
"""
|
| 84 |
+
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 85 |
+
client = result.scalar_one_or_none()
|
| 86 |
+
if not client:
|
| 87 |
+
return None, None
|
| 88 |
+
result = await db.execute(select(Company).where(Company.id == client.company_id))
|
| 89 |
+
company = result.scalar_one_or_none()
|
| 90 |
+
return client, company
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# =============================================================================
|
| 94 |
+
# 1. RECRUITER SENDS MESSAGE -> AI MEDIATED -> TALENT
|
| 95 |
+
# =============================================================================
|
| 96 |
+
|
| 97 |
+
async def send_recruiter_message(
|
| 98 |
+
db: AsyncSession,
|
| 99 |
+
recruiter_email: str,
|
| 100 |
+
talent_id: str,
|
| 101 |
+
raw_message: str,
|
| 102 |
+
existing_conversation_id: Optional[str] = None,
|
| 103 |
+
) -> dict:
|
| 104 |
+
"""Recruiter sends a message to a talent. AI mediates it.
|
| 105 |
+
|
| 106 |
+
Flow:
|
| 107 |
+
1. Verify talent exists
|
| 108 |
+
2. Get or create conversation
|
| 109 |
+
3. AI mediates the message (LOW tier -> algorithmic fallback)
|
| 110 |
+
4. Save to database
|
| 111 |
+
5. Return conversation ID
|
| 112 |
+
"""
|
| 113 |
+
# Verify talent exists
|
| 114 |
+
talent = await _get_talent_by_id(db, talent_id)
|
| 115 |
+
if not talent:
|
| 116 |
+
raise_error(f"Talent {talent_id} not found.", ErrorCode.NOT_FOUND, 404)
|
| 117 |
+
|
| 118 |
+
# Get or create conversation
|
| 119 |
+
conversation_id = existing_conversation_id or _generate_conversation_id()
|
| 120 |
+
chat_id = _generate_chat_id()
|
| 121 |
+
|
| 122 |
+
# AI-mediated message (LOW tier = Gemini 3.5 Flash lightweight)
|
| 123 |
+
mediated_message = None
|
| 124 |
+
try:
|
| 125 |
+
prompt = (
|
| 126 |
+
f"Anda adalah Brigawan Matchmaker. Seorang recruiter dari Sustainability "
|
| 127 |
+
f'mengirim pesan ini: "{raw_message[:500]}".\n'
|
| 128 |
+
f"Ubah pesan ini menjadi format Brigawan Relay untuk Talent.\n"
|
| 129 |
+
f"Gunakan gaya: 'Hey [talent], recruiter dari perusahaan [industri] "
|
| 130 |
+
f"bertanya mengenai [topik]. [Pertanyaan rephrased].'\n"
|
| 131 |
+
f"JANGAN sebutkan nama perusahaan recruiter.\n"
|
| 132 |
+
f"BALAS LANGSUNG dengan pesan yang sudah di-mediate, tanpa penjelasan tambahan."
|
| 133 |
+
)
|
| 134 |
+
mediated_message = await call_low(prompt=prompt, temperature=0.7, max_output_tokens=512)
|
| 135 |
+
except Exception as e:
|
| 136 |
+
logger.error(f"AI mediation failed for recruiter message: {e}")
|
| 137 |
+
|
| 138 |
+
if not mediated_message:
|
| 139 |
+
mediated_message = _algorithmic_mediate_recruiter_message(raw_message)
|
| 140 |
+
|
| 141 |
+
# Save to DB
|
| 142 |
+
chat = MediatedChat(
|
| 143 |
+
chat_id=chat_id,
|
| 144 |
+
conversation_id=conversation_id,
|
| 145 |
+
sender_email=recruiter_email,
|
| 146 |
+
receiver_email=talent.email,
|
| 147 |
+
sender_role="RECRUITER",
|
| 148 |
+
original_message=raw_message,
|
| 149 |
+
mediated_message=mediated_message,
|
| 150 |
+
is_identity_unlocked=False,
|
| 151 |
+
status="PENDING_TALENT",
|
| 152 |
+
timestamp=datetime.now(timezone.utc),
|
| 153 |
+
)
|
| 154 |
+
db.add(chat)
|
| 155 |
+
await db.commit()
|
| 156 |
+
|
| 157 |
+
logger.info(f"Chat message sent: {conversation_id} ({recruiter_email} -> {talent_id})")
|
| 158 |
+
|
| 159 |
+
return {
|
| 160 |
+
"success": True,
|
| 161 |
+
"ai_feedback": f"Halo {recruiter_email.split('@')[0]}, saya tanyakan dulu ya sama kandidatnya.",
|
| 162 |
+
"conversation_id": conversation_id,
|
| 163 |
+
"message": "Message sent and mediated.",
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# =============================================================================
|
| 168 |
+
# 2. TALENT REPLIES -> AI SUMMARIZED -> RECRUITER
|
| 169 |
+
# =============================================================================
|
| 170 |
+
|
| 171 |
+
async def send_talent_reply(
|
| 172 |
+
db: AsyncSession,
|
| 173 |
+
talent_email: str,
|
| 174 |
+
conversation_id: str,
|
| 175 |
+
raw_reply: str,
|
| 176 |
+
) -> dict:
|
| 177 |
+
"""Talent replies to a conversation. AI summarizes for recruiter.
|
| 178 |
+
|
| 179 |
+
Flow:
|
| 180 |
+
1. Verify conversation exists and talent is a participant
|
| 181 |
+
2. AI summarizes the reply (LOW tier -> algorithmic fallback)
|
| 182 |
+
3. Save to database
|
| 183 |
+
4. Return success
|
| 184 |
+
"""
|
| 185 |
+
# Verify conversation exists
|
| 186 |
+
result = await db.execute(
|
| 187 |
+
select(MediatedChat)
|
| 188 |
+
.where(MediatedChat.conversation_id == conversation_id)
|
| 189 |
+
.limit(1)
|
| 190 |
+
)
|
| 191 |
+
existing = result.scalar_one_or_none()
|
| 192 |
+
if not existing:
|
| 193 |
+
raise_error("Conversation not found.", ErrorCode.NOT_FOUND, 404)
|
| 194 |
+
|
| 195 |
+
# Verify talent is a participant
|
| 196 |
+
result = await db.execute(select(MediatedChat).where(
|
| 197 |
+
MediatedChat.conversation_id == conversation_id,
|
| 198 |
+
MediatedChat.receiver_email == talent_email,
|
| 199 |
+
).limit(1))
|
| 200 |
+
participant = result.scalar_one_or_none()
|
| 201 |
+
if not participant:
|
| 202 |
+
result = await db.execute(select(MediatedChat).where(
|
| 203 |
+
MediatedChat.conversation_id == conversation_id,
|
| 204 |
+
or_(
|
| 205 |
+
MediatedChat.sender_email == talent_email,
|
| 206 |
+
MediatedChat.receiver_email == talent_email,
|
| 207 |
+
)
|
| 208 |
+
).limit(1))
|
| 209 |
+
if not result.scalar_one_or_none():
|
| 210 |
+
raise_error("You are not a participant in this conversation.", ErrorCode.NOT_AUTHORIZED, 403)
|
| 211 |
+
|
| 212 |
+
# Find recruiter email from conversation
|
| 213 |
+
result = await db.execute(
|
| 214 |
+
select(MediatedChat)
|
| 215 |
+
.where(
|
| 216 |
+
MediatedChat.conversation_id == conversation_id,
|
| 217 |
+
MediatedChat.sender_role == "RECRUITER",
|
| 218 |
+
)
|
| 219 |
+
.limit(1)
|
| 220 |
+
)
|
| 221 |
+
recruiter_msg = result.scalar_one_or_none()
|
| 222 |
+
recruiter_email = recruiter_msg.sender_email if recruiter_msg else ""
|
| 223 |
+
|
| 224 |
+
if not recruiter_email:
|
| 225 |
+
raise_error("Could not find conversation partner.", ErrorCode.NOT_FOUND, 404)
|
| 226 |
+
|
| 227 |
+
chat_id = _generate_chat_id()
|
| 228 |
+
talent_id_str = talent_email
|
| 229 |
+
|
| 230 |
+
# AI-mediated reply (LOW tier -> algorithmic fallback)
|
| 231 |
+
mediated_summary = None
|
| 232 |
+
try:
|
| 233 |
+
prompt = (
|
| 234 |
+
f"Anda adalah Brigawan Matchmaker. Talent ({talent_id_str}) menjawab "
|
| 235 |
+
f'pertanyaan recruiter: "{raw_reply[:500]}".\n'
|
| 236 |
+
f"Ubah jawaban ini menjadi format Brigawan Insight untuk Recruiter.\n"
|
| 237 |
+
f"Gunakan gaya: 'Respon dari [Talent ID], dia [rangkuman jawaban]. "
|
| 238 |
+
f"[Saran tindak lanjut jika ada].'\n"
|
| 239 |
+
f"JANGAN sebutkan nama asli talent.\n"
|
| 240 |
+
f"BALAS LANGSUNG dengan pesan yang sudah di-mediate."
|
| 241 |
+
)
|
| 242 |
+
mediated_summary = await call_low(prompt=prompt, temperature=0.7, max_output_tokens=512)
|
| 243 |
+
except Exception as e:
|
| 244 |
+
logger.error(f"AI mediation failed for talent reply: {e}")
|
| 245 |
+
|
| 246 |
+
if not mediated_summary:
|
| 247 |
+
mediated_summary = _algorithmic_mediate_talent_reply(raw_reply, talent_id_str)
|
| 248 |
+
|
| 249 |
+
# Save to DB
|
| 250 |
+
chat = MediatedChat(
|
| 251 |
+
chat_id=chat_id,
|
| 252 |
+
conversation_id=conversation_id,
|
| 253 |
+
sender_email=talent_email,
|
| 254 |
+
receiver_email=recruiter_email,
|
| 255 |
+
sender_role="TALENT",
|
| 256 |
+
original_message=raw_reply,
|
| 257 |
+
mediated_message=mediated_summary,
|
| 258 |
+
is_identity_unlocked=False,
|
| 259 |
+
status="PENDING_RECRUITER",
|
| 260 |
+
timestamp=datetime.now(timezone.utc),
|
| 261 |
+
)
|
| 262 |
+
db.add(chat)
|
| 263 |
+
await db.commit()
|
| 264 |
+
|
| 265 |
+
logger.info(f"Talent reply mediated: {conversation_id}")
|
| 266 |
+
|
| 267 |
+
return {
|
| 268 |
+
"success": True,
|
| 269 |
+
"message": "Balasan Anda telah dikirimkan ke Recruiter melalui Brigawan.",
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# =============================================================================
|
| 274 |
+
# 3. UNLOCK IDENTITY (costs 5 coins)
|
| 275 |
+
# =============================================================================
|
| 276 |
+
|
| 277 |
+
async def unlock_chat_identity(
|
| 278 |
+
db: AsyncSession,
|
| 279 |
+
recruiter_email: str,
|
| 280 |
+
talent_id: str,
|
| 281 |
+
) -> dict:
|
| 282 |
+
"""Unlock talent identity in chat. Costs 5 Briga coins.
|
| 283 |
+
|
| 284 |
+
Flow:
|
| 285 |
+
1. Verify employer has enough coins
|
| 286 |
+
2. Deduct coins + log transaction with proper FK
|
| 287 |
+
3. Mark all messages in conversation as unlocked
|
| 288 |
+
4. Return full talent profile
|
| 289 |
+
"""
|
| 290 |
+
talent = await _get_talent_by_id(db, talent_id)
|
| 291 |
+
if not talent:
|
| 292 |
+
raise_error(f"Talent {talent_id} not found.", ErrorCode.NOT_FOUND, 404)
|
| 293 |
+
|
| 294 |
+
client, company = await _get_client_and_company_by_email(db, recruiter_email)
|
| 295 |
+
if not client or not company:
|
| 296 |
+
raise_error("Employer account not found.", ErrorCode.NOT_FOUND, 404)
|
| 297 |
+
|
| 298 |
+
# Check if already unlocked
|
| 299 |
+
result = await db.execute(
|
| 300 |
+
select(MediatedChat).where(
|
| 301 |
+
MediatedChat.sender_email == recruiter_email,
|
| 302 |
+
MediatedChat.receiver_email == talent.email,
|
| 303 |
+
MediatedChat.is_identity_unlocked == True,
|
| 304 |
+
).limit(1)
|
| 305 |
+
)
|
| 306 |
+
if result.scalar_one_or_none():
|
| 307 |
+
return {
|
| 308 |
+
"success": True,
|
| 309 |
+
"message": "Identity already unlocked. No coins deducted.",
|
| 310 |
+
"talent_name": talent.name or "",
|
| 311 |
+
"talent_email": talent.email or "",
|
| 312 |
+
"talent_phone": talent.phone or "",
|
| 313 |
+
"credits_remaining": company.credit_balance or 0,
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
# Check balance
|
| 317 |
+
if (company.credit_balance or 0) < UNLOCK_COST:
|
| 318 |
+
raise_error(
|
| 319 |
+
f"Insufficient coins. Unlock costs {UNLOCK_COST} coins. Balance: {company.credit_balance or 0}",
|
| 320 |
+
code=ErrorCode.NOT_AUTHORIZED,
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
# Deduct
|
| 324 |
+
company.credit_balance = (company.credit_balance or 0) - UNLOCK_COST
|
| 325 |
+
db.add(company)
|
| 326 |
+
|
| 327 |
+
# Log transaction with proper client FK (ClientAccount.id, not email)
|
| 328 |
+
tx = Transaction(
|
| 329 |
+
id=f"TX-UNL-CHAT-{secrets.token_hex(4).upper()}",
|
| 330 |
+
client_id=client.id,
|
| 331 |
+
amount=UNLOCK_COST,
|
| 332 |
+
type="IdentityUnlock",
|
| 333 |
+
status="Settled",
|
| 334 |
+
)
|
| 335 |
+
db.add(tx)
|
| 336 |
+
|
| 337 |
+
# Mark all messages between this recruiter and talent as unlocked
|
| 338 |
+
result = await db.execute(
|
| 339 |
+
select(MediatedChat).where(
|
| 340 |
+
MediatedChat.sender_email == recruiter_email,
|
| 341 |
+
MediatedChat.receiver_email == talent.email,
|
| 342 |
+
)
|
| 343 |
+
)
|
| 344 |
+
for chat in result.scalars().all():
|
| 345 |
+
chat.is_identity_unlocked = True
|
| 346 |
+
db.add(chat)
|
| 347 |
+
|
| 348 |
+
result = await db.execute(
|
| 349 |
+
select(MediatedChat).where(
|
| 350 |
+
MediatedChat.sender_email == talent.email,
|
| 351 |
+
MediatedChat.receiver_email == recruiter_email,
|
| 352 |
+
)
|
| 353 |
+
)
|
| 354 |
+
for chat in result.scalars().all():
|
| 355 |
+
chat.is_identity_unlocked = True
|
| 356 |
+
db.add(chat)
|
| 357 |
+
|
| 358 |
+
await db.commit()
|
| 359 |
+
|
| 360 |
+
logger.info(f"Chat identity unlocked: {recruiter_email} -> {talent_id} (cost: {UNLOCK_COST})")
|
| 361 |
+
|
| 362 |
+
return {
|
| 363 |
+
"success": True,
|
| 364 |
+
"message": f"Identitas Talent berhasil dibuka! {UNLOCK_COST} coins deducted.",
|
| 365 |
+
"talent_name": talent.name or "",
|
| 366 |
+
"talent_email": talent.email or "",
|
| 367 |
+
"talent_phone": talent.phone or "",
|
| 368 |
+
"credits_remaining": company.credit_balance or 0,
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
# =============================================================================
|
| 373 |
+
# 4. GET CONVERSATION LIST (for recruiter)
|
| 374 |
+
# =============================================================================
|
| 375 |
+
|
| 376 |
+
async def get_recruiter_conversations(
|
| 377 |
+
db: AsyncSession,
|
| 378 |
+
recruiter_email: str,
|
| 379 |
+
) -> list:
|
| 380 |
+
"""Get all conversations for a recruiter, sorted by latest message.
|
| 381 |
+
|
| 382 |
+
Groups messages by partner (talent), returns the latest message per partner.
|
| 383 |
+
"""
|
| 384 |
+
result = await db.execute(
|
| 385 |
+
select(MediatedChat)
|
| 386 |
+
.where(
|
| 387 |
+
or_(
|
| 388 |
+
MediatedChat.sender_email == recruiter_email,
|
| 389 |
+
MediatedChat.receiver_email == recruiter_email,
|
| 390 |
+
)
|
| 391 |
+
)
|
| 392 |
+
.order_by(MediatedChat.timestamp.desc())
|
| 393 |
+
)
|
| 394 |
+
all_messages = result.scalars().all()
|
| 395 |
+
|
| 396 |
+
conversations = {}
|
| 397 |
+
for msg in all_messages:
|
| 398 |
+
partner_id = msg.receiver_email if msg.sender_email == recruiter_email else msg.sender_email
|
| 399 |
+
if partner_id not in conversations:
|
| 400 |
+
talent_name = partner_id
|
| 401 |
+
t_result = await db.execute(
|
| 402 |
+
select(Talent).where(Talent.email == partner_id)
|
| 403 |
+
)
|
| 404 |
+
talent = t_result.scalar_one_or_none()
|
| 405 |
+
if talent:
|
| 406 |
+
talent_name = talent.name or talent.talent_id
|
| 407 |
+
|
| 408 |
+
conversations[partner_id] = {
|
| 409 |
+
"partner_id": partner_id,
|
| 410 |
+
"conversation_id": msg.conversation_id,
|
| 411 |
+
"last_message": msg.original_message if msg.sender_role == "RECRUITER" else msg.mediated_message,
|
| 412 |
+
"timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
|
| 413 |
+
"status": msg.status,
|
| 414 |
+
"is_unlocked": msg.is_identity_unlocked,
|
| 415 |
+
"partner_name": talent_name,
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
return {
|
| 419 |
+
"success": True,
|
| 420 |
+
"data": sorted(conversations.values(), key=lambda c: c["timestamp"], reverse=True),
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
# =============================================================================
|
| 425 |
+
# 5. GET CONVERSATION LIST (for talent)
|
| 426 |
+
# =============================================================================
|
| 427 |
+
|
| 428 |
+
async def get_talent_conversations(
|
| 429 |
+
db: AsyncSession,
|
| 430 |
+
talent_email: str,
|
| 431 |
+
) -> list:
|
| 432 |
+
"""Get all conversations for a talent, grouped by conversation ID."""
|
| 433 |
+
result = await db.execute(
|
| 434 |
+
select(MediatedChat)
|
| 435 |
+
.where(
|
| 436 |
+
or_(
|
| 437 |
+
MediatedChat.sender_email == talent_email,
|
| 438 |
+
MediatedChat.receiver_email == talent_email,
|
| 439 |
+
)
|
| 440 |
+
)
|
| 441 |
+
.order_by(MediatedChat.timestamp.desc())
|
| 442 |
+
)
|
| 443 |
+
all_messages = result.scalars().all()
|
| 444 |
+
|
| 445 |
+
conversations = {}
|
| 446 |
+
for msg in all_messages:
|
| 447 |
+
conv_id = msg.conversation_id
|
| 448 |
+
if conv_id not in conversations:
|
| 449 |
+
conversations[conv_id] = {
|
| 450 |
+
"partner_id": conv_id,
|
| 451 |
+
"conversation_id": conv_id,
|
| 452 |
+
"last_message": msg.original_message if msg.sender_role == "TALENT" else msg.mediated_message,
|
| 453 |
+
"timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
|
| 454 |
+
"status": msg.status,
|
| 455 |
+
"is_unlocked": msg.is_identity_unlocked,
|
| 456 |
+
"partner_name": "Recruiter",
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
return {
|
| 460 |
+
"success": True,
|
| 461 |
+
"data": sorted(conversations.values(), key=lambda c: c["timestamp"], reverse=True),
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# =============================================================================
|
| 466 |
+
# 6. GET CHAT HISTORY
|
| 467 |
+
# =============================================================================
|
| 468 |
+
|
| 469 |
+
async def get_chat_history(
|
| 470 |
+
db: AsyncSession,
|
| 471 |
+
email: str,
|
| 472 |
+
partner_id: str,
|
| 473 |
+
role: str = "RECRUITER",
|
| 474 |
+
) -> list:
|
| 475 |
+
"""Get full message history for a conversation.
|
| 476 |
+
|
| 477 |
+
For recruiters: partner_id is talent email
|
| 478 |
+
For talents: partner_id is conversation ID
|
| 479 |
+
"""
|
| 480 |
+
e = email.lower().strip()
|
| 481 |
+
p = partner_id.strip()
|
| 482 |
+
|
| 483 |
+
if role == "RECRUITER":
|
| 484 |
+
result = await db.execute(
|
| 485 |
+
select(MediatedChat)
|
| 486 |
+
.where(
|
| 487 |
+
or_(
|
| 488 |
+
(MediatedChat.sender_email == e) & (MediatedChat.receiver_email == p),
|
| 489 |
+
(MediatedChat.sender_email == p) & (MediatedChat.receiver_email == e),
|
| 490 |
+
)
|
| 491 |
+
)
|
| 492 |
+
.order_by(MediatedChat.timestamp.asc())
|
| 493 |
+
)
|
| 494 |
+
else:
|
| 495 |
+
result = await db.execute(
|
| 496 |
+
select(MediatedChat)
|
| 497 |
+
.where(
|
| 498 |
+
MediatedChat.conversation_id == p,
|
| 499 |
+
or_(
|
| 500 |
+
MediatedChat.sender_email == e,
|
| 501 |
+
MediatedChat.receiver_email == e,
|
| 502 |
+
),
|
| 503 |
+
)
|
| 504 |
+
.order_by(MediatedChat.timestamp.asc())
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
messages = result.scalars().all()
|
| 508 |
+
|
| 509 |
+
history = []
|
| 510 |
+
for msg in messages:
|
| 511 |
+
if msg.sender_role == "RECRUITER":
|
| 512 |
+
display_text = msg.original_message if role == "RECRUITER" else msg.mediated_message
|
| 513 |
+
else:
|
| 514 |
+
display_text = msg.mediated_message if role == "RECRUITER" else msg.original_message
|
| 515 |
+
|
| 516 |
+
history.append({
|
| 517 |
+
"sender": msg.sender_role,
|
| 518 |
+
"text": display_text,
|
| 519 |
+
"timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
|
| 520 |
+
"is_unlocked": msg.is_identity_unlocked,
|
| 521 |
+
})
|
| 522 |
+
|
| 523 |
+
return {
|
| 524 |
+
"success": True,
|
| 525 |
+
"data": history,
|
| 526 |
+
}
|
app/services/content_scheduler_service.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Content Scheduler Service — Humanized Posting Scheduler.
|
| 2 |
+
|
| 3 |
+
Implements "fuzzy scheduling" to avoid robotic exact-time posting.
|
| 4 |
+
Instead of posting exactly at 09:00:00, it posts randomly between
|
| 5 |
+
a specified time window (e.g., 09:00 to 10:00).
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import asyncio
|
| 9 |
+
import random
|
| 10 |
+
from datetime import datetime, timedelta
|
| 11 |
+
from loguru import logger
|
| 12 |
+
from typing import Callable, Any
|
| 13 |
+
|
| 14 |
+
class ContentSchedulerService:
|
| 15 |
+
"""Manages scheduled tasks with human-like jitter/fuzziness."""
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
async def schedule_fuzzy_post(
|
| 19 |
+
cls,
|
| 20 |
+
task_name: str,
|
| 21 |
+
publish_func: Callable,
|
| 22 |
+
start_hour: int,
|
| 23 |
+
end_hour: int,
|
| 24 |
+
*args,
|
| 25 |
+
**kwargs
|
| 26 |
+
):
|
| 27 |
+
"""
|
| 28 |
+
Schedules a task to run randomly between start_hour and end_hour today.
|
| 29 |
+
If the time window has already passed, it schedules for tomorrow.
|
| 30 |
+
"""
|
| 31 |
+
now = datetime.now()
|
| 32 |
+
|
| 33 |
+
# Determine target date (today or tomorrow)
|
| 34 |
+
target_date = now.date()
|
| 35 |
+
if now.hour >= end_hour:
|
| 36 |
+
target_date += timedelta(days=1)
|
| 37 |
+
|
| 38 |
+
start_time = datetime.combine(target_date, datetime.min.time()) + timedelta(hours=start_hour)
|
| 39 |
+
end_time = datetime.combine(target_date, datetime.min.time()) + timedelta(hours=end_hour)
|
| 40 |
+
|
| 41 |
+
# If we are currently inside the window, calculate delay from now to end_time
|
| 42 |
+
if start_time <= now <= end_time:
|
| 43 |
+
window_seconds = int((end_time - now).total_seconds())
|
| 44 |
+
delay_seconds = random.randint(0, window_seconds)
|
| 45 |
+
run_time = now + timedelta(seconds=delay_seconds)
|
| 46 |
+
else:
|
| 47 |
+
# We are before the window
|
| 48 |
+
window_seconds = int((end_time - start_time).total_seconds())
|
| 49 |
+
delay_within_window = random.randint(0, window_seconds)
|
| 50 |
+
run_time = start_time + timedelta(seconds=delay_within_window)
|
| 51 |
+
delay_seconds = int((run_time - now).total_seconds())
|
| 52 |
+
|
| 53 |
+
logger.info(f"[Scheduler] Task '{task_name}' scheduled for {run_time.strftime('%Y-%m-%d %H:%M:%S')} (Delay: {delay_seconds//60} mins). Window: {start_hour}:00 - {end_hour}:00.")
|
| 54 |
+
|
| 55 |
+
# Run the background task
|
| 56 |
+
asyncio.create_task(cls._wait_and_execute(task_name, delay_seconds, publish_func, *args, **kwargs))
|
| 57 |
+
|
| 58 |
+
return {
|
| 59 |
+
"status": "scheduled",
|
| 60 |
+
"task": task_name,
|
| 61 |
+
"scheduled_time": run_time.isoformat(),
|
| 62 |
+
"window": f"{start_hour}:00 - {end_hour}:00"
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
async def _wait_and_execute(cls, task_name: str, delay_seconds: int, func: Callable, *args, **kwargs):
|
| 67 |
+
"""Internal worker that waits the specified time then executes the function."""
|
| 68 |
+
try:
|
| 69 |
+
await asyncio.sleep(delay_seconds)
|
| 70 |
+
logger.info(f"[Scheduler] EXECUTING fuzzy task: '{task_name}' now!")
|
| 71 |
+
|
| 72 |
+
# Execute the actual publishing function (e.g., calling social media API)
|
| 73 |
+
if asyncio.iscoroutinefunction(func):
|
| 74 |
+
await func(*args, **kwargs)
|
| 75 |
+
else:
|
| 76 |
+
func(*args, **kwargs)
|
| 77 |
+
|
| 78 |
+
logger.success(f"[Scheduler] Task '{task_name}' completed successfully.")
|
| 79 |
+
except asyncio.CancelledError:
|
| 80 |
+
logger.warning(f"[Scheduler] Task '{task_name}' was cancelled.")
|
| 81 |
+
except Exception as e:
|
| 82 |
+
logger.error(f"[Scheduler] Task '{task_name}' failed during execution: {e}")
|
| 83 |
+
|
| 84 |
+
# =========================================================================
|
| 85 |
+
# Example integration with the pipeline
|
| 86 |
+
# =========================================================================
|
| 87 |
+
@classmethod
|
| 88 |
+
async def trigger_daily_content_pipeline(cls):
|
| 89 |
+
"""
|
| 90 |
+
Example trigger called every morning (e.g., 06:00 AM) to plan
|
| 91 |
+
today's content and schedule the publishing times.
|
| 92 |
+
"""
|
| 93 |
+
logger.info("[ContentPipeline] Starting daily content planning...")
|
| 94 |
+
|
| 95 |
+
# 1. Content Generation & Fact Checking would happen here...
|
| 96 |
+
# ... (calling VisualContentService.generate_carousel)
|
| 97 |
+
|
| 98 |
+
# 2. Schedule the publishing
|
| 99 |
+
# Instead of posting exactly at 09:00, we give it a human "fuzzy" window
|
| 100 |
+
|
| 101 |
+
async def dummy_publish_action(topic):
|
| 102 |
+
logger.info(f"[PublishingAgent] Pushing '{topic}' to LinkedIn/Instagram API...")
|
| 103 |
+
await asyncio.sleep(2)
|
| 104 |
+
logger.success(f"[PublishingAgent] '{topic}' is LIVE!")
|
| 105 |
+
|
| 106 |
+
# Morning Post (Range: 09:00 - 10:00)
|
| 107 |
+
await cls.schedule_fuzzy_post(
|
| 108 |
+
task_name="Morning Carousel: Green Skills",
|
| 109 |
+
publish_func=dummy_publish_action,
|
| 110 |
+
start_hour=9,
|
| 111 |
+
end_hour=10,
|
| 112 |
+
topic="Green Skills 2026"
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Afternoon Post (Range: 16:00 - 18:00)
|
| 116 |
+
await cls.schedule_fuzzy_post(
|
| 117 |
+
task_name="Afternoon Reels: Career Advice",
|
| 118 |
+
publish_func=dummy_publish_action,
|
| 119 |
+
start_hour=16,
|
| 120 |
+
end_hour=18,
|
| 121 |
+
topic="Cara Nego Gaji Perusahaan ESG"
|
| 122 |
+
)
|
app/services/deploy_service.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
from loguru import logger
|
| 4 |
+
|
| 5 |
+
CF_ACCOUNT_ID = os.environ.get("CF_ACCOUNT_ID")
|
| 6 |
+
CF_API_TOKEN = os.environ.get("CF_API_TOKEN")
|
| 7 |
+
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
|
| 8 |
+
TELEGRAM_CEO_CHAT_ID = os.environ.get("TELEGRAM_CEO_CHAT_ID")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class DeployService:
|
| 12 |
+
"""Simple service to trigger Cloudflare Pages preview deploys and notify CEO via Telegram."""
|
| 13 |
+
|
| 14 |
+
@staticmethod
|
| 15 |
+
def trigger_cloudflare_preview(project_name: str) -> dict:
|
| 16 |
+
"""Trigger a Cloudflare Pages deployment via the Pages API and return preview URL.
|
| 17 |
+
|
| 18 |
+
Requires CF_ACCOUNT_ID and CF_API_TOKEN environment variables.
|
| 19 |
+
"""
|
| 20 |
+
if not CF_ACCOUNT_ID or not CF_API_TOKEN:
|
| 21 |
+
logger.error("Cloudflare credentials missing")
|
| 22 |
+
return {"success": False, "error": "missing_cf_credentials"}
|
| 23 |
+
|
| 24 |
+
url = f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/pages/projects/{project_name}/deployments"
|
| 25 |
+
headers = {"Authorization": f"Bearer {CF_API_TOKEN}", "Content-Type": "application/json"}
|
| 26 |
+
payload = {"commit_ref": "preview"}
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
resp = requests.post(url, json=payload, headers=headers, timeout=20)
|
| 30 |
+
data = resp.json()
|
| 31 |
+
if not data.get("success"):
|
| 32 |
+
logger.error(f"Cloudflare API error: {data}")
|
| 33 |
+
return {"success": False, "error": data}
|
| 34 |
+
|
| 35 |
+
# Extract preview url if available
|
| 36 |
+
preview = None
|
| 37 |
+
if "result" in data and data["result"].get("url"):
|
| 38 |
+
preview = data["result"]["url"]
|
| 39 |
+
return {"success": True, "preview_url": preview, "raw": data}
|
| 40 |
+
except Exception as e:
|
| 41 |
+
logger.exception(f"Failed to call Cloudflare API: {e}")
|
| 42 |
+
return {"success": False, "error": str(e)}
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
def notify_ceo_preview(preview_url: str, deploy_id: str):
|
| 46 |
+
"""Send Telegram message to CEO chat id with approve/reject instructions."""
|
| 47 |
+
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CEO_CHAT_ID:
|
| 48 |
+
logger.warning("Telegram config missing; cannot notify CEO")
|
| 49 |
+
return {"success": False, "error": "missing_telegram_config"}
|
| 50 |
+
|
| 51 |
+
text = f"Daily preview ready: {preview_url}\nApprove to merge? Reply: /approve {deploy_id} or /reject {deploy_id}"
|
| 52 |
+
tg_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
|
| 53 |
+
try:
|
| 54 |
+
resp = requests.post(tg_url, json={"chat_id": TELEGRAM_CEO_CHAT_ID, "text": text}, timeout=10)
|
| 55 |
+
return resp.json()
|
| 56 |
+
except Exception as e:
|
| 57 |
+
logger.exception(f"Failed to send Telegram message: {e}")
|
| 58 |
+
return {"success": False, "error": str(e)}
|
app/services/email_service.py
CHANGED
|
@@ -1,47 +1,47 @@
|
|
| 1 |
-
"""Email Service — Native SMTP transactional email sender.
|
| 2 |
-
|
| 3 |
-
Replaces legacy GAS email sending webhooks.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import smtplib
|
| 7 |
-
from email.mime.text import MIMEText
|
| 8 |
-
from email.mime.multipart import MIMEMultipart
|
| 9 |
-
from loguru import logger
|
| 10 |
-
from app.config import settings
|
| 11 |
-
|
| 12 |
-
class EmailService:
|
| 13 |
-
def send_html_email(self, to_email: str, subject: str, html_content: str) -> bool:
|
| 14 |
-
"""Sends an HTML email using SMTP configuration."""
|
| 15 |
-
if not settings.smtp_user or not settings.smtp_password:
|
| 16 |
-
logger.warning("[EmailService] SMTP credentials not fully configured. Skipping email send.")
|
| 17 |
-
return False
|
| 18 |
-
|
| 19 |
-
try:
|
| 20 |
-
msg = MIMEMultipart("alternative")
|
| 21 |
-
msg["Subject"] = subject
|
| 22 |
-
msg["From"] = settings.smtp_user
|
| 23 |
-
msg["To"] = to_email
|
| 24 |
-
|
| 25 |
-
# Attach HTML body
|
| 26 |
-
part = MIMEText(html_content, "html")
|
| 27 |
-
msg.attach(part)
|
| 28 |
-
|
| 29 |
-
# Establish connection
|
| 30 |
-
if settings.smtp_port == 465:
|
| 31 |
-
server = smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port, timeout=15)
|
| 32 |
-
else:
|
| 33 |
-
server = smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=15)
|
| 34 |
-
server.starttls()
|
| 35 |
-
|
| 36 |
-
server.login(settings.smtp_user, settings.smtp_password)
|
| 37 |
-
server.sendmail(settings.smtp_user, to_email, msg.as_string())
|
| 38 |
-
server.quit()
|
| 39 |
-
|
| 40 |
-
logger.info(f"[EmailService] Email sent successfully to {to_email} with subject: {subject}")
|
| 41 |
-
return True
|
| 42 |
-
except Exception as e:
|
| 43 |
-
logger.error(f"[EmailService] Failed to send email to {to_email}: {e}")
|
| 44 |
-
return False
|
| 45 |
-
|
| 46 |
-
# Singleton instance
|
| 47 |
-
email_service = EmailService()
|
|
|
|
| 1 |
+
"""Email Service — Native SMTP transactional email sender.
|
| 2 |
+
|
| 3 |
+
Replaces legacy GAS email sending webhooks.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import smtplib
|
| 7 |
+
from email.mime.text import MIMEText
|
| 8 |
+
from email.mime.multipart import MIMEMultipart
|
| 9 |
+
from loguru import logger
|
| 10 |
+
from app.config import settings
|
| 11 |
+
|
| 12 |
+
class EmailService:
|
| 13 |
+
def send_html_email(self, to_email: str, subject: str, html_content: str) -> bool:
|
| 14 |
+
"""Sends an HTML email using SMTP configuration."""
|
| 15 |
+
if not settings.smtp_user or not settings.smtp_password:
|
| 16 |
+
logger.warning("[EmailService] SMTP credentials not fully configured. Skipping email send.")
|
| 17 |
+
return False
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
msg = MIMEMultipart("alternative")
|
| 21 |
+
msg["Subject"] = subject
|
| 22 |
+
msg["From"] = settings.smtp_user
|
| 23 |
+
msg["To"] = to_email
|
| 24 |
+
|
| 25 |
+
# Attach HTML body
|
| 26 |
+
part = MIMEText(html_content, "html")
|
| 27 |
+
msg.attach(part)
|
| 28 |
+
|
| 29 |
+
# Establish connection
|
| 30 |
+
if settings.smtp_port == 465:
|
| 31 |
+
server = smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port, timeout=15)
|
| 32 |
+
else:
|
| 33 |
+
server = smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=15)
|
| 34 |
+
server.starttls()
|
| 35 |
+
|
| 36 |
+
server.login(settings.smtp_user, settings.smtp_password)
|
| 37 |
+
server.sendmail(settings.smtp_user, to_email, msg.as_string())
|
| 38 |
+
server.quit()
|
| 39 |
+
|
| 40 |
+
logger.info(f"[EmailService] Email sent successfully to {to_email} with subject: {subject}")
|
| 41 |
+
return True
|
| 42 |
+
except Exception as e:
|
| 43 |
+
logger.error(f"[EmailService] Failed to send email to {to_email}: {e}")
|
| 44 |
+
return False
|
| 45 |
+
|
| 46 |
+
# Singleton instance
|
| 47 |
+
email_service = EmailService()
|
app/services/google_workspace_service.py
CHANGED
|
@@ -1,210 +1,210 @@
|
|
| 1 |
-
"""Google Workspace Service — Automated Document Management (The Spark Agent).
|
| 2 |
-
|
| 3 |
-
Handles Google Drive folder orchestration, CV storage, and automated
|
| 4 |
-
Google Docs resume generation.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import os
|
| 8 |
-
import json
|
| 9 |
-
from typing import Dict, Any, Optional, List
|
| 10 |
-
from loguru import logger
|
| 11 |
-
from google.oauth2 import service_account
|
| 12 |
-
from googleapiclient.discovery import build
|
| 13 |
-
from googleapiclient.http import MediaInMemoryUpload
|
| 14 |
-
|
| 15 |
-
from app.config import settings
|
| 16 |
-
|
| 17 |
-
class GoogleWorkspaceService:
|
| 18 |
-
def __init__(self):
|
| 19 |
-
self.scopes = [
|
| 20 |
-
'https://www.googleapis.com/auth/drive',
|
| 21 |
-
'https://www.googleapis.com/auth/documents',
|
| 22 |
-
'https://www.googleapis.com/auth/calendar',
|
| 23 |
-
'https://www.googleapis.com/auth/spreadsheets'
|
| 24 |
-
]
|
| 25 |
-
self.creds = self._load_credentials()
|
| 26 |
-
self.drive_service = build('drive', 'v3', credentials=self.creds) if self.creds else None
|
| 27 |
-
self.docs_service = build('docs', 'v1', credentials=self.creds) if self.creds else None
|
| 28 |
-
self.calendar_service = build('calendar', 'v3', credentials=self.creds) if self.creds else None
|
| 29 |
-
self.sheets_service = build('sheets', 'v4', credentials=self.creds) if self.creds else None
|
| 30 |
-
|
| 31 |
-
async def append_row_to_sheet(self, spreadsheet_id: str, range_name: str, row_values: List[Any]) -> bool:
|
| 32 |
-
"""Appends a row of values to a specified Google Sheet using the Sheets API."""
|
| 33 |
-
if not self.sheets_service:
|
| 34 |
-
logger.warning("[SparkAgent] Sheets service not initialized.")
|
| 35 |
-
return False
|
| 36 |
-
|
| 37 |
-
try:
|
| 38 |
-
body = {
|
| 39 |
-
'values': [row_values]
|
| 40 |
-
}
|
| 41 |
-
import asyncio
|
| 42 |
-
def run_append():
|
| 43 |
-
return self.sheets_service.spreadsheets().values().append(
|
| 44 |
-
spreadsheetId=spreadsheet_id,
|
| 45 |
-
range=range_name,
|
| 46 |
-
valueInputOption="USER_ENTERED",
|
| 47 |
-
insertDataOption="INSERT_ROWS",
|
| 48 |
-
body=body
|
| 49 |
-
).execute()
|
| 50 |
-
|
| 51 |
-
await asyncio.to_thread(run_append)
|
| 52 |
-
logger.info(f"[SparkAgent] Appended row to sheet {range_name} in spreadsheet {spreadsheet_id}")
|
| 53 |
-
return True
|
| 54 |
-
except Exception as e:
|
| 55 |
-
logger.error(f"[SparkAgent] Failed to append row to sheet {range_name}: {e}")
|
| 56 |
-
return False
|
| 57 |
-
|
| 58 |
-
async def get_founder_availability(self, start_time: str, end_time: str) -> List[Dict[str, Any]]:
|
| 59 |
-
"""Checks founder's Google Calendar for busy slots."""
|
| 60 |
-
if not self.calendar_service: return []
|
| 61 |
-
|
| 62 |
-
try:
|
| 63 |
-
body = {
|
| 64 |
-
"timeMin": start_time,
|
| 65 |
-
"timeMax": end_time,
|
| 66 |
-
"items": [{"id": "primary"}]
|
| 67 |
-
}
|
| 68 |
-
res = self.calendar_service.freebusy().query(body=body).execute()
|
| 69 |
-
return res.get('calendars', {}).get('primary', {}).get('busy', [])
|
| 70 |
-
except Exception as e:
|
| 71 |
-
logger.error(f"[SparkAgent] Calendar check failed: {e}")
|
| 72 |
-
return []
|
| 73 |
-
|
| 74 |
-
async def schedule_ceo_meeting(self, summary: str, start_iso: str, end_iso: str, attendee_email: str) -> Optional[str]:
|
| 75 |
-
"""Schedules a meeting on the founder's calendar."""
|
| 76 |
-
if not self.calendar_service: return None
|
| 77 |
-
|
| 78 |
-
try:
|
| 79 |
-
event = {
|
| 80 |
-
'summary': summary,
|
| 81 |
-
'description': 'Scheduled by Brigawan AI CEO',
|
| 82 |
-
'start': {'dateTime': start_iso, 'timeZone': 'Asia/Jakarta'},
|
| 83 |
-
'end': {'dateTime': end_iso, 'timeZone': 'Asia/Jakarta'},
|
| 84 |
-
'attendees': [{'email': attendee_email}],
|
| 85 |
-
'conferenceData': {'createRequest': {'requestId': str(uuid.uuid4()), 'conferenceSolutionKey': {'type': 'hangoutsMeet'}}}
|
| 86 |
-
}
|
| 87 |
-
event = self.calendar_service.events().insert(
|
| 88 |
-
calendarId='primary', body=event, conferenceDataVersion=1
|
| 89 |
-
).execute()
|
| 90 |
-
return event.get('htmlLink')
|
| 91 |
-
except Exception as e:
|
| 92 |
-
logger.error(f"[SparkAgent] Meeting scheduling failed: {e}")
|
| 93 |
-
return None
|
| 94 |
-
|
| 95 |
-
def _load_credentials(self):
|
| 96 |
-
"""Loads Service Account credentials from settings."""
|
| 97 |
-
# Use getattr for safety on Hugging Face environments
|
| 98 |
-
json_creds = getattr(settings, "google_service_account_json", None)
|
| 99 |
-
|
| 100 |
-
if not json_creds:
|
| 101 |
-
logger.warning("[SparkAgent] Google Service Account JSON not configured.")
|
| 102 |
-
return None
|
| 103 |
-
try:
|
| 104 |
-
creds_info = json.loads(json_creds)
|
| 105 |
-
return service_account.Credentials.from_service_account_info(
|
| 106 |
-
creds_info, scopes=self.scopes
|
| 107 |
-
)
|
| 108 |
-
except Exception as e:
|
| 109 |
-
logger.error(f"[SparkAgent] Failed to load credentials: {e}")
|
| 110 |
-
return None
|
| 111 |
-
|
| 112 |
-
async def get_or_create_folder(self, folder_name: str, parent_id: Optional[str] = None) -> Optional[str]:
|
| 113 |
-
"""Finds or creates a folder in Google Drive."""
|
| 114 |
-
if not self.drive_service: return None
|
| 115 |
-
|
| 116 |
-
query = f"name = '{folder_name}' and mimeType = 'application/vnd.google-apps.folder' and trashed = false"
|
| 117 |
-
if parent_id:
|
| 118 |
-
query += f" and '{parent_id}' in parents"
|
| 119 |
-
|
| 120 |
-
try:
|
| 121 |
-
results = self.drive_service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
|
| 122 |
-
files = results.get('files', [])
|
| 123 |
-
|
| 124 |
-
if files:
|
| 125 |
-
return files[0]['id']
|
| 126 |
-
|
| 127 |
-
# Create if not exists
|
| 128 |
-
folder_metadata = {
|
| 129 |
-
'name': folder_name,
|
| 130 |
-
'mimeType': 'application/vnd.google-apps.folder'
|
| 131 |
-
}
|
| 132 |
-
if parent_id:
|
| 133 |
-
folder_metadata['parents'] = [parent_id]
|
| 134 |
-
|
| 135 |
-
folder = self.drive_service.files().create(body=folder_metadata, fields='id').execute()
|
| 136 |
-
logger.info(f"[SparkAgent] Created folder: {folder_name} ({folder.get('id')})")
|
| 137 |
-
return folder.get('id')
|
| 138 |
-
except Exception as e:
|
| 139 |
-
logger.error(f"[SparkAgent] Folder error: {e}")
|
| 140 |
-
return None
|
| 141 |
-
|
| 142 |
-
async def upload_cv(self, file_content: bytes, file_name: str, employer_folder_id: str) -> Optional[str]:
|
| 143 |
-
"""Uploads a CV to a specific employer's folder."""
|
| 144 |
-
if not self.drive_service: return None
|
| 145 |
-
|
| 146 |
-
try:
|
| 147 |
-
file_metadata = {
|
| 148 |
-
'name': file_name,
|
| 149 |
-
'parents': [employer_folder_id]
|
| 150 |
-
}
|
| 151 |
-
media = MediaInMemoryUpload(file_content, resumable=True)
|
| 152 |
-
file = self.drive_service.files().create(body=file_metadata, media_body=media, fields='id, webViewLink').execute()
|
| 153 |
-
|
| 154 |
-
# Make readable by link
|
| 155 |
-
self.drive_service.permissions().create(
|
| 156 |
-
fileId=file.get('id'),
|
| 157 |
-
body={'type': 'anyone', 'role': 'reader'}
|
| 158 |
-
).execute()
|
| 159 |
-
|
| 160 |
-
return file.get('webViewLink')
|
| 161 |
-
except Exception as e:
|
| 162 |
-
logger.error(f"[SparkAgent] CV upload failed: {e}")
|
| 163 |
-
return None
|
| 164 |
-
|
| 165 |
-
async def generate_standardized_resume(self, talent_data: Dict[str, Any], doc_name: str) -> Optional[str]:
|
| 166 |
-
"""Generates a standardized Google Doc resume for a talent."""
|
| 167 |
-
if not self.docs_service or not self.drive_service: return None
|
| 168 |
-
|
| 169 |
-
try:
|
| 170 |
-
# 1. Create a blank doc
|
| 171 |
-
doc = self.docs_service.documents().create(body={'title': doc_name}).execute()
|
| 172 |
-
doc_id = doc.get('documentId')
|
| 173 |
-
|
| 174 |
-
# 2. Populate with data
|
| 175 |
-
requests = [
|
| 176 |
-
{
|
| 177 |
-
'insertText': {
|
| 178 |
-
'location': {'index': 1},
|
| 179 |
-
'text': f"{talent_data.get('name', 'Talent Name').upper()}\n"
|
| 180 |
-
f"Email: {talent_data.get('email', '-')}\n"
|
| 181 |
-
f"Location: {talent_data.get('location', '-')}\n\n"
|
| 182 |
-
f"EXPERIENCE\n{talent_data.get('experience', '-')}\n\n"
|
| 183 |
-
f"SKILLS\n{talent_data.get('skills', '-')}\n\n"
|
| 184 |
-
f"Generated by Brigawan AI — Green Talent Ecosystem\n"
|
| 185 |
-
}
|
| 186 |
-
},
|
| 187 |
-
{
|
| 188 |
-
'updateTextStyle': {
|
| 189 |
-
'range': {'startIndex': 1, 'endIndex': len(talent_data.get('name', '')) + 1},
|
| 190 |
-
'textStyle': {'bold': True, 'fontSize': {'magnitude': 18, 'unit': 'PT'}},
|
| 191 |
-
'fields': 'bold,fontSize'
|
| 192 |
-
}
|
| 193 |
-
}
|
| 194 |
-
]
|
| 195 |
-
self.docs_service.documents().batchUpdate(documentId=doc_id, body={'requests': requests}).execute()
|
| 196 |
-
|
| 197 |
-
# 3. Share and return link
|
| 198 |
-
file = self.drive_service.files().get(fileId=doc_id, fields='webViewLink').execute()
|
| 199 |
-
self.drive_service.permissions().create(
|
| 200 |
-
fileId=doc_id,
|
| 201 |
-
body={'type': 'anyone', 'role': 'reader'}
|
| 202 |
-
).execute()
|
| 203 |
-
|
| 204 |
-
return file.get('webViewLink')
|
| 205 |
-
except Exception as e:
|
| 206 |
-
logger.error(f"[SparkAgent] Resume generation failed: {e}")
|
| 207 |
-
return None
|
| 208 |
-
|
| 209 |
-
# Singleton instance
|
| 210 |
-
spark_agent = GoogleWorkspaceService()
|
|
|
|
| 1 |
+
"""Google Workspace Service — Automated Document Management (The Spark Agent).
|
| 2 |
+
|
| 3 |
+
Handles Google Drive folder orchestration, CV storage, and automated
|
| 4 |
+
Google Docs resume generation.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
from typing import Dict, Any, Optional, List
|
| 10 |
+
from loguru import logger
|
| 11 |
+
from google.oauth2 import service_account
|
| 12 |
+
from googleapiclient.discovery import build
|
| 13 |
+
from googleapiclient.http import MediaInMemoryUpload
|
| 14 |
+
|
| 15 |
+
from app.config import settings
|
| 16 |
+
|
| 17 |
+
class GoogleWorkspaceService:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.scopes = [
|
| 20 |
+
'https://www.googleapis.com/auth/drive',
|
| 21 |
+
'https://www.googleapis.com/auth/documents',
|
| 22 |
+
'https://www.googleapis.com/auth/calendar',
|
| 23 |
+
'https://www.googleapis.com/auth/spreadsheets'
|
| 24 |
+
]
|
| 25 |
+
self.creds = self._load_credentials()
|
| 26 |
+
self.drive_service = build('drive', 'v3', credentials=self.creds) if self.creds else None
|
| 27 |
+
self.docs_service = build('docs', 'v1', credentials=self.creds) if self.creds else None
|
| 28 |
+
self.calendar_service = build('calendar', 'v3', credentials=self.creds) if self.creds else None
|
| 29 |
+
self.sheets_service = build('sheets', 'v4', credentials=self.creds) if self.creds else None
|
| 30 |
+
|
| 31 |
+
async def append_row_to_sheet(self, spreadsheet_id: str, range_name: str, row_values: List[Any]) -> bool:
|
| 32 |
+
"""Appends a row of values to a specified Google Sheet using the Sheets API."""
|
| 33 |
+
if not self.sheets_service:
|
| 34 |
+
logger.warning("[SparkAgent] Sheets service not initialized.")
|
| 35 |
+
return False
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
body = {
|
| 39 |
+
'values': [row_values]
|
| 40 |
+
}
|
| 41 |
+
import asyncio
|
| 42 |
+
def run_append():
|
| 43 |
+
return self.sheets_service.spreadsheets().values().append(
|
| 44 |
+
spreadsheetId=spreadsheet_id,
|
| 45 |
+
range=range_name,
|
| 46 |
+
valueInputOption="USER_ENTERED",
|
| 47 |
+
insertDataOption="INSERT_ROWS",
|
| 48 |
+
body=body
|
| 49 |
+
).execute()
|
| 50 |
+
|
| 51 |
+
await asyncio.to_thread(run_append)
|
| 52 |
+
logger.info(f"[SparkAgent] Appended row to sheet {range_name} in spreadsheet {spreadsheet_id}")
|
| 53 |
+
return True
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.error(f"[SparkAgent] Failed to append row to sheet {range_name}: {e}")
|
| 56 |
+
return False
|
| 57 |
+
|
| 58 |
+
async def get_founder_availability(self, start_time: str, end_time: str) -> List[Dict[str, Any]]:
|
| 59 |
+
"""Checks founder's Google Calendar for busy slots."""
|
| 60 |
+
if not self.calendar_service: return []
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
body = {
|
| 64 |
+
"timeMin": start_time,
|
| 65 |
+
"timeMax": end_time,
|
| 66 |
+
"items": [{"id": "primary"}]
|
| 67 |
+
}
|
| 68 |
+
res = self.calendar_service.freebusy().query(body=body).execute()
|
| 69 |
+
return res.get('calendars', {}).get('primary', {}).get('busy', [])
|
| 70 |
+
except Exception as e:
|
| 71 |
+
logger.error(f"[SparkAgent] Calendar check failed: {e}")
|
| 72 |
+
return []
|
| 73 |
+
|
| 74 |
+
async def schedule_ceo_meeting(self, summary: str, start_iso: str, end_iso: str, attendee_email: str) -> Optional[str]:
|
| 75 |
+
"""Schedules a meeting on the founder's calendar."""
|
| 76 |
+
if not self.calendar_service: return None
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
event = {
|
| 80 |
+
'summary': summary,
|
| 81 |
+
'description': 'Scheduled by Brigawan AI CEO',
|
| 82 |
+
'start': {'dateTime': start_iso, 'timeZone': 'Asia/Jakarta'},
|
| 83 |
+
'end': {'dateTime': end_iso, 'timeZone': 'Asia/Jakarta'},
|
| 84 |
+
'attendees': [{'email': attendee_email}],
|
| 85 |
+
'conferenceData': {'createRequest': {'requestId': str(uuid.uuid4()), 'conferenceSolutionKey': {'type': 'hangoutsMeet'}}}
|
| 86 |
+
}
|
| 87 |
+
event = self.calendar_service.events().insert(
|
| 88 |
+
calendarId='primary', body=event, conferenceDataVersion=1
|
| 89 |
+
).execute()
|
| 90 |
+
return event.get('htmlLink')
|
| 91 |
+
except Exception as e:
|
| 92 |
+
logger.error(f"[SparkAgent] Meeting scheduling failed: {e}")
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
+
def _load_credentials(self):
|
| 96 |
+
"""Loads Service Account credentials from settings."""
|
| 97 |
+
# Use getattr for safety on Hugging Face environments
|
| 98 |
+
json_creds = getattr(settings, "google_service_account_json", None)
|
| 99 |
+
|
| 100 |
+
if not json_creds:
|
| 101 |
+
logger.warning("[SparkAgent] Google Service Account JSON not configured.")
|
| 102 |
+
return None
|
| 103 |
+
try:
|
| 104 |
+
creds_info = json.loads(json_creds)
|
| 105 |
+
return service_account.Credentials.from_service_account_info(
|
| 106 |
+
creds_info, scopes=self.scopes
|
| 107 |
+
)
|
| 108 |
+
except Exception as e:
|
| 109 |
+
logger.error(f"[SparkAgent] Failed to load credentials: {e}")
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
async def get_or_create_folder(self, folder_name: str, parent_id: Optional[str] = None) -> Optional[str]:
|
| 113 |
+
"""Finds or creates a folder in Google Drive."""
|
| 114 |
+
if not self.drive_service: return None
|
| 115 |
+
|
| 116 |
+
query = f"name = '{folder_name}' and mimeType = 'application/vnd.google-apps.folder' and trashed = false"
|
| 117 |
+
if parent_id:
|
| 118 |
+
query += f" and '{parent_id}' in parents"
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
results = self.drive_service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
|
| 122 |
+
files = results.get('files', [])
|
| 123 |
+
|
| 124 |
+
if files:
|
| 125 |
+
return files[0]['id']
|
| 126 |
+
|
| 127 |
+
# Create if not exists
|
| 128 |
+
folder_metadata = {
|
| 129 |
+
'name': folder_name,
|
| 130 |
+
'mimeType': 'application/vnd.google-apps.folder'
|
| 131 |
+
}
|
| 132 |
+
if parent_id:
|
| 133 |
+
folder_metadata['parents'] = [parent_id]
|
| 134 |
+
|
| 135 |
+
folder = self.drive_service.files().create(body=folder_metadata, fields='id').execute()
|
| 136 |
+
logger.info(f"[SparkAgent] Created folder: {folder_name} ({folder.get('id')})")
|
| 137 |
+
return folder.get('id')
|
| 138 |
+
except Exception as e:
|
| 139 |
+
logger.error(f"[SparkAgent] Folder error: {e}")
|
| 140 |
+
return None
|
| 141 |
+
|
| 142 |
+
async def upload_cv(self, file_content: bytes, file_name: str, employer_folder_id: str) -> Optional[str]:
|
| 143 |
+
"""Uploads a CV to a specific employer's folder."""
|
| 144 |
+
if not self.drive_service: return None
|
| 145 |
+
|
| 146 |
+
try:
|
| 147 |
+
file_metadata = {
|
| 148 |
+
'name': file_name,
|
| 149 |
+
'parents': [employer_folder_id]
|
| 150 |
+
}
|
| 151 |
+
media = MediaInMemoryUpload(file_content, resumable=True)
|
| 152 |
+
file = self.drive_service.files().create(body=file_metadata, media_body=media, fields='id, webViewLink').execute()
|
| 153 |
+
|
| 154 |
+
# Make readable by link
|
| 155 |
+
self.drive_service.permissions().create(
|
| 156 |
+
fileId=file.get('id'),
|
| 157 |
+
body={'type': 'anyone', 'role': 'reader'}
|
| 158 |
+
).execute()
|
| 159 |
+
|
| 160 |
+
return file.get('webViewLink')
|
| 161 |
+
except Exception as e:
|
| 162 |
+
logger.error(f"[SparkAgent] CV upload failed: {e}")
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
async def generate_standardized_resume(self, talent_data: Dict[str, Any], doc_name: str) -> Optional[str]:
|
| 166 |
+
"""Generates a standardized Google Doc resume for a talent."""
|
| 167 |
+
if not self.docs_service or not self.drive_service: return None
|
| 168 |
+
|
| 169 |
+
try:
|
| 170 |
+
# 1. Create a blank doc
|
| 171 |
+
doc = self.docs_service.documents().create(body={'title': doc_name}).execute()
|
| 172 |
+
doc_id = doc.get('documentId')
|
| 173 |
+
|
| 174 |
+
# 2. Populate with data
|
| 175 |
+
requests = [
|
| 176 |
+
{
|
| 177 |
+
'insertText': {
|
| 178 |
+
'location': {'index': 1},
|
| 179 |
+
'text': f"{talent_data.get('name', 'Talent Name').upper()}\n"
|
| 180 |
+
f"Email: {talent_data.get('email', '-')}\n"
|
| 181 |
+
f"Location: {talent_data.get('location', '-')}\n\n"
|
| 182 |
+
f"EXPERIENCE\n{talent_data.get('experience', '-')}\n\n"
|
| 183 |
+
f"SKILLS\n{talent_data.get('skills', '-')}\n\n"
|
| 184 |
+
f"Generated by Brigawan AI — Green Talent Ecosystem\n"
|
| 185 |
+
}
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
'updateTextStyle': {
|
| 189 |
+
'range': {'startIndex': 1, 'endIndex': len(talent_data.get('name', '')) + 1},
|
| 190 |
+
'textStyle': {'bold': True, 'fontSize': {'magnitude': 18, 'unit': 'PT'}},
|
| 191 |
+
'fields': 'bold,fontSize'
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
]
|
| 195 |
+
self.docs_service.documents().batchUpdate(documentId=doc_id, body={'requests': requests}).execute()
|
| 196 |
+
|
| 197 |
+
# 3. Share and return link
|
| 198 |
+
file = self.drive_service.files().get(fileId=doc_id, fields='webViewLink').execute()
|
| 199 |
+
self.drive_service.permissions().create(
|
| 200 |
+
fileId=doc_id,
|
| 201 |
+
body={'type': 'anyone', 'role': 'reader'}
|
| 202 |
+
).execute()
|
| 203 |
+
|
| 204 |
+
return file.get('webViewLink')
|
| 205 |
+
except Exception as e:
|
| 206 |
+
logger.error(f"[SparkAgent] Resume generation failed: {e}")
|
| 207 |
+
return None
|
| 208 |
+
|
| 209 |
+
# Singleton instance
|
| 210 |
+
spark_agent = GoogleWorkspaceService()
|
app/services/interview_service.py
CHANGED
|
@@ -1,558 +1,558 @@
|
|
| 1 |
-
"""Interview & AI Notulen Service — Schedule, Transcript, AI Summary, Comparison.
|
| 2 |
-
|
| 3 |
-
Business Model:
|
| 4 |
-
- Schedule interview: costs 5 coins (deducted from Company CreditBalance)
|
| 5 |
-
- Enterprise tier: free AI interview scheduling
|
| 6 |
-
- AI Notulen: automated meeting summaries via Gemini MEDIUM tier
|
| 7 |
-
- Competency analysis + multi-candidate comparison via Gemini HIGH tier
|
| 8 |
-
|
| 9 |
-
All operations crash-proof: never throw, always return structured response.
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
import json
|
| 13 |
-
import secrets
|
| 14 |
-
import uuid
|
| 15 |
-
from datetime import datetime, timezone
|
| 16 |
-
from typing import Any, Dict, List, Optional
|
| 17 |
-
|
| 18 |
-
from loguru import logger
|
| 19 |
-
from sqlalchemy import func, select
|
| 20 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 21 |
-
|
| 22 |
-
from app.models.finance import Interview
|
| 23 |
-
from app.models.talent import Talent
|
| 24 |
-
from app.models.employer import ClientAccount, Company
|
| 25 |
-
from app.models.finance import Transaction
|
| 26 |
-
from app.services.ai_service import call_medium, call_high
|
| 27 |
-
from app.config.settings import settings, FINANCE_CONFIG
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
INTERVIEW_COST = 5 # Coins per interview (Enterprise = free)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# =============================================================================
|
| 34 |
-
# HELPERS
|
| 35 |
-
# =============================================================================
|
| 36 |
-
|
| 37 |
-
async def _get_talent_by_id(db: AsyncSession, talent_id: str) -> Optional[Talent]:
|
| 38 |
-
result = await db.execute(select(Talent).where(Talent.talent_id == talent_id))
|
| 39 |
-
return result.scalar_one_or_none()
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
async def _get_client_and_company(db: AsyncSession, email: str) -> tuple:
|
| 43 |
-
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 44 |
-
client = result.scalar_one_or_none()
|
| 45 |
-
if not client:
|
| 46 |
-
return None, None
|
| 47 |
-
result = await db.execute(select(Company).where(Company.id == client.company_id))
|
| 48 |
-
company = result.scalar_one_or_none()
|
| 49 |
-
return client, company
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
async def _get_interview(db: AsyncSession, interview_id: str) -> Optional[Interview]:
|
| 53 |
-
try:
|
| 54 |
-
uid = uuid.UUID(interview_id)
|
| 55 |
-
result = await db.execute(
|
| 56 |
-
select(Interview).where(Interview.id == uid)
|
| 57 |
-
)
|
| 58 |
-
return result.scalar_one_or_none()
|
| 59 |
-
except Exception:
|
| 60 |
-
return None
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def _tier_is_enterprise(tier: str) -> bool:
|
| 64 |
-
return tier and tier.lower() == "enterprise"
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
# =============================================================================
|
| 68 |
-
# 1. SCHEDULE INTERVIEW
|
| 69 |
-
# =============================================================================
|
| 70 |
-
|
| 71 |
-
async def schedule_interview(
|
| 72 |
-
db: AsyncSession,
|
| 73 |
-
recruiter_email: str,
|
| 74 |
-
candidate_id: str,
|
| 75 |
-
scheduled_time: str,
|
| 76 |
-
) -> dict:
|
| 77 |
-
"""Schedule an interview with a candidate.
|
| 78 |
-
|
| 79 |
-
Business rules:
|
| 80 |
-
1. Verify talent exists
|
| 81 |
-
2. Verify employer has enough coins (unless Enterprise tier)
|
| 82 |
-
3. Deduct 5 coins (free for Enterprise)
|
| 83 |
-
4. Create Interview record
|
| 84 |
-
|
| 85 |
-
Returns structured response with interview_id and credit info.
|
| 86 |
-
"""
|
| 87 |
-
try:
|
| 88 |
-
# Verify talent
|
| 89 |
-
talent = await _get_talent_by_id(db, candidate_id)
|
| 90 |
-
if not talent:
|
| 91 |
-
return {"success": False, "error": f"Talent {candidate_id} tidak ditemukan."}
|
| 92 |
-
|
| 93 |
-
# Verify employer & company
|
| 94 |
-
client, company = await _get_client_and_company(db, recruiter_email)
|
| 95 |
-
if not client or not company:
|
| 96 |
-
return {"success": False, "error": "Akun employer tidak ditemukan."}
|
| 97 |
-
|
| 98 |
-
credits_deducted = 0
|
| 99 |
-
|
| 100 |
-
# Check if Enterprise — free scheduling
|
| 101 |
-
if not _tier_is_enterprise(company.tier or ""):
|
| 102 |
-
if (company.credit_balance or 0) < INTERVIEW_COST:
|
| 103 |
-
return {
|
| 104 |
-
"success": False,
|
| 105 |
-
"error": f"Koin tidak mencukupi. Interview membutuhkan {INTERVIEW_COST} koin. "
|
| 106 |
-
f"Saldo: {company.credit_balance or 0}. "
|
| 107 |
-
f"Upgrade ke Enterprise untuk interview gratis tanpa batas.",
|
| 108 |
-
}
|
| 109 |
-
# Deduct coins
|
| 110 |
-
company.credit_balance = (company.credit_balance or 0) - INTERVIEW_COST
|
| 111 |
-
credits_deducted = INTERVIEW_COST
|
| 112 |
-
db.add(company)
|
| 113 |
-
|
| 114 |
-
# Log transaction
|
| 115 |
-
tx = Transaction(
|
| 116 |
-
id=f"TX-IVW-{secrets.token_hex(4).upper()}",
|
| 117 |
-
client_id=client.id,
|
| 118 |
-
amount=INTERVIEW_COST,
|
| 119 |
-
type="Interview",
|
| 120 |
-
status="Settled",
|
| 121 |
-
)
|
| 122 |
-
db.add(tx)
|
| 123 |
-
|
| 124 |
-
# Parse scheduled time
|
| 125 |
-
try:
|
| 126 |
-
sched_dt = datetime.fromisoformat(scheduled_time.replace("Z", "+00:00"))
|
| 127 |
-
except Exception:
|
| 128 |
-
sched_dt = datetime.now(timezone.utc)
|
| 129 |
-
|
| 130 |
-
# Create interview record
|
| 131 |
-
interview = Interview(
|
| 132 |
-
id=uuid.uuid4(),
|
| 133 |
-
company_id=company.id,
|
| 134 |
-
client_id=client.id,
|
| 135 |
-
candidate_id=candidate_id,
|
| 136 |
-
scheduled_time=sched_dt,
|
| 137 |
-
status="Scheduled",
|
| 138 |
-
)
|
| 139 |
-
db.add(interview)
|
| 140 |
-
await db.commit()
|
| 141 |
-
|
| 142 |
-
logger.info(f"Interview scheduled: {interview.id} ({recruiter_email} -> {candidate_id})")
|
| 143 |
-
|
| 144 |
-
return {
|
| 145 |
-
"success": True,
|
| 146 |
-
"interview_id": str(interview.id),
|
| 147 |
-
"candidate_name": talent.name or "Talent",
|
| 148 |
-
"candidate_id": candidate_id,
|
| 149 |
-
"scheduled_time": sched_dt.isoformat(),
|
| 150 |
-
"credits_deducted": credits_deducted,
|
| 151 |
-
"credits_remaining": company.credit_balance or 0,
|
| 152 |
-
"message": f"Interview berhasil dijadwalkan dengan {talent.name or 'Talent'}."
|
| 153 |
-
+ (f" ({INTERVIEW_COST} koin digunakan)" if credits_deducted > 0
|
| 154 |
-
else " (Gratis — Enterprise tier)"),
|
| 155 |
-
}
|
| 156 |
-
|
| 157 |
-
except Exception as e:
|
| 158 |
-
logger.error(f"schedule_interview error: {e}")
|
| 159 |
-
await db.rollback()
|
| 160 |
-
return {"success": False, "error": f"Gagal menjadwalkan interview: {str(e)}"}
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
# =============================================================================
|
| 164 |
-
# 2. SAVE TRANSCRIPT
|
| 165 |
-
# =============================================================================
|
| 166 |
-
|
| 167 |
-
async def save_transcript(
|
| 168 |
-
db: AsyncSession,
|
| 169 |
-
interview_id: str,
|
| 170 |
-
transcript_text: str,
|
| 171 |
-
) -> dict:
|
| 172 |
-
"""Save interview transcript after the interview is completed."""
|
| 173 |
-
try:
|
| 174 |
-
interview = await _get_interview(db, interview_id)
|
| 175 |
-
if not interview:
|
| 176 |
-
return {"success": False, "error": "Interview tidak ditemukan."}
|
| 177 |
-
|
| 178 |
-
interview.transcript_text = transcript_text
|
| 179 |
-
interview.status = "Completed"
|
| 180 |
-
db.add(interview)
|
| 181 |
-
await db.commit()
|
| 182 |
-
|
| 183 |
-
logger.info(f"Transcript saved: {interview_id}")
|
| 184 |
-
|
| 185 |
-
return {
|
| 186 |
-
"success": True,
|
| 187 |
-
"interview_id": interview_id,
|
| 188 |
-
"message": "Transkrip interview berhasil disimpan.",
|
| 189 |
-
}
|
| 190 |
-
|
| 191 |
-
except Exception as e:
|
| 192 |
-
logger.error(f"save_transcript error: {e}")
|
| 193 |
-
await db.rollback()
|
| 194 |
-
return {"success": False, "error": f"Gagal menyimpan transkrip: {str(e)}"}
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
# =============================================================================
|
| 198 |
-
# 3. AI NOTULEN (Meeting Summary)
|
| 199 |
-
# =============================================================================
|
| 200 |
-
|
| 201 |
-
async def generate_ai_notulen(
|
| 202 |
-
db: AsyncSession,
|
| 203 |
-
interview_id: str,
|
| 204 |
-
) -> dict:
|
| 205 |
-
"""Generate AI meeting summary (Notulen) from interview transcript.
|
| 206 |
-
|
| 207 |
-
Uses Gemini MEDIUM tier (3.5 Flash) for summarization.
|
| 208 |
-
Falls back to algorithmic extraction if AI unavailable.
|
| 209 |
-
"""
|
| 210 |
-
try:
|
| 211 |
-
interview = await _get_interview(db, interview_id)
|
| 212 |
-
if not interview:
|
| 213 |
-
return {"success": False, "error": "Interview tidak ditemukan."}
|
| 214 |
-
|
| 215 |
-
if not interview.transcript_text:
|
| 216 |
-
return {"success": False, "error": "Transkrip interview belum tersedia. Simpan transkrip terlebih dahulu."}
|
| 217 |
-
|
| 218 |
-
transcript = interview.transcript_text[:8000]
|
| 219 |
-
|
| 220 |
-
# Get candidate info for context
|
| 221 |
-
talent = await _get_talent_by_id(db, interview.candidate_id)
|
| 222 |
-
candidate_name = talent.name if talent else "Kandidat"
|
| 223 |
-
|
| 224 |
-
# AI Notulen via MEDIUM tier
|
| 225 |
-
ai_used = False
|
| 226 |
-
summary = None
|
| 227 |
-
try:
|
| 228 |
-
prompt = (
|
| 229 |
-
f"Anda adalah AI Notulen Brigawan, asisten yang membuat notulen rapat interview yang profesional dan terstruktur.\\n\\n"
|
| 230 |
-
f"Buat notulen interview untuk kandidat: {candidate_name}\\n\\n"
|
| 231 |
-
f"Berikut adalah transkrip interview:\\n{transcript}\\n\\n"
|
| 232 |
-
f"Buat notulen dengan format berikut (dalam Bahasa Indonesia):\\n"
|
| 233 |
-
f"1. RINGKASAN EKSEKUTIF: 2-3 kalimat\\n"
|
| 234 |
-
f"2. PERTANYAAN & JAWABAN: Poin-poin penting\\n"
|
| 235 |
-
f"3. KESAN KANDIDAT: Kesan umum, komunikasi, dan sikap\\n"
|
| 236 |
-
f"4. KECOCOKAN: Analisis kecocokan\\n"
|
| 237 |
-
f"5. REKOMENDASI: Langkah selanjutnya"
|
| 238 |
-
)
|
| 239 |
-
result = await call_medium(prompt=prompt, temperature=0.5, max_output_tokens=2048)
|
| 240 |
-
if result:
|
| 241 |
-
summary = result.strip()
|
| 242 |
-
ai_used = True
|
| 243 |
-
except Exception as e:
|
| 244 |
-
logger.error(f"AI Notulen generation error: {e}")
|
| 245 |
-
|
| 246 |
-
# Algorithmic fallback
|
| 247 |
-
if not summary:
|
| 248 |
-
summary = (
|
| 249 |
-
f"=== NOTULEN INTERVIEW ({candidate_name}) ===\\n\\n"
|
| 250 |
-
f"RINGKASAN EKSEKUTIF:\\n"
|
| 251 |
-
f"Interview dengan {candidate_name} telah dilaksanakan.\\n\\n"
|
| 252 |
-
f"*Notulen AI tidak tersedia - menggunakan ringkasan otomatis.*"
|
| 253 |
-
)
|
| 254 |
-
|
| 255 |
-
# Save to interview record
|
| 256 |
-
interview.ai_summary = summary
|
| 257 |
-
db.add(interview)
|
| 258 |
-
await db.commit()
|
| 259 |
-
|
| 260 |
-
return {
|
| 261 |
-
"success": True,
|
| 262 |
-
"interview_id": interview_id,
|
| 263 |
-
"summary": summary,
|
| 264 |
-
"ai_used": ai_used,
|
| 265 |
-
}
|
| 266 |
-
|
| 267 |
-
except Exception as e:
|
| 268 |
-
logger.error(f"generate_ai_notulen error: {e}")
|
| 269 |
-
await db.rollback()
|
| 270 |
-
return {"success": False, "error": f"Gagal membuat notulen: {str(e)}"}
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
# =============================================================================
|
| 274 |
-
# 4. COMPETENCY ANALYSIS
|
| 275 |
-
# =============================================================================
|
| 276 |
-
|
| 277 |
-
async def analyze_competency(
|
| 278 |
-
db: AsyncSession,
|
| 279 |
-
interview_id: str,
|
| 280 |
-
) -> dict:
|
| 281 |
-
"""Analyze candidate competency from interview transcript.
|
| 282 |
-
|
| 283 |
-
Uses Gemini MEDIUM tier for structured competency scoring.
|
| 284 |
-
Returns scores across multiple competency dimensions.
|
| 285 |
-
"""
|
| 286 |
-
try:
|
| 287 |
-
interview = await _get_interview(db, interview_id)
|
| 288 |
-
if not interview:
|
| 289 |
-
return {"success": False, "error": "Interview tidak ditemukan."}
|
| 290 |
-
|
| 291 |
-
if not interview.transcript_text:
|
| 292 |
-
return {"success": False, "error": "Transkrip interview belum tersedia."}
|
| 293 |
-
|
| 294 |
-
transcript = interview.transcript_text[:8000]
|
| 295 |
-
talent = await _get_talent_by_id(db, interview.candidate_id)
|
| 296 |
-
candidate_name = talent.name if talent else "Kandidat"
|
| 297 |
-
|
| 298 |
-
# AI competency analysis via MEDIUM tier
|
| 299 |
-
ai_used = False
|
| 300 |
-
analysis = None
|
| 301 |
-
try:
|
| 302 |
-
prompt = (
|
| 303 |
-
f"Anda adalah AI Assessment Brigawan, spesialis evaluasi kompetensi kandidat.\\n\\n"
|
| 304 |
-
f"Evaluasi kandidat berikut berdasarkan transkrip interview:\\n"
|
| 305 |
-
f"Nama Kandidat: {candidate_name}\\n\\n"
|
| 306 |
-
f"Transkrip Interview:\\n{transcript}\\n\\n"
|
| 307 |
-
f"Berikan analisis dalam format JSON SAJA (tanpa markdown):\\n"
|
| 308 |
-
'{\"overall_score\": 0-100, \"competencies\": [{\"name\": \"Pengetahuan Teknis\", \"score\": 0-100, \"notes\": \"...\"}], \"strengths\": \"...\", \"weaknesses\": \"...\", \"recommendation\": \"...\"}'
|
| 309 |
-
)
|
| 310 |
-
result = await call_medium(prompt=prompt, temperature=0.4, max_output_tokens=2048)
|
| 311 |
-
if result:
|
| 312 |
-
cleaned = result.strip()
|
| 313 |
-
if cleaned.startswith("```json"):
|
| 314 |
-
cleaned = cleaned[7:]
|
| 315 |
-
if cleaned.startswith("```"):
|
| 316 |
-
cleaned = cleaned[3:]
|
| 317 |
-
if cleaned.endswith("```"):
|
| 318 |
-
cleaned = cleaned[:-3]
|
| 319 |
-
cleaned = cleaned.strip()
|
| 320 |
-
analysis = json.loads(cleaned)
|
| 321 |
-
ai_used = True
|
| 322 |
-
except Exception as e:
|
| 323 |
-
logger.error(f"Competency analysis AI error: {e}")
|
| 324 |
-
|
| 325 |
-
if not analysis:
|
| 326 |
-
# Algorithmic fallback
|
| 327 |
-
word_count = len(transcript.split())
|
| 328 |
-
score = min(70 + (word_count // 50), 90)
|
| 329 |
-
analysis = {
|
| 330 |
-
"overall_score": score,
|
| 331 |
-
"competencies": [
|
| 332 |
-
{"name": "Pengetahuan Teknis", "score": score - 5, "notes": "Dinilai dari transkrip (fallback)"},
|
| 333 |
-
{"name": "Komunikasi", "score": score, "notes": "Dinilai dari transkrip (fallback)"},
|
| 334 |
-
{"name": "Pemecahan Masalah", "score": score - 10, "notes": "Dinilai dari transkrip (fallback)"},
|
| 335 |
-
{"name": "Pengalaman Relevan", "score": score - 5, "notes": "Dinilai dari transkrip (fallback)"},
|
| 336 |
-
{"name": "Sikap dan Motivasi", "score": score, "notes": "Dinilai dari transkrip (fallback)"},
|
| 337 |
-
],
|
| 338 |
-
"strengths": "Analisis AI tidak tersedia. Gunakan penilaian manual.",
|
| 339 |
-
"weaknesses": "Analisis AI tidak tersedia. Gunakan penilaian manual.",
|
| 340 |
-
"recommendation": "Lanjut ke tahap berikutnya berdasarkan penilaian manual.",
|
| 341 |
-
}
|
| 342 |
-
|
| 343 |
-
# Save competency score to interview record
|
| 344 |
-
interview.ai_competency_score = analysis.get("overall_score", 0)
|
| 345 |
-
interview.ai_performance_analysis = json.dumps(analysis)
|
| 346 |
-
db.add(interview)
|
| 347 |
-
await db.commit()
|
| 348 |
-
|
| 349 |
-
return {
|
| 350 |
-
"success": True,
|
| 351 |
-
"interview_id": interview_id,
|
| 352 |
-
"overall_score": analysis.get("overall_score", 0),
|
| 353 |
-
"competencies": analysis.get("competencies", []),
|
| 354 |
-
"strengths": analysis.get("strengths", ""),
|
| 355 |
-
"weaknesses": analysis.get("weaknesses", ""),
|
| 356 |
-
"recommendation": analysis.get("recommendation", ""),
|
| 357 |
-
"ai_used": ai_used,
|
| 358 |
-
}
|
| 359 |
-
|
| 360 |
-
except Exception as e:
|
| 361 |
-
logger.error(f"analyze_competency error: {e}")
|
| 362 |
-
return {"success": False, "error": f"Gagal menganalisis kompetensi: {str(e)}"}
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
# =============================================================================
|
| 366 |
-
# 5. MULTI-CANDIDATE COMPARISON
|
| 367 |
-
# =============================================================================
|
| 368 |
-
|
| 369 |
-
async def compare_candidates(
|
| 370 |
-
db: AsyncSession,
|
| 371 |
-
interview_ids: List[str],
|
| 372 |
-
) -> dict:
|
| 373 |
-
"""Compare multiple candidates from their interviews.
|
| 374 |
-
|
| 375 |
-
Uses Gemini HIGH tier (3.1 Pro) for intelligent comparison.
|
| 376 |
-
Generates a comparison matrix with recommendations.
|
| 377 |
-
Max 10 candidates per comparison.
|
| 378 |
-
"""
|
| 379 |
-
try:
|
| 380 |
-
if len(interview_ids) < 2:
|
| 381 |
-
return {"success": False, "error": "Minimal 2 kandidat untuk perbandingan."}
|
| 382 |
-
if len(interview_ids) > 10:
|
| 383 |
-
interview_ids = interview_ids[:10]
|
| 384 |
-
|
| 385 |
-
# Fetch all interviews and their data
|
| 386 |
-
candidates_data = []
|
| 387 |
-
for iid in interview_ids:
|
| 388 |
-
interview = await _get_interview(db, iid)
|
| 389 |
-
if not interview:
|
| 390 |
-
continue
|
| 391 |
-
talent = await _get_talent_by_id(db, interview.candidate_id)
|
| 392 |
-
candidates_data.append({
|
| 393 |
-
"interview_id": iid,
|
| 394 |
-
"candidate_id": interview.candidate_id,
|
| 395 |
-
"candidate_name": talent.name if talent else interview.candidate_id,
|
| 396 |
-
"score": interview.ai_competency_score or 0,
|
| 397 |
-
"summary": interview.ai_summary or "",
|
| 398 |
-
"transcript": (interview.transcript_text or "")[:2000],
|
| 399 |
-
"analysis": interview.ai_performance_analysis or "",
|
| 400 |
-
})
|
| 401 |
-
|
| 402 |
-
if len(candidates_data) < 2:
|
| 403 |
-
return {"success": False, "error": "Tidak cukup data interview untuk perbandingan."}
|
| 404 |
-
|
| 405 |
-
# AI comparison via HIGH tier
|
| 406 |
-
ai_used = False
|
| 407 |
-
comparison_result = None
|
| 408 |
-
try:
|
| 409 |
-
candidates_text = ""
|
| 410 |
-
for c in candidates_data:
|
| 411 |
-
candidates_text += (
|
| 412 |
-
f"--- Kandidat: {c['candidate_name']} (ID: {c['candidate_id']}) ---\\n"
|
| 413 |
-
f"Skor Kompetensi: {c['score']}/100\\n"
|
| 414 |
-
f"Ringkasan: {c['summary'][:500]}\\n\\n"
|
| 415 |
-
)
|
| 416 |
-
|
| 417 |
-
prompt = (
|
| 418 |
-
f"Anda adalah AI Recruiter Brigawan, spesialis perbandingan kandidat.\\n\\n"
|
| 419 |
-
f"Bandingkan kandidat-kandidat berikut:\\n{candidates_text}\\n"
|
| 420 |
-
f"Buat analisis JSON: candidates[] dengan overall_score 0-100, competency_scores, strengths, weaknesses. Serta recommendation dan matrix_summary."
|
| 421 |
-
)
|
| 422 |
-
result = await call_high(prompt=prompt, temperature=0.3, max_output_tokens=3072)
|
| 423 |
-
if result:
|
| 424 |
-
cleaned = result.strip()
|
| 425 |
-
if cleaned.startswith("```json"):
|
| 426 |
-
cleaned = cleaned[7:]
|
| 427 |
-
if cleaned.startswith("```"):
|
| 428 |
-
cleaned = cleaned[3:]
|
| 429 |
-
if cleaned.endswith("```"):
|
| 430 |
-
cleaned = cleaned[:-3]
|
| 431 |
-
cleaned = cleaned.strip()
|
| 432 |
-
comparison_result = json.loads(cleaned)
|
| 433 |
-
ai_used = True
|
| 434 |
-
except Exception as e:
|
| 435 |
-
logger.error(f"Candidate comparison AI error: {e}")
|
| 436 |
-
|
| 437 |
-
if not comparison_result:
|
| 438 |
-
# Algorithmic fallback: sort by score
|
| 439 |
-
candidates_data.sort(key=lambda c: c["score"], reverse=True)
|
| 440 |
-
comparison_result = {
|
| 441 |
-
"candidates": [
|
| 442 |
-
{
|
| 443 |
-
"candidate_id": c["candidate_id"],
|
| 444 |
-
"candidate_name": c["candidate_name"],
|
| 445 |
-
"overall_score": c["score"],
|
| 446 |
-
"competency_scores": {"Umum": c["score"]},
|
| 447 |
-
"strengths": "Data terbatas",
|
| 448 |
-
"weaknesses": "Data terbatas",
|
| 449 |
-
}
|
| 450 |
-
for c in candidates_data
|
| 451 |
-
],
|
| 452 |
-
"recommendation": f"Kandidat terbaik: {candidates_data[0]['candidate_name']} (skor {candidates_data[0]['score']}). Verifikasi manual diperlukan.",
|
| 453 |
-
"matrix_summary": f"Perbandingan {len(candidates_data)} kandidat berdasarkan skor kompetensi.",
|
| 454 |
-
}
|
| 455 |
-
|
| 456 |
-
return {
|
| 457 |
-
"success": True,
|
| 458 |
-
"candidates": comparison_result.get("candidates", []),
|
| 459 |
-
"recommendation": comparison_result.get("recommendation", ""),
|
| 460 |
-
"matrix_summary": comparison_result.get("matrix_summary", ""),
|
| 461 |
-
"ai_used": ai_used,
|
| 462 |
-
}
|
| 463 |
-
|
| 464 |
-
except Exception as e:
|
| 465 |
-
logger.error(f"compare_candidates error: {e}")
|
| 466 |
-
return {"success": False, "error": f"Gagal membandingkan kandidat: {str(e)}"}
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
# =============================================================================
|
| 470 |
-
# 6. LIST & DETAIL INTERVIEWS
|
| 471 |
-
# =============================================================================
|
| 472 |
-
|
| 473 |
-
async def list_interviews(
|
| 474 |
-
db: AsyncSession,
|
| 475 |
-
email: str,
|
| 476 |
-
status: Optional[str] = None,
|
| 477 |
-
) -> dict:
|
| 478 |
-
"""List all interviews for an employer, with optional status filter."""
|
| 479 |
-
try:
|
| 480 |
-
_, company = await _get_client_and_company(db, email)
|
| 481 |
-
if not company:
|
| 482 |
-
return {"success": False, "error": "Company not found."}
|
| 483 |
-
|
| 484 |
-
query = select(Interview).where(Interview.company_id == company.id)
|
| 485 |
-
if status:
|
| 486 |
-
query = query.where(Interview.status == status)
|
| 487 |
-
query = query.order_by(Interview.scheduled_time.desc())
|
| 488 |
-
|
| 489 |
-
result = await db.execute(query)
|
| 490 |
-
interviews = result.scalars().all()
|
| 491 |
-
|
| 492 |
-
data = []
|
| 493 |
-
for iv in interviews:
|
| 494 |
-
talent = await _get_talent_by_id(db, iv.candidate_id)
|
| 495 |
-
data.append({
|
| 496 |
-
"interview_id": str(iv.id),
|
| 497 |
-
"candidate_id": iv.candidate_id,
|
| 498 |
-
"candidate_name": talent.name if talent else iv.candidate_id,
|
| 499 |
-
"scheduled_time": iv.scheduled_time.isoformat() if iv.scheduled_time else None,
|
| 500 |
-
"status": iv.status or "Scheduled",
|
| 501 |
-
"has_transcript": bool(iv.transcript_text),
|
| 502 |
-
"has_ai_summary": bool(iv.ai_summary),
|
| 503 |
-
"competency_score": iv.ai_competency_score or 0,
|
| 504 |
-
"created_at": iv.created_at.isoformat() if iv.created_at else None,
|
| 505 |
-
})
|
| 506 |
-
|
| 507 |
-
return {
|
| 508 |
-
"success": True,
|
| 509 |
-
"data": data,
|
| 510 |
-
"total": len(data),
|
| 511 |
-
}
|
| 512 |
-
|
| 513 |
-
except Exception as e:
|
| 514 |
-
logger.error(f"list_interviews error: {e}")
|
| 515 |
-
return {"success": False, "error": str(e), "data": [], "total": 0}
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
async def get_interview_detail(
|
| 519 |
-
db: AsyncSession,
|
| 520 |
-
interview_id: str,
|
| 521 |
-
) -> dict:
|
| 522 |
-
"""Get full interview detail including transcript, AI summary, and competency analysis."""
|
| 523 |
-
try:
|
| 524 |
-
interview = await _get_interview(db, interview_id)
|
| 525 |
-
if not interview:
|
| 526 |
-
return {"success": False, "error": "Interview tidak ditemukan."}
|
| 527 |
-
|
| 528 |
-
talent = await _get_talent_by_id(db, interview.candidate_id)
|
| 529 |
-
|
| 530 |
-
competency_analysis = None
|
| 531 |
-
if interview.ai_performance_analysis:
|
| 532 |
-
try:
|
| 533 |
-
competency_analysis = json.loads(interview.ai_performance_analysis)
|
| 534 |
-
except Exception:
|
| 535 |
-
competency_analysis = {"raw": interview.ai_performance_analysis}
|
| 536 |
-
|
| 537 |
-
return {
|
| 538 |
-
"success": True,
|
| 539 |
-
"data": {
|
| 540 |
-
"interview_id": str(interview.id),
|
| 541 |
-
"candidate_id": interview.candidate_id,
|
| 542 |
-
"candidate_name": talent.name if talent else interview.candidate_id,
|
| 543 |
-
"scheduled_time": interview.scheduled_time.isoformat() if interview.scheduled_time else None,
|
| 544 |
-
"status": interview.status or "Scheduled",
|
| 545 |
-
"has_transcript": bool(interview.transcript_text),
|
| 546 |
-
"has_ai_summary": bool(interview.ai_summary),
|
| 547 |
-
"competency_score": interview.ai_competency_score or 0,
|
| 548 |
-
"created_at": interview.created_at.isoformat() if interview.created_at else None,
|
| 549 |
-
},
|
| 550 |
-
"transcript": interview.transcript_text or "",
|
| 551 |
-
"ai_summary": interview.ai_summary or "",
|
| 552 |
-
"competency_analysis": competency_analysis,
|
| 553 |
-
}
|
| 554 |
-
|
| 555 |
-
except Exception as e:
|
| 556 |
-
logger.error(f"get_interview_detail error: {e}")
|
| 557 |
-
return {"success": False, "error": str(e)}
|
| 558 |
-
|
|
|
|
| 1 |
+
"""Interview & AI Notulen Service — Schedule, Transcript, AI Summary, Comparison.
|
| 2 |
+
|
| 3 |
+
Business Model:
|
| 4 |
+
- Schedule interview: costs 5 coins (deducted from Company CreditBalance)
|
| 5 |
+
- Enterprise tier: free AI interview scheduling
|
| 6 |
+
- AI Notulen: automated meeting summaries via Gemini MEDIUM tier
|
| 7 |
+
- Competency analysis + multi-candidate comparison via Gemini HIGH tier
|
| 8 |
+
|
| 9 |
+
All operations crash-proof: never throw, always return structured response.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import secrets
|
| 14 |
+
import uuid
|
| 15 |
+
from datetime import datetime, timezone
|
| 16 |
+
from typing import Any, Dict, List, Optional
|
| 17 |
+
|
| 18 |
+
from loguru import logger
|
| 19 |
+
from sqlalchemy import func, select
|
| 20 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 21 |
+
|
| 22 |
+
from app.models.finance import Interview
|
| 23 |
+
from app.models.talent import Talent
|
| 24 |
+
from app.models.employer import ClientAccount, Company
|
| 25 |
+
from app.models.finance import Transaction
|
| 26 |
+
from app.services.ai_service import call_medium, call_high
|
| 27 |
+
from app.config.settings import settings, FINANCE_CONFIG
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
INTERVIEW_COST = 5 # Coins per interview (Enterprise = free)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# =============================================================================
|
| 34 |
+
# HELPERS
|
| 35 |
+
# =============================================================================
|
| 36 |
+
|
| 37 |
+
async def _get_talent_by_id(db: AsyncSession, talent_id: str) -> Optional[Talent]:
|
| 38 |
+
result = await db.execute(select(Talent).where(Talent.talent_id == talent_id))
|
| 39 |
+
return result.scalar_one_or_none()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
async def _get_client_and_company(db: AsyncSession, email: str) -> tuple:
|
| 43 |
+
result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
|
| 44 |
+
client = result.scalar_one_or_none()
|
| 45 |
+
if not client:
|
| 46 |
+
return None, None
|
| 47 |
+
result = await db.execute(select(Company).where(Company.id == client.company_id))
|
| 48 |
+
company = result.scalar_one_or_none()
|
| 49 |
+
return client, company
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
async def _get_interview(db: AsyncSession, interview_id: str) -> Optional[Interview]:
|
| 53 |
+
try:
|
| 54 |
+
uid = uuid.UUID(interview_id)
|
| 55 |
+
result = await db.execute(
|
| 56 |
+
select(Interview).where(Interview.id == uid)
|
| 57 |
+
)
|
| 58 |
+
return result.scalar_one_or_none()
|
| 59 |
+
except Exception:
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _tier_is_enterprise(tier: str) -> bool:
|
| 64 |
+
return tier and tier.lower() == "enterprise"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# =============================================================================
|
| 68 |
+
# 1. SCHEDULE INTERVIEW
|
| 69 |
+
# =============================================================================
|
| 70 |
+
|
| 71 |
+
async def schedule_interview(
|
| 72 |
+
db: AsyncSession,
|
| 73 |
+
recruiter_email: str,
|
| 74 |
+
candidate_id: str,
|
| 75 |
+
scheduled_time: str,
|
| 76 |
+
) -> dict:
|
| 77 |
+
"""Schedule an interview with a candidate.
|
| 78 |
+
|
| 79 |
+
Business rules:
|
| 80 |
+
1. Verify talent exists
|
| 81 |
+
2. Verify employer has enough coins (unless Enterprise tier)
|
| 82 |
+
3. Deduct 5 coins (free for Enterprise)
|
| 83 |
+
4. Create Interview record
|
| 84 |
+
|
| 85 |
+
Returns structured response with interview_id and credit info.
|
| 86 |
+
"""
|
| 87 |
+
try:
|
| 88 |
+
# Verify talent
|
| 89 |
+
talent = await _get_talent_by_id(db, candidate_id)
|
| 90 |
+
if not talent:
|
| 91 |
+
return {"success": False, "error": f"Talent {candidate_id} tidak ditemukan."}
|
| 92 |
+
|
| 93 |
+
# Verify employer & company
|
| 94 |
+
client, company = await _get_client_and_company(db, recruiter_email)
|
| 95 |
+
if not client or not company:
|
| 96 |
+
return {"success": False, "error": "Akun employer tidak ditemukan."}
|
| 97 |
+
|
| 98 |
+
credits_deducted = 0
|
| 99 |
+
|
| 100 |
+
# Check if Enterprise — free scheduling
|
| 101 |
+
if not _tier_is_enterprise(company.tier or ""):
|
| 102 |
+
if (company.credit_balance or 0) < INTERVIEW_COST:
|
| 103 |
+
return {
|
| 104 |
+
"success": False,
|
| 105 |
+
"error": f"Koin tidak mencukupi. Interview membutuhkan {INTERVIEW_COST} koin. "
|
| 106 |
+
f"Saldo: {company.credit_balance or 0}. "
|
| 107 |
+
f"Upgrade ke Enterprise untuk interview gratis tanpa batas.",
|
| 108 |
+
}
|
| 109 |
+
# Deduct coins
|
| 110 |
+
company.credit_balance = (company.credit_balance or 0) - INTERVIEW_COST
|
| 111 |
+
credits_deducted = INTERVIEW_COST
|
| 112 |
+
db.add(company)
|
| 113 |
+
|
| 114 |
+
# Log transaction
|
| 115 |
+
tx = Transaction(
|
| 116 |
+
id=f"TX-IVW-{secrets.token_hex(4).upper()}",
|
| 117 |
+
client_id=client.id,
|
| 118 |
+
amount=INTERVIEW_COST,
|
| 119 |
+
type="Interview",
|
| 120 |
+
status="Settled",
|
| 121 |
+
)
|
| 122 |
+
db.add(tx)
|
| 123 |
+
|
| 124 |
+
# Parse scheduled time
|
| 125 |
+
try:
|
| 126 |
+
sched_dt = datetime.fromisoformat(scheduled_time.replace("Z", "+00:00"))
|
| 127 |
+
except Exception:
|
| 128 |
+
sched_dt = datetime.now(timezone.utc)
|
| 129 |
+
|
| 130 |
+
# Create interview record
|
| 131 |
+
interview = Interview(
|
| 132 |
+
id=uuid.uuid4(),
|
| 133 |
+
company_id=company.id,
|
| 134 |
+
client_id=client.id,
|
| 135 |
+
candidate_id=candidate_id,
|
| 136 |
+
scheduled_time=sched_dt,
|
| 137 |
+
status="Scheduled",
|
| 138 |
+
)
|
| 139 |
+
db.add(interview)
|
| 140 |
+
await db.commit()
|
| 141 |
+
|
| 142 |
+
logger.info(f"Interview scheduled: {interview.id} ({recruiter_email} -> {candidate_id})")
|
| 143 |
+
|
| 144 |
+
return {
|
| 145 |
+
"success": True,
|
| 146 |
+
"interview_id": str(interview.id),
|
| 147 |
+
"candidate_name": talent.name or "Talent",
|
| 148 |
+
"candidate_id": candidate_id,
|
| 149 |
+
"scheduled_time": sched_dt.isoformat(),
|
| 150 |
+
"credits_deducted": credits_deducted,
|
| 151 |
+
"credits_remaining": company.credit_balance or 0,
|
| 152 |
+
"message": f"Interview berhasil dijadwalkan dengan {talent.name or 'Talent'}."
|
| 153 |
+
+ (f" ({INTERVIEW_COST} koin digunakan)" if credits_deducted > 0
|
| 154 |
+
else " (Gratis — Enterprise tier)"),
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
except Exception as e:
|
| 158 |
+
logger.error(f"schedule_interview error: {e}")
|
| 159 |
+
await db.rollback()
|
| 160 |
+
return {"success": False, "error": f"Gagal menjadwalkan interview: {str(e)}"}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# =============================================================================
|
| 164 |
+
# 2. SAVE TRANSCRIPT
|
| 165 |
+
# =============================================================================
|
| 166 |
+
|
| 167 |
+
async def save_transcript(
|
| 168 |
+
db: AsyncSession,
|
| 169 |
+
interview_id: str,
|
| 170 |
+
transcript_text: str,
|
| 171 |
+
) -> dict:
|
| 172 |
+
"""Save interview transcript after the interview is completed."""
|
| 173 |
+
try:
|
| 174 |
+
interview = await _get_interview(db, interview_id)
|
| 175 |
+
if not interview:
|
| 176 |
+
return {"success": False, "error": "Interview tidak ditemukan."}
|
| 177 |
+
|
| 178 |
+
interview.transcript_text = transcript_text
|
| 179 |
+
interview.status = "Completed"
|
| 180 |
+
db.add(interview)
|
| 181 |
+
await db.commit()
|
| 182 |
+
|
| 183 |
+
logger.info(f"Transcript saved: {interview_id}")
|
| 184 |
+
|
| 185 |
+
return {
|
| 186 |
+
"success": True,
|
| 187 |
+
"interview_id": interview_id,
|
| 188 |
+
"message": "Transkrip interview berhasil disimpan.",
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
except Exception as e:
|
| 192 |
+
logger.error(f"save_transcript error: {e}")
|
| 193 |
+
await db.rollback()
|
| 194 |
+
return {"success": False, "error": f"Gagal menyimpan transkrip: {str(e)}"}
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# =============================================================================
|
| 198 |
+
# 3. AI NOTULEN (Meeting Summary)
|
| 199 |
+
# =============================================================================
|
| 200 |
+
|
| 201 |
+
async def generate_ai_notulen(
|
| 202 |
+
db: AsyncSession,
|
| 203 |
+
interview_id: str,
|
| 204 |
+
) -> dict:
|
| 205 |
+
"""Generate AI meeting summary (Notulen) from interview transcript.
|
| 206 |
+
|
| 207 |
+
Uses Gemini MEDIUM tier (3.5 Flash) for summarization.
|
| 208 |
+
Falls back to algorithmic extraction if AI unavailable.
|
| 209 |
+
"""
|
| 210 |
+
try:
|
| 211 |
+
interview = await _get_interview(db, interview_id)
|
| 212 |
+
if not interview:
|
| 213 |
+
return {"success": False, "error": "Interview tidak ditemukan."}
|
| 214 |
+
|
| 215 |
+
if not interview.transcript_text:
|
| 216 |
+
return {"success": False, "error": "Transkrip interview belum tersedia. Simpan transkrip terlebih dahulu."}
|
| 217 |
+
|
| 218 |
+
transcript = interview.transcript_text[:8000]
|
| 219 |
+
|
| 220 |
+
# Get candidate info for context
|
| 221 |
+
talent = await _get_talent_by_id(db, interview.candidate_id)
|
| 222 |
+
candidate_name = talent.name if talent else "Kandidat"
|
| 223 |
+
|
| 224 |
+
# AI Notulen via MEDIUM tier
|
| 225 |
+
ai_used = False
|
| 226 |
+
summary = None
|
| 227 |
+
try:
|
| 228 |
+
prompt = (
|
| 229 |
+
f"Anda adalah AI Notulen Brigawan, asisten yang membuat notulen rapat interview yang profesional dan terstruktur.\\n\\n"
|
| 230 |
+
f"Buat notulen interview untuk kandidat: {candidate_name}\\n\\n"
|
| 231 |
+
f"Berikut adalah transkrip interview:\\n{transcript}\\n\\n"
|
| 232 |
+
f"Buat notulen dengan format berikut (dalam Bahasa Indonesia):\\n"
|
| 233 |
+
f"1. RINGKASAN EKSEKUTIF: 2-3 kalimat\\n"
|
| 234 |
+
f"2. PERTANYAAN & JAWABAN: Poin-poin penting\\n"
|
| 235 |
+
f"3. KESAN KANDIDAT: Kesan umum, komunikasi, dan sikap\\n"
|
| 236 |
+
f"4. KECOCOKAN: Analisis kecocokan\\n"
|
| 237 |
+
f"5. REKOMENDASI: Langkah selanjutnya"
|
| 238 |
+
)
|
| 239 |
+
result = await call_medium(prompt=prompt, temperature=0.5, max_output_tokens=2048)
|
| 240 |
+
if result:
|
| 241 |
+
summary = result.strip()
|
| 242 |
+
ai_used = True
|
| 243 |
+
except Exception as e:
|
| 244 |
+
logger.error(f"AI Notulen generation error: {e}")
|
| 245 |
+
|
| 246 |
+
# Algorithmic fallback
|
| 247 |
+
if not summary:
|
| 248 |
+
summary = (
|
| 249 |
+
f"=== NOTULEN INTERVIEW ({candidate_name}) ===\\n\\n"
|
| 250 |
+
f"RINGKASAN EKSEKUTIF:\\n"
|
| 251 |
+
f"Interview dengan {candidate_name} telah dilaksanakan.\\n\\n"
|
| 252 |
+
f"*Notulen AI tidak tersedia - menggunakan ringkasan otomatis.*"
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# Save to interview record
|
| 256 |
+
interview.ai_summary = summary
|
| 257 |
+
db.add(interview)
|
| 258 |
+
await db.commit()
|
| 259 |
+
|
| 260 |
+
return {
|
| 261 |
+
"success": True,
|
| 262 |
+
"interview_id": interview_id,
|
| 263 |
+
"summary": summary,
|
| 264 |
+
"ai_used": ai_used,
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
except Exception as e:
|
| 268 |
+
logger.error(f"generate_ai_notulen error: {e}")
|
| 269 |
+
await db.rollback()
|
| 270 |
+
return {"success": False, "error": f"Gagal membuat notulen: {str(e)}"}
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# =============================================================================
|
| 274 |
+
# 4. COMPETENCY ANALYSIS
|
| 275 |
+
# =============================================================================
|
| 276 |
+
|
| 277 |
+
async def analyze_competency(
|
| 278 |
+
db: AsyncSession,
|
| 279 |
+
interview_id: str,
|
| 280 |
+
) -> dict:
|
| 281 |
+
"""Analyze candidate competency from interview transcript.
|
| 282 |
+
|
| 283 |
+
Uses Gemini MEDIUM tier for structured competency scoring.
|
| 284 |
+
Returns scores across multiple competency dimensions.
|
| 285 |
+
"""
|
| 286 |
+
try:
|
| 287 |
+
interview = await _get_interview(db, interview_id)
|
| 288 |
+
if not interview:
|
| 289 |
+
return {"success": False, "error": "Interview tidak ditemukan."}
|
| 290 |
+
|
| 291 |
+
if not interview.transcript_text:
|
| 292 |
+
return {"success": False, "error": "Transkrip interview belum tersedia."}
|
| 293 |
+
|
| 294 |
+
transcript = interview.transcript_text[:8000]
|
| 295 |
+
talent = await _get_talent_by_id(db, interview.candidate_id)
|
| 296 |
+
candidate_name = talent.name if talent else "Kandidat"
|
| 297 |
+
|
| 298 |
+
# AI competency analysis via MEDIUM tier
|
| 299 |
+
ai_used = False
|
| 300 |
+
analysis = None
|
| 301 |
+
try:
|
| 302 |
+
prompt = (
|
| 303 |
+
f"Anda adalah AI Assessment Brigawan, spesialis evaluasi kompetensi kandidat.\\n\\n"
|
| 304 |
+
f"Evaluasi kandidat berikut berdasarkan transkrip interview:\\n"
|
| 305 |
+
f"Nama Kandidat: {candidate_name}\\n\\n"
|
| 306 |
+
f"Transkrip Interview:\\n{transcript}\\n\\n"
|
| 307 |
+
f"Berikan analisis dalam format JSON SAJA (tanpa markdown):\\n"
|
| 308 |
+
'{\"overall_score\": 0-100, \"competencies\": [{\"name\": \"Pengetahuan Teknis\", \"score\": 0-100, \"notes\": \"...\"}], \"strengths\": \"...\", \"weaknesses\": \"...\", \"recommendation\": \"...\"}'
|
| 309 |
+
)
|
| 310 |
+
result = await call_medium(prompt=prompt, temperature=0.4, max_output_tokens=2048)
|
| 311 |
+
if result:
|
| 312 |
+
cleaned = result.strip()
|
| 313 |
+
if cleaned.startswith("```json"):
|
| 314 |
+
cleaned = cleaned[7:]
|
| 315 |
+
if cleaned.startswith("```"):
|
| 316 |
+
cleaned = cleaned[3:]
|
| 317 |
+
if cleaned.endswith("```"):
|
| 318 |
+
cleaned = cleaned[:-3]
|
| 319 |
+
cleaned = cleaned.strip()
|
| 320 |
+
analysis = json.loads(cleaned)
|
| 321 |
+
ai_used = True
|
| 322 |
+
except Exception as e:
|
| 323 |
+
logger.error(f"Competency analysis AI error: {e}")
|
| 324 |
+
|
| 325 |
+
if not analysis:
|
| 326 |
+
# Algorithmic fallback
|
| 327 |
+
word_count = len(transcript.split())
|
| 328 |
+
score = min(70 + (word_count // 50), 90)
|
| 329 |
+
analysis = {
|
| 330 |
+
"overall_score": score,
|
| 331 |
+
"competencies": [
|
| 332 |
+
{"name": "Pengetahuan Teknis", "score": score - 5, "notes": "Dinilai dari transkrip (fallback)"},
|
| 333 |
+
{"name": "Komunikasi", "score": score, "notes": "Dinilai dari transkrip (fallback)"},
|
| 334 |
+
{"name": "Pemecahan Masalah", "score": score - 10, "notes": "Dinilai dari transkrip (fallback)"},
|
| 335 |
+
{"name": "Pengalaman Relevan", "score": score - 5, "notes": "Dinilai dari transkrip (fallback)"},
|
| 336 |
+
{"name": "Sikap dan Motivasi", "score": score, "notes": "Dinilai dari transkrip (fallback)"},
|
| 337 |
+
],
|
| 338 |
+
"strengths": "Analisis AI tidak tersedia. Gunakan penilaian manual.",
|
| 339 |
+
"weaknesses": "Analisis AI tidak tersedia. Gunakan penilaian manual.",
|
| 340 |
+
"recommendation": "Lanjut ke tahap berikutnya berdasarkan penilaian manual.",
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
# Save competency score to interview record
|
| 344 |
+
interview.ai_competency_score = analysis.get("overall_score", 0)
|
| 345 |
+
interview.ai_performance_analysis = json.dumps(analysis)
|
| 346 |
+
db.add(interview)
|
| 347 |
+
await db.commit()
|
| 348 |
+
|
| 349 |
+
return {
|
| 350 |
+
"success": True,
|
| 351 |
+
"interview_id": interview_id,
|
| 352 |
+
"overall_score": analysis.get("overall_score", 0),
|
| 353 |
+
"competencies": analysis.get("competencies", []),
|
| 354 |
+
"strengths": analysis.get("strengths", ""),
|
| 355 |
+
"weaknesses": analysis.get("weaknesses", ""),
|
| 356 |
+
"recommendation": analysis.get("recommendation", ""),
|
| 357 |
+
"ai_used": ai_used,
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
except Exception as e:
|
| 361 |
+
logger.error(f"analyze_competency error: {e}")
|
| 362 |
+
return {"success": False, "error": f"Gagal menganalisis kompetensi: {str(e)}"}
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
# =============================================================================
|
| 366 |
+
# 5. MULTI-CANDIDATE COMPARISON
|
| 367 |
+
# =============================================================================
|
| 368 |
+
|
| 369 |
+
async def compare_candidates(
|
| 370 |
+
db: AsyncSession,
|
| 371 |
+
interview_ids: List[str],
|
| 372 |
+
) -> dict:
|
| 373 |
+
"""Compare multiple candidates from their interviews.
|
| 374 |
+
|
| 375 |
+
Uses Gemini HIGH tier (3.1 Pro) for intelligent comparison.
|
| 376 |
+
Generates a comparison matrix with recommendations.
|
| 377 |
+
Max 10 candidates per comparison.
|
| 378 |
+
"""
|
| 379 |
+
try:
|
| 380 |
+
if len(interview_ids) < 2:
|
| 381 |
+
return {"success": False, "error": "Minimal 2 kandidat untuk perbandingan."}
|
| 382 |
+
if len(interview_ids) > 10:
|
| 383 |
+
interview_ids = interview_ids[:10]
|
| 384 |
+
|
| 385 |
+
# Fetch all interviews and their data
|
| 386 |
+
candidates_data = []
|
| 387 |
+
for iid in interview_ids:
|
| 388 |
+
interview = await _get_interview(db, iid)
|
| 389 |
+
if not interview:
|
| 390 |
+
continue
|
| 391 |
+
talent = await _get_talent_by_id(db, interview.candidate_id)
|
| 392 |
+
candidates_data.append({
|
| 393 |
+
"interview_id": iid,
|
| 394 |
+
"candidate_id": interview.candidate_id,
|
| 395 |
+
"candidate_name": talent.name if talent else interview.candidate_id,
|
| 396 |
+
"score": interview.ai_competency_score or 0,
|
| 397 |
+
"summary": interview.ai_summary or "",
|
| 398 |
+
"transcript": (interview.transcript_text or "")[:2000],
|
| 399 |
+
"analysis": interview.ai_performance_analysis or "",
|
| 400 |
+
})
|
| 401 |
+
|
| 402 |
+
if len(candidates_data) < 2:
|
| 403 |
+
return {"success": False, "error": "Tidak cukup data interview untuk perbandingan."}
|
| 404 |
+
|
| 405 |
+
# AI comparison via HIGH tier
|
| 406 |
+
ai_used = False
|
| 407 |
+
comparison_result = None
|
| 408 |
+
try:
|
| 409 |
+
candidates_text = ""
|
| 410 |
+
for c in candidates_data:
|
| 411 |
+
candidates_text += (
|
| 412 |
+
f"--- Kandidat: {c['candidate_name']} (ID: {c['candidate_id']}) ---\\n"
|
| 413 |
+
f"Skor Kompetensi: {c['score']}/100\\n"
|
| 414 |
+
f"Ringkasan: {c['summary'][:500]}\\n\\n"
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
prompt = (
|
| 418 |
+
f"Anda adalah AI Recruiter Brigawan, spesialis perbandingan kandidat.\\n\\n"
|
| 419 |
+
f"Bandingkan kandidat-kandidat berikut:\\n{candidates_text}\\n"
|
| 420 |
+
f"Buat analisis JSON: candidates[] dengan overall_score 0-100, competency_scores, strengths, weaknesses. Serta recommendation dan matrix_summary."
|
| 421 |
+
)
|
| 422 |
+
result = await call_high(prompt=prompt, temperature=0.3, max_output_tokens=3072)
|
| 423 |
+
if result:
|
| 424 |
+
cleaned = result.strip()
|
| 425 |
+
if cleaned.startswith("```json"):
|
| 426 |
+
cleaned = cleaned[7:]
|
| 427 |
+
if cleaned.startswith("```"):
|
| 428 |
+
cleaned = cleaned[3:]
|
| 429 |
+
if cleaned.endswith("```"):
|
| 430 |
+
cleaned = cleaned[:-3]
|
| 431 |
+
cleaned = cleaned.strip()
|
| 432 |
+
comparison_result = json.loads(cleaned)
|
| 433 |
+
ai_used = True
|
| 434 |
+
except Exception as e:
|
| 435 |
+
logger.error(f"Candidate comparison AI error: {e}")
|
| 436 |
+
|
| 437 |
+
if not comparison_result:
|
| 438 |
+
# Algorithmic fallback: sort by score
|
| 439 |
+
candidates_data.sort(key=lambda c: c["score"], reverse=True)
|
| 440 |
+
comparison_result = {
|
| 441 |
+
"candidates": [
|
| 442 |
+
{
|
| 443 |
+
"candidate_id": c["candidate_id"],
|
| 444 |
+
"candidate_name": c["candidate_name"],
|
| 445 |
+
"overall_score": c["score"],
|
| 446 |
+
"competency_scores": {"Umum": c["score"]},
|
| 447 |
+
"strengths": "Data terbatas",
|
| 448 |
+
"weaknesses": "Data terbatas",
|
| 449 |
+
}
|
| 450 |
+
for c in candidates_data
|
| 451 |
+
],
|
| 452 |
+
"recommendation": f"Kandidat terbaik: {candidates_data[0]['candidate_name']} (skor {candidates_data[0]['score']}). Verifikasi manual diperlukan.",
|
| 453 |
+
"matrix_summary": f"Perbandingan {len(candidates_data)} kandidat berdasarkan skor kompetensi.",
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
return {
|
| 457 |
+
"success": True,
|
| 458 |
+
"candidates": comparison_result.get("candidates", []),
|
| 459 |
+
"recommendation": comparison_result.get("recommendation", ""),
|
| 460 |
+
"matrix_summary": comparison_result.get("matrix_summary", ""),
|
| 461 |
+
"ai_used": ai_used,
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
except Exception as e:
|
| 465 |
+
logger.error(f"compare_candidates error: {e}")
|
| 466 |
+
return {"success": False, "error": f"Gagal membandingkan kandidat: {str(e)}"}
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
# =============================================================================
|
| 470 |
+
# 6. LIST & DETAIL INTERVIEWS
|
| 471 |
+
# =============================================================================
|
| 472 |
+
|
| 473 |
+
async def list_interviews(
|
| 474 |
+
db: AsyncSession,
|
| 475 |
+
email: str,
|
| 476 |
+
status: Optional[str] = None,
|
| 477 |
+
) -> dict:
|
| 478 |
+
"""List all interviews for an employer, with optional status filter."""
|
| 479 |
+
try:
|
| 480 |
+
_, company = await _get_client_and_company(db, email)
|
| 481 |
+
if not company:
|
| 482 |
+
return {"success": False, "error": "Company not found."}
|
| 483 |
+
|
| 484 |
+
query = select(Interview).where(Interview.company_id == company.id)
|
| 485 |
+
if status:
|
| 486 |
+
query = query.where(Interview.status == status)
|
| 487 |
+
query = query.order_by(Interview.scheduled_time.desc())
|
| 488 |
+
|
| 489 |
+
result = await db.execute(query)
|
| 490 |
+
interviews = result.scalars().all()
|
| 491 |
+
|
| 492 |
+
data = []
|
| 493 |
+
for iv in interviews:
|
| 494 |
+
talent = await _get_talent_by_id(db, iv.candidate_id)
|
| 495 |
+
data.append({
|
| 496 |
+
"interview_id": str(iv.id),
|
| 497 |
+
"candidate_id": iv.candidate_id,
|
| 498 |
+
"candidate_name": talent.name if talent else iv.candidate_id,
|
| 499 |
+
"scheduled_time": iv.scheduled_time.isoformat() if iv.scheduled_time else None,
|
| 500 |
+
"status": iv.status or "Scheduled",
|
| 501 |
+
"has_transcript": bool(iv.transcript_text),
|
| 502 |
+
"has_ai_summary": bool(iv.ai_summary),
|
| 503 |
+
"competency_score": iv.ai_competency_score or 0,
|
| 504 |
+
"created_at": iv.created_at.isoformat() if iv.created_at else None,
|
| 505 |
+
})
|
| 506 |
+
|
| 507 |
+
return {
|
| 508 |
+
"success": True,
|
| 509 |
+
"data": data,
|
| 510 |
+
"total": len(data),
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
except Exception as e:
|
| 514 |
+
logger.error(f"list_interviews error: {e}")
|
| 515 |
+
return {"success": False, "error": str(e), "data": [], "total": 0}
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
async def get_interview_detail(
|
| 519 |
+
db: AsyncSession,
|
| 520 |
+
interview_id: str,
|
| 521 |
+
) -> dict:
|
| 522 |
+
"""Get full interview detail including transcript, AI summary, and competency analysis."""
|
| 523 |
+
try:
|
| 524 |
+
interview = await _get_interview(db, interview_id)
|
| 525 |
+
if not interview:
|
| 526 |
+
return {"success": False, "error": "Interview tidak ditemukan."}
|
| 527 |
+
|
| 528 |
+
talent = await _get_talent_by_id(db, interview.candidate_id)
|
| 529 |
+
|
| 530 |
+
competency_analysis = None
|
| 531 |
+
if interview.ai_performance_analysis:
|
| 532 |
+
try:
|
| 533 |
+
competency_analysis = json.loads(interview.ai_performance_analysis)
|
| 534 |
+
except Exception:
|
| 535 |
+
competency_analysis = {"raw": interview.ai_performance_analysis}
|
| 536 |
+
|
| 537 |
+
return {
|
| 538 |
+
"success": True,
|
| 539 |
+
"data": {
|
| 540 |
+
"interview_id": str(interview.id),
|
| 541 |
+
"candidate_id": interview.candidate_id,
|
| 542 |
+
"candidate_name": talent.name if talent else interview.candidate_id,
|
| 543 |
+
"scheduled_time": interview.scheduled_time.isoformat() if interview.scheduled_time else None,
|
| 544 |
+
"status": interview.status or "Scheduled",
|
| 545 |
+
"has_transcript": bool(interview.transcript_text),
|
| 546 |
+
"has_ai_summary": bool(interview.ai_summary),
|
| 547 |
+
"competency_score": interview.ai_competency_score or 0,
|
| 548 |
+
"created_at": interview.created_at.isoformat() if interview.created_at else None,
|
| 549 |
+
},
|
| 550 |
+
"transcript": interview.transcript_text or "",
|
| 551 |
+
"ai_summary": interview.ai_summary or "",
|
| 552 |
+
"competency_analysis": competency_analysis,
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
except Exception as e:
|
| 556 |
+
logger.error(f"get_interview_detail error: {e}")
|
| 557 |
+
return {"success": False, "error": str(e)}
|
| 558 |
+
|
app/services/job_service.py
CHANGED
|
@@ -1,288 +1,288 @@
|
|
| 1 |
-
"""Job Service - Posting CRUD, Outreach, Compatibility, Limits, Vouchers."""
|
| 2 |
-
|
| 3 |
-
import json
|
| 4 |
-
import secrets
|
| 5 |
-
from datetime import datetime, timezone
|
| 6 |
-
|
| 7 |
-
from loguru import logger
|
| 8 |
-
from sqlalchemy import func, select
|
| 9 |
-
|
| 10 |
-
from app.models.job import JobPosting, RecruiterOutreach
|
| 11 |
-
from app.models.employer import ClientAccount, Company
|
| 12 |
-
from app.services.talent_service import get_talent_profile
|
| 13 |
-
from app.config.settings import FINANCE_CONFIG
|
| 14 |
-
from app.services.ai_service import call_medium
|
| 15 |
-
|
| 16 |
-
TIERS = FINANCE_CONFIG.get("TIERS", {})
|
| 17 |
-
OUTREACH_COST = FINANCE_CONFIG.get("DEDUCTION", {}).get("DIRECT_OUTREACH", 10)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def _sanitize(val, max_len=500):
|
| 21 |
-
if val is None:
|
| 22 |
-
return ""
|
| 23 |
-
return str(val).replace("<", "").replace(">", "").strip()[:max_len]
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
async def get_job_posting(db, job_id):
|
| 27 |
-
|
| 28 |
-
"""Get single job posting (public-safe)."""
|
| 29 |
-
try:
|
| 30 |
-
if not job_id:
|
| 31 |
-
return {"success": False, "error": "JobID tidak boleh kosong."}
|
| 32 |
-
r = await db.execute(select(JobPosting).where(JobPosting.job_id == job_id).limit(1))
|
| 33 |
-
job = r.scalar_one_or_none()
|
| 34 |
-
if not job:
|
| 35 |
-
return {"success": False, "error": "Lowongan tidak ditemukan."}
|
| 36 |
-
skills = [s.strip() for s in (job.required_skills or "").split(",") if s.strip()]
|
| 37 |
-
return {"success": True, "data": {
|
| 38 |
-
"job_id": job.job_id, "title": job.title or "",
|
| 39 |
-
"company_category": job.company_category or "Sustainability Sector",
|
| 40 |
-
"location": job.location or "", "description": job.description or "",
|
| 41 |
-
"required_skills": skills,
|
| 42 |
-
"salary_range": job.salary_range or "Negotiable",
|
| 43 |
-
"source": job.source or "", "status": job.status or "",
|
| 44 |
-
"sector_match": job.sector_match or "",
|
| 45 |
-
"linkedin_post_url": job.linkedin_post_url or "",
|
| 46 |
-
"timestamp": job.timestamp.isoformat() if job.timestamp else None,
|
| 47 |
-
"posted_at": job.posted_at.isoformat() if job.posted_at else None,
|
| 48 |
-
}}
|
| 49 |
-
except Exception as e:
|
| 50 |
-
logger.error(f"get_job_posting error: {e}")
|
| 51 |
-
return {"success": False, "error": str(e)}
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
async def create_job_posting(db, employer_email, data):
|
| 56 |
-
try:
|
| 57 |
-
lc = await check_active_job_posting_limit(db, employer_email)
|
| 58 |
-
if not lc.get("allowed"): return lc
|
| 59 |
-
import uuid
|
| 60 |
-
job_id = "JOB-" + secrets.token_hex(4).upper()
|
| 61 |
-
now = datetime.now(timezone.utc)
|
| 62 |
-
p = JobPosting(id=uuid.uuid4(), job_id=job_id,
|
| 63 |
-
title=_sanitize(data.get("title",""),255), company_name=employer_email,
|
| 64 |
-
company_category=_sanitize(data.get("company_category",""),255),
|
| 65 |
-
location=_sanitize(data.get("location",""),255),
|
| 66 |
-
description=_sanitize(data.get("description",""),10000),
|
| 67 |
-
required_skills=_sanitize(data.get("required_skills",""),1000),
|
| 68 |
-
salary_range=_sanitize(data.get("salary_range","Negotiable"),100),
|
| 69 |
-
sector_match=_sanitize(data.get("sector_match",""),255),
|
| 70 |
-
linkedin_post_url=_sanitize(data.get("linkedin_post_url",""),500),
|
| 71 |
-
source="Employer Posting", status="posted", posted_at=now, timestamp=now, is_active=True)
|
| 72 |
-
db.add(p); await db.commit()
|
| 73 |
-
return {"success":True,"job_id":job_id,"message":"Lowongan berhasil dipublikasikan."}
|
| 74 |
-
except Exception as e:
|
| 75 |
-
logger.error(f"create_job_posting error: {e}")
|
| 76 |
-
return {"success":False,"error":str(e)}
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
async def get_job_postings(db, page=1, limit=10):
|
| 81 |
-
try:
|
| 82 |
-
p, lim = max(1, int(page)), max(1, min(50, int(limit)))
|
| 83 |
-
r = await db.execute(
|
| 84 |
-
select(JobPosting).where(JobPosting.status.in_(["posted", "analyzed"]))
|
| 85 |
-
.order_by(JobPosting.timestamp.desc()).offset((p-1)*lim).limit(lim)
|
| 86 |
-
)
|
| 87 |
-
jobs = list(r.scalars().all())
|
| 88 |
-
tr = await db.execute(select(func.count()).select_from(JobPosting).where(JobPosting.status.in_(["posted", "analyzed"])))
|
| 89 |
-
total = tr.scalar() or 0
|
| 90 |
-
return {"success": True, "page": p, "limit": lim, "total": total, "data": [
|
| 91 |
-
{"job_id": j.job_id, "title": j.title,
|
| 92 |
-
"company_category": j.company_category or "Sustainability Sector",
|
| 93 |
-
"location": j.location,
|
| 94 |
-
"description": (j.description or "")[:200] + "..." if j.description and len(j.description) > 200 else (j.description or ""),
|
| 95 |
-
"required_skills": [s.strip() for s in (j.required_skills or "").split(",") if s.strip()],
|
| 96 |
-
"salary_range": j.salary_range or "Negotiable",
|
| 97 |
-
"status": j.status, "sector_match": j.sector_match or "",
|
| 98 |
-
"timestamp": j.timestamp.isoformat() if j.timestamp else None}
|
| 99 |
-
for j in jobs
|
| 100 |
-
]}
|
| 101 |
-
except Exception as e:
|
| 102 |
-
logger.error(f"get_job_postings error: {e}")
|
| 103 |
-
return {"success": False, "error": str(e), "data": []}
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
async def update_job_status(db, job_id, status):
|
| 108 |
-
try:
|
| 109 |
-
r = await db.execute(select(JobPosting).where(JobPosting.job_id==job_id).limit(1))
|
| 110 |
-
job = r.scalar_one_or_none()
|
| 111 |
-
if not job: return {"success":False,"error":"Lowongan tidak ditemukan."}
|
| 112 |
-
valid = ["draft","posted","closed","archived"]
|
| 113 |
-
if status not in valid: return {"success":False,"error":f"Status invalid. Use: {', '.join(valid)}"}
|
| 114 |
-
job.status=status; job.is_active=(status=="posted")
|
| 115 |
-
db.add(job); await db.commit()
|
| 116 |
-
return {"success":True,"message":f"Status diubah menjadi {status}."}
|
| 117 |
-
except Exception as e:
|
| 118 |
-
logger.error(f"update_job_status error: {e}")
|
| 119 |
-
return {"success":False,"error":str(e)}
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
async def check_active_job_posting_limit(db, employer_email):
|
| 123 |
-
try:
|
| 124 |
-
e = employer_email.lower().strip()
|
| 125 |
-
cr = await db.execute(select(ClientAccount).where(func.lower(ClientAccount.email)==e).limit(1))
|
| 126 |
-
client = cr.scalar_one_or_none()
|
| 127 |
-
tier_name = "free"
|
| 128 |
-
if client and client.company_id:
|
| 129 |
-
cor = await db.execute(select(Company).where(Company.id==client.company_id).limit(1))
|
| 130 |
-
co = cor.scalar_one_or_none()
|
| 131 |
-
if co: tier_name = (co.tier or "free").lower()
|
| 132 |
-
tier = TIERS.get(tier_name, TIERS.get("free",{}))
|
| 133 |
-
max_jobs = tier.get("max_jobs", 1) if isinstance(tier,dict) else 1
|
| 134 |
-
if max_jobs == -1: return {"allowed":True,"tier":tier_name,"active_count":0,"limit":-1}
|
| 135 |
-
nr = await db.execute(select(func.count()).select_from(JobPosting).where(JobPosting.company_name==e,JobPosting.status.in_(["posted","analyzed"])))
|
| 136 |
-
active = nr.scalar() or 0
|
| 137 |
-
if active >= max_jobs: return {"allowed":False,"tier":tier_name,"active_count":active,"limit":max_jobs,"error":f"Batas posting ({max_jobs}) tercapai. Upgrade paket."}
|
| 138 |
-
return {"allowed":True,"tier":tier_name,"active_count":active,"limit":max_jobs}
|
| 139 |
-
except Exception as e:
|
| 140 |
-
logger.error(f"check_job_limit error: {e}")
|
| 141 |
-
return {"allowed":True,"tier":"free","active_count":0,"limit":1}
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
async def analyze_job_compatibility(db, email, job_id):
|
| 146 |
-
"""Refactored: Uses Antigravity gateway for semantic matching."""
|
| 147 |
-
try:
|
| 148 |
-
if not email or not job_id:
|
| 149 |
-
return {"success": False, "error": "Parameter tidak lengkap."}
|
| 150 |
-
|
| 151 |
-
e = email.lower().strip()
|
| 152 |
-
pr = await get_talent_profile(db, e)
|
| 153 |
-
if not pr.get("success"):
|
| 154 |
-
return {"success": False, "error": "Gagal memuat profil talent."}
|
| 155 |
-
p = pr["data"]
|
| 156 |
-
|
| 157 |
-
jr = await get_job_posting(db, job_id)
|
| 158 |
-
if not jr.get("success"):
|
| 159 |
-
return {"success": False, "error": "Gagal memuat pekerjaan."}
|
| 160 |
-
j = jr["data"]
|
| 161 |
-
|
| 162 |
-
# Use Antigravity Orchestrator
|
| 163 |
-
from app.services.antigravity import AntigravityOrchestrator
|
| 164 |
-
orchestrator = AntigravityOrchestrator(db)
|
| 165 |
-
|
| 166 |
-
payload = {
|
| 167 |
-
"query": j.get("title", ""),
|
| 168 |
-
"talent_data": {
|
| 169 |
-
"skill_tags": ",".join(p.get("skills", [])),
|
| 170 |
-
"experience": p.get("experience", ""),
|
| 171 |
-
"sector_focus": p.get("sector_focus", ""),
|
| 172 |
-
"location": p.get("location", "")
|
| 173 |
-
}
|
| 174 |
-
}
|
| 175 |
-
|
| 176 |
-
res = await orchestrator.execute_task(
|
| 177 |
-
agent_name="RecruiterStrategicAdvisor",
|
| 178 |
-
task_name="semantic_matching",
|
| 179 |
-
payload=payload,
|
| 180 |
-
user_email=email
|
| 181 |
-
)
|
| 182 |
-
|
| 183 |
-
if res.get("status") == "success":
|
| 184 |
-
data = res["data"]
|
| 185 |
-
return {
|
| 186 |
-
"success": True,
|
| 187 |
-
"data": {
|
| 188 |
-
"matchScore": data.get("score", 0),
|
| 189 |
-
"matchedSkills": [], # Will be implemented in Pro prompt refinement
|
| 190 |
-
"gapSkills": [],
|
| 191 |
-
"strategy": data.get("summary", ""),
|
| 192 |
-
"ai_used": data.get("ai_used", True)
|
| 193 |
-
}
|
| 194 |
-
}
|
| 195 |
-
|
| 196 |
-
return {"success": False, "error": "AI processing failed"}
|
| 197 |
-
|
| 198 |
-
except Exception as e:
|
| 199 |
-
logger.error(f"analyze_job error: {e}")
|
| 200 |
-
return {"success": False, "error": str(e)}
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
async def record_pending_outreach(db, job_id, talent_email, match_score, recruiter_email, method, subject, body):
|
| 205 |
-
try:
|
| 206 |
-
import uuid
|
| 207 |
-
oid = f"RO-{secrets.randbelow(89999) + 10001}"
|
| 208 |
-
o = RecruiterOutreach(id=uuid.uuid4(), outreach_id=oid, job_id=job_id,
|
| 209 |
-
talent_email=talent_email, match_score=match_score, recruiter_email=recruiter_email,
|
| 210 |
-
contact_method=method, outreach_subject=subject, outreach_body=body,
|
| 211 |
-
status="pending_approval", triggered_at=datetime.now(timezone.utc))
|
| 212 |
-
db.add(o); await db.commit()
|
| 213 |
-
return {"success":True,"outreach_id":oid}
|
| 214 |
-
except Exception as e:
|
| 215 |
-
logger.error(f"record_outreach error: {e}")
|
| 216 |
-
return {"success":False,"error":str(e)}
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
async def send_instant_outreach(db, recruiter_email, job_id, talent_email, match_score, method, subject, body):
|
| 220 |
-
try:
|
| 221 |
-
from app.services.employer_service import deduct_coins
|
| 222 |
-
dr = await deduct_coins(db, recruiter_email, OUTREACH_COST, "Outreach", f"To: {talent_email}")
|
| 223 |
-
if not dr.get("success"): return {"success":False,"error":dr.get("error","Gagal potong koin.")}
|
| 224 |
-
import uuid; now = datetime.now(timezone.utc)
|
| 225 |
-
oid = f"RO-{secrets.randbelow(89999) + 10001}"
|
| 226 |
-
o = RecruiterOutreach(id=uuid.uuid4(), outreach_id=oid, job_id=job_id,
|
| 227 |
-
talent_email=talent_email, match_score=match_score, recruiter_email=recruiter_email,
|
| 228 |
-
contact_method=method, outreach_subject=subject, outreach_body=body,
|
| 229 |
-
status="sent", triggered_at=now, sent_at=now)
|
| 230 |
-
db.add(o); await db.commit()
|
| 231 |
-
return {"success":True,"outreach_id":oid,"remaining":dr.get("remaining",0)}
|
| 232 |
-
except Exception as e:
|
| 233 |
-
logger.error(f"send_outreach error: {e}")
|
| 234 |
-
return {"success":False,"error":str(e)}
|
| 235 |
-
|
| 236 |
-
async def list_outreach_history(db, recruiter_email):
|
| 237 |
-
try:
|
| 238 |
-
r = await db.execute(select(RecruiterOutreach).where(func.lower(RecruiterOutreach.recruiter_email)==recruiter_email.lower().strip()).order_by(RecruiterOutreach.triggered_at.desc()).limit(50))
|
| 239 |
-
return {"success":True,"data":[{"outreach_id":x.outreach_id,"job_id":x.job_id,"talent_email":x.talent_email,"match_score":x.match_score,"status":x.status,"triggered_at":x.triggered_at.isoformat() if x.triggered_at else None,"sent_at":x.sent_at.isoformat() if x.sent_at else None} for x in list(r.scalars().all())]}
|
| 240 |
-
except Exception as e:
|
| 241 |
-
logger.error(f"outreach_history error: {e}")
|
| 242 |
-
return {"success":False,"error":str(e),"data":[]}
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
async def generate_vouchers(db, lpk_id, quantity):
|
| 247 |
-
CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
| 248 |
-
try:
|
| 249 |
-
qty = max(1, min(100, int(quantity)))
|
| 250 |
-
now = datetime.now(timezone.utc); codes = []
|
| 251 |
-
for _ in range(qty):
|
| 252 |
-
code = "BRG-LPK-" + "".join(CHARS[secrets.randbelow(36)] for _ in range(8))
|
| 253 |
-
import uuid
|
| 254 |
-
db.add(RecruiterOutreach(id=uuid.uuid4(), outreach_id=code, recruiter_email=lpk_id, contact_method="voucher", status="Available", triggered_at=now))
|
| 255 |
-
codes.append(code)
|
| 256 |
-
await db.commit()
|
| 257 |
-
return {"success":True,"message":f"{qty} voucher berhasil dibuat.","vouchers":codes,"count":qty}
|
| 258 |
-
except Exception as e:
|
| 259 |
-
logger.error(f"generate_vouchers error: {e}")
|
| 260 |
-
return {"success":False,"error":str(e)}
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
async def redeem_voucher(db, email, candidate_email, voucher_code):
|
| 264 |
-
try:
|
| 265 |
-
if email.lower().strip() != candidate_email.lower().strip(): return {"success":False,"error":"Email tidak cocok."}
|
| 266 |
-
code = voucher_code.upper().strip()
|
| 267 |
-
r = await db.execute(select(RecruiterOutreach).where(RecruiterOutreach.outreach_id==code,RecruiterOutreach.status=="Available").limit(1))
|
| 268 |
-
v = r.scalar_one_or_none()
|
| 269 |
-
if not v: return {"success":False,"error":"Voucher tidak valid."}
|
| 270 |
-
lpk_id = v.recruiter_email; now = datetime.now(timezone.utc)
|
| 271 |
-
v.status,v.talent_email,v.sent_at = "Used",candidate_email.lower().strip(),now
|
| 272 |
-
db.add(v); await db.commit()
|
| 273 |
-
return {"success":True,"message":"Voucher berhasil diaktifkan.","lpk_id":lpk_id,"voucher_code":code}
|
| 274 |
-
except Exception as e:
|
| 275 |
-
logger.error(f"redeem_voucher error: {e}")
|
| 276 |
-
return {"success":False,"error":str(e)}
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
async def get_lpk_vouchers(db, lpk_id):
|
| 280 |
-
try:
|
| 281 |
-
r = await db.execute(select(RecruiterOutreach).where(RecruiterOutreach.recruiter_email==lpk_id,RecruiterOutreach.contact_method=="voucher").order_by(RecruiterOutreach.triggered_at.desc()))
|
| 282 |
-
vouchers = list(r.scalars().all())
|
| 283 |
-
avail = sum(1 for v in vouchers if v.status=="Available")
|
| 284 |
-
used = sum(1 for v in vouchers if v.status=="Used")
|
| 285 |
-
return {"success":True,"vouchers":[{"voucher_id":v.outreach_id,"lpk_id":v.recruiter_email,"candidate_email":v.talent_email or "","status":v.status,"date_generated":v.triggered_at.isoformat() if v.triggered_at else None,"date_used":v.sent_at.isoformat() if v.sent_at and v.status=="Used" else None} for v in vouchers],"counts":{"Available":avail,"Used":used,"Total":len(vouchers)}}
|
| 286 |
-
except Exception as e:
|
| 287 |
-
logger.error(f"get_lpk_vouchers error: {e}")
|
| 288 |
-
return {"success":False,"error":str(e),"vouchers":[],"counts":{"Available":0,"Used":0,"Total":0}}
|
|
|
|
| 1 |
+
"""Job Service - Posting CRUD, Outreach, Compatibility, Limits, Vouchers."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import secrets
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
|
| 7 |
+
from loguru import logger
|
| 8 |
+
from sqlalchemy import func, select
|
| 9 |
+
|
| 10 |
+
from app.models.job import JobPosting, RecruiterOutreach
|
| 11 |
+
from app.models.employer import ClientAccount, Company
|
| 12 |
+
from app.services.talent_service import get_talent_profile
|
| 13 |
+
from app.config.settings import FINANCE_CONFIG
|
| 14 |
+
from app.services.ai_service import call_medium
|
| 15 |
+
|
| 16 |
+
TIERS = FINANCE_CONFIG.get("TIERS", {})
|
| 17 |
+
OUTREACH_COST = FINANCE_CONFIG.get("DEDUCTION", {}).get("DIRECT_OUTREACH", 10)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _sanitize(val, max_len=500):
|
| 21 |
+
if val is None:
|
| 22 |
+
return ""
|
| 23 |
+
return str(val).replace("<", "").replace(">", "").strip()[:max_len]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
async def get_job_posting(db, job_id):
|
| 27 |
+
|
| 28 |
+
"""Get single job posting (public-safe)."""
|
| 29 |
+
try:
|
| 30 |
+
if not job_id:
|
| 31 |
+
return {"success": False, "error": "JobID tidak boleh kosong."}
|
| 32 |
+
r = await db.execute(select(JobPosting).where(JobPosting.job_id == job_id).limit(1))
|
| 33 |
+
job = r.scalar_one_or_none()
|
| 34 |
+
if not job:
|
| 35 |
+
return {"success": False, "error": "Lowongan tidak ditemukan."}
|
| 36 |
+
skills = [s.strip() for s in (job.required_skills or "").split(",") if s.strip()]
|
| 37 |
+
return {"success": True, "data": {
|
| 38 |
+
"job_id": job.job_id, "title": job.title or "",
|
| 39 |
+
"company_category": job.company_category or "Sustainability Sector",
|
| 40 |
+
"location": job.location or "", "description": job.description or "",
|
| 41 |
+
"required_skills": skills,
|
| 42 |
+
"salary_range": job.salary_range or "Negotiable",
|
| 43 |
+
"source": job.source or "", "status": job.status or "",
|
| 44 |
+
"sector_match": job.sector_match or "",
|
| 45 |
+
"linkedin_post_url": job.linkedin_post_url or "",
|
| 46 |
+
"timestamp": job.timestamp.isoformat() if job.timestamp else None,
|
| 47 |
+
"posted_at": job.posted_at.isoformat() if job.posted_at else None,
|
| 48 |
+
}}
|
| 49 |
+
except Exception as e:
|
| 50 |
+
logger.error(f"get_job_posting error: {e}")
|
| 51 |
+
return {"success": False, "error": str(e)}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
async def create_job_posting(db, employer_email, data):
|
| 56 |
+
try:
|
| 57 |
+
lc = await check_active_job_posting_limit(db, employer_email)
|
| 58 |
+
if not lc.get("allowed"): return lc
|
| 59 |
+
import uuid
|
| 60 |
+
job_id = "JOB-" + secrets.token_hex(4).upper()
|
| 61 |
+
now = datetime.now(timezone.utc)
|
| 62 |
+
p = JobPosting(id=uuid.uuid4(), job_id=job_id,
|
| 63 |
+
title=_sanitize(data.get("title",""),255), company_name=employer_email,
|
| 64 |
+
company_category=_sanitize(data.get("company_category",""),255),
|
| 65 |
+
location=_sanitize(data.get("location",""),255),
|
| 66 |
+
description=_sanitize(data.get("description",""),10000),
|
| 67 |
+
required_skills=_sanitize(data.get("required_skills",""),1000),
|
| 68 |
+
salary_range=_sanitize(data.get("salary_range","Negotiable"),100),
|
| 69 |
+
sector_match=_sanitize(data.get("sector_match",""),255),
|
| 70 |
+
linkedin_post_url=_sanitize(data.get("linkedin_post_url",""),500),
|
| 71 |
+
source="Employer Posting", status="posted", posted_at=now, timestamp=now, is_active=True)
|
| 72 |
+
db.add(p); await db.commit()
|
| 73 |
+
return {"success":True,"job_id":job_id,"message":"Lowongan berhasil dipublikasikan."}
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"create_job_posting error: {e}")
|
| 76 |
+
return {"success":False,"error":str(e)}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
async def get_job_postings(db, page=1, limit=10):
|
| 81 |
+
try:
|
| 82 |
+
p, lim = max(1, int(page)), max(1, min(50, int(limit)))
|
| 83 |
+
r = await db.execute(
|
| 84 |
+
select(JobPosting).where(JobPosting.status.in_(["posted", "analyzed"]))
|
| 85 |
+
.order_by(JobPosting.timestamp.desc()).offset((p-1)*lim).limit(lim)
|
| 86 |
+
)
|
| 87 |
+
jobs = list(r.scalars().all())
|
| 88 |
+
tr = await db.execute(select(func.count()).select_from(JobPosting).where(JobPosting.status.in_(["posted", "analyzed"])))
|
| 89 |
+
total = tr.scalar() or 0
|
| 90 |
+
return {"success": True, "page": p, "limit": lim, "total": total, "data": [
|
| 91 |
+
{"job_id": j.job_id, "title": j.title,
|
| 92 |
+
"company_category": j.company_category or "Sustainability Sector",
|
| 93 |
+
"location": j.location,
|
| 94 |
+
"description": (j.description or "")[:200] + "..." if j.description and len(j.description) > 200 else (j.description or ""),
|
| 95 |
+
"required_skills": [s.strip() for s in (j.required_skills or "").split(",") if s.strip()],
|
| 96 |
+
"salary_range": j.salary_range or "Negotiable",
|
| 97 |
+
"status": j.status, "sector_match": j.sector_match or "",
|
| 98 |
+
"timestamp": j.timestamp.isoformat() if j.timestamp else None}
|
| 99 |
+
for j in jobs
|
| 100 |
+
]}
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"get_job_postings error: {e}")
|
| 103 |
+
return {"success": False, "error": str(e), "data": []}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
async def update_job_status(db, job_id, status):
|
| 108 |
+
try:
|
| 109 |
+
r = await db.execute(select(JobPosting).where(JobPosting.job_id==job_id).limit(1))
|
| 110 |
+
job = r.scalar_one_or_none()
|
| 111 |
+
if not job: return {"success":False,"error":"Lowongan tidak ditemukan."}
|
| 112 |
+
valid = ["draft","posted","closed","archived"]
|
| 113 |
+
if status not in valid: return {"success":False,"error":f"Status invalid. Use: {', '.join(valid)}"}
|
| 114 |
+
job.status=status; job.is_active=(status=="posted")
|
| 115 |
+
db.add(job); await db.commit()
|
| 116 |
+
return {"success":True,"message":f"Status diubah menjadi {status}."}
|
| 117 |
+
except Exception as e:
|
| 118 |
+
logger.error(f"update_job_status error: {e}")
|
| 119 |
+
return {"success":False,"error":str(e)}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
async def check_active_job_posting_limit(db, employer_email):
|
| 123 |
+
try:
|
| 124 |
+
e = employer_email.lower().strip()
|
| 125 |
+
cr = await db.execute(select(ClientAccount).where(func.lower(ClientAccount.email)==e).limit(1))
|
| 126 |
+
client = cr.scalar_one_or_none()
|
| 127 |
+
tier_name = "free"
|
| 128 |
+
if client and client.company_id:
|
| 129 |
+
cor = await db.execute(select(Company).where(Company.id==client.company_id).limit(1))
|
| 130 |
+
co = cor.scalar_one_or_none()
|
| 131 |
+
if co: tier_name = (co.tier or "free").lower()
|
| 132 |
+
tier = TIERS.get(tier_name, TIERS.get("free",{}))
|
| 133 |
+
max_jobs = tier.get("max_jobs", 1) if isinstance(tier,dict) else 1
|
| 134 |
+
if max_jobs == -1: return {"allowed":True,"tier":tier_name,"active_count":0,"limit":-1}
|
| 135 |
+
nr = await db.execute(select(func.count()).select_from(JobPosting).where(JobPosting.company_name==e,JobPosting.status.in_(["posted","analyzed"])))
|
| 136 |
+
active = nr.scalar() or 0
|
| 137 |
+
if active >= max_jobs: return {"allowed":False,"tier":tier_name,"active_count":active,"limit":max_jobs,"error":f"Batas posting ({max_jobs}) tercapai. Upgrade paket."}
|
| 138 |
+
return {"allowed":True,"tier":tier_name,"active_count":active,"limit":max_jobs}
|
| 139 |
+
except Exception as e:
|
| 140 |
+
logger.error(f"check_job_limit error: {e}")
|
| 141 |
+
return {"allowed":True,"tier":"free","active_count":0,"limit":1}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
async def analyze_job_compatibility(db, email, job_id):
|
| 146 |
+
"""Refactored: Uses Antigravity gateway for semantic matching."""
|
| 147 |
+
try:
|
| 148 |
+
if not email or not job_id:
|
| 149 |
+
return {"success": False, "error": "Parameter tidak lengkap."}
|
| 150 |
+
|
| 151 |
+
e = email.lower().strip()
|
| 152 |
+
pr = await get_talent_profile(db, e)
|
| 153 |
+
if not pr.get("success"):
|
| 154 |
+
return {"success": False, "error": "Gagal memuat profil talent."}
|
| 155 |
+
p = pr["data"]
|
| 156 |
+
|
| 157 |
+
jr = await get_job_posting(db, job_id)
|
| 158 |
+
if not jr.get("success"):
|
| 159 |
+
return {"success": False, "error": "Gagal memuat pekerjaan."}
|
| 160 |
+
j = jr["data"]
|
| 161 |
+
|
| 162 |
+
# Use Antigravity Orchestrator
|
| 163 |
+
from app.services.antigravity import AntigravityOrchestrator
|
| 164 |
+
orchestrator = AntigravityOrchestrator(db)
|
| 165 |
+
|
| 166 |
+
payload = {
|
| 167 |
+
"query": j.get("title", ""),
|
| 168 |
+
"talent_data": {
|
| 169 |
+
"skill_tags": ",".join(p.get("skills", [])),
|
| 170 |
+
"experience": p.get("experience", ""),
|
| 171 |
+
"sector_focus": p.get("sector_focus", ""),
|
| 172 |
+
"location": p.get("location", "")
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
res = await orchestrator.execute_task(
|
| 177 |
+
agent_name="RecruiterStrategicAdvisor",
|
| 178 |
+
task_name="semantic_matching",
|
| 179 |
+
payload=payload,
|
| 180 |
+
user_email=email
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
if res.get("status") == "success":
|
| 184 |
+
data = res["data"]
|
| 185 |
+
return {
|
| 186 |
+
"success": True,
|
| 187 |
+
"data": {
|
| 188 |
+
"matchScore": data.get("score", 0),
|
| 189 |
+
"matchedSkills": [], # Will be implemented in Pro prompt refinement
|
| 190 |
+
"gapSkills": [],
|
| 191 |
+
"strategy": data.get("summary", ""),
|
| 192 |
+
"ai_used": data.get("ai_used", True)
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
return {"success": False, "error": "AI processing failed"}
|
| 197 |
+
|
| 198 |
+
except Exception as e:
|
| 199 |
+
logger.error(f"analyze_job error: {e}")
|
| 200 |
+
return {"success": False, "error": str(e)}
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
async def record_pending_outreach(db, job_id, talent_email, match_score, recruiter_email, method, subject, body):
|
| 205 |
+
try:
|
| 206 |
+
import uuid
|
| 207 |
+
oid = f"RO-{secrets.randbelow(89999) + 10001}"
|
| 208 |
+
o = RecruiterOutreach(id=uuid.uuid4(), outreach_id=oid, job_id=job_id,
|
| 209 |
+
talent_email=talent_email, match_score=match_score, recruiter_email=recruiter_email,
|
| 210 |
+
contact_method=method, outreach_subject=subject, outreach_body=body,
|
| 211 |
+
status="pending_approval", triggered_at=datetime.now(timezone.utc))
|
| 212 |
+
db.add(o); await db.commit()
|
| 213 |
+
return {"success":True,"outreach_id":oid}
|
| 214 |
+
except Exception as e:
|
| 215 |
+
logger.error(f"record_outreach error: {e}")
|
| 216 |
+
return {"success":False,"error":str(e)}
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
async def send_instant_outreach(db, recruiter_email, job_id, talent_email, match_score, method, subject, body):
|
| 220 |
+
try:
|
| 221 |
+
from app.services.employer_service import deduct_coins
|
| 222 |
+
dr = await deduct_coins(db, recruiter_email, OUTREACH_COST, "Outreach", f"To: {talent_email}")
|
| 223 |
+
if not dr.get("success"): return {"success":False,"error":dr.get("error","Gagal potong koin.")}
|
| 224 |
+
import uuid; now = datetime.now(timezone.utc)
|
| 225 |
+
oid = f"RO-{secrets.randbelow(89999) + 10001}"
|
| 226 |
+
o = RecruiterOutreach(id=uuid.uuid4(), outreach_id=oid, job_id=job_id,
|
| 227 |
+
talent_email=talent_email, match_score=match_score, recruiter_email=recruiter_email,
|
| 228 |
+
contact_method=method, outreach_subject=subject, outreach_body=body,
|
| 229 |
+
status="sent", triggered_at=now, sent_at=now)
|
| 230 |
+
db.add(o); await db.commit()
|
| 231 |
+
return {"success":True,"outreach_id":oid,"remaining":dr.get("remaining",0)}
|
| 232 |
+
except Exception as e:
|
| 233 |
+
logger.error(f"send_outreach error: {e}")
|
| 234 |
+
return {"success":False,"error":str(e)}
|
| 235 |
+
|
| 236 |
+
async def list_outreach_history(db, recruiter_email):
|
| 237 |
+
try:
|
| 238 |
+
r = await db.execute(select(RecruiterOutreach).where(func.lower(RecruiterOutreach.recruiter_email)==recruiter_email.lower().strip()).order_by(RecruiterOutreach.triggered_at.desc()).limit(50))
|
| 239 |
+
return {"success":True,"data":[{"outreach_id":x.outreach_id,"job_id":x.job_id,"talent_email":x.talent_email,"match_score":x.match_score,"status":x.status,"triggered_at":x.triggered_at.isoformat() if x.triggered_at else None,"sent_at":x.sent_at.isoformat() if x.sent_at else None} for x in list(r.scalars().all())]}
|
| 240 |
+
except Exception as e:
|
| 241 |
+
logger.error(f"outreach_history error: {e}")
|
| 242 |
+
return {"success":False,"error":str(e),"data":[]}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
async def generate_vouchers(db, lpk_id, quantity):
|
| 247 |
+
CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
| 248 |
+
try:
|
| 249 |
+
qty = max(1, min(100, int(quantity)))
|
| 250 |
+
now = datetime.now(timezone.utc); codes = []
|
| 251 |
+
for _ in range(qty):
|
| 252 |
+
code = "BRG-LPK-" + "".join(CHARS[secrets.randbelow(36)] for _ in range(8))
|
| 253 |
+
import uuid
|
| 254 |
+
db.add(RecruiterOutreach(id=uuid.uuid4(), outreach_id=code, recruiter_email=lpk_id, contact_method="voucher", status="Available", triggered_at=now))
|
| 255 |
+
codes.append(code)
|
| 256 |
+
await db.commit()
|
| 257 |
+
return {"success":True,"message":f"{qty} voucher berhasil dibuat.","vouchers":codes,"count":qty}
|
| 258 |
+
except Exception as e:
|
| 259 |
+
logger.error(f"generate_vouchers error: {e}")
|
| 260 |
+
return {"success":False,"error":str(e)}
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
async def redeem_voucher(db, email, candidate_email, voucher_code):
|
| 264 |
+
try:
|
| 265 |
+
if email.lower().strip() != candidate_email.lower().strip(): return {"success":False,"error":"Email tidak cocok."}
|
| 266 |
+
code = voucher_code.upper().strip()
|
| 267 |
+
r = await db.execute(select(RecruiterOutreach).where(RecruiterOutreach.outreach_id==code,RecruiterOutreach.status=="Available").limit(1))
|
| 268 |
+
v = r.scalar_one_or_none()
|
| 269 |
+
if not v: return {"success":False,"error":"Voucher tidak valid."}
|
| 270 |
+
lpk_id = v.recruiter_email; now = datetime.now(timezone.utc)
|
| 271 |
+
v.status,v.talent_email,v.sent_at = "Used",candidate_email.lower().strip(),now
|
| 272 |
+
db.add(v); await db.commit()
|
| 273 |
+
return {"success":True,"message":"Voucher berhasil diaktifkan.","lpk_id":lpk_id,"voucher_code":code}
|
| 274 |
+
except Exception as e:
|
| 275 |
+
logger.error(f"redeem_voucher error: {e}")
|
| 276 |
+
return {"success":False,"error":str(e)}
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
async def get_lpk_vouchers(db, lpk_id):
|
| 280 |
+
try:
|
| 281 |
+
r = await db.execute(select(RecruiterOutreach).where(RecruiterOutreach.recruiter_email==lpk_id,RecruiterOutreach.contact_method=="voucher").order_by(RecruiterOutreach.triggered_at.desc()))
|
| 282 |
+
vouchers = list(r.scalars().all())
|
| 283 |
+
avail = sum(1 for v in vouchers if v.status=="Available")
|
| 284 |
+
used = sum(1 for v in vouchers if v.status=="Used")
|
| 285 |
+
return {"success":True,"vouchers":[{"voucher_id":v.outreach_id,"lpk_id":v.recruiter_email,"candidate_email":v.talent_email or "","status":v.status,"date_generated":v.triggered_at.isoformat() if v.triggered_at else None,"date_used":v.sent_at.isoformat() if v.sent_at and v.status=="Used" else None} for v in vouchers],"counts":{"Available":avail,"Used":used,"Total":len(vouchers)}}
|
| 286 |
+
except Exception as e:
|
| 287 |
+
logger.error(f"get_lpk_vouchers error: {e}")
|
| 288 |
+
return {"success":False,"error":str(e),"vouchers":[],"counts":{"Available":0,"Used":0,"Total":0}}
|
app/services/kms_service.py
CHANGED
|
@@ -1,82 +1,82 @@
|
|
| 1 |
-
"""KMS Service for Key Encryption Key (KEK) management.
|
| 2 |
-
|
| 3 |
-
Provides an abstraction for Google Cloud KMS to encrypt/decrypt profile DEKs.
|
| 4 |
-
Supports local fallback for development environments.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import base64
|
| 8 |
-
import os
|
| 9 |
-
from typing import Optional
|
| 10 |
-
from loguru import logger
|
| 11 |
-
|
| 12 |
-
from app.config.settings import settings
|
| 13 |
-
|
| 14 |
-
try:
|
| 15 |
-
from google.cloud import kms
|
| 16 |
-
GCP_KMS_AVAILABLE = True
|
| 17 |
-
except ImportError:
|
| 18 |
-
GCP_KMS_AVAILABLE = False
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
class KMSService:
|
| 22 |
-
"""Service to interact with Google Cloud KMS or local simulation."""
|
| 23 |
-
|
| 24 |
-
def __init__(self):
|
| 25 |
-
self.project_id = settings.gcp_project_id
|
| 26 |
-
self.location_id = settings.gcp_kms_location
|
| 27 |
-
self.key_ring_id = settings.gcp_kms_key_ring
|
| 28 |
-
self.key_id = settings.gcp_kms_key_id
|
| 29 |
-
|
| 30 |
-
# Local fallback key
|
| 31 |
-
self.local_master_key = settings.master_encryption_key.encode("utf-8")[:32]
|
| 32 |
-
|
| 33 |
-
self.client = None
|
| 34 |
-
if GCP_KMS_AVAILABLE and self.project_id:
|
| 35 |
-
try:
|
| 36 |
-
self.client = kms.KeyManagementServiceClient()
|
| 37 |
-
self.key_name = self.client.encrypt_path(
|
| 38 |
-
self.project_id, self.location_id, self.key_ring_id, self.key_id
|
| 39 |
-
)
|
| 40 |
-
logger.info(f"KMS Service initialized with GCP KMS: {self.key_name}")
|
| 41 |
-
except Exception as e:
|
| 42 |
-
logger.warning(f"Failed to initialize GCP KMS client: {e}. Falling back to local.")
|
| 43 |
-
else:
|
| 44 |
-
logger.info("KMS Service using local simulation (dev mode).")
|
| 45 |
-
|
| 46 |
-
def encrypt_dek(self, plaintext_dek: str) -> str:
|
| 47 |
-
"""Encrypt a profile's Data Encryption Key (DEK)."""
|
| 48 |
-
if self.client and self.project_id:
|
| 49 |
-
try:
|
| 50 |
-
response = self.client.encrypt(
|
| 51 |
-
request={"name": self.key_name, "plaintext": plaintext_dek.encode("utf-8")}
|
| 52 |
-
)
|
| 53 |
-
return base64.b64encode(response.ciphertext).decode("utf-8")
|
| 54 |
-
except Exception as e:
|
| 55 |
-
logger.error(f"GCP KMS encryption failed: {e}")
|
| 56 |
-
raise
|
| 57 |
-
|
| 58 |
-
# Local simulation (AES-256-CBC)
|
| 59 |
-
from app.services.security_service import SecurityService
|
| 60 |
-
sim = SecurityService()
|
| 61 |
-
return sim._encrypt_with_dek(self.local_master_key, plaintext_dek)
|
| 62 |
-
|
| 63 |
-
def decrypt_dek(self, encrypted_dek: str) -> str:
|
| 64 |
-
"""Decrypt a profile's Data Encryption Key (DEK)."""
|
| 65 |
-
if self.client and self.project_id:
|
| 66 |
-
try:
|
| 67 |
-
ciphertext = base64.b64decode(encrypted_dek)
|
| 68 |
-
response = self.client.decrypt(
|
| 69 |
-
request={"name": self.key_name, "ciphertext": ciphertext}
|
| 70 |
-
)
|
| 71 |
-
return response.plaintext.decode("utf-8")
|
| 72 |
-
except Exception as e:
|
| 73 |
-
logger.error(f"GCP KMS decryption failed: {e}")
|
| 74 |
-
raise
|
| 75 |
-
|
| 76 |
-
# Local simulation
|
| 77 |
-
from app.services.security_service import SecurityService
|
| 78 |
-
sim = SecurityService()
|
| 79 |
-
return sim._decrypt_with_dek(self.local_master_key, encrypted_dek)
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
kms_service = KMSService()
|
|
|
|
| 1 |
+
"""KMS Service for Key Encryption Key (KEK) management.
|
| 2 |
+
|
| 3 |
+
Provides an abstraction for Google Cloud KMS to encrypt/decrypt profile DEKs.
|
| 4 |
+
Supports local fallback for development environments.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import base64
|
| 8 |
+
import os
|
| 9 |
+
from typing import Optional
|
| 10 |
+
from loguru import logger
|
| 11 |
+
|
| 12 |
+
from app.config.settings import settings
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
from google.cloud import kms
|
| 16 |
+
GCP_KMS_AVAILABLE = True
|
| 17 |
+
except ImportError:
|
| 18 |
+
GCP_KMS_AVAILABLE = False
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class KMSService:
|
| 22 |
+
"""Service to interact with Google Cloud KMS or local simulation."""
|
| 23 |
+
|
| 24 |
+
def __init__(self):
|
| 25 |
+
self.project_id = settings.gcp_project_id
|
| 26 |
+
self.location_id = settings.gcp_kms_location
|
| 27 |
+
self.key_ring_id = settings.gcp_kms_key_ring
|
| 28 |
+
self.key_id = settings.gcp_kms_key_id
|
| 29 |
+
|
| 30 |
+
# Local fallback key
|
| 31 |
+
self.local_master_key = settings.master_encryption_key.encode("utf-8")[:32]
|
| 32 |
+
|
| 33 |
+
self.client = None
|
| 34 |
+
if GCP_KMS_AVAILABLE and self.project_id:
|
| 35 |
+
try:
|
| 36 |
+
self.client = kms.KeyManagementServiceClient()
|
| 37 |
+
self.key_name = self.client.encrypt_path(
|
| 38 |
+
self.project_id, self.location_id, self.key_ring_id, self.key_id
|
| 39 |
+
)
|
| 40 |
+
logger.info(f"KMS Service initialized with GCP KMS: {self.key_name}")
|
| 41 |
+
except Exception as e:
|
| 42 |
+
logger.warning(f"Failed to initialize GCP KMS client: {e}. Falling back to local.")
|
| 43 |
+
else:
|
| 44 |
+
logger.info("KMS Service using local simulation (dev mode).")
|
| 45 |
+
|
| 46 |
+
def encrypt_dek(self, plaintext_dek: str) -> str:
|
| 47 |
+
"""Encrypt a profile's Data Encryption Key (DEK)."""
|
| 48 |
+
if self.client and self.project_id:
|
| 49 |
+
try:
|
| 50 |
+
response = self.client.encrypt(
|
| 51 |
+
request={"name": self.key_name, "plaintext": plaintext_dek.encode("utf-8")}
|
| 52 |
+
)
|
| 53 |
+
return base64.b64encode(response.ciphertext).decode("utf-8")
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.error(f"GCP KMS encryption failed: {e}")
|
| 56 |
+
raise
|
| 57 |
+
|
| 58 |
+
# Local simulation (AES-256-CBC)
|
| 59 |
+
from app.services.security_service import SecurityService
|
| 60 |
+
sim = SecurityService()
|
| 61 |
+
return sim._encrypt_with_dek(self.local_master_key, plaintext_dek)
|
| 62 |
+
|
| 63 |
+
def decrypt_dek(self, encrypted_dek: str) -> str:
|
| 64 |
+
"""Decrypt a profile's Data Encryption Key (DEK)."""
|
| 65 |
+
if self.client and self.project_id:
|
| 66 |
+
try:
|
| 67 |
+
ciphertext = base64.b64decode(encrypted_dek)
|
| 68 |
+
response = self.client.decrypt(
|
| 69 |
+
request={"name": self.key_name, "ciphertext": ciphertext}
|
| 70 |
+
)
|
| 71 |
+
return response.plaintext.decode("utf-8")
|
| 72 |
+
except Exception as e:
|
| 73 |
+
logger.error(f"GCP KMS decryption failed: {e}")
|
| 74 |
+
raise
|
| 75 |
+
|
| 76 |
+
# Local simulation
|
| 77 |
+
from app.services.security_service import SecurityService
|
| 78 |
+
sim = SecurityService()
|
| 79 |
+
return sim._decrypt_with_dek(self.local_master_key, encrypted_dek)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
kms_service = KMSService()
|