diff --git a/app/api/academy.py b/app/api/academy.py
index f94c60da4a6614291bc79f0f067de562b13e5b06..e627855b787de5c050212cef90a281ef81e2b167 100644
--- a/app/api/academy.py
+++ b/app/api/academy.py
@@ -1,94 +1,94 @@
-"""Academy API Routes."""
-from fastapi import APIRouter, Depends, Request
-from pydantic import BaseModel
-from sqlalchemy.ext.asyncio import AsyncSession
-from app.database import get_db
-from app.services.academy_email_service import AcademyEmailService
-router = APIRouter(prefix="/v1/academy", tags=["Academy"])
-_service = None
-def get_svc():
- global _service
- if _service is None:
- _service = AcademyEmailService()
- return _service
-class FeedbackReq(BaseModel):
- email: str | None = None # Optional: if admin wants to trigger for specific talent
-@router.post("/feedback")
-async def trigger_feedback(req: Request, body: FeedbackReq, db: AsyncSession = Depends(get_db)):
- target = body.email or getattr(req.state, "user_email", None)
- if not target:
- return {"success": False, "error": "Email atau autentikasi diperlukan"}
- return await get_svc().process_academy_feedback(db=db, email=target)
-@router.post("/feedback/bulk")
-async def trigger_bulk_feedback(req: Request, db: AsyncSession = Depends(get_db)):
- email = getattr(req.state, "user_email", None)
- role = getattr(req.state, "user_role", None)
- if not email or role != "admin":
- return {"success": False, "error": "Admin access required"}
- return await get_svc().process_bulk_academy_feedback(db=db, limit=50)
-
-
-@router.get("/leads")
-async def get_academy_leads(db: AsyncSession = Depends(get_db)):
- """
- Fetch all scraped LPK partnership leads (Admin only).
- """
- from sqlalchemy import text
- 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")
- res = await db.execute(query)
- rows = res.fetchall()
-
- leads = []
- for row in rows:
- leads.append({
- "id": str(row.id),
- "name": row.name,
- "course_title": row.course_title,
- "syllabus_text": row.syllabus_text,
- "matched_skills": row.matched_skills,
- "similarity_score": row.similarity_score,
- "contact_email": row.contact_email,
- "status": row.status,
- "created_at": row.created_at.isoformat() if row.created_at else None
- })
- return {"success": True, "data": leads}
-
-
-class ContactLeadRequest(BaseModel):
- subject: str
- body: str
-
-
-@router.post("/leads/{lead_id}/contact")
-async def contact_academy_lead(lead_id: str, body: ContactLeadRequest, db: AsyncSession = Depends(get_db)):
- """
- Send an outreach email proposal to the LPK partner and set status to 'contacted'.
- """
- from sqlalchemy import text
- query = text("SELECT id, name, contact_email, status FROM academy_leads WHERE id = :id")
- res = await db.execute(query, {"id": lead_id})
- lead = res.fetchone()
- if not lead:
- return {"success": False, "error": "Lead tidak ditemukan"}
-
- if lead.status == "contacted":
- return {"success": False, "error": "Outreach proposal sudah dikirim sebelumnya"}
-
- from app.services.email_service import email_service
- import asyncio
-
- success = await asyncio.to_thread(
- email_service.send_html_email,
- lead.contact_email,
- body.subject,
- body.body
- )
-
- if success:
- update_query = text("UPDATE academy_leads SET status = 'contacted', updated_at = now() WHERE id = :id")
- await db.execute(update_query, {"id": lead_id})
- await db.commit()
- return {"success": True, "message": "Email outreach berhasil dikirim"}
-
- return {"success": False, "error": "Gagal mengirim email via SMTP"}
-
+"""Academy API Routes."""
+from fastapi import APIRouter, Depends, Request
+from pydantic import BaseModel
+from sqlalchemy.ext.asyncio import AsyncSession
+from app.database import get_db
+from app.services.academy_email_service import AcademyEmailService
+router = APIRouter(prefix="/v1/academy", tags=["Academy"])
+_service = None
+def get_svc():
+ global _service
+ if _service is None:
+ _service = AcademyEmailService()
+ return _service
+class FeedbackReq(BaseModel):
+ email: str | None = None # Optional: if admin wants to trigger for specific talent
+@router.post("/feedback")
+async def trigger_feedback(req: Request, body: FeedbackReq, db: AsyncSession = Depends(get_db)):
+ target = body.email or getattr(req.state, "user_email", None)
+ if not target:
+ return {"success": False, "error": "Email atau autentikasi diperlukan"}
+ return await get_svc().process_academy_feedback(db=db, email=target)
+@router.post("/feedback/bulk")
+async def trigger_bulk_feedback(req: Request, db: AsyncSession = Depends(get_db)):
+ email = getattr(req.state, "user_email", None)
+ role = getattr(req.state, "user_role", None)
+ if not email or role != "admin":
+ return {"success": False, "error": "Admin access required"}
+ return await get_svc().process_bulk_academy_feedback(db=db, limit=50)
+
+
+@router.get("/leads")
+async def get_academy_leads(db: AsyncSession = Depends(get_db)):
+ """
+ Fetch all scraped LPK partnership leads (Admin only).
+ """
+ from sqlalchemy import text
+ 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")
+ res = await db.execute(query)
+ rows = res.fetchall()
+
+ leads = []
+ for row in rows:
+ leads.append({
+ "id": str(row.id),
+ "name": row.name,
+ "course_title": row.course_title,
+ "syllabus_text": row.syllabus_text,
+ "matched_skills": row.matched_skills,
+ "similarity_score": row.similarity_score,
+ "contact_email": row.contact_email,
+ "status": row.status,
+ "created_at": row.created_at.isoformat() if row.created_at else None
+ })
+ return {"success": True, "data": leads}
+
+
+class ContactLeadRequest(BaseModel):
+ subject: str
+ body: str
+
+
+@router.post("/leads/{lead_id}/contact")
+async def contact_academy_lead(lead_id: str, body: ContactLeadRequest, db: AsyncSession = Depends(get_db)):
+ """
+ Send an outreach email proposal to the LPK partner and set status to 'contacted'.
+ """
+ from sqlalchemy import text
+ query = text("SELECT id, name, contact_email, status FROM academy_leads WHERE id = :id")
+ res = await db.execute(query, {"id": lead_id})
+ lead = res.fetchone()
+ if not lead:
+ return {"success": False, "error": "Lead tidak ditemukan"}
+
+ if lead.status == "contacted":
+ return {"success": False, "error": "Outreach proposal sudah dikirim sebelumnya"}
+
+ from app.services.email_service import email_service
+ import asyncio
+
+ success = await asyncio.to_thread(
+ email_service.send_html_email,
+ lead.contact_email,
+ body.subject,
+ body.body
+ )
+
+ if success:
+ update_query = text("UPDATE academy_leads SET status = 'contacted', updated_at = now() WHERE id = :id")
+ await db.execute(update_query, {"id": lead_id})
+ await db.commit()
+ return {"success": True, "message": "Email outreach berhasil dikirim"}
+
+ return {"success": False, "error": "Gagal mengirim email via SMTP"}
+
diff --git a/app/api/admin.py b/app/api/admin.py
index 20a6cc34c86fa15c9a0a56b6834a30ddda7c54eb..3c2e8952673ad4201e73f433a868b5f20953c9f7 100644
--- a/app/api/admin.py
+++ b/app/api/admin.py
@@ -1,92 +1,92 @@
-from fastapi import APIRouter, Depends, Request, HTTPException
-from sqlalchemy.ext.asyncio import AsyncSession
-from sqlalchemy import select, update
-from datetime import datetime, timezone
-from loguru import logger
-
-from app.database import get_db
-from app.models.system import WorkflowConfig, ActivityLog
-
-router = APIRouter(prefix="/v1/admin", tags=["Admin"])
-
-
-def _ensure_admin(request: Request):
- """Enforce admin role requirement."""
- role = getattr(request.state, "user_role", None)
- if role not in ("admin", "ADMIN"):
- raise HTTPException(status_code=403, detail="Admin role required")
-
-
-async def _get_workflow_or_404(workflow_name: str, db: AsyncSession) -> WorkflowConfig:
- """Fetch a workflow by name or raise 404."""
- result = await db.execute(
- select(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name)
- )
- row = result.scalar_one_or_none()
- if row is None:
- raise HTTPException(status_code=404, detail=f"Workflow '{workflow_name}' not found")
- return row
-
-
-async def _log_activity(db: AsyncSession, request: Request, action: str, metadata: str):
- """Record an activity log entry. Errors are logged but do not fail the request."""
- try:
- log = ActivityLog(
- actor=getattr(request.state, 'user_email', None) or 'system',
- action=action,
- log_metadata=metadata,
- )
- db.add(log)
- await db.commit()
- except Exception as e:
- logger.warning(f"Failed to log activity '{action}': {e}")
- try:
- await db.rollback()
- except Exception:
- pass
-
-
-@router.get("/workflows")
-async def list_workflows(request: Request, db: AsyncSession = Depends(get_db)):
- _ensure_admin(request)
- result = await db.execute(select(WorkflowConfig))
- rows = result.scalars().all()
- return [
- {
- "workflow_name": r.workflow_name,
- "is_active": r.is_active,
- "schedule_cron": r.schedule_cron,
- "last_run": r.last_run,
- "updated_at": r.updated_at,
- }
- for r in rows
- ]
-
-
-@router.patch("/workflows/{workflow_name}")
-async def update_workflow(workflow_name: str, payload: dict, request: Request, db: AsyncSession = Depends(get_db)):
- _ensure_admin(request)
- await _get_workflow_or_404(workflow_name, db)
- # Only allow specific fields
- allowed = {"is_active", "schedule_cron"}
- update_values = {k: v for k, v in payload.items() if k in allowed}
- if not update_values:
- raise HTTPException(status_code=400, detail="No valid fields to update. Allowed: is_active, schedule_cron")
- update_values["updated_at"] = datetime.now(timezone.utc)
- stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values(**update_values)
- await db.execute(stmt)
- await db.commit()
- await _log_activity(db, request, f"workflow_update:{workflow_name}", str(update_values))
- return {"success": True, "updated": update_values}
-
-
-@router.post("/workflows/{workflow_name}/run")
-async def run_workflow(workflow_name: str, request: Request, db: AsyncSession = Depends(get_db)):
- _ensure_admin(request)
- await _get_workflow_or_404(workflow_name, db)
- # Manual trigger stub: update last_run and return accepted. Actual orchestrator should listen to this event.
- stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values({"last_run": datetime.now(timezone.utc), "updated_at": datetime.now(timezone.utc)})
- await db.execute(stmt)
- await db.commit()
- await _log_activity(db, request, f"workflow_manual_trigger:{workflow_name}", "Manual trigger via admin panel")
- return {"success": True, "message": "Workflow run recorded (manual trigger)."}
+from fastapi import APIRouter, Depends, Request, HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select, update
+from datetime import datetime, timezone
+from loguru import logger
+
+from app.database import get_db
+from app.models.system import WorkflowConfig, ActivityLog
+
+router = APIRouter(prefix="/v1/admin", tags=["Admin"])
+
+
+def _ensure_admin(request: Request):
+ """Enforce admin role requirement."""
+ role = getattr(request.state, "user_role", None)
+ if role not in ("admin", "ADMIN"):
+ raise HTTPException(status_code=403, detail="Admin role required")
+
+
+async def _get_workflow_or_404(workflow_name: str, db: AsyncSession) -> WorkflowConfig:
+ """Fetch a workflow by name or raise 404."""
+ result = await db.execute(
+ select(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name)
+ )
+ row = result.scalar_one_or_none()
+ if row is None:
+ raise HTTPException(status_code=404, detail=f"Workflow '{workflow_name}' not found")
+ return row
+
+
+async def _log_activity(db: AsyncSession, request: Request, action: str, metadata: str):
+ """Record an activity log entry. Errors are logged but do not fail the request."""
+ try:
+ log = ActivityLog(
+ actor=getattr(request.state, 'user_email', None) or 'system',
+ action=action,
+ log_metadata=metadata,
+ )
+ db.add(log)
+ await db.commit()
+ except Exception as e:
+ logger.warning(f"Failed to log activity '{action}': {e}")
+ try:
+ await db.rollback()
+ except Exception:
+ pass
+
+
+@router.get("/workflows")
+async def list_workflows(request: Request, db: AsyncSession = Depends(get_db)):
+ _ensure_admin(request)
+ result = await db.execute(select(WorkflowConfig))
+ rows = result.scalars().all()
+ return [
+ {
+ "workflow_name": r.workflow_name,
+ "is_active": r.is_active,
+ "schedule_cron": r.schedule_cron,
+ "last_run": r.last_run,
+ "updated_at": r.updated_at,
+ }
+ for r in rows
+ ]
+
+
+@router.patch("/workflows/{workflow_name}")
+async def update_workflow(workflow_name: str, payload: dict, request: Request, db: AsyncSession = Depends(get_db)):
+ _ensure_admin(request)
+ await _get_workflow_or_404(workflow_name, db)
+ # Only allow specific fields
+ allowed = {"is_active", "schedule_cron"}
+ update_values = {k: v for k, v in payload.items() if k in allowed}
+ if not update_values:
+ raise HTTPException(status_code=400, detail="No valid fields to update. Allowed: is_active, schedule_cron")
+ update_values["updated_at"] = datetime.now(timezone.utc)
+ stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values(**update_values)
+ await db.execute(stmt)
+ await db.commit()
+ await _log_activity(db, request, f"workflow_update:{workflow_name}", str(update_values))
+ return {"success": True, "updated": update_values}
+
+
+@router.post("/workflows/{workflow_name}/run")
+async def run_workflow(workflow_name: str, request: Request, db: AsyncSession = Depends(get_db)):
+ _ensure_admin(request)
+ await _get_workflow_or_404(workflow_name, db)
+ # Manual trigger stub: update last_run and return accepted. Actual orchestrator should listen to this event.
+ stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name).values({"last_run": datetime.now(timezone.utc), "updated_at": datetime.now(timezone.utc)})
+ await db.execute(stmt)
+ await db.commit()
+ await _log_activity(db, request, f"workflow_manual_trigger:{workflow_name}", "Manual trigger via admin panel")
+ return {"success": True, "message": "Workflow run recorded (manual trigger)."}
diff --git a/app/api/agents.py b/app/api/agents.py
new file mode 100644
index 0000000000000000000000000000000000000000..2479758ad8925a5a670c5618ca569cff625db0eb
--- /dev/null
+++ b/app/api/agents.py
@@ -0,0 +1,273 @@
+"""AI Agents API — Antigravity Gateway."""
+
+from typing import Any, Dict, Optional, List
+from fastapi import APIRouter, Depends, HTTPException, Security, Request
+from fastapi.security.api_key import APIKeyHeader
+from sqlalchemy.ext.asyncio import AsyncSession
+from pydantic import BaseModel
+
+from app.database import get_db
+from app.services.antigravity import AntigravityOrchestrator
+from app.services.orchestrator_service import Orchestrator
+from app.services.deploy_service import DeployService
+from app.config.settings import settings
+from sqlalchemy import text
+
+router = APIRouter(prefix="/v1/agents", tags=["AI Agents"])
+
+# Boardroom Security setup
+API_KEY_NAME = "Authorization"
+api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
+
+async def verify_boardroom_token(api_key_header: str = Security(api_key_header)):
+ if not api_key_header:
+ raise HTTPException(status_code=401, detail="Missing Authorization Header")
+
+ # Extract token (remove 'Bearer ' if present)
+ token = api_key_header.replace("Bearer ", "").strip()
+
+ # Check against the secure token in .env
+ expected_token = settings.security_webhook_token
+ if not expected_token or token != expected_token:
+ raise HTTPException(status_code=403, detail="Invalid Super Admin Token")
+
+ return token
+
+class AgentTaskRequest(BaseModel):
+ agent_name: str
+ task_name: str
+ payload: Dict[str, Any]
+ priority: int = 0
+ user_email: Optional[str] = None
+
+class BoardDirectiveRequest(BaseModel):
+ directive: str
+
+@router.get("/boardroom/activities")
+async def get_agent_activities(
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(verify_boardroom_token)
+):
+ """Fetch the latest agent activities for the Boardroom Kanban (Admin Only)."""
+
+ query = text("""
+ SELECT id, agent_id, task_description, status, next_action, requires_intervention, created_at, updated_at
+ FROM agent_activities
+ ORDER BY created_at DESC
+ LIMIT 50
+ """)
+ res = await db.execute(query)
+ rows = res.fetchall()
+
+ activities = []
+ for row in rows:
+ activities.append({
+ "id": row.id,
+ "agent_id": row.agent_id,
+ "task_description": row.task_description,
+ "status": row.status,
+ "next_action": row.next_action,
+ "requires_intervention": row.requires_intervention,
+ "created_at": row.created_at.isoformat(),
+ "updated_at": row.updated_at.isoformat()
+ })
+ return {"success": True, "data": activities}
+
+@router.post("/boardroom/directive")
+async def process_board_directive(
+ request: BoardDirectiveRequest
+):
+ """Send a high-level directive to the AI Organization Boardroom (CEO Orchestrated)."""
+ result = await Orchestrator.process_board_directive(request.directive)
+ return result
+
+@router.post("/execute")
+async def execute_agent_task(
+ request: AgentTaskRequest,
+ db: AsyncSession = Depends(get_db)
+):
+ """Execute an autonomous AI task through the Antigravity gateway."""
+ orchestrator = AntigravityOrchestrator(db)
+
+ result = await orchestrator.execute_task(
+ agent_name=request.agent_name,
+ task_name=request.task_name,
+ payload=request.payload,
+ priority=request.priority,
+ user_email=request.user_email
+ )
+
+ if result.get("status") == "error":
+ raise HTTPException(status_code=503, detail=result.get("message"))
+
+ return result
+
+@router.get("/stats")
+async def get_agent_stats(
+ db: AsyncSession = Depends(get_db)
+):
+ """Exposes Antigravity Command Center data for the Admin Dashboard."""
+ orchestrator = AntigravityOrchestrator(db)
+ stats = await orchestrator.get_command_center_stats()
+ return stats
+
+
+@router.post('/deploy/preview')
+async def trigger_preview(request: Request):
+ body = await request.json()
+ project = body.get('project', 'main-frontend-native')
+ # Trigger CF preview and notify CEO
+ deploy_resp = DeployService.trigger_cloudflare_preview(project)
+ if not deploy_resp.get('success'):
+ return {'success': False, 'error': deploy_resp.get('error')}
+ preview_url = deploy_resp.get('preview_url')
+ deploy_id = deploy_resp.get('raw', {}).get('result', {}).get('id', 'unknown')
+ DeployService.notify_ceo_preview(preview_url, deploy_id)
+ return {'success': True, 'preview_url': preview_url, 'deploy_id': deploy_id}
+
+
+class HealApprovalRequest(BaseModel):
+ task_id: str
+ approved: bool
+
+
+@router.post("/heal/approve")
+async def approve_heal_task(
+ request: HealApprovalRequest,
+ req: Request,
+ db: AsyncSession = Depends(get_db)
+):
+ """
+ Receives authorization to apply code patch and deploy sync for a failed task.
+ Enforces header verification (X-Webhook-Token).
+ """
+ import os
+ import json
+ import shutil
+ import subprocess
+ from datetime import datetime
+ from loguru import logger
+ from app.models.content import KnowledgeQueue
+
+ # 1. Verification of incoming token
+ received_token = req.headers.get("X-Security-Token") or req.headers.get("X-Webhook-Token")
+ expected_token = settings.webhook_secret or os.getenv("WEBHOOK_SECRET", "briga_secret_webhook_123_xyz")
+ if not received_token or received_token != expected_token:
+ logger.warning("[CTOAgent Webhook] Unauthorized approval attempt.")
+ raise HTTPException(status_code=403, detail="Unauthorized webhook token")
+
+ if not request.approved:
+ return {"success": False, "message": "Approval rejected by client"}
+
+ # 2. Fetch the task from knowledge_queue
+ from sqlalchemy import select
+ stmt = select(KnowledgeQueue).where(KnowledgeQueue.id == request.task_id)
+ res = await db.execute(stmt)
+ task = res.scalar_one_or_none()
+ if not task:
+ raise HTTPException(status_code=404, detail="Task not found in queue")
+
+ # Parse fact JSON
+ try:
+ fact_data = json.loads(task.fact) if isinstance(task.fact, str) else task.fact
+ if not isinstance(fact_data, dict):
+ fact_data = {}
+ except Exception:
+ fact_data = {}
+
+ target_file = fact_data.get("target_file")
+ target_code = fact_data.get("target_code_to_replace")
+ replacement_code = fact_data.get("replacement_code")
+
+ if not target_file or not target_code:
+ raise HTTPException(status_code=400, detail="Missing patch parameters in task fact data")
+
+ # 3. Resolve file paths
+ base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+ if not os.path.isabs(target_file):
+ abs_path = os.path.join(base_dir, target_file)
+ else:
+ abs_path = target_file
+
+ if not os.path.exists(abs_path):
+ # Fallback to direct path check
+ abs_path = target_file
+ if not os.path.exists(abs_path):
+ raise HTTPException(status_code=404, detail=f"Target file {target_file} not found in workspace")
+
+ # Create Safety Backup (.bak)
+ try:
+ backup_path = abs_path + ".bak"
+ shutil.copy2(abs_path, backup_path)
+ logger.info(f"[CTOAgent Webhook] Created safety backup at {backup_path}")
+ except Exception as e:
+ logger.error(f"[CTOAgent Webhook] Backup failed: {e}")
+ raise HTTPException(status_code=500, detail=f"Failed to create file backup: {str(e)}")
+
+ # Replace content and compile-check
+ try:
+ with open(abs_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ if target_code not in content:
+ raise HTTPException(status_code=400, detail="Target code block not found in file content")
+
+ new_content = content.replace(target_code, replacement_code)
+
+ # Dry-run compile check (if Python)
+ if abs_path.endswith(".py"):
+ try:
+ compile(new_content, abs_path, "exec")
+ logger.info("[CTOAgent Webhook] Patch dry-run compile validation passed.")
+ except Exception as ce:
+ logger.error(f"[CTOAgent Webhook] Compilation error: {ce}")
+ raise HTTPException(status_code=422, detail=f"Patch compilation check failed: {str(ce)}")
+
+ # Write verified patch
+ with open(abs_path, "w", encoding="utf-8") as f:
+ f.write(new_content)
+ logger.info(f"[CTOAgent Webhook] Patch applied successfully to {abs_path}")
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"[CTOAgent Webhook] Error writing patch: {e}")
+ raise HTTPException(status_code=500, detail=f"Failed to write patch: {str(e)}")
+
+ # 4. RUN DEPLOYMENT PIPELINE
+ deploy_output = []
+ try:
+ workspace_root = os.path.dirname(base_dir)
+ git_root = os.path.join(workspace_root, "brigawan")
+
+ # Git operations (best-effort)
+ if os.path.exists(git_root):
+ subprocess.run(["git", "add", "-A"], cwd=git_root, capture_output=True, text=True)
+ 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)
+ push_res = subprocess.run(["git", "push", "origin", "master"], cwd=git_root, capture_output=True, text=True)
+ deploy_output.append(f"Git commit/push exit code: {push_res.returncode}")
+
+ # Run split_monolith.py
+ split_script = os.path.join(workspace_root, "split_monolith.py")
+ if os.path.exists(split_script):
+ split_res = subprocess.run(["python", "split_monolith.py"], cwd=workspace_root, capture_output=True, text=True)
+ deploy_output.append(f"split_monolith exit code: {split_res.returncode}")
+
+ # Run hf upload
+ hf_res = subprocess.run([
+ "hf", "upload", "yabeskn/briga-agent-worker",
+ "./spaces/briga-agent-worker/", ".", "--repo-type", "space"
+ ], cwd=workspace_root, capture_output=True, text=True)
+ deploy_output.append(f"hf upload exit code: {hf_res.returncode}")
+
+ except Exception as de:
+ logger.error(f"[CTOAgent Webhook] Deploy sync error: {de}")
+ deploy_output.append(f"Deploy sync failed: {str(de)}")
+
+ # 5. Update Task Status
+ task.status = "Healed"
+ task.timestamp = datetime.now()
+ fact_data["healing_logs"] = deploy_output
+ task.fact = json.dumps(fact_data)
+ await db.commit()
+
+ return {"success": True, "message": f"Patch applied to {target_file}", "logs": deploy_output}
diff --git a/app/api/career.py b/app/api/career.py
index f367447fa07218fc075024dae87070c1f028e886..03e1c94ced37bbbc50679beda4d5179eb4732cb7 100644
--- a/app/api/career.py
+++ b/app/api/career.py
@@ -1,141 +1,141 @@
-"""Career history API router.
-
-Provides endpoints for managing secure experiences and credentials.
-Enforces PDP compliance and cryptographic integrity checks.
-"""
-
-from typing import List, Optional
-from uuid import UUID
-
-from fastapi import APIRouter, Depends, HTTPException, Request, status
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.database import get_db
-from app.schemas.career import (
- ExperienceCreate, ExperienceRead, ExperiencePublicRead,
- CredentialCreate, CredentialRead, CredentialPublicRead,
- ProfileRead, ProfilePublicRead, OrganizationRead
-)
-from app.services.career_service import career_service
-from app.services.audit_service import audit_service
-from app.utils.errors import error_response, ErrorCode
-
-router = APIRouter(prefix="/v1/career", tags=["Career History"])
-
-
-def get_current_user_id(request: Request) -> UUID:
- """Extract user UUID from request state (set by AuthMiddleware)."""
- user = getattr(request.state, "user", None)
- if not user or "sub" not in user:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Authentication required"
- )
- return UUID(user["sub"])
-
-
-# ─── Experience ─────────────────────────────────────────────────────────────
-
-@router.post("/experience", response_model=ExperienceRead)
-async def add_experience(
- data: ExperienceCreate,
- db: AsyncSession = Depends(get_db),
- user_id: UUID = Depends(get_current_user_id)
-):
- """Add a new employment record. Payload is AES-256 encrypted before storage."""
- try:
- return await career_service.add_experience(db, user_id, data)
- except Exception as e:
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Failed to save experience: {str(e)}"
- )
-
-
-@router.get("/experience", response_model=List[ExperienceRead])
-async def list_experiences(
- db: AsyncSession = Depends(get_db),
- user_id: UUID = Depends(get_current_user_id)
-):
- """Retrieve all personal experience records (decrypted)."""
- return await career_service.list_experiences(db, user_id)
-
-
-# ─── Credential ─────────────────────────────────────────────────────────────
-
-@router.post("/credential", response_model=CredentialRead)
-async def add_credential(
- data: CredentialCreate,
- issuer_signature: str,
- db: AsyncSession = Depends(get_db),
- user_id: UUID = Depends(get_current_user_id)
-):
- """Add a new certification. Requires a valid issuer signature."""
- try:
- return await career_service.add_credential(db, user_id, data, issuer_signature)
- except Exception as e:
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Failed to save credential: {str(e)}"
- )
-
-
-@router.get("/credential", response_model=List[CredentialRead])
-async def list_credentials(
- db: AsyncSession = Depends(get_db),
- user_id: UUID = Depends(get_current_user_id)
-):
- """Retrieve all personal credentials (decrypted)."""
- return await career_service.list_credentials(db, user_id)
-
-
-# ─── Public Profile ─────────────────────────────────────────────────────────
-
-@router.get("/profile/{profile_id}", response_model=ProfilePublicRead)
-async def get_public_profile(
- profile_id: UUID,
- db: AsyncSession = Depends(get_db)
-):
- """Fetch public profile data with masked email and verified counts."""
- profile = await career_service.get_profile(db, profile_id)
- if not profile:
- raise HTTPException(status_code=404, detail="Profile not found")
-
- # In a real implementation, this would query the public view or
- # use a specific public schema/mapper.
- return ProfilePublicRead(
- id=profile.id,
- full_name=profile.full_name,
- industry=profile.industry,
- general_skills=profile.general_skills or [],
- masked_email="***@***.***", # Masking logic should be here or in model
- verified_credential_count=0, # Placeholder
- created_at=profile.created_at
- )
-
-
-# ─── System / Admin Operations ──────────────────────────────────────────────
-
-@router.get("/system/verify-audit")
-async def verify_audit_trail(
- db: AsyncSession = Depends(get_db),
- user_role: str = Depends(lambda r: getattr(r.state, "user_role", "talent"))
-):
- """Verify the integrity of the cryptographic audit trail (Admin only)."""
- if user_role != "admin":
- raise HTTPException(status_code=403, detail="Admin access required")
-
- return await audit_service.verify_integrity(db)
-
-
-@router.post("/system/archive-logs")
-async def run_audit_archiving(
- days: int = 365,
- db: AsyncSession = Depends(get_db),
- user_role: str = Depends(lambda r: getattr(r.state, "user_role", "talent"))
-):
- """Archive old audit logs to cold storage (Admin only)."""
- if user_role != "admin":
- raise HTTPException(status_code=403, detail="Admin access required")
-
- return await audit_service.run_archiving(db, days_threshold=days)
+"""Career history API router.
+
+Provides endpoints for managing secure experiences and credentials.
+Enforces PDP compliance and cryptographic integrity checks.
+"""
+
+from typing import List, Optional
+from uuid import UUID
+
+from fastapi import APIRouter, Depends, HTTPException, Request, status
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.database import get_db
+from app.schemas.career import (
+ ExperienceCreate, ExperienceRead, ExperiencePublicRead,
+ CredentialCreate, CredentialRead, CredentialPublicRead,
+ ProfileRead, ProfilePublicRead, OrganizationRead
+)
+from app.services.career_service import career_service
+from app.services.audit_service import audit_service
+from app.utils.errors import error_response, ErrorCode
+
+router = APIRouter(prefix="/v1/career", tags=["Career History"])
+
+
+def get_current_user_id(request: Request) -> UUID:
+ """Extract user UUID from request state (set by AuthMiddleware)."""
+ user = getattr(request.state, "user", None)
+ if not user or "sub" not in user:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Authentication required"
+ )
+ return UUID(user["sub"])
+
+
+# ─── Experience ─────────────────────────────────────────────────────────────
+
+@router.post("/experience", response_model=ExperienceRead)
+async def add_experience(
+ data: ExperienceCreate,
+ db: AsyncSession = Depends(get_db),
+ user_id: UUID = Depends(get_current_user_id)
+):
+ """Add a new employment record. Payload is AES-256 encrypted before storage."""
+ try:
+ return await career_service.add_experience(db, user_id, data)
+ except Exception as e:
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail=f"Failed to save experience: {str(e)}"
+ )
+
+
+@router.get("/experience", response_model=List[ExperienceRead])
+async def list_experiences(
+ db: AsyncSession = Depends(get_db),
+ user_id: UUID = Depends(get_current_user_id)
+):
+ """Retrieve all personal experience records (decrypted)."""
+ return await career_service.list_experiences(db, user_id)
+
+
+# ─── Credential ─────────────────────────────────────────────────────────────
+
+@router.post("/credential", response_model=CredentialRead)
+async def add_credential(
+ data: CredentialCreate,
+ issuer_signature: str,
+ db: AsyncSession = Depends(get_db),
+ user_id: UUID = Depends(get_current_user_id)
+):
+ """Add a new certification. Requires a valid issuer signature."""
+ try:
+ return await career_service.add_credential(db, user_id, data, issuer_signature)
+ except Exception as e:
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail=f"Failed to save credential: {str(e)}"
+ )
+
+
+@router.get("/credential", response_model=List[CredentialRead])
+async def list_credentials(
+ db: AsyncSession = Depends(get_db),
+ user_id: UUID = Depends(get_current_user_id)
+):
+ """Retrieve all personal credentials (decrypted)."""
+ return await career_service.list_credentials(db, user_id)
+
+
+# ─── Public Profile ─────────────────────────────────────────────────────────
+
+@router.get("/profile/{profile_id}", response_model=ProfilePublicRead)
+async def get_public_profile(
+ profile_id: UUID,
+ db: AsyncSession = Depends(get_db)
+):
+ """Fetch public profile data with masked email and verified counts."""
+ profile = await career_service.get_profile(db, profile_id)
+ if not profile:
+ raise HTTPException(status_code=404, detail="Profile not found")
+
+ # In a real implementation, this would query the public view or
+ # use a specific public schema/mapper.
+ return ProfilePublicRead(
+ id=profile.id,
+ full_name=profile.full_name,
+ industry=profile.industry,
+ general_skills=profile.general_skills or [],
+ masked_email="***@***.***", # Masking logic should be here or in model
+ verified_credential_count=0, # Placeholder
+ created_at=profile.created_at
+ )
+
+
+# ─── System / Admin Operations ──────────────────────────────────────────────
+
+@router.get("/system/verify-audit")
+async def verify_audit_trail(
+ db: AsyncSession = Depends(get_db),
+ user_role: str = Depends(lambda r: getattr(r.state, "user_role", "talent"))
+):
+ """Verify the integrity of the cryptographic audit trail (Admin only)."""
+ if user_role != "admin":
+ raise HTTPException(status_code=403, detail="Admin access required")
+
+ return await audit_service.verify_integrity(db)
+
+
+@router.post("/system/archive-logs")
+async def run_audit_archiving(
+ days: int = 365,
+ db: AsyncSession = Depends(get_db),
+ user_role: str = Depends(lambda r: getattr(r.state, "user_role", "talent"))
+):
+ """Archive old audit logs to cold storage (Admin only)."""
+ if user_role != "admin":
+ raise HTTPException(status_code=403, detail="Admin access required")
+
+ return await audit_service.run_archiving(db, days_threshold=days)
diff --git a/app/api/debug_admin.py b/app/api/debug_admin.py
index c769a4634f897510492716e5c01e628ce263a57c..83ce29af912c2ceca7a24cb4ee07165be499fcd4 100644
--- a/app/api/debug_admin.py
+++ b/app/api/debug_admin.py
@@ -1,29 +1,29 @@
-from fastapi import APIRouter, Depends, Request, HTTPException
-from sqlalchemy.ext.asyncio import AsyncSession
-from sqlalchemy import select
-
-from app.database import get_db
-from app.models.system import WorkflowConfig
-
-router = APIRouter(prefix="/v1/debug", tags=["Debug"])
-
-
-@router.get("/workflows")
-async def debug_list_workflows(request: Request, db: AsyncSession = Depends(get_db)):
- """Debug endpoint: admin-only workflow listing."""
- role = getattr(request.state, "user_role", None)
- if role not in ("admin", "ADMIN"):
- raise HTTPException(status_code=403, detail="Admin role required")
-
- result = await db.execute(select(WorkflowConfig))
- rows = result.scalars().all()
- return {"success": True, "workflows": [
- {
- "workflow_name": r.workflow_name,
- "is_active": r.is_active,
- "schedule_cron": r.schedule_cron,
- "last_run": r.last_run,
- "updated_at": r.updated_at,
- }
- for r in rows
- ]}
+from fastapi import APIRouter, Depends, Request, HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select
+
+from app.database import get_db
+from app.models.system import WorkflowConfig
+
+router = APIRouter(prefix="/v1/debug", tags=["Debug"])
+
+
+@router.get("/workflows")
+async def debug_list_workflows(request: Request, db: AsyncSession = Depends(get_db)):
+ """Debug endpoint: admin-only workflow listing."""
+ role = getattr(request.state, "user_role", None)
+ if role not in ("admin", "ADMIN"):
+ raise HTTPException(status_code=403, detail="Admin role required")
+
+ result = await db.execute(select(WorkflowConfig))
+ rows = result.scalars().all()
+ return {"success": True, "workflows": [
+ {
+ "workflow_name": r.workflow_name,
+ "is_active": r.is_active,
+ "schedule_cron": r.schedule_cron,
+ "last_run": r.last_run,
+ "updated_at": r.updated_at,
+ }
+ for r in rows
+ ]}
diff --git a/app/api/interview.py b/app/api/interview.py
index ebfe003bfb035e492669c9e2e5c19d88143863bb..fd5f3e8ad1909c753d98a8ce3c40bc8a1e0f1ee9 100644
--- a/app/api/interview.py
+++ b/app/api/interview.py
@@ -1,174 +1,174 @@
-"""Interview & AI Notulen API Routes.
-
-Endpoints:
- POST /v1/interviews/schedule — Schedule interview (costs 5 coins)
- POST /v1/interviews/{id}/transcript — Save transcript
- POST /v1/interviews/{id}/notulen — Generate AI Notulen (meeting summary)
- POST /v1/interviews/{id}/competency — Analyze competency
- POST /v1/interviews/compare — Multi-candidate comparison
- GET /v1/interviews — List interviews for employer
- GET /v1/interviews/{id} — Get interview detail
-
-All endpoints require employer authentication.
-"""
-
-from fastapi import APIRouter, Depends, Query, Request
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.database import get_db
-from app.schemas.interview import (
- ComparisonRequest,
- ComparisonResponse,
- CompetencyAnalysisResponse,
- InterviewDetailResponse,
- InterviewListResponse,
- NotulenResponse,
- SaveTranscriptRequest,
- SaveTranscriptResponse,
- ScheduleInterviewRequest,
- ScheduleInterviewResponse,
-)
-from app.services.interview_service import (
- analyze_competency,
- compare_candidates,
- generate_ai_notulen,
- get_interview_detail,
- list_interviews,
- save_transcript,
- schedule_interview,
-)
-from app.utils.errors import ErrorCode, raise_error
-
-
-router = APIRouter(prefix="/v1/interviews", tags=["Interviews & AI Notulen"])
-
-
-@router.post("/schedule", response_model=ScheduleInterviewResponse)
-async def api_schedule_interview(
- req: Request,
- body: ScheduleInterviewRequest,
- db: AsyncSession = Depends(get_db),
-):
- """Schedule an interview with a candidate.
- Costs 5 coins (except Enterprise tier — free).
- """
- email = getattr(req.state, "user_email", None)
- if not email:
- raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
-
- return await schedule_interview(
- db=db,
- recruiter_email=email,
- candidate_id=body.candidate_id,
- scheduled_time=body.scheduled_time,
- )
-
-
-@router.post("/{interview_id}/transcript", response_model=SaveTranscriptResponse)
-async def api_save_transcript(
- req: Request,
- interview_id: str,
- body: SaveTranscriptRequest,
- db: AsyncSession = Depends(get_db),
-):
- """Save interview transcript after completion.
- Sets status to "Completed".
- """
- email = getattr(req.state, "user_email", None)
- if not email:
- raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
-
- return await save_transcript(
- db=db,
- interview_id=interview_id,
- transcript_text=body.transcript_text,
- )
-
-
-@router.post("/{interview_id}/notulen", response_model=NotulenResponse)
-async def api_generate_notulen(
- req: Request,
- interview_id: str,
- db: AsyncSession = Depends(get_db),
-):
- """Generate AI Notulen (meeting summary) from interview transcript.
- Uses Gemini MEDIUM tier (3.5 Flash).
- """
- email = getattr(req.state, "user_email", None)
- if not email:
- raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
-
- return await generate_ai_notulen(
- db=db,
- interview_id=interview_id,
- )
-
-
-@router.post("/{interview_id}/competency", response_model=CompetencyAnalysisResponse)
-async def api_analyze_competency(
- req: Request,
- interview_id: str,
- db: AsyncSession = Depends(get_db),
-):
- """Analyze candidate competency from interview transcript.
- Uses Gemini MEDIUM tier for structured scoring.
- """
- email = getattr(req.state, "user_email", None)
- if not email:
- raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
-
- return await analyze_competency(
- db=db,
- interview_id=interview_id,
- )
-
-
-@router.post("/compare", response_model=ComparisonResponse)
-async def api_compare_candidates(
- req: Request,
- body: ComparisonRequest,
- db: AsyncSession = Depends(get_db),
-):
- """Compare multiple candidates from their interviews.
- Uses Gemini HIGH tier (3.1 Pro) for intelligent comparison.
- Min 2 candidates, max 10.
- """
- email = getattr(req.state, "user_email", None)
- if not email:
- raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
-
- return await compare_candidates(
- db=db,
- interview_ids=body.interview_ids,
- )
-
-
-@router.get("", response_model=InterviewListResponse)
-async def api_list_interviews(
- req: Request,
- status: str = Query(None, description="Filter by status: Scheduled, Completed, Cancelled"),
- db: AsyncSession = Depends(get_db),
-):
- """List all interviews for the authenticated employer."""
- email = getattr(req.state, "user_email", None)
- if not email:
- raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
-
- return await list_interviews(db=db, email=email, status=status)
-
-
-@router.get("/{interview_id}", response_model=InterviewDetailResponse)
-async def api_get_interview_detail(
- req: Request,
- interview_id: str,
- db: AsyncSession = Depends(get_db),
-):
- """Get full interview detail with transcript, AI summary, and competency analysis."""
- email = getattr(req.state, "user_email", None)
- if not email:
- raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
-
- return await get_interview_detail(
- db=db,
- interview_id=interview_id,
- )
+"""Interview & AI Notulen API Routes.
+
+Endpoints:
+ POST /v1/interviews/schedule — Schedule interview (costs 5 coins)
+ POST /v1/interviews/{id}/transcript — Save transcript
+ POST /v1/interviews/{id}/notulen — Generate AI Notulen (meeting summary)
+ POST /v1/interviews/{id}/competency — Analyze competency
+ POST /v1/interviews/compare — Multi-candidate comparison
+ GET /v1/interviews — List interviews for employer
+ GET /v1/interviews/{id} — Get interview detail
+
+All endpoints require employer authentication.
+"""
+
+from fastapi import APIRouter, Depends, Query, Request
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.database import get_db
+from app.schemas.interview import (
+ ComparisonRequest,
+ ComparisonResponse,
+ CompetencyAnalysisResponse,
+ InterviewDetailResponse,
+ InterviewListResponse,
+ NotulenResponse,
+ SaveTranscriptRequest,
+ SaveTranscriptResponse,
+ ScheduleInterviewRequest,
+ ScheduleInterviewResponse,
+)
+from app.services.interview_service import (
+ analyze_competency,
+ compare_candidates,
+ generate_ai_notulen,
+ get_interview_detail,
+ list_interviews,
+ save_transcript,
+ schedule_interview,
+)
+from app.utils.errors import ErrorCode, raise_error
+
+
+router = APIRouter(prefix="/v1/interviews", tags=["Interviews & AI Notulen"])
+
+
+@router.post("/schedule", response_model=ScheduleInterviewResponse)
+async def api_schedule_interview(
+ req: Request,
+ body: ScheduleInterviewRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """Schedule an interview with a candidate.
+ Costs 5 coins (except Enterprise tier — free).
+ """
+ email = getattr(req.state, "user_email", None)
+ if not email:
+ raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
+
+ return await schedule_interview(
+ db=db,
+ recruiter_email=email,
+ candidate_id=body.candidate_id,
+ scheduled_time=body.scheduled_time,
+ )
+
+
+@router.post("/{interview_id}/transcript", response_model=SaveTranscriptResponse)
+async def api_save_transcript(
+ req: Request,
+ interview_id: str,
+ body: SaveTranscriptRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """Save interview transcript after completion.
+ Sets status to "Completed".
+ """
+ email = getattr(req.state, "user_email", None)
+ if not email:
+ raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
+
+ return await save_transcript(
+ db=db,
+ interview_id=interview_id,
+ transcript_text=body.transcript_text,
+ )
+
+
+@router.post("/{interview_id}/notulen", response_model=NotulenResponse)
+async def api_generate_notulen(
+ req: Request,
+ interview_id: str,
+ db: AsyncSession = Depends(get_db),
+):
+ """Generate AI Notulen (meeting summary) from interview transcript.
+ Uses Gemini MEDIUM tier (3.5 Flash).
+ """
+ email = getattr(req.state, "user_email", None)
+ if not email:
+ raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
+
+ return await generate_ai_notulen(
+ db=db,
+ interview_id=interview_id,
+ )
+
+
+@router.post("/{interview_id}/competency", response_model=CompetencyAnalysisResponse)
+async def api_analyze_competency(
+ req: Request,
+ interview_id: str,
+ db: AsyncSession = Depends(get_db),
+):
+ """Analyze candidate competency from interview transcript.
+ Uses Gemini MEDIUM tier for structured scoring.
+ """
+ email = getattr(req.state, "user_email", None)
+ if not email:
+ raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
+
+ return await analyze_competency(
+ db=db,
+ interview_id=interview_id,
+ )
+
+
+@router.post("/compare", response_model=ComparisonResponse)
+async def api_compare_candidates(
+ req: Request,
+ body: ComparisonRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """Compare multiple candidates from their interviews.
+ Uses Gemini HIGH tier (3.1 Pro) for intelligent comparison.
+ Min 2 candidates, max 10.
+ """
+ email = getattr(req.state, "user_email", None)
+ if not email:
+ raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
+
+ return await compare_candidates(
+ db=db,
+ interview_ids=body.interview_ids,
+ )
+
+
+@router.get("", response_model=InterviewListResponse)
+async def api_list_interviews(
+ req: Request,
+ status: str = Query(None, description="Filter by status: Scheduled, Completed, Cancelled"),
+ db: AsyncSession = Depends(get_db),
+):
+ """List all interviews for the authenticated employer."""
+ email = getattr(req.state, "user_email", None)
+ if not email:
+ raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
+
+ return await list_interviews(db=db, email=email, status=status)
+
+
+@router.get("/{interview_id}", response_model=InterviewDetailResponse)
+async def api_get_interview_detail(
+ req: Request,
+ interview_id: str,
+ db: AsyncSession = Depends(get_db),
+):
+ """Get full interview detail with transcript, AI summary, and competency analysis."""
+ email = getattr(req.state, "user_email", None)
+ if not email:
+ raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401)
+
+ return await get_interview_detail(
+ db=db,
+ interview_id=interview_id,
+ )
diff --git a/app/api/job.py b/app/api/job.py
index ffc2b2cd636026ba8c5e02491f9c98a3786adee0..c129fa6ccb414ecaa4c49c720975da3b6c00bab5 100644
--- a/app/api/job.py
+++ b/app/api/job.py
@@ -1,219 +1,219 @@
-"""Job API Routes - Posting CRUD, Outreach, Compatibility, Vouchers, Limits."""
-
-from typing import Optional
-
-from fastapi import APIRouter, Depends, Query, Request
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.database import get_db
-from app.schemas.job import (
- AnalyzeCompatibilityRequest, AnalyzeCompatibilityResponse,
- CheckJobLimitResponse, CreateJobRequest, JobListResponse,
- JobPostingResponse, OutreachRecordResponse, SendOutreachRequest,
- SendOutreachResponse, UpdateJobStatusRequest,
- VoucherGenerateRequest, VoucherGenerateResponse,
- VoucherListResponse, VoucherRedeemRequest, VoucherRedeemResponse,
-)
-from app.services.job_service import (
- analyze_job_compatibility, check_active_job_posting_limit,
- create_job_posting, generate_vouchers, get_job_posting,
- get_job_postings, get_lpk_vouchers, list_outreach_history,
- record_pending_outreach, redeem_voucher, send_instant_outreach,
- update_job_status,
-)
-
-router = APIRouter(prefix="/v1/jobs", tags=["Jobs"])
-
-
-def _check_auth(req: Request) -> Optional[str]:
- return getattr(req.state, "user_email", None)
-
-
-@router.get("", response_model=JobListResponse)
-async def api_get_jobs(
- page: int = Query(1, ge=1),
- limit: int = Query(10, ge=1, le=50),
- db: AsyncSession = Depends(get_db),
-):
- result = await get_job_postings(db, page, limit)
- return JobListResponse(
- success=result.get("success", False),
- page=result.get("page", page),
- limit=result.get("limit", limit),
- total=result.get("total", 0),
- data=result.get("data", []),
- error=result.get("error"),
- )
-
-
-@router.get("/{job_id}", response_model=JobPostingResponse)
-async def api_get_job(
- job_id: str,
- db: AsyncSession = Depends(get_db),
-):
- result = await get_job_posting(db, job_id)
- if not result.get("success"):
- return JobPostingResponse(job_id=job_id, error=result.get("error", "Not found"))
- data = result.get("data", {})
- return JobPostingResponse(**data)
-
-
-@router.post("", response_model=dict)
-async def api_create_job(
- req: Request,
- body: CreateJobRequest,
- db: AsyncSession = Depends(get_db),
-):
- email = _check_auth(req)
- if not email:
- return {"success": False, "error": "Authentication required."}
- return await create_job_posting(db, email, body.model_dump())
-
-
-@router.put("/status", response_model=dict)
-async def api_update_job_status(
- req: Request,
- body: UpdateJobStatusRequest,
- db: AsyncSession = Depends(get_db),
-):
- email = _check_auth(req)
- if not email:
- return {"success": False, "error": "Authentication required."}
- return await update_job_status(db, body.job_id, body.status)
-
-
-@router.get("/limit/check", response_model=CheckJobLimitResponse)
-async def api_check_job_limit(
- req: Request,
- db: AsyncSession = Depends(get_db),
-):
- email = _check_auth(req)
- if not email:
- return CheckJobLimitResponse(allowed=False, error="Authentication required.")
- result = await check_active_job_posting_limit(db, email)
- return CheckJobLimitResponse(
- allowed=result.get("allowed", False),
- tier=result.get("tier", "free"),
- active_count=result.get("active_count", 0),
- limit=result.get("limit", 1),
- error=result.get("error"),
- )
-
-
-@router.post("/analyze-compatibility", response_model=AnalyzeCompatibilityResponse)
-async def api_analyze_compatibility(
- req: Request,
- body: AnalyzeCompatibilityRequest,
- db: AsyncSession = Depends(get_db),
-):
- email = _check_auth(req)
- if not email:
- return AnalyzeCompatibilityResponse(success=False, error="Authentication required.")
- result = await analyze_job_compatibility(db, email, body.job_id)
- return AnalyzeCompatibilityResponse(
- success=result.get("success", False),
- data=result.get("data"),
- error=result.get("error"),
- )
-
-
-@router.post("/outreach/record", response_model=OutreachRecordResponse)
-async def api_record_outreach(
- req: Request,
- body: SendOutreachRequest,
- db: AsyncSession = Depends(get_db),
-):
- email = _check_auth(req)
- if not email:
- return OutreachRecordResponse(success=False, error="Authentication required.")
- result = await record_pending_outreach(
- db, body.job_id, body.talent_email, body.match_score,
- email, body.method, body.subject, body.body)
- return OutreachRecordResponse(
- success=result.get("success", False),
- outreach_id=result.get("outreach_id", ""),
- error=result.get("error"),
- )
-
-
-@router.post("/outreach/send", response_model=SendOutreachResponse)
-async def api_send_instant_outreach(
- req: Request,
- body: SendOutreachRequest,
- db: AsyncSession = Depends(get_db),
-):
- email = _check_auth(req)
- if not email:
- return SendOutreachResponse(success=False, error="Authentication required.")
- result = await send_instant_outreach(
- db, email, body.job_id, body.talent_email, body.match_score,
- body.method, body.subject, body.body)
- return SendOutreachResponse(
- success=result.get("success", False),
- outreach_id=result.get("outreach_id", ""),
- remaining=result.get("remaining", 0),
- error=result.get("error"),
- )
-
-
-@router.get("/outreach/history", response_model=dict)
-async def api_outreach_history(
- req: Request,
- db: AsyncSession = Depends(get_db),
-):
- email = _check_auth(req)
- if not email:
- return {"success": False, "error": "Authentication required."}
- return await list_outreach_history(db, email)
-
-
-@router.post("/vouchers/generate", response_model=VoucherGenerateResponse)
-async def api_generate_vouchers(
- req: Request,
- body: VoucherGenerateRequest,
- db: AsyncSession = Depends(get_db),
-):
- email = _check_auth(req)
- if not email:
- return VoucherGenerateResponse(success=False, error="Authentication required.")
- result = await generate_vouchers(db, body.lpk_id, body.quantity)
- return VoucherGenerateResponse(
- success=result.get("success", False),
- message=result.get("message", ""),
- vouchers=result.get("vouchers", []),
- count=result.get("count", 0),
- error=result.get("error"),
- )
-
-
-@router.post("/vouchers/redeem", response_model=VoucherRedeemResponse)
-async def api_redeem_voucher(
- req: Request,
- body: VoucherRedeemRequest,
- db: AsyncSession = Depends(get_db),
-):
- email = _check_auth(req)
- if not email:
- return VoucherRedeemResponse(success=False, error="Authentication required.")
- result = await redeem_voucher(db, email, email, body.voucher_code)
- return VoucherRedeemResponse(
- success=result.get("success", False),
- message=result.get("message", ""),
- lpk_id=result.get("lpk_id", ""),
- voucher_code=result.get("voucher_code", ""),
- error=result.get("error"),
- )
-
-
-@router.get("/vouchers/{lpk_id}", response_model=VoucherListResponse)
-async def api_get_lpk_vouchers(
- lpk_id: str,
- db: AsyncSession = Depends(get_db),
-):
- result = await get_lpk_vouchers(db, lpk_id)
- return VoucherListResponse(
- success=result.get("success", False),
- vouchers=result.get("vouchers", []),
- counts=result.get("counts", {"Available":0,"Used":0,"Total":0}),
- error=result.get("error"),
- )
+"""Job API Routes - Posting CRUD, Outreach, Compatibility, Vouchers, Limits."""
+
+from typing import Optional
+
+from fastapi import APIRouter, Depends, Query, Request
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.database import get_db
+from app.schemas.job import (
+ AnalyzeCompatibilityRequest, AnalyzeCompatibilityResponse,
+ CheckJobLimitResponse, CreateJobRequest, JobListResponse,
+ JobPostingResponse, OutreachRecordResponse, SendOutreachRequest,
+ SendOutreachResponse, UpdateJobStatusRequest,
+ VoucherGenerateRequest, VoucherGenerateResponse,
+ VoucherListResponse, VoucherRedeemRequest, VoucherRedeemResponse,
+)
+from app.services.job_service import (
+ analyze_job_compatibility, check_active_job_posting_limit,
+ create_job_posting, generate_vouchers, get_job_posting,
+ get_job_postings, get_lpk_vouchers, list_outreach_history,
+ record_pending_outreach, redeem_voucher, send_instant_outreach,
+ update_job_status,
+)
+
+router = APIRouter(prefix="/v1/jobs", tags=["Jobs"])
+
+
+def _check_auth(req: Request) -> Optional[str]:
+ return getattr(req.state, "user_email", None)
+
+
+@router.get("", response_model=JobListResponse)
+async def api_get_jobs(
+ page: int = Query(1, ge=1),
+ limit: int = Query(10, ge=1, le=50),
+ db: AsyncSession = Depends(get_db),
+):
+ result = await get_job_postings(db, page, limit)
+ return JobListResponse(
+ success=result.get("success", False),
+ page=result.get("page", page),
+ limit=result.get("limit", limit),
+ total=result.get("total", 0),
+ data=result.get("data", []),
+ error=result.get("error"),
+ )
+
+
+@router.get("/{job_id}", response_model=JobPostingResponse)
+async def api_get_job(
+ job_id: str,
+ db: AsyncSession = Depends(get_db),
+):
+ result = await get_job_posting(db, job_id)
+ if not result.get("success"):
+ return JobPostingResponse(job_id=job_id, error=result.get("error", "Not found"))
+ data = result.get("data", {})
+ return JobPostingResponse(**data)
+
+
+@router.post("", response_model=dict)
+async def api_create_job(
+ req: Request,
+ body: CreateJobRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ email = _check_auth(req)
+ if not email:
+ return {"success": False, "error": "Authentication required."}
+ return await create_job_posting(db, email, body.model_dump())
+
+
+@router.put("/status", response_model=dict)
+async def api_update_job_status(
+ req: Request,
+ body: UpdateJobStatusRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ email = _check_auth(req)
+ if not email:
+ return {"success": False, "error": "Authentication required."}
+ return await update_job_status(db, body.job_id, body.status)
+
+
+@router.get("/limit/check", response_model=CheckJobLimitResponse)
+async def api_check_job_limit(
+ req: Request,
+ db: AsyncSession = Depends(get_db),
+):
+ email = _check_auth(req)
+ if not email:
+ return CheckJobLimitResponse(allowed=False, error="Authentication required.")
+ result = await check_active_job_posting_limit(db, email)
+ return CheckJobLimitResponse(
+ allowed=result.get("allowed", False),
+ tier=result.get("tier", "free"),
+ active_count=result.get("active_count", 0),
+ limit=result.get("limit", 1),
+ error=result.get("error"),
+ )
+
+
+@router.post("/analyze-compatibility", response_model=AnalyzeCompatibilityResponse)
+async def api_analyze_compatibility(
+ req: Request,
+ body: AnalyzeCompatibilityRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ email = _check_auth(req)
+ if not email:
+ return AnalyzeCompatibilityResponse(success=False, error="Authentication required.")
+ result = await analyze_job_compatibility(db, email, body.job_id)
+ return AnalyzeCompatibilityResponse(
+ success=result.get("success", False),
+ data=result.get("data"),
+ error=result.get("error"),
+ )
+
+
+@router.post("/outreach/record", response_model=OutreachRecordResponse)
+async def api_record_outreach(
+ req: Request,
+ body: SendOutreachRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ email = _check_auth(req)
+ if not email:
+ return OutreachRecordResponse(success=False, error="Authentication required.")
+ result = await record_pending_outreach(
+ db, body.job_id, body.talent_email, body.match_score,
+ email, body.method, body.subject, body.body)
+ return OutreachRecordResponse(
+ success=result.get("success", False),
+ outreach_id=result.get("outreach_id", ""),
+ error=result.get("error"),
+ )
+
+
+@router.post("/outreach/send", response_model=SendOutreachResponse)
+async def api_send_instant_outreach(
+ req: Request,
+ body: SendOutreachRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ email = _check_auth(req)
+ if not email:
+ return SendOutreachResponse(success=False, error="Authentication required.")
+ result = await send_instant_outreach(
+ db, email, body.job_id, body.talent_email, body.match_score,
+ body.method, body.subject, body.body)
+ return SendOutreachResponse(
+ success=result.get("success", False),
+ outreach_id=result.get("outreach_id", ""),
+ remaining=result.get("remaining", 0),
+ error=result.get("error"),
+ )
+
+
+@router.get("/outreach/history", response_model=dict)
+async def api_outreach_history(
+ req: Request,
+ db: AsyncSession = Depends(get_db),
+):
+ email = _check_auth(req)
+ if not email:
+ return {"success": False, "error": "Authentication required."}
+ return await list_outreach_history(db, email)
+
+
+@router.post("/vouchers/generate", response_model=VoucherGenerateResponse)
+async def api_generate_vouchers(
+ req: Request,
+ body: VoucherGenerateRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ email = _check_auth(req)
+ if not email:
+ return VoucherGenerateResponse(success=False, error="Authentication required.")
+ result = await generate_vouchers(db, body.lpk_id, body.quantity)
+ return VoucherGenerateResponse(
+ success=result.get("success", False),
+ message=result.get("message", ""),
+ vouchers=result.get("vouchers", []),
+ count=result.get("count", 0),
+ error=result.get("error"),
+ )
+
+
+@router.post("/vouchers/redeem", response_model=VoucherRedeemResponse)
+async def api_redeem_voucher(
+ req: Request,
+ body: VoucherRedeemRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ email = _check_auth(req)
+ if not email:
+ return VoucherRedeemResponse(success=False, error="Authentication required.")
+ result = await redeem_voucher(db, email, email, body.voucher_code)
+ return VoucherRedeemResponse(
+ success=result.get("success", False),
+ message=result.get("message", ""),
+ lpk_id=result.get("lpk_id", ""),
+ voucher_code=result.get("voucher_code", ""),
+ error=result.get("error"),
+ )
+
+
+@router.get("/vouchers/{lpk_id}", response_model=VoucherListResponse)
+async def api_get_lpk_vouchers(
+ lpk_id: str,
+ db: AsyncSession = Depends(get_db),
+):
+ result = await get_lpk_vouchers(db, lpk_id)
+ return VoucherListResponse(
+ success=result.get("success", False),
+ vouchers=result.get("vouchers", []),
+ counts=result.get("counts", {"Available":0,"Used":0,"Total":0}),
+ error=result.get("error"),
+ )
diff --git a/app/api/legacy_compat.py b/app/api/legacy_compat.py
index c54cfe6491170f81e8752c900dbddab1308499f5..72ffcfa4405c2f7d51c616a3ee15bad4e931346a 100644
--- a/app/api/legacy_compat.py
+++ b/app/api/legacy_compat.py
@@ -1,718 +1,720 @@
-"""Legacy GAS Compatibility Endpoint — Emulates legacy Google Apps Script webhooks.
-
-Ensures GEO-security by applying 'X-Robots-Tag: noindex, nofollow, noai' on all responses.
-"""
-
-import secrets
-import re
-import asyncio
-from datetime import datetime, timedelta, timezone
-from typing import Any, Dict, List, Optional
-from pydantic import BaseModel
-
-from fastapi import APIRouter, Depends, Request, Response
-from sqlalchemy import select, func, update
-from sqlalchemy.ext.asyncio import AsyncSession
-from loguru import logger
-
-from app.database import get_db
-from app.config.settings import settings, FINANCE_CONFIG
-from app.utils.security import decode_access_token, hash_password
-from app.models.talent import Talent
-from app.models.employer import ClientAccount, Company, PendingEmployer
-from app.models.finance import ProfileUnlock, Transaction, Interview
-from app.models.system import ActivityLog, AnalyticsTraffic
-from app.models.skkni import LPKRegistrationLead
-from app.services.employer_service import deduct_coins
-from app.services.google_workspace_service import spark_agent
-from app.services.email_service import email_service
-
-router = APIRouter(prefix="/v1", tags=["Legacy Compatibility"])
-
-class LegacyPayload(BaseModel):
- action: str
- params: List[Any] = []
-
-def calculate_exp_tier(text: str) -> str:
- """Calculates experience tier based on years matching.
-
- Under 3 years: Junior
- 3 to 7 years: Mid
- 8+ years: Senior
- """
- if not text:
- return "Junior"
- match = re.search(r'\d+', str(text))
- if not match:
- return "Junior"
- y = int(match.group())
- if y >= 8:
- return "Senior"
- elif y >= 3:
- return "Mid"
- else:
- return "Junior"
-
-async def local_verify_session(db: AsyncSession, email: str, token: str) -> bool:
- """Helper to verify a session token (JWT or auth_key)."""
- if not email or not token:
- return False
-
- email_clean = email.lower().strip()
-
- # 1. Mock token override
- if token in ("mock_session_token_123", "mock_session_token"):
- return True
-
- # 2. Try JWT Decode first
- payload = decode_access_token(token)
- if payload:
- if payload.get("email", "").lower().strip() == email_clean:
- return True
-
- # 3. Check Admin Role
- if email_clean == "admin@briga.id":
- if token == settings.admin_password:
- return True
-
- # 4. Check ClientAccount auth_key in DB
- stmt_client = select(ClientAccount).where(ClientAccount.email == email_clean)
- res_client = await db.execute(stmt_client)
- client = res_client.scalar_one_or_none()
- if client and client.auth_key == token:
- return True
-
- return False
-
-@router.post("/legacy-gas-compat")
-async def legacy_gas_compat(
- payload: LegacyPayload,
- response: Response,
- db: AsyncSession = Depends(get_db)
-):
- # Enforce GEO-Security headers as mandated by Brigawan rules
- response.headers["X-Robots-Tag"] = "noindex, nofollow, noai"
- response.headers["X-Content-Type-Options"] = "nosniff"
- response.headers["X-Frame-Options"] = "DENY"
-
- action = payload.action
- params = payload.params
-
- logger.info(f"[LegacyGASCompat] Action: {action}, Params: {params}")
-
- try:
- if action == "verifySession":
- if len(params) < 2:
- return {"success": False, "error": "Parameter email dan token diperlukan."}
- email, token = params[0], params[1]
- success = await local_verify_session(db, email, token)
- if success:
- return {"success": True}
- return {"success": False, "error": "Sesi tidak valid atau telah berakhir."}
-
- elif action == "deductEmployerToken":
- if len(params) < 3:
- return {"success": False, "error": "Parameter kurang."}
- email, token, amount = params[0], params[1], int(params[2])
-
- if not await local_verify_session(db, email, token):
- return {"success": False, "error": "Sesi tidak valid."}
-
- res = await deduct_coins(db, email, amount, tx_type="Deduction", description="Employer Token Deduction")
- return {"success": True, "remaining": res["remaining"]}
-
- elif action == "deductCoinsForAIReport":
- if len(params) < 3:
- return {"success": False, "error": "Parameter kurang."}
- email, token, reason = params[0], params[1], params[2]
-
- if not await local_verify_session(db, email, token):
- return {"success": False, "error": "Sesi tidak valid."}
-
- cost = FINANCE_CONFIG["DEDUCTION"]["AI_MATCH_REPORT"]
- res = await deduct_coins(db, email, cost, tx_type="AIReport", description=f"AI Match Report: {reason}")
- return {"success": True, "remaining": res["remaining"]}
-
- elif action == "deductCoinsForOutreach":
- if len(params) < 3:
- return {"success": False, "error": "Parameter kurang."}
- email, token, candidate_email = params[0], params[1], params[2]
-
- if not await local_verify_session(db, email, token):
- return {"success": False, "error": "Sesi tidak valid."}
-
- cost = FINANCE_CONFIG["DEDUCTION"]["DIRECT_OUTREACH"]
- res = await deduct_coins(db, email, cost, tx_type="Outreach", description=f"Direct Outreach to: {candidate_email}")
- return {"success": True, "remaining": res["remaining"]}
-
- elif action == "unlockCandidate":
- if len(params) < 3:
- return {"success": False, "error": "Parameter kurang."}
- email, token, candidate_id = params[0], params[1], params[2]
- query = params[3] if len(params) > 3 else "-"
-
- if not await local_verify_session(db, email, token):
- return {"success": False, "error": "Sesi tidak valid."}
-
- stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
- client_res = await db.execute(stmt_client)
- client = client_res.scalar_one_or_none()
- if not client or not client.company_id:
- return {"success": False, "error": "Akun Employer tidak ditemukan."}
-
- stmt_unlock = select(ProfileUnlock).where(
- ProfileUnlock.company_id == client.company_id,
- ProfileUnlock.candidate_id == candidate_id
- )
- unlock_res = await db.execute(stmt_unlock)
- if unlock_res.scalar_one_or_none():
- return {"success": True, "message": "Already unlocked.", "cvUrl": f"https://briga.id/ats/cv/{candidate_id}"}
-
- stmt_talent = select(Talent).where(Talent.talent_id == candidate_id)
- talent_res = await db.execute(stmt_talent)
- talent = talent_res.scalar_one_or_none()
- if not talent:
- return {"success": False, "error": "Talenta tidak ditemukan."}
-
- exp_tier = calculate_exp_tier(talent.experience)
- costs = {
- "Senior": FINANCE_CONFIG["DEDUCTION"]["UNLOCK_SENIOR"],
- "Mid": FINANCE_CONFIG["DEDUCTION"]["UNLOCK_MID"],
- "Junior": FINANCE_CONFIG["DEDUCTION"]["UNLOCK_JUNIOR"]
- }
- cost = costs.get(exp_tier, FINANCE_CONFIG["DEDUCTION"]["UNLOCK_JUNIOR"])
-
- res = await deduct_coins(db, email, cost, tx_type="Unlock", description=f"Unlock Profile: {candidate_id}")
-
- new_unlock = ProfileUnlock(
- company_id=client.company_id,
- candidate_id=candidate_id,
- is_masked_only=False
- )
- db.add(new_unlock)
- await db.commit()
-
- if settings.google_sheets_spreadsheet_id:
- row_values = [
- f"UNL-{secrets.token_hex(4).upper()}",
- email,
- candidate_id,
- datetime.now(timezone.utc).isoformat(),
- query
- ]
- await spark_agent.append_row_to_sheet(
- settings.google_sheets_spreadsheet_id,
- "Unlocks!A1",
- row_values
- )
-
- return {
- "success": True,
- "message": "Unlocked successfully.",
- "deducted": cost,
- "remaining": res["remaining"],
- "cvUrl": f"https://briga.id/ats/cv/{candidate_id}"
- }
-
- elif action == "getUnlockHistory":
- if len(params) < 2:
- return {"success": False, "error": "Parameter kurang."}
- email, token = params[0], params[1]
-
- if not await local_verify_session(db, email, token):
- return {"success": False, "error": "Sesi tidak valid."}
-
- stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
- client_res = await db.execute(stmt_client)
- client = client_res.scalar_one_or_none()
- if not client or not client.company_id:
- return {"success": True, "data": []}
-
- stmt_unlocks = select(ProfileUnlock).where(ProfileUnlock.company_id == client.company_id)
- unlocks_res = await db.execute(stmt_unlocks)
- unlocks = unlocks_res.scalars().all()
-
- history = []
- for u in unlocks:
- history.append({
- "id": u.candidate_id,
- "date": int(u.created_at.timestamp() * 1000) if u.created_at else int(datetime.now(timezone.utc).timestamp() * 1000),
- "query": "Sustainability Role"
- })
- history.sort(key=lambda x: x["date"], reverse=True)
- return {"success": True, "data": history}
-
- elif action == "getEmployerProfile":
- if len(params) < 1:
- return {"success": False, "error": "Parameter kurang."}
- email = params[0]
-
- stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
- client_res = await db.execute(stmt_client)
- client = client_res.scalar_one_or_none()
- if not client or not client.company_id:
- return {"success": False, "error": "Employer profile not found."}
-
- stmt_company = select(Company).where(Company.id == client.company_id)
- comp_res = await db.execute(stmt_company)
- company = comp_res.scalar_one_or_none()
- if not company:
- return {"success": False, "error": "Company not found."}
-
- return {
- "success": True,
- "name": client.name,
- "tokens": company.credit_balance or 0
- }
-
- elif action == "getEmployerTokens":
- if len(params) < 1:
- return {"success": False, "error": "Parameter kurang."}
- email = params[0]
-
- stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
- client_res = await db.execute(stmt_client)
- client = client_res.scalar_one_or_none()
- if not client or not client.company_id:
- return 0
-
- stmt_company = select(Company).where(Company.id == client.company_id)
- comp_res = await db.execute(stmt_company)
- company = comp_res.scalar_one_or_none()
- if not company:
- return 0
-
- return company.credit_balance or 0
-
- elif action == "checkTalentVerificationStatus":
- if len(params) < 1:
- return {"success": False, "error": "Parameter kurang."}
- email = params[0]
- is_admin = params[1] if len(params) > 1 else False
-
- stmt = select(Talent).where(Talent.email == email.lower().strip())
- res = await db.execute(stmt)
- t = res.scalar_one_or_none()
- if not t:
- return {"success": False, "found": False, "error": "Data talenta tidak ditemukan."}
-
- return {
- "success": True,
- "found": True,
- "nama": t.name,
- "email": t.email,
- "talentId": t.talent_id if is_admin else "****",
- "pddikti_status": t.verification_status or "Verifikasi Otomatis",
- "ai_readiness_score": t.score or 70,
- "kategori": t.category or "Semi-Skilled",
- "ai_pathway": t.advisory_snippet or "Peta jalan Karir...",
- "ai_pathway_full": t.advisory_full or "-",
- "ai_skills": t.skill_tags or "-",
- "badges": t.badges or [],
- "isUnlocked": t.is_unlocked or is_admin,
- "sessionToken": None
- }
-
- elif action == "getAdminDashboardData":
- talents_count = (await db.execute(select(func.count(Talent.id)))).scalar() or 0
- companies_count = (await db.execute(select(func.count(Company.id)))).scalar() or 0
- pending_count = (await db.execute(select(func.count(PendingEmployer.id)).where(PendingEmployer.status == "PENDING"))).scalar() or 0
-
- recent_logs = []
- try:
- stmt_logs = select(ActivityLog).order_by(ActivityLog.timestamp.desc()).limit(5)
- logs_res = await db.execute(stmt_logs)
- recent_logs = [{
- "timestamp": l.timestamp.isoformat() if l.timestamp else None,
- "actor": l.actor,
- "action": l.action,
- "metadata": l.log_metadata
- } for l in logs_res.scalars().all()]
- except Exception:
- pass
-
- return {
- "success": True,
- "stats": {
- "talents": talents_count,
- "employers": companies_count,
- "pending": pending_count,
- "tokens": 1000
- },
- "recentLogs": recent_logs
- }
-
- elif action == "fetchAnalyticsOverview":
- now = datetime.now(timezone.utc)
- total_hits = (await db.execute(select(func.count(AnalyticsTraffic.id)))).scalar() or 0
-
- stmt_pages = select(AnalyticsTraffic.page, func.count(AnalyticsTraffic.id))\
- .group_by(AnalyticsTraffic.page)\
- .order_by(func.count(AnalyticsTraffic.id).desc())\
- .limit(5)
- top_pages_res = await db.execute(stmt_pages)
- top_pages = [{"page": r[0] or "Unknown", "count": r[1]} for r in top_pages_res.all()]
-
- stmt_geo = select(AnalyticsTraffic.geo, func.count(AnalyticsTraffic.id))\
- .group_by(AnalyticsTraffic.geo)\
- .order_by(func.count(AnalyticsTraffic.id).desc())\
- .limit(5)
- top_geo_res = await db.execute(stmt_geo)
- top_geo = [{"geo": r[0] or "Unknown", "count": r[1]} for r in top_geo_res.all()]
-
- daily_trend = []
- for i in range(6, -1, -1):
- day = now - timedelta(days=i)
- day_start = day.replace(hour=0, minute=0, second=0, microsecond=0)
- day_end = day.replace(hour=23, minute=59, second=59, microsecond=999999)
- stmt_trend = select(func.count(AnalyticsTraffic.id))\
- .where(AnalyticsTraffic.timestamp.between(day_start, day_end))
- count = (await db.execute(stmt_trend)).scalar() or 0
- daily_trend.append({"date": day_start.date().isoformat(), "count": count})
-
- return {
- "success": True,
- "totalHits": total_hits,
- "topPages": top_pages,
- "topGeo": top_geo,
- "dailyTrend": daily_trend
- }
-
- elif action == "getLPKDashboardDataServer":
- stmt_leads = select(LPKRegistrationLead)
- leads_res = await db.execute(stmt_leads)
- lead_records = leads_res.scalars().all()
-
- stmt_talents = select(Talent.email, Talent.name, Talent.phone)
- talents_res = await db.execute(stmt_talents)
- talent_lookup = {r[0].lower().strip(): {"name": r[1], "phone": r[2]} for r in talents_res.all() if r[0]}
-
- leads = []
- completed_leads = 0
- outreach_leads = 0
-
- for record in reversed(lead_records):
- email = record.email.lower().strip() if record.email else ""
- status = record.status or "Pending LPK Outreach"
-
- if status in ["Onsite Certified", "Certified"]:
- completed_leads += 1
- if status in ["Ongoing Outreach", "LPK Outreach"]:
- outreach_leads += 1
-
- t_info = talent_lookup.get(email, {"name": "Talenta Brigawan", "phone": record.talent_phone or "-"})
-
- leads.append({
- "timestamp": record.timestamp.isoformat() if record.timestamp else None,
- "email": record.email,
- "moduleId": record.module_id,
- "branch": record.lpk_branch,
- "status": status,
- "phone": t_info["phone"] or record.talent_phone or "-",
- "name": t_info["name"]
- })
-
- commission_flat_rate = 150000
- total_commission = completed_leads * commission_flat_rate
-
- return {
- "success": True,
- "stats": {
- "total": len(lead_records),
- "completed": completed_leads,
- "outreach": outreach_leads,
- "commission": total_commission
- },
- "leads": leads
- }
-
- elif action == "updateLPKLeadStatusServer":
- if len(params) < 5:
- return {"success": False, "error": "Parameter kurang."}
- admin_email, admin_token, target_email, module_id, next_status = params[0], params[1], params[2], params[3], params[4]
-
- if not await local_verify_session(db, admin_email, admin_token):
- return {"success": False, "error": "Sesi admin tidak valid."}
-
- stmt = select(LPKRegistrationLead).where(
- LPKRegistrationLead.email == target_email.lower().strip(),
- LPKRegistrationLead.module_id == module_id
- )
- lead_res = await db.execute(stmt)
- lead = lead_res.scalar_one_or_none()
- if lead:
- lead.status = next_status
- else:
- new_lead = LPKRegistrationLead(
- email=target_email.lower().strip(),
- module_id=module_id,
- lpk_branch="Regional Hub",
- status=next_status
- )
- db.add(new_lead)
-
- if next_status == "Onsite Certified":
- stmt_t = select(Talent).where(Talent.email == target_email.lower().strip())
- t_res = await db.execute(stmt_t)
- t = t_res.scalar_one_or_none()
- if t:
- t.green_score = (t.green_score or 0) + 100
- db.add(t)
-
- db.add(ActivityLog(
- actor=admin_email,
- action="Update LPK Lead Status",
- log_metadata=f"Email: {target_email}, Module: {module_id}, Status: {next_status}"
- ))
- await db.commit()
- return {"success": True, "message": "Status lead berhasil diperbarui!"}
-
- elif action == "updateCRMRecordServer":
- if len(params) < 3:
- return {"success": False, "error": "Parameter kurang."}
- admin_email, admin_token, crm_data = params[0], params[1], params[2]
-
- if not await local_verify_session(db, admin_email, admin_token):
- return {"success": False, "error": "Sesi admin tidak valid."}
-
- crm_type = crm_data.get("type")
- crm_id = crm_data.get("id")
- crm_status = crm_data.get("status")
-
- if crm_type == "talent":
- stmt = select(Talent).where(Talent.talent_id == crm_id)
- t_res = await db.execute(stmt)
- t = t_res.scalar_one_or_none()
- if t:
- t.verification_status = crm_status
- db.add(t)
-
- db.add(ActivityLog(
- actor=admin_email,
- action="Update CRM",
- log_metadata=f"Type: {crm_type}, ID: {crm_id}, Status: {crm_status}"
- ))
- await db.commit()
- return {"success": True}
-
- elif action == "getCRMDataServer":
- return {"success": True, "data": {}}
-
- elif action == "getAdminUsersServer":
- if len(params) < 2:
- return {"success": False, "error": "Parameter kurang."}
- admin_email, admin_token = params[0], params[1]
- if not await local_verify_session(db, admin_email, admin_token):
- return {"success": False, "error": "Sesi admin tidak valid."}
-
- stmt = select(ClientAccount).where(ClientAccount.role == "Admin")
- admin_res = await db.execute(stmt)
- admins = admin_res.scalars().all()
-
- users = []
- for i, a in enumerate(admins):
- users.append({
- "name": a.name,
- "email": a.email,
- "role": a.role,
- "index": i
- })
- return {"success": True, "data": users}
-
- elif action == "getAdminTalentsServer":
- if len(params) < 2:
- return {"success": False, "error": "Parameter kurang."}
- admin_email, admin_token = params[0], params[1]
- if not await local_verify_session(db, admin_email, admin_token):
- return {"success": False, "error": "Sesi admin tidak valid."}
-
- stmt = select(Talent).order_by(Talent.created_at.desc())
- talents_res = await db.execute(stmt)
- talents = talents_res.scalars().all()
-
- data = []
- for t in talents:
- data.append({
- "talentId": t.talent_id,
- "nama": t.name,
- "kategori": t.category or "-",
- "email": t.email,
- "status": t.verification_status or "New",
- "analysis": t.analysis or "-",
- "cvLink": t.cv_link or "-"
- })
- return {"success": True, "data": data}
-
- elif action == "getAdminEmployersServer":
- if len(params) < 2:
- return {"success": False, "error": "Parameter kurang."}
- admin_email, admin_token = params[0], params[1]
- if not await local_verify_session(db, admin_email, admin_token):
- return {"success": False, "error": "Sesi admin tidak valid."}
-
- stmt = select(ClientAccount, Company).join(Company, ClientAccount.company_id == Company.id)
- res = await db.execute(stmt)
-
- data = []
- for client, company in res.all():
- data.append({
- "email": client.email,
- "name": client.name,
- "perusahaan": company.name,
- "role": client.role,
- "tokens": company.credit_balance or 0,
- "tier": company.tier or "free",
- "status": client.status or "PENDING"
- })
- return {"success": True, "data": data}
-
- elif action == "getPendingApprovalsServer":
- if len(params) < 2:
- return {"success": False, "error": "Parameter kurang."}
- admin_email, admin_token = params[0], params[1]
- if not await local_verify_session(db, admin_email, admin_token):
- return {"success": False, "error": "Sesi admin tidak valid."}
-
- stmt = select(PendingEmployer).where(PendingEmployer.status == "PENDING")
- pendings_res = await db.execute(stmt)
- pendings = pendings_res.scalars().all()
-
- data = []
- for p in pendings:
- data.append({
- "type": "employer",
- "id": p.email,
- "name": p.pic_name,
- "entitas": p.entity_name,
- "website": p.website,
- "jabatan": p.pic_jabatan,
- "detail": "Registrasi Akun Korporasi",
- "timestamp": p.timestamp.isoformat() if p.timestamp else None
- })
- return {"success": True, "data": data}
-
- elif action == "prosesMeetingRequest":
- if len(params) < 3:
- return {"success": False, "error": "Parameter kurang."}
- email, token, data_meeting = params[0], params[1], params[2]
-
- if not await local_verify_session(db, email, token):
- return {"success": False, "error": "Sesi tidak valid."}
-
- client_email = data_meeting.get("email")
- perusahaan = data_meeting.get("perusahaan", "MOCK CORP")
- nama = data_meeting.get("nama", "Recruiter")
- topik = data_meeting.get("topik", "ESG Partnership")
- pesan = data_meeting.get("pesan", "-")
- selected_date = data_meeting.get("date", "")
- selected_time = data_meeting.get("time", "")
-
- date_text = f"{selected_date} {selected_time} WIB"
- meet_url = f"https://meet.google.com/brg-esg-{secrets.token_hex(3)}"
-
- subject = f"Thank You & Meeting Minutes: ESG Partnership Exploration - {perusahaan}"
- html_body = f"""
-
Dear {nama},
- Thank you for scheduling the B2B ESG Partnership Exploration with the Brigawan Sustainability Advisor team.
- Meeting Details:
-
- Topic: {topik}
- Company: {perusahaan}
- Date & Time: {date_text}
- Google Meet Room: {meet_url}
-
- Best regards, yabeskn@briga.id Brigawan AI Notetaker & Compliance Assistant
- """
- await asyncio.to_thread(email_service.send_html_email, client_email, subject, html_body)
-
- admin_subject = f"[NEW BOOKING] ESG B2B Meeting - {perusahaan}"
- admin_body = f"""
- Ada permintaan meeting terverifikasi baru:
- Nama: {nama}
- Perusahaan: {perusahaan}
- Email Klien: {client_email}
- Topik: {topik}
- Waktu: {date_text}
- Google Meet Link: {meet_url}
- Pesan Klien:
- {pesan}
- """
- await asyncio.to_thread(email_service.send_html_email, "info@briga.id", admin_subject, admin_body)
-
- return {
- "success": True,
- "meetUrl": meet_url,
- "dateText": date_text,
- "host": "Brigawan Sustainability Advisor"
- }
-
- elif action == "submitTalentRegistration":
- if len(params) < 1:
- return {"success": False, "error": "Parameter kurang."}
- form_data = params[0]
-
- name = form_data.get("nama")
- email = form_data.get("email")
- password = form_data.get("password")
-
- if not email or not name or not password:
- return {"success": False, "error": "Nama, email, dan password wajib diisi."}
-
- from app.services.auth_service import register_talent
- reg_data = {
- "name": name,
- "email": email,
- "password": password,
- "phone": form_data.get("telepon", ""),
- "education": form_data.get("pendidikan", ""),
- "experience": form_data.get("pengalaman", ""),
- "location": form_data.get("kota", ""),
- "skill_tags": form_data.get("sertifikasiLain", ""),
- "cv_link": form_data.get("cvLink", "")
- }
-
- try:
- res = await register_talent(db, reg_data)
- welcome_subject = "Selamat Datang di Brigawan - Portal Green Talent"
- welcome_html = f"""
- Halo {name}!
- Pendaftaran akun Anda di portal Brigawan telah berhasil dilakukan.
- 3 koin gratis trial Anda telah diaktifkan untuk memulai navigasi karir hijau Anda.
- """
- await asyncio.to_thread(email_service.send_html_email, email, welcome_subject, welcome_html)
-
- talent_id = res.get("user", {}).get("id", "BRIGA-GT-MOCK")
- return {
- "success": True,
- "talentId": talent_id,
- "data": {
- "id": talent_id,
- "name": name,
- "email": email,
- "verification": "Pending Docs",
- "score": 70,
- "kategori": "Semi-Skilled"
- },
- "evaluation": {
- "nama": name,
- "skor": "70",
- "kategori": "Semi-Skilled",
- "analisis": "Initial Registration Vetting",
- "advisory": "-",
- "skills": [],
- "verified": False
- }
- }
- except Exception as e:
- return {"success": False, "error": str(e)}
-
- elif action == "purgeSheetTalent":
- return {"success": True}
-
- else:
- logger.warning(f"[LegacyGASCompat] Unknown Action: {action}")
- return {"success": False, "error": f"Aksi '{action}' belum didukung."}
-
- except Exception as ex:
- logger.error(f"[LegacyGASCompat] Error during action {action}: {ex}")
- return {"success": False, "error": str(ex)}
+"""Legacy GAS Compatibility Endpoint — Emulates legacy Google Apps Script webhooks.
+
+Ensures GEO-security by applying 'X-Robots-Tag: noindex, nofollow, noai' on all responses.
+"""
+
+import secrets
+import re
+import asyncio
+from datetime import datetime, timedelta, timezone
+from typing import Any, Dict, List, Optional
+from pydantic import BaseModel
+
+from fastapi import APIRouter, Depends, Request, Response
+from sqlalchemy import select, func, update
+from sqlalchemy.ext.asyncio import AsyncSession
+from loguru import logger
+
+from app.database import get_db
+from app.config.settings import settings, FINANCE_CONFIG
+from app.utils.security import decode_access_token, hash_password, verify_supabase_token
+from app.models.talent import Talent
+from app.models.employer import ClientAccount, Company, PendingEmployer
+from app.models.finance import ProfileUnlock, Transaction, Interview
+from app.models.system import ActivityLog, AnalyticsTraffic
+from app.models.skkni import LPKRegistrationLead
+from app.services.employer_service import deduct_coins
+from app.services.google_workspace_service import spark_agent
+from app.services.email_service import email_service
+
+router = APIRouter(prefix="/v1", tags=["Legacy Compatibility"])
+
+class LegacyPayload(BaseModel):
+ action: str
+ params: List[Any] = []
+
+def calculate_exp_tier(text: str) -> str:
+ """Calculates experience tier based on years matching.
+
+ Under 3 years: Junior
+ 3 to 7 years: Mid
+ 8+ years: Senior
+ """
+ if not text:
+ return "Junior"
+ match = re.search(r'\d+', str(text))
+ if not match:
+ return "Junior"
+ y = int(match.group())
+ if y >= 8:
+ return "Senior"
+ elif y >= 3:
+ return "Mid"
+ else:
+ return "Junior"
+
+async def local_verify_session(db: AsyncSession, email: str, token: str) -> bool:
+ """Helper to verify a session token (JWT or auth_key)."""
+ if not email or not token:
+ return False
+
+ email_clean = email.lower().strip()
+
+ # 1. Mock token override
+ if token in ("mock_session_token_123", "mock_session_token"):
+ return True
+
+ # 2. Try JWT Decode first
+ payload = decode_access_token(token)
+ if not payload:
+ payload = await verify_supabase_token(token)
+ if payload:
+ if payload.get("email", "").lower().strip() == email_clean:
+ return True
+
+ # 3. Check Admin Role
+ if email_clean == "admin@briga.id":
+ if token == settings.admin_password:
+ return True
+
+ # 4. Check ClientAccount auth_key in DB
+ stmt_client = select(ClientAccount).where(ClientAccount.email == email_clean)
+ res_client = await db.execute(stmt_client)
+ client = res_client.scalar_one_or_none()
+ if client and client.auth_key == token:
+ return True
+
+ return False
+
+@router.post("/legacy-gas-compat")
+async def legacy_gas_compat(
+ payload: LegacyPayload,
+ response: Response,
+ db: AsyncSession = Depends(get_db)
+):
+ # Enforce GEO-Security headers as mandated by Brigawan rules
+ response.headers["X-Robots-Tag"] = "noindex, nofollow, noai"
+ response.headers["X-Content-Type-Options"] = "nosniff"
+ response.headers["X-Frame-Options"] = "DENY"
+
+ action = payload.action
+ params = payload.params
+
+ logger.info(f"[LegacyGASCompat] Action: {action}, Params: {params}")
+
+ try:
+ if action == "verifySession":
+ if len(params) < 2:
+ return {"success": False, "error": "Parameter email dan token diperlukan."}
+ email, token = params[0], params[1]
+ success = await local_verify_session(db, email, token)
+ if success:
+ return {"success": True}
+ return {"success": False, "error": "Sesi tidak valid atau telah berakhir."}
+
+ elif action == "deductEmployerToken":
+ if len(params) < 3:
+ return {"success": False, "error": "Parameter kurang."}
+ email, token, amount = params[0], params[1], int(params[2])
+
+ if not await local_verify_session(db, email, token):
+ return {"success": False, "error": "Sesi tidak valid."}
+
+ res = await deduct_coins(db, email, amount, tx_type="Deduction", description="Employer Token Deduction")
+ return {"success": True, "remaining": res["remaining"]}
+
+ elif action == "deductCoinsForAIReport":
+ if len(params) < 3:
+ return {"success": False, "error": "Parameter kurang."}
+ email, token, reason = params[0], params[1], params[2]
+
+ if not await local_verify_session(db, email, token):
+ return {"success": False, "error": "Sesi tidak valid."}
+
+ cost = FINANCE_CONFIG["DEDUCTION"]["AI_MATCH_REPORT"]
+ res = await deduct_coins(db, email, cost, tx_type="AIReport", description=f"AI Match Report: {reason}")
+ return {"success": True, "remaining": res["remaining"]}
+
+ elif action == "deductCoinsForOutreach":
+ if len(params) < 3:
+ return {"success": False, "error": "Parameter kurang."}
+ email, token, candidate_email = params[0], params[1], params[2]
+
+ if not await local_verify_session(db, email, token):
+ return {"success": False, "error": "Sesi tidak valid."}
+
+ cost = FINANCE_CONFIG["DEDUCTION"]["DIRECT_OUTREACH"]
+ res = await deduct_coins(db, email, cost, tx_type="Outreach", description=f"Direct Outreach to: {candidate_email}")
+ return {"success": True, "remaining": res["remaining"]}
+
+ elif action == "unlockCandidate":
+ if len(params) < 3:
+ return {"success": False, "error": "Parameter kurang."}
+ email, token, candidate_id = params[0], params[1], params[2]
+ query = params[3] if len(params) > 3 else "-"
+
+ if not await local_verify_session(db, email, token):
+ return {"success": False, "error": "Sesi tidak valid."}
+
+ stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
+ client_res = await db.execute(stmt_client)
+ client = client_res.scalar_one_or_none()
+ if not client or not client.company_id:
+ return {"success": False, "error": "Akun Employer tidak ditemukan."}
+
+ stmt_unlock = select(ProfileUnlock).where(
+ ProfileUnlock.company_id == client.company_id,
+ ProfileUnlock.candidate_id == candidate_id
+ )
+ unlock_res = await db.execute(stmt_unlock)
+ if unlock_res.scalar_one_or_none():
+ return {"success": True, "message": "Already unlocked.", "cvUrl": f"https://briga.id/ats/cv/{candidate_id}"}
+
+ stmt_talent = select(Talent).where(Talent.talent_id == candidate_id)
+ talent_res = await db.execute(stmt_talent)
+ talent = talent_res.scalar_one_or_none()
+ if not talent:
+ return {"success": False, "error": "Talenta tidak ditemukan."}
+
+ exp_tier = calculate_exp_tier(talent.experience)
+ costs = {
+ "Senior": FINANCE_CONFIG["DEDUCTION"]["UNLOCK_SENIOR"],
+ "Mid": FINANCE_CONFIG["DEDUCTION"]["UNLOCK_MID"],
+ "Junior": FINANCE_CONFIG["DEDUCTION"]["UNLOCK_JUNIOR"]
+ }
+ cost = costs.get(exp_tier, FINANCE_CONFIG["DEDUCTION"]["UNLOCK_JUNIOR"])
+
+ res = await deduct_coins(db, email, cost, tx_type="Unlock", description=f"Unlock Profile: {candidate_id}")
+
+ new_unlock = ProfileUnlock(
+ company_id=client.company_id,
+ candidate_id=candidate_id,
+ is_masked_only=False
+ )
+ db.add(new_unlock)
+ await db.commit()
+
+ if settings.google_sheets_spreadsheet_id:
+ row_values = [
+ f"UNL-{secrets.token_hex(4).upper()}",
+ email,
+ candidate_id,
+ datetime.now(timezone.utc).isoformat(),
+ query
+ ]
+ await spark_agent.append_row_to_sheet(
+ settings.google_sheets_spreadsheet_id,
+ "Unlocks!A1",
+ row_values
+ )
+
+ return {
+ "success": True,
+ "message": "Unlocked successfully.",
+ "deducted": cost,
+ "remaining": res["remaining"],
+ "cvUrl": f"https://briga.id/ats/cv/{candidate_id}"
+ }
+
+ elif action == "getUnlockHistory":
+ if len(params) < 2:
+ return {"success": False, "error": "Parameter kurang."}
+ email, token = params[0], params[1]
+
+ if not await local_verify_session(db, email, token):
+ return {"success": False, "error": "Sesi tidak valid."}
+
+ stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
+ client_res = await db.execute(stmt_client)
+ client = client_res.scalar_one_or_none()
+ if not client or not client.company_id:
+ return {"success": True, "data": []}
+
+ stmt_unlocks = select(ProfileUnlock).where(ProfileUnlock.company_id == client.company_id)
+ unlocks_res = await db.execute(stmt_unlocks)
+ unlocks = unlocks_res.scalars().all()
+
+ history = []
+ for u in unlocks:
+ history.append({
+ "id": u.candidate_id,
+ "date": int(u.created_at.timestamp() * 1000) if u.created_at else int(datetime.now(timezone.utc).timestamp() * 1000),
+ "query": "Sustainability Role"
+ })
+ history.sort(key=lambda x: x["date"], reverse=True)
+ return {"success": True, "data": history}
+
+ elif action == "getEmployerProfile":
+ if len(params) < 1:
+ return {"success": False, "error": "Parameter kurang."}
+ email = params[0]
+
+ stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
+ client_res = await db.execute(stmt_client)
+ client = client_res.scalar_one_or_none()
+ if not client or not client.company_id:
+ return {"success": False, "error": "Employer profile not found."}
+
+ stmt_company = select(Company).where(Company.id == client.company_id)
+ comp_res = await db.execute(stmt_company)
+ company = comp_res.scalar_one_or_none()
+ if not company:
+ return {"success": False, "error": "Company not found."}
+
+ return {
+ "success": True,
+ "name": client.name,
+ "tokens": company.credit_balance or 0
+ }
+
+ elif action == "getEmployerTokens":
+ if len(params) < 1:
+ return {"success": False, "error": "Parameter kurang."}
+ email = params[0]
+
+ stmt_client = select(ClientAccount).where(ClientAccount.email == email.lower().strip())
+ client_res = await db.execute(stmt_client)
+ client = client_res.scalar_one_or_none()
+ if not client or not client.company_id:
+ return 0
+
+ stmt_company = select(Company).where(Company.id == client.company_id)
+ comp_res = await db.execute(stmt_company)
+ company = comp_res.scalar_one_or_none()
+ if not company:
+ return 0
+
+ return company.credit_balance or 0
+
+ elif action == "checkTalentVerificationStatus":
+ if len(params) < 1:
+ return {"success": False, "error": "Parameter kurang."}
+ email = params[0]
+ is_admin = params[1] if len(params) > 1 else False
+
+ stmt = select(Talent).where(Talent.email == email.lower().strip())
+ res = await db.execute(stmt)
+ t = res.scalar_one_or_none()
+ if not t:
+ return {"success": False, "found": False, "error": "Data talenta tidak ditemukan."}
+
+ return {
+ "success": True,
+ "found": True,
+ "nama": t.name,
+ "email": t.email,
+ "talentId": t.talent_id if is_admin else "****",
+ "pddikti_status": t.verification_status or "Verifikasi Otomatis",
+ "ai_readiness_score": t.score or 70,
+ "kategori": t.category or "Semi-Skilled",
+ "ai_pathway": t.advisory_snippet or "Peta jalan Karir...",
+ "ai_pathway_full": t.advisory_full or "-",
+ "ai_skills": t.skill_tags or "-",
+ "badges": t.badges or [],
+ "isUnlocked": t.is_unlocked or is_admin,
+ "sessionToken": None
+ }
+
+ elif action == "getAdminDashboardData":
+ talents_count = (await db.execute(select(func.count(Talent.id)))).scalar() or 0
+ companies_count = (await db.execute(select(func.count(Company.id)))).scalar() or 0
+ pending_count = (await db.execute(select(func.count(PendingEmployer.id)).where(PendingEmployer.status == "PENDING"))).scalar() or 0
+
+ recent_logs = []
+ try:
+ stmt_logs = select(ActivityLog).order_by(ActivityLog.timestamp.desc()).limit(5)
+ logs_res = await db.execute(stmt_logs)
+ recent_logs = [{
+ "timestamp": l.timestamp.isoformat() if l.timestamp else None,
+ "actor": l.actor,
+ "action": l.action,
+ "metadata": l.log_metadata
+ } for l in logs_res.scalars().all()]
+ except Exception:
+ pass
+
+ return {
+ "success": True,
+ "stats": {
+ "talents": talents_count,
+ "employers": companies_count,
+ "pending": pending_count,
+ "tokens": 1000
+ },
+ "recentLogs": recent_logs
+ }
+
+ elif action == "fetchAnalyticsOverview":
+ now = datetime.now(timezone.utc)
+ total_hits = (await db.execute(select(func.count(AnalyticsTraffic.id)))).scalar() or 0
+
+ stmt_pages = select(AnalyticsTraffic.page, func.count(AnalyticsTraffic.id))\
+ .group_by(AnalyticsTraffic.page)\
+ .order_by(func.count(AnalyticsTraffic.id).desc())\
+ .limit(5)
+ top_pages_res = await db.execute(stmt_pages)
+ top_pages = [{"page": r[0] or "Unknown", "count": r[1]} for r in top_pages_res.all()]
+
+ stmt_geo = select(AnalyticsTraffic.geo, func.count(AnalyticsTraffic.id))\
+ .group_by(AnalyticsTraffic.geo)\
+ .order_by(func.count(AnalyticsTraffic.id).desc())\
+ .limit(5)
+ top_geo_res = await db.execute(stmt_geo)
+ top_geo = [{"geo": r[0] or "Unknown", "count": r[1]} for r in top_geo_res.all()]
+
+ daily_trend = []
+ for i in range(6, -1, -1):
+ day = now - timedelta(days=i)
+ day_start = day.replace(hour=0, minute=0, second=0, microsecond=0)
+ day_end = day.replace(hour=23, minute=59, second=59, microsecond=999999)
+ stmt_trend = select(func.count(AnalyticsTraffic.id))\
+ .where(AnalyticsTraffic.timestamp.between(day_start, day_end))
+ count = (await db.execute(stmt_trend)).scalar() or 0
+ daily_trend.append({"date": day_start.date().isoformat(), "count": count})
+
+ return {
+ "success": True,
+ "totalHits": total_hits,
+ "topPages": top_pages,
+ "topGeo": top_geo,
+ "dailyTrend": daily_trend
+ }
+
+ elif action == "getLPKDashboardDataServer":
+ stmt_leads = select(LPKRegistrationLead)
+ leads_res = await db.execute(stmt_leads)
+ lead_records = leads_res.scalars().all()
+
+ stmt_talents = select(Talent.email, Talent.name, Talent.phone)
+ talents_res = await db.execute(stmt_talents)
+ talent_lookup = {r[0].lower().strip(): {"name": r[1], "phone": r[2]} for r in talents_res.all() if r[0]}
+
+ leads = []
+ completed_leads = 0
+ outreach_leads = 0
+
+ for record in reversed(lead_records):
+ email = record.email.lower().strip() if record.email else ""
+ status = record.status or "Pending LPK Outreach"
+
+ if status in ["Onsite Certified", "Certified"]:
+ completed_leads += 1
+ if status in ["Ongoing Outreach", "LPK Outreach"]:
+ outreach_leads += 1
+
+ t_info = talent_lookup.get(email, {"name": "Talenta Brigawan", "phone": record.talent_phone or "-"})
+
+ leads.append({
+ "timestamp": record.timestamp.isoformat() if record.timestamp else None,
+ "email": record.email,
+ "moduleId": record.module_id,
+ "branch": record.lpk_branch,
+ "status": status,
+ "phone": t_info["phone"] or record.talent_phone or "-",
+ "name": t_info["name"]
+ })
+
+ commission_flat_rate = 150000
+ total_commission = completed_leads * commission_flat_rate
+
+ return {
+ "success": True,
+ "stats": {
+ "total": len(lead_records),
+ "completed": completed_leads,
+ "outreach": outreach_leads,
+ "commission": total_commission
+ },
+ "leads": leads
+ }
+
+ elif action == "updateLPKLeadStatusServer":
+ if len(params) < 5:
+ return {"success": False, "error": "Parameter kurang."}
+ admin_email, admin_token, target_email, module_id, next_status = params[0], params[1], params[2], params[3], params[4]
+
+ if not await local_verify_session(db, admin_email, admin_token):
+ return {"success": False, "error": "Sesi admin tidak valid."}
+
+ stmt = select(LPKRegistrationLead).where(
+ LPKRegistrationLead.email == target_email.lower().strip(),
+ LPKRegistrationLead.module_id == module_id
+ )
+ lead_res = await db.execute(stmt)
+ lead = lead_res.scalar_one_or_none()
+ if lead:
+ lead.status = next_status
+ else:
+ new_lead = LPKRegistrationLead(
+ email=target_email.lower().strip(),
+ module_id=module_id,
+ lpk_branch="Regional Hub",
+ status=next_status
+ )
+ db.add(new_lead)
+
+ if next_status == "Onsite Certified":
+ stmt_t = select(Talent).where(Talent.email == target_email.lower().strip())
+ t_res = await db.execute(stmt_t)
+ t = t_res.scalar_one_or_none()
+ if t:
+ t.green_score = (t.green_score or 0) + 100
+ db.add(t)
+
+ db.add(ActivityLog(
+ actor=admin_email,
+ action="Update LPK Lead Status",
+ log_metadata=f"Email: {target_email}, Module: {module_id}, Status: {next_status}"
+ ))
+ await db.commit()
+ return {"success": True, "message": "Status lead berhasil diperbarui!"}
+
+ elif action == "updateCRMRecordServer":
+ if len(params) < 3:
+ return {"success": False, "error": "Parameter kurang."}
+ admin_email, admin_token, crm_data = params[0], params[1], params[2]
+
+ if not await local_verify_session(db, admin_email, admin_token):
+ return {"success": False, "error": "Sesi admin tidak valid."}
+
+ crm_type = crm_data.get("type")
+ crm_id = crm_data.get("id")
+ crm_status = crm_data.get("status")
+
+ if crm_type == "talent":
+ stmt = select(Talent).where(Talent.talent_id == crm_id)
+ t_res = await db.execute(stmt)
+ t = t_res.scalar_one_or_none()
+ if t:
+ t.verification_status = crm_status
+ db.add(t)
+
+ db.add(ActivityLog(
+ actor=admin_email,
+ action="Update CRM",
+ log_metadata=f"Type: {crm_type}, ID: {crm_id}, Status: {crm_status}"
+ ))
+ await db.commit()
+ return {"success": True}
+
+ elif action == "getCRMDataServer":
+ return {"success": True, "data": {}}
+
+ elif action == "getAdminUsersServer":
+ if len(params) < 2:
+ return {"success": False, "error": "Parameter kurang."}
+ admin_email, admin_token = params[0], params[1]
+ if not await local_verify_session(db, admin_email, admin_token):
+ return {"success": False, "error": "Sesi admin tidak valid."}
+
+ stmt = select(ClientAccount).where(ClientAccount.role == "Admin")
+ admin_res = await db.execute(stmt)
+ admins = admin_res.scalars().all()
+
+ users = []
+ for i, a in enumerate(admins):
+ users.append({
+ "name": a.name,
+ "email": a.email,
+ "role": a.role,
+ "index": i
+ })
+ return {"success": True, "data": users}
+
+ elif action == "getAdminTalentsServer":
+ if len(params) < 2:
+ return {"success": False, "error": "Parameter kurang."}
+ admin_email, admin_token = params[0], params[1]
+ if not await local_verify_session(db, admin_email, admin_token):
+ return {"success": False, "error": "Sesi admin tidak valid."}
+
+ stmt = select(Talent).order_by(Talent.created_at.desc())
+ talents_res = await db.execute(stmt)
+ talents = talents_res.scalars().all()
+
+ data = []
+ for t in talents:
+ data.append({
+ "talentId": t.talent_id,
+ "nama": t.name,
+ "kategori": t.category or "-",
+ "email": t.email,
+ "status": t.verification_status or "New",
+ "analysis": t.analysis or "-",
+ "cvLink": t.cv_link or "-"
+ })
+ return {"success": True, "data": data}
+
+ elif action == "getAdminEmployersServer":
+ if len(params) < 2:
+ return {"success": False, "error": "Parameter kurang."}
+ admin_email, admin_token = params[0], params[1]
+ if not await local_verify_session(db, admin_email, admin_token):
+ return {"success": False, "error": "Sesi admin tidak valid."}
+
+ stmt = select(ClientAccount, Company).join(Company, ClientAccount.company_id == Company.id)
+ res = await db.execute(stmt)
+
+ data = []
+ for client, company in res.all():
+ data.append({
+ "email": client.email,
+ "name": client.name,
+ "perusahaan": company.name,
+ "role": client.role,
+ "tokens": company.credit_balance or 0,
+ "tier": company.tier or "free",
+ "status": client.status or "PENDING"
+ })
+ return {"success": True, "data": data}
+
+ elif action == "getPendingApprovalsServer":
+ if len(params) < 2:
+ return {"success": False, "error": "Parameter kurang."}
+ admin_email, admin_token = params[0], params[1]
+ if not await local_verify_session(db, admin_email, admin_token):
+ return {"success": False, "error": "Sesi admin tidak valid."}
+
+ stmt = select(PendingEmployer).where(PendingEmployer.status == "PENDING")
+ pendings_res = await db.execute(stmt)
+ pendings = pendings_res.scalars().all()
+
+ data = []
+ for p in pendings:
+ data.append({
+ "type": "employer",
+ "id": p.email,
+ "name": p.pic_name,
+ "entitas": p.entity_name,
+ "website": p.website,
+ "jabatan": p.pic_jabatan,
+ "detail": "Registrasi Akun Korporasi",
+ "timestamp": p.timestamp.isoformat() if p.timestamp else None
+ })
+ return {"success": True, "data": data}
+
+ elif action == "prosesMeetingRequest":
+ if len(params) < 3:
+ return {"success": False, "error": "Parameter kurang."}
+ email, token, data_meeting = params[0], params[1], params[2]
+
+ if not await local_verify_session(db, email, token):
+ return {"success": False, "error": "Sesi tidak valid."}
+
+ client_email = data_meeting.get("email")
+ perusahaan = data_meeting.get("perusahaan", "MOCK CORP")
+ nama = data_meeting.get("nama", "Recruiter")
+ topik = data_meeting.get("topik", "ESG Partnership")
+ pesan = data_meeting.get("pesan", "-")
+ selected_date = data_meeting.get("date", "")
+ selected_time = data_meeting.get("time", "")
+
+ date_text = f"{selected_date} {selected_time} WIB"
+ meet_url = f"https://meet.google.com/brg-esg-{secrets.token_hex(3)}"
+
+ subject = f"Thank You & Meeting Minutes: ESG Partnership Exploration - {perusahaan}"
+ html_body = f"""
+ Dear {nama},
+ Thank you for scheduling the B2B ESG Partnership Exploration with the Brigawan Sustainability Advisor team.
+ Meeting Details:
+
+ Topic: {topik}
+ Company: {perusahaan}
+ Date & Time: {date_text}
+ Google Meet Room: {meet_url}
+
+ Best regards, yabeskn@briga.id Brigawan AI Notetaker & Compliance Assistant
+ """
+ await asyncio.to_thread(email_service.send_html_email, client_email, subject, html_body)
+
+ admin_subject = f"[NEW BOOKING] ESG B2B Meeting - {perusahaan}"
+ admin_body = f"""
+ Ada permintaan meeting terverifikasi baru:
+ Nama: {nama}
+ Perusahaan: {perusahaan}
+ Email Klien: {client_email}
+ Topik: {topik}
+ Waktu: {date_text}
+ Google Meet Link: {meet_url}
+ Pesan Klien:
+ {pesan}
+ """
+ await asyncio.to_thread(email_service.send_html_email, "info@briga.id", admin_subject, admin_body)
+
+ return {
+ "success": True,
+ "meetUrl": meet_url,
+ "dateText": date_text,
+ "host": "Brigawan Sustainability Advisor"
+ }
+
+ elif action == "submitTalentRegistration":
+ if len(params) < 1:
+ return {"success": False, "error": "Parameter kurang."}
+ form_data = params[0]
+
+ name = form_data.get("nama")
+ email = form_data.get("email")
+ password = form_data.get("password")
+
+ if not email or not name or not password:
+ return {"success": False, "error": "Nama, email, dan password wajib diisi."}
+
+ from app.services.auth_service import register_talent
+ reg_data = {
+ "name": name,
+ "email": email,
+ "password": password,
+ "phone": form_data.get("telepon", ""),
+ "education": form_data.get("pendidikan", ""),
+ "experience": form_data.get("pengalaman", ""),
+ "location": form_data.get("kota", ""),
+ "skill_tags": form_data.get("sertifikasiLain", ""),
+ "cv_link": form_data.get("cvLink", "")
+ }
+
+ try:
+ res = await register_talent(db, reg_data)
+ welcome_subject = "Selamat Datang di Brigawan - Portal Green Talent"
+ welcome_html = f"""
+ Halo {name}!
+ Pendaftaran akun Anda di portal Brigawan telah berhasil dilakukan.
+ 3 koin gratis trial Anda telah diaktifkan untuk memulai navigasi karir hijau Anda.
+ """
+ await asyncio.to_thread(email_service.send_html_email, email, welcome_subject, welcome_html)
+
+ talent_id = res.get("user", {}).get("id", "BRIGA-GT-MOCK")
+ return {
+ "success": True,
+ "talentId": talent_id,
+ "data": {
+ "id": talent_id,
+ "name": name,
+ "email": email,
+ "verification": "Pending Docs",
+ "score": 70,
+ "kategori": "Semi-Skilled"
+ },
+ "evaluation": {
+ "nama": name,
+ "skor": "70",
+ "kategori": "Semi-Skilled",
+ "analisis": "Initial Registration Vetting",
+ "advisory": "-",
+ "skills": [],
+ "verified": False
+ }
+ }
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+ elif action == "purgeSheetTalent":
+ return {"success": True}
+
+ else:
+ logger.warning(f"[LegacyGASCompat] Unknown Action: {action}")
+ return {"success": False, "error": f"Aksi '{action}' belum didukung."}
+
+ except Exception as ex:
+ logger.error(f"[LegacyGASCompat] Error during action {action}: {ex}")
+ return {"success": False, "error": str(ex)}
diff --git a/app/api/talent.py b/app/api/talent.py
index 6ea21c229c9676bfde1370a565d6a3770b3912b8..d8e5ab5a84ae5325a907fa564ad930e8b437bf91 100644
--- a/app/api/talent.py
+++ b/app/api/talent.py
@@ -1,876 +1,876 @@
-"""Talent API Routes — Profile, Pathway, Green Score, Interview, Secure Data.
-
-All endpoints require authentication via JWT middleware.
-Public endpoints: /v1/talent/verify-certificate
-"""
-
-import base64
-import re
-from datetime import datetime, timezone
-from typing import Optional, Dict, Any
-
-from fastapi import APIRouter, Depends, Query, Request, UploadFile, File, Form
-from pydantic import BaseModel
-from sqlalchemy import select, func
-from sqlalchemy.ext.asyncio import AsyncSession
-import httpx
-from loguru import logger
-
-from app.database import get_db
-from app.models.talent import Talent
-from app.models.job import TalentPathway
-from app.config.settings import settings
-from app.services.security_service import security_service
-from app.services.ai_service import verify_screenshot_with_gemini
-
-from app.schemas.talent import (
- CertificateResponse,
- ChatRequest,
- ChatResponse,
- EvaluateGrillMeRequest,
- EvaluateGrillMeResponse,
- GrillMeQuestionsResponse,
- PathwayResponse,
- SecureTalentDataResponse,
- SubmitProofRequest,
- SubmitProofResponse,
- SubmitQuizRequest,
- SubmitQuizResponse,
- TalentProfileResponse,
- UpdateProfileRequest,
- UpdateProfileResponse,
- VerifyCertificateRequest,
- VerifyCertificateResponse,
-)
-from app.services.talent_service import (
- _get_chat_stats,
- _get_pathway,
- chat_with_brigawan,
- evaluate_grillme,
- generate_career_pathway,
- generate_grillme_questions,
- get_pathway_certificate,
- get_secure_talent_data,
- get_talent_profile,
- submit_action_proof,
- submit_quiz_answers,
- update_talent_profile,
- verify_certificate,
-)
-
-router = APIRouter(prefix="/v1/talent", tags=["Talent"])
-
-
-class LinkedInOAuthRequest(BaseModel):
- code: str
- redirect_uri: str
-
-
-def _calc_green_score(progress, completed):
- from app.services.talent_service import POINTS_PROOF, POINTS_QUIZ
- score = 0
- for stg_key, actions in (progress or {}).items():
- if isinstance(actions, list):
- for a in actions:
- if isinstance(a, dict) and a.get("done"):
- score += POINTS_PROOF
- score += len(completed or []) * POINTS_QUIZ
- return score
-
-
-def _check_auth(req: Request) -> Optional[str]:
- """Check authentication from middleware. Returns user email or None."""
- email = getattr(req.state, "user_email", None)
- if not email:
- return None
- return email
-
-
-# ─── Profile ────────────────────────────────────────────────────────────────
-
-
-@router.get("/profile", response_model=TalentProfileResponse)
-async def api_get_talent_profile(
- req: Request,
- db: AsyncSession = Depends(get_db),
-):
- """Get full talent dashboard profile with badges, pathway, academy, chat stats."""
- email = _check_auth(req)
- if not email:
- return TalentProfileResponse(success=False, error="Authentication required.")
-
- result = await get_talent_profile(db, email)
- return TalentProfileResponse(
- success=result.get("success", False),
- data=result.get("data"),
- error=result.get("error"),
- )
-
-
-@router.put("/profile", response_model=UpdateProfileResponse)
-async def api_update_talent_profile(
- req: Request,
- form_data: UpdateProfileRequest,
- db: AsyncSession = Depends(get_db),
-):
- """Update talent profile fields."""
- email = _check_auth(req)
- if not email:
- return UpdateProfileResponse(success=False, error="Authentication required.")
-
- result = await update_talent_profile(db, email, form_data.model_dump(exclude_none=True))
- return UpdateProfileResponse(
- success=result.get("success", False),
- message=result.get("message", ""),
- error=result.get("error"),
- )
-
-
-# ─── Career Pathway ─────────────────────────────────────────────────────────
-
-
-@router.get("/pathway", response_model=PathwayResponse)
-async def api_get_pathway(
- req: Request,
- db: AsyncSession = Depends(get_db),
-):
- """Get existing career pathway for the authenticated talent."""
- email = _check_auth(req)
- if not email:
- return PathwayResponse(success=False, error="Authentication required.")
-
- result = await _get_pathway(db, email)
- return PathwayResponse(
- success=True,
- pathway=result.get("pathway", []),
- progress=result.get("progress", {}),
- completedStages=result.get("completedStages", []),
- greenScore=result.get("greenScore", 0),
- cached=True,
- )
-
-
-@router.post("/pathway/generate", response_model=PathwayResponse)
-async def api_generate_pathway(
- req: Request,
- db: AsyncSession = Depends(get_db),
-):
- """Generate AI-powered career pathway (5 stages with actions, quizzes).
- Returns cached version if exists.
- """
- email = _check_auth(req)
- if not email:
- return PathwayResponse(success=False, error="Authentication required.")
-
- result = await generate_career_pathway(db, email)
- return PathwayResponse(
- success=result.get("success", False),
- pathway=result.get("pathway", []),
- progress=result.get("progress", {}),
- completedStages=result.get("completedStages", []),
- greenScore=result.get("greenScore", 0),
- cached=result.get("cached", False),
- error=result.get("error"),
- )
-
-
-@router.post("/pathway/proof", response_model=SubmitProofResponse)
-async def api_submit_proof(
- req: Request,
- body: SubmitProofRequest,
- db: AsyncSession = Depends(get_db),
-):
- """Submit proof for a specific action in the career pathway."""
- email = _check_auth(req)
- if not email:
- return SubmitProofResponse(success=False, error="Authentication required.")
-
- result = await submit_action_proof(db, email, body.stage, body.action_index, body.proof_text)
- return SubmitProofResponse(
- success=result.get("success", False),
- progress=result.get("progress", {}),
- completedStages=result.get("completedStages", []),
- greenScore=result.get("greenScore", 0),
- allActionsProven=result.get("allActionsProven", False),
- error=result.get("error"),
- )
-
-
-@router.post("/pathway/quiz", response_model=SubmitQuizResponse)
-async def api_submit_quiz(
- req: Request,
- body: SubmitQuizRequest,
- db: AsyncSession = Depends(get_db),
-):
- """Submit quiz answers for a stage. All actions must be proven first.
- All answers must be correct to pass.
- """
- email = _check_auth(req)
- if not email:
- return SubmitQuizResponse(success=False, error="Authentication required.")
-
- result = await submit_quiz_answers(db, email, body.stage, body.answers)
- return SubmitQuizResponse(
- success=result.get("success", False),
- completedStages=result.get("completedStages", []),
- greenScore=result.get("greenScore", 0),
- stageCompleted=result.get("stageCompleted", False),
- completedStageTitle=result.get("completedStageTitle", ""),
- error=result.get("error"),
- )
-
-
-@router.get("/pathway/certificate", response_model=CertificateResponse)
-async def api_get_certificate(
- req: Request,
- stage: int = Query(..., description="Stage number (1-5)"),
- db: AsyncSession = Depends(get_db),
-):
- """Get certificate for a completed stage."""
- email = _check_auth(req)
- if not email:
- return CertificateResponse(success=False, error="Authentication required.")
-
- result = await get_pathway_certificate(db, email, stage)
- return CertificateResponse(
- success=result.get("success", False),
- certificate=result.get("certificate"),
- error=result.get("error"),
- )
-
-
-@router.post("/linkedin-oauth")
-async def api_linkedin_oauth(
- req: Request,
- body: LinkedInOAuthRequest,
- db: AsyncSession = Depends(get_db)
-):
- """Exchange OAuth code for LinkedIn Access Token, verify name, encrypt, and save to DB."""
- email = _check_auth(req)
- if not email:
- return {"success": False, "error": "Authentication required."}
-
- # 1. Fetch Talent from DB
- result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
- talent = result.scalar_one_or_none()
- if not talent:
- return {"success": False, "error": "Profil talent tidak ditemukan."}
-
- # Mock/Bypass mode for development
- if settings.debug and (body.code.startswith("mock_code_") or not settings.linkedin_client_id or settings.linkedin_client_id == "YOUR_LINKEDIN_CLIENT_ID"):
- if body.code.startswith("mock_code_"):
- linkedin_name = body.code.replace("mock_code_", "").replace("_", " ").strip()
- else:
- linkedin_name = talent.name
-
- import difflib
- n1 = " ".join(talent.name.lower().strip().split())
- n2 = " ".join(linkedin_name.lower().strip().split())
- similarity_ratio = difflib.SequenceMatcher(None, n1, n2).ratio()
-
- n1_words = n1.split()
- n2_words = n2.split()
- common_words = set(n1_words).intersection(set(n2_words))
- num_common_words = len(common_words)
- either_single_word = (len(n1_words) <= 1 or len(n2_words) <= 1)
-
- is_valid = (
- similarity_ratio >= 0.75 or
- num_common_words >= 2 or
- (either_single_word and num_common_words >= 1)
- )
-
- logger.info(f"[Mock OAuth] Name comparison: Talent='{talent.name}', LinkedIn='{linkedin_name}', ratio={similarity_ratio:.4f}, common={num_common_words}")
-
- if not is_valid:
- return {
- "success": False,
- "error": f"Nama akun LinkedIn ('{linkedin_name}') tidak sesuai dengan nama profil Anda ('{talent.name}')."
- }
-
- dek = await security_service.get_or_create_profile_dek(db, talent.id)
- mock_token = f"mock_access_token_{linkedin_name.replace(' ', '_')}"
- encrypted_token = security_service._encrypt_with_dek(dek, mock_token)
-
- talent.linkedin_token = encrypted_token
- if not talent.linkedin_link:
- talent.linkedin_link = f"https://linkedin.com/in/mock_{linkedin_name.replace(' ', '_').lower()}"
-
- db.add(talent)
- await db.commit()
-
- return {
- "success": True,
- "message": "Akun LinkedIn berhasil dihubungkan dan diverifikasi (Mock Mode).",
- "linkedin_name": linkedin_name
- }
-
- # 2. Call LinkedIn Token API
- token_url = "https://www.linkedin.com/oauth/v2/accessToken"
- payload = {
- "grant_type": "authorization_code",
- "code": body.code,
- "redirect_uri": body.redirect_uri,
- "client_id": settings.linkedin_client_id,
- "client_secret": settings.linkedin_client_secret
- }
-
- try:
- async with httpx.AsyncClient(timeout=15.0) as client:
- resp = await client.post(token_url, data=payload)
- if resp.status_code != 200:
- logger.error(f"LinkedIn Token Exchange failed: {resp.status_code} - {resp.text}")
- return {"success": False, "error": "Gagal menukarkan kode otorisasi LinkedIn."}
-
- token_data = resp.json()
- access_token = token_data.get("access_token")
- if not access_token:
- return {"success": False, "error": "Token otorisasi kosong dari LinkedIn."}
-
- # 3. Retrieve User Profile from LinkedIn (OpenID Connect /userinfo or /v2/me)
- # Modern OIDC endpoint returns full name & email
- profile_url = "https://api.linkedin.com/v2/userinfo"
- headers = {"Authorization": f"Bearer {access_token}"}
- profile_resp = await client.get(profile_url, headers=headers)
-
- if profile_resp.status_code != 200:
- # Fallback to legacy v2 profile endpoint if OIDC is not active
- profile_url = "https://api.linkedin.com/v2/me"
- profile_resp = await client.get(profile_url, headers=headers)
-
- if profile_resp.status_code != 200:
- return {"success": False, "error": "Gagal mengambil profil akun LinkedIn Anda."}
-
- profile_data = profile_resp.json()
- # Try to resolve full name
- linkedin_name = profile_data.get("name")
- if not linkedin_name:
- given_name = profile_data.get("givenName", {}).get("localized", {}).get("en_US", "")
- family_name = profile_data.get("familyName", {}).get("localized", {}).get("en_US", "")
- linkedin_name = f"{given_name} {family_name}".strip()
-
- if not linkedin_name:
- linkedin_name = f"{profile_data.get('given_name', '')} {profile_data.get('family_name', '')}".strip()
-
- # 4. Perform Name Verification (Enhanced Similarity Match via difflib)
- import difflib
- n1 = " ".join(talent.name.lower().strip().split())
- n2 = " ".join(linkedin_name.lower().strip().split())
-
- similarity_ratio = difflib.SequenceMatcher(None, n1, n2).ratio()
-
- n1_words = n1.split()
- n2_words = n2.split()
- common_words = set(n1_words).intersection(set(n2_words))
- num_common_words = len(common_words)
- either_single_word = (len(n1_words) <= 1 or len(n2_words) <= 1)
-
- is_valid = (
- similarity_ratio >= 0.75 or
- num_common_words >= 2 or
- (either_single_word and num_common_words >= 1)
- )
-
- logger.info(f"LinkedIn Name comparison details: Talent='{talent.name}', LinkedIn='{linkedin_name}', ratio={similarity_ratio:.4f}, common={num_common_words}")
-
- if not is_valid:
- logger.warning(f"LinkedIn Identity verification failed: Talent='{talent.name}', LinkedIn='{linkedin_name}' (ratio={similarity_ratio:.4f}, common={num_common_words})")
- return {
- "success": False,
- "error": f"Nama akun LinkedIn ('{linkedin_name}') tidak sesuai dengan nama profil Anda ('{talent.name}')."
- }
-
- # 5. Encrypt access token using DEK Envelope Encryption
- dek = await security_service.get_or_create_profile_dek(db, talent.id)
- encrypted_token = security_service._encrypt_with_dek(dek, access_token)
-
- # 6. Save encrypted token and LinkedIn link to DB
- talent.linkedin_token = encrypted_token
- # Optionally sync the public LinkedIn link if found or set it
- sub_id = profile_data.get("sub", "")
- if sub_id and not talent.linkedin_link:
- talent.linkedin_link = f"https://linkedin.com/in/{sub_id}"
-
- db.add(talent)
- await db.commit()
-
- return {
- "success": True,
- "message": "Akun LinkedIn berhasil dihubungkan dan diverifikasi.",
- "linkedin_name": linkedin_name
- }
-
- except Exception as e:
- logger.error(f"api_linkedin_oauth exception: {e}")
- return {"success": False, "error": f"Kesalahan sistem: {str(e)}"}
-
-
-@router.post("/pathway/verify-linkedin-api")
-async def api_verify_pathway_linkedin(
- req: Request,
- body: Dict[str, Any], # expects stage, action_index
- db: AsyncSession = Depends(get_db)
-):
- """Pulls connected talent's posts from LinkedIn, verifies hashtag and Talent ID to approve action."""
- email = _check_auth(req)
- if not email:
- return {"success": False, "error": "Authentication required."}
-
- stage = body.get("stage")
- action_index = body.get("action_index")
- if stage is None or action_index is None:
- return {"success": False, "error": "Parameters 'stage' and 'action_index' are required."}
-
- # 1. Fetch Talent & Pathway
- t_result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
- talent = t_result.scalar_one_or_none()
-
- pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1))
- pw = pw_result.scalar_one_or_none()
-
- if not talent or not pw:
- return {"success": False, "error": "Data profil atau pathway tidak ditemukan."}
-
- if not talent.linkedin_token:
- return {"success": False, "error": "Silakan hubungkan akun LinkedIn Anda terlebih dahulu."}
-
- # 2. Decrypt LinkedIn token
- dek = await security_service.get_or_create_profile_dek(db, talent.id)
- access_token = security_service._decrypt_with_dek(dek, talent.linkedin_token)
-
- challenge_code = f"BRG-CH-{stage}-{action_index + 1}"
- verified_post_link = None
-
- # 3. Handle Mock Verification Mode
- if settings.debug and access_token.startswith("mock_"):
- logger.info(f"[Mock OAuth] Simulating successful LinkedIn post validation for {challenge_code}")
- verified_post_link = f"https://www.linkedin.com/feed/update/urn:li:share:mock_{challenge_code}"
- else:
- # Pull posts from LinkedIn API
- # Retrieves author's posts/shares
- sub_id = None
- try:
- async with httpx.AsyncClient(timeout=10.0) as client:
- # Try userinfo (OIDC)
- me_resp = await client.get("https://api.linkedin.com/v2/userinfo", headers={"Authorization": f"Bearer {access_token}"})
- if me_resp.status_code == 200:
- sub_id = me_resp.json().get("sub", "")
- else:
- # Try legacy v2/me
- me_resp = await client.get("https://api.linkedin.com/v2/me", headers={"Authorization": f"Bearer {access_token}"})
- if me_resp.status_code == 200:
- sub_id = me_resp.json().get("id", "")
- except Exception as e:
- logger.error(f"Failed to fetch LinkedIn me profile URN: {e}")
-
- if not sub_id:
- # Fallback to parsed vanity URL link ONLY if API fetches failed
- if talent.linkedin_link:
- sub_id = talent.linkedin_link.split("/in/")[-1].split("?")[0].strip("/")
- if not sub_id or sub_id == "me":
- sub_id = "me"
-
- shares_url = f"https://api.linkedin.com/v2/shares?q=owners&owners=urn:li:person:{sub_id}&count=20"
- headers = {"Authorization": f"Bearer {access_token}", "X-Restli-Protocol-Version": "2.0.0"}
-
- try:
- async with httpx.AsyncClient(timeout=15.0) as client:
- resp = await client.get(shares_url, headers=headers)
- if resp.status_code != 200:
- logger.error(f"Failed to fetch LinkedIn shares: {resp.status_code} - {resp.text}")
- return {"success": False, "error": "Gagal menarik kiriman dari LinkedIn. Silakan coba beberapa saat lagi."}
-
- posts_data = resp.json()
- elements = posts_data.get("elements", [])
-
- # 4. Search elements for validation criteria
- # Hashtag: #BrigaPathway
- # Text contains challenge_code (e.g. BRG-CH-1-1)
- hashtag_pattern = re.compile(r"#BrigaPathway", re.IGNORECASE)
- code_pattern = re.compile(re.escape(challenge_code), re.IGNORECASE)
-
- for post in elements:
- text = post.get("text", {}).get("text", "")
- if hashtag_pattern.search(text) and code_pattern.search(text):
- activity_urn = post.get("activity", "")
- # Construct public URL template
- verified_post_link = f"https://www.linkedin.com/feed/update/{activity_urn}"
- break
-
- if not verified_post_link:
- return {
- "success": False,
- "error": f"Kiriman LinkedIn tidak ditemukan. Pastikan Anda telah memposting dengan hashtag '#BrigaPathway' dan Kode Tantangan '{challenge_code}' secara publik."
- }
- except Exception as e:
- logger.error(f"api_verify_pathway_linkedin API call exception: {e}")
- return {"success": False, "error": f"Gagal menghubungi server LinkedIn: {str(e)}"}
-
- try:
- # 5. Update Pathway Progress
- progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
- completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
- pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
-
- sk = str(stage)
- if sk not in progress:
- progress[sk] = []
-
- while len(progress[sk]) <= action_index:
- progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
-
- progress[sk][action_index] = {
- "done": True,
- "proof": f"LinkedIn Verified Post: {verified_post_link}",
- "ts": datetime.now(timezone.utc).isoformat(),
- "status": "Approved"
- }
-
- # Recalculate score and save
- new_score = _calc_green_score(progress, completed)
- pw.progress_json = progress
- pw.green_score = new_score
- db.add(pw)
- talent.green_score = new_score
- db.add(talent)
- await db.commit()
-
- # Check if all actions in this stage are completed
- stage_data = next((s for s in pathway if s.get("stage") == stage), None)
- all_proven = False
- if stage_data:
- expected = len(stage_data.get("actions", []))
- all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
-
- return {
- "success": True,
- "progress": progress,
- "completedStages": [str(s) for s in completed],
- "greenScore": new_score,
- "allActionsProven": all_proven,
- "feedback": "Kiriman LinkedIn berhasil diverifikasi secara otomatis via API!"
- }
-
- except Exception as e:
- logger.error(f"api_verify_pathway_linkedin exception: {e}")
- return {"success": False, "error": f"Kesalahan sistem: {str(e)}"}
-
-
-@router.post("/pathway/verify-linkedin-screenshot")
-async def api_verify_pathway_screenshot(
- req: Request,
- file: UploadFile = File(...),
- stage: int = Form(...),
- action_index: int = Form(...),
- db: AsyncSession = Depends(get_db)
-):
- """Upload screenshot of LinkedIn post and use Gemini Vision to vet post contents."""
- email = _check_auth(req)
- if not email:
- return {"success": False, "error": "Authentication required."}
-
- # 1. Fetch Talent & Pathway
- t_result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
- talent = t_result.scalar_one_or_none()
-
- pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1))
- pw = pw_result.scalar_one_or_none()
-
- if not talent or not pw:
- return {"success": False, "error": "Data profil atau pathway tidak ditemukan."}
-
- # 2. Read image bytes
- try:
- image_bytes = await file.read()
- except Exception as e:
- return {"success": False, "error": f"Gagal membaca file gambar: {str(e)}"}
-
- challenge_code = f"BRG-CH-{stage}-{action_index + 1}"
-
- # 3. Call AI Service Vetting Function or Bypass in Mock mode
- if settings.debug and file.filename and "mock" in file.filename.lower():
- logger.info(f"[Mock Vision] Bypassing Gemini Vision API for screenshot file {file.filename}")
- vetting_result = {
- "success": True,
- "match": True,
- "extracted_name": talent.name,
- "has_hashtag": True,
- "has_challenge_code": True,
- "confidence": 0.95,
- "feedback": "Screenshot postingan LinkedIn berhasil diverifikasi secara otomatis via AI (Mock Mode)."
- }
- else:
- vetting_result = await verify_screenshot_with_gemini(
- image_bytes=image_bytes,
- talent_name=talent.name,
- challenge_code=challenge_code
- )
-
- if not vetting_result.get("success"):
- return {
- "success": False,
- "error": vetting_result.get("feedback", "Gagal menganalisis gambar screenshot via AI.")
- }
-
- if not vetting_result.get("match"):
- return {
- "success": False,
- "error": vetting_result.get("feedback", "Hasil analisis AI: Gambar tidak memenuhi kriteria verifikasi.")
- }
-
- # 4. AI Verification Successful - Update Progress
- progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
- completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
- pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
-
- sk = str(stage)
- if sk not in progress:
- progress[sk] = []
-
- while len(progress[sk]) <= action_index:
- progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
-
- progress[sk][action_index] = {
- "done": True,
- "proof": f"LinkedIn Screenshot verified by Gemini (Name: {vetting_result.get('extracted_name')}, Conf: {vetting_result.get('confidence')})",
- "ts": datetime.now(timezone.utc).isoformat(),
- "status": "Approved"
- }
-
- new_score = _calc_green_score(progress, completed)
- pw.progress_json = progress
- pw.green_score = new_score
- db.add(pw)
- talent.green_score = new_score
- db.add(talent)
- await db.commit()
-
- stage_data = next((s for s in pathway if s.get("stage") == stage), None)
- all_proven = False
- if stage_data:
- expected = len(stage_data.get("actions", []))
- all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
-
- return {
- "success": True,
- "progress": progress,
- "completedStages": [str(s) for s in completed],
- "greenScore": new_score,
- "allActionsProven": all_proven,
- "feedback": vetting_result.get("feedback", "Screenshot postingan LinkedIn berhasil diverifikasi secara otomatis via AI!")
- }
-
-
-# ─── AI Chat (Brigawan Career Coach) ────────────────────────────────────────
-
-
-@router.post("/chat", response_model=ChatResponse)
-async def api_chat(
- req: Request,
- body: ChatRequest,
- db: AsyncSession = Depends(get_db),
-):
- """Chat with Brigawan AI Career Coach. Limited to 10 chats per 24 hours."""
- email = _check_auth(req)
- if not email:
- return ChatResponse(success=False, error="Authentication required.")
-
- result = await chat_with_brigawan(db, email, body.message)
- return ChatResponse(
- success=result.get("success", False),
- reply=result.get("reply", ""),
- chatUsed=result.get("chatUsed", 0),
- chatLimit=result.get("chatLimit", 10),
- chatExpiry=result.get("chatExpiry", "-"),
- limitReached=result.get("limitReached", False),
- error=result.get("error"),
- )
-
-
-@router.get("/chat/stats", response_model=ChatResponse)
-async def api_chat_stats(
- req: Request,
- db: AsyncSession = Depends(get_db),
-):
- """Get AI chat usage statistics."""
- email = _check_auth(req)
- if not email:
- return ChatResponse(success=False, error="Authentication required.")
-
- stats = await _get_chat_stats(db, email)
- return ChatResponse(
- success=True,
- chatUsed=stats.get("used", 0),
- chatLimit=10,
- chatExpiry=stats.get("expiryTime", "-"),
- limitReached=stats.get("used", 0) >= 10,
- )
-
-
-# ─── Grill-Me Interview Simulation ──────────────────────────────────────────
-
-
-@router.get("/grillme/questions", response_model=GrillMeQuestionsResponse)
-async def api_grillme_questions(
- req: Request,
- category: str = Query("ESG Specialist", description="Green job category"),
-):
- """Generate 3 interview simulation questions for a green job category."""
- email = _check_auth(req)
- if not email:
- return GrillMeQuestionsResponse(success=False, error="Authentication required.")
-
- result = generate_grillme_questions(category)
- return GrillMeQuestionsResponse(
- success=result.get("success", False),
- questions=result.get("questions", []),
- isFallback=result.get("isFallback", False),
- error=result.get("error"),
- )
-
-
-@router.post("/grillme/evaluate", response_model=EvaluateGrillMeResponse)
-async def api_grillme_evaluate(
- req: Request,
- body: EvaluateGrillMeRequest,
-):
- """Evaluate interview answers and generate SWOT analysis."""
- email = _check_auth(req)
- if not email:
- return EvaluateGrillMeResponse(success=False, error="Authentication required.")
-
- result = evaluate_grillme(body.category, body.questions, body.answers)
- return EvaluateGrillMeResponse(
- success=result.get("success", False),
- score=result.get("score", 0),
- swot=result.get("swot"),
- rawSWOTText=result.get("rawSWOTText", ""),
- error=result.get("error"),
- )
-
-
-# ─── Secure Talent Data (PDP Compliant) ─────────────────────────────────────
-
-
-@router.get("/secure/{talent_id}", response_model=SecureTalentDataResponse)
-async def api_secure_talent_data(
- req: Request,
- talent_id: str,
- db: AsyncSession = Depends(get_db),
-):
- """Get secure talent data with PDP-compliant masking.
- Returns full data if requester has unlocked this candidate, masked otherwise.
- """
- email = _check_auth(req)
- if not email:
- return SecureTalentDataResponse(success=False, error="Authentication required.")
-
- result = await get_secure_talent_data(db, talent_id, email)
- return SecureTalentDataResponse(
- success=result.get("success", False),
- id_kandidat=result.get("id_kandidat", ""),
- nama=result.get("nama", ""),
- email=result.get("email", "[LOCKED]"),
- pendidikan=result.get("pendidikan", ""),
- pengalaman=result.get("pengalaman", ""),
- k3_dasar=result.get("k3_dasar", ""),
- k3_khusus=result.get("k3_khusus", ""),
- sertifikasi=result.get("sertifikasi", ""),
- bahasa=result.get("bahasa", ""),
- cv_link=result.get("cv_link", "[LOCKED - Reveal to Download]"),
- skor=result.get("skor", 0),
- kategori=result.get("kategori", ""),
- analisis=result.get("analisis", ""),
- status=result.get("status", ""),
- unlocked=result.get("unlocked", False),
- error=result.get("error"),
- )
-
-
-# ─── Public: Certificate Verification ───────────────────────────────────────
-
-
-@router.post("/verify-certificate", response_model=VerifyCertificateResponse)
-async def api_verify_certificate(
- body: VerifyCertificateRequest,
- db: AsyncSession = Depends(get_db),
-):
- """Public certificate verification via talent ID or SHA-256 hash.
- No authentication required — used for shareable certificate links.
- """
- result = await verify_certificate(db, body.talent_id, body.stage)
- return VerifyCertificateResponse(
- success=result.get("success", False),
- data=result.get("data"),
- error=result.get("error"),
- )
-
-
-# ─── Public: Magic Fill CV Vetting (Local Converter) ───────────────────────
-
-from pydantic import BaseModel
-
-class MagicFillRequest(BaseModel):
- name: str
- type: str
- base64: str
-
-@router.post("/magic-fill")
-async def api_magic_fill_cv(
- body: MagicFillRequest,
-):
- """Refined CV Parsing: Convert PDF to MD using markitdown, then extract profile with Gemini.
- No authentication required (called during signup flow).
- """
- import base64
- import tempfile
- import os
- from markitdown import MarkItDown
- from app.services.ai_service import extract_cv_metadata
- from loguru import logger
-
- try:
- # 1. Decode base64 to bytes
- file_bytes = base64.b64decode(body.base64)
-
- # 2. Determine file suffix
- ext = ".pdf"
- if "word" in body.type or body.name.lower().endswith(".docx"):
- ext = ".docx"
- elif body.name.lower().endswith(".doc"):
- ext = ".doc"
- elif body.name.lower().endswith(".html") or body.name.lower().endswith(".htm"):
- ext = ".html"
- elif body.name.lower().endswith(".txt"):
- ext = ".txt"
-
- # 3. Write temporarily to local storage
- with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp_file:
- temp_file.write(file_bytes)
- temp_path = temp_file.name
-
- # 4. Process conversion via local markitdown
- try:
- markitdown = MarkItDown()
- result = markitdown.convert(temp_path)
- cv_markdown = result.text_content
- finally:
- # Clean up temp file safely
- if os.path.exists(temp_path):
- os.remove(temp_path)
-
- # 5. Extract JSON metadata from the Markdown text using Gemini
- if not cv_markdown or len(cv_markdown.strip()) < 50:
- return {"success": False, "error": "Teks CV terlalu pendek atau kosong untuk dianalisis."}
-
- extracted_data = await extract_cv_metadata(cv_markdown)
-
- if "error" in extracted_data:
- return {"success": False, "error": extracted_data["error"]}
-
- return {"success": True, "data": extracted_data}
-
- except Exception as e:
- logger.error(f"api_magic_fill_cv error: {e}")
- return {"success": False, "error": f"Gagal mengekstrak berkas CV: {str(e)}"}
-
+"""Talent API Routes — Profile, Pathway, Green Score, Interview, Secure Data.
+
+All endpoints require authentication via JWT middleware.
+Public endpoints: /v1/talent/verify-certificate
+"""
+
+import base64
+import re
+from datetime import datetime, timezone
+from typing import Optional, Dict, Any
+
+from fastapi import APIRouter, Depends, Query, Request, UploadFile, File, Form
+from pydantic import BaseModel
+from sqlalchemy import select, func
+from sqlalchemy.ext.asyncio import AsyncSession
+import httpx
+from loguru import logger
+
+from app.database import get_db
+from app.models.talent import Talent
+from app.models.job import TalentPathway
+from app.config.settings import settings
+from app.services.security_service import security_service
+from app.services.ai_service import verify_screenshot_with_gemini
+
+from app.schemas.talent import (
+ CertificateResponse,
+ ChatRequest,
+ ChatResponse,
+ EvaluateGrillMeRequest,
+ EvaluateGrillMeResponse,
+ GrillMeQuestionsResponse,
+ PathwayResponse,
+ SecureTalentDataResponse,
+ SubmitProofRequest,
+ SubmitProofResponse,
+ SubmitQuizRequest,
+ SubmitQuizResponse,
+ TalentProfileResponse,
+ UpdateProfileRequest,
+ UpdateProfileResponse,
+ VerifyCertificateRequest,
+ VerifyCertificateResponse,
+)
+from app.services.talent_service import (
+ _get_chat_stats,
+ _get_pathway,
+ chat_with_brigawan,
+ evaluate_grillme,
+ generate_career_pathway,
+ generate_grillme_questions,
+ get_pathway_certificate,
+ get_secure_talent_data,
+ get_talent_profile,
+ submit_action_proof,
+ submit_quiz_answers,
+ update_talent_profile,
+ verify_certificate,
+)
+
+router = APIRouter(prefix="/v1/talent", tags=["Talent"])
+
+
+class LinkedInOAuthRequest(BaseModel):
+ code: str
+ redirect_uri: str
+
+
+def _calc_green_score(progress, completed):
+ from app.services.talent_service import POINTS_PROOF, POINTS_QUIZ
+ score = 0
+ for stg_key, actions in (progress or {}).items():
+ if isinstance(actions, list):
+ for a in actions:
+ if isinstance(a, dict) and a.get("done"):
+ score += POINTS_PROOF
+ score += len(completed or []) * POINTS_QUIZ
+ return score
+
+
+def _check_auth(req: Request) -> Optional[str]:
+ """Check authentication from middleware. Returns user email or None."""
+ email = getattr(req.state, "user_email", None)
+ if not email:
+ return None
+ return email
+
+
+# ─── Profile ────────────────────────────────────────────────────────────────
+
+
+@router.get("/profile", response_model=TalentProfileResponse)
+async def api_get_talent_profile(
+ req: Request,
+ db: AsyncSession = Depends(get_db),
+):
+ """Get full talent dashboard profile with badges, pathway, academy, chat stats."""
+ email = _check_auth(req)
+ if not email:
+ return TalentProfileResponse(success=False, error="Authentication required.")
+
+ result = await get_talent_profile(db, email)
+ return TalentProfileResponse(
+ success=result.get("success", False),
+ data=result.get("data"),
+ error=result.get("error"),
+ )
+
+
+@router.put("/profile", response_model=UpdateProfileResponse)
+async def api_update_talent_profile(
+ req: Request,
+ form_data: UpdateProfileRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """Update talent profile fields."""
+ email = _check_auth(req)
+ if not email:
+ return UpdateProfileResponse(success=False, error="Authentication required.")
+
+ result = await update_talent_profile(db, email, form_data.model_dump(exclude_none=True))
+ return UpdateProfileResponse(
+ success=result.get("success", False),
+ message=result.get("message", ""),
+ error=result.get("error"),
+ )
+
+
+# ─── Career Pathway ─────────────────────────────────────────────────────────
+
+
+@router.get("/pathway", response_model=PathwayResponse)
+async def api_get_pathway(
+ req: Request,
+ db: AsyncSession = Depends(get_db),
+):
+ """Get existing career pathway for the authenticated talent."""
+ email = _check_auth(req)
+ if not email:
+ return PathwayResponse(success=False, error="Authentication required.")
+
+ result = await _get_pathway(db, email)
+ return PathwayResponse(
+ success=True,
+ pathway=result.get("pathway", []),
+ progress=result.get("progress", {}),
+ completedStages=result.get("completedStages", []),
+ greenScore=result.get("greenScore", 0),
+ cached=True,
+ )
+
+
+@router.post("/pathway/generate", response_model=PathwayResponse)
+async def api_generate_pathway(
+ req: Request,
+ db: AsyncSession = Depends(get_db),
+):
+ """Generate AI-powered career pathway (5 stages with actions, quizzes).
+ Returns cached version if exists.
+ """
+ email = _check_auth(req)
+ if not email:
+ return PathwayResponse(success=False, error="Authentication required.")
+
+ result = await generate_career_pathway(db, email)
+ return PathwayResponse(
+ success=result.get("success", False),
+ pathway=result.get("pathway", []),
+ progress=result.get("progress", {}),
+ completedStages=result.get("completedStages", []),
+ greenScore=result.get("greenScore", 0),
+ cached=result.get("cached", False),
+ error=result.get("error"),
+ )
+
+
+@router.post("/pathway/proof", response_model=SubmitProofResponse)
+async def api_submit_proof(
+ req: Request,
+ body: SubmitProofRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """Submit proof for a specific action in the career pathway."""
+ email = _check_auth(req)
+ if not email:
+ return SubmitProofResponse(success=False, error="Authentication required.")
+
+ result = await submit_action_proof(db, email, body.stage, body.action_index, body.proof_text)
+ return SubmitProofResponse(
+ success=result.get("success", False),
+ progress=result.get("progress", {}),
+ completedStages=result.get("completedStages", []),
+ greenScore=result.get("greenScore", 0),
+ allActionsProven=result.get("allActionsProven", False),
+ error=result.get("error"),
+ )
+
+
+@router.post("/pathway/quiz", response_model=SubmitQuizResponse)
+async def api_submit_quiz(
+ req: Request,
+ body: SubmitQuizRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """Submit quiz answers for a stage. All actions must be proven first.
+ All answers must be correct to pass.
+ """
+ email = _check_auth(req)
+ if not email:
+ return SubmitQuizResponse(success=False, error="Authentication required.")
+
+ result = await submit_quiz_answers(db, email, body.stage, body.answers)
+ return SubmitQuizResponse(
+ success=result.get("success", False),
+ completedStages=result.get("completedStages", []),
+ greenScore=result.get("greenScore", 0),
+ stageCompleted=result.get("stageCompleted", False),
+ completedStageTitle=result.get("completedStageTitle", ""),
+ error=result.get("error"),
+ )
+
+
+@router.get("/pathway/certificate", response_model=CertificateResponse)
+async def api_get_certificate(
+ req: Request,
+ stage: int = Query(..., description="Stage number (1-5)"),
+ db: AsyncSession = Depends(get_db),
+):
+ """Get certificate for a completed stage."""
+ email = _check_auth(req)
+ if not email:
+ return CertificateResponse(success=False, error="Authentication required.")
+
+ result = await get_pathway_certificate(db, email, stage)
+ return CertificateResponse(
+ success=result.get("success", False),
+ certificate=result.get("certificate"),
+ error=result.get("error"),
+ )
+
+
+@router.post("/linkedin-oauth")
+async def api_linkedin_oauth(
+ req: Request,
+ body: LinkedInOAuthRequest,
+ db: AsyncSession = Depends(get_db)
+):
+ """Exchange OAuth code for LinkedIn Access Token, verify name, encrypt, and save to DB."""
+ email = _check_auth(req)
+ if not email:
+ return {"success": False, "error": "Authentication required."}
+
+ # 1. Fetch Talent from DB
+ result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
+ talent = result.scalar_one_or_none()
+ if not talent:
+ return {"success": False, "error": "Profil talent tidak ditemukan."}
+
+ # Mock/Bypass mode for development
+ if settings.debug and (body.code.startswith("mock_code_") or not settings.linkedin_client_id or settings.linkedin_client_id == "YOUR_LINKEDIN_CLIENT_ID"):
+ if body.code.startswith("mock_code_"):
+ linkedin_name = body.code.replace("mock_code_", "").replace("_", " ").strip()
+ else:
+ linkedin_name = talent.name
+
+ import difflib
+ n1 = " ".join(talent.name.lower().strip().split())
+ n2 = " ".join(linkedin_name.lower().strip().split())
+ similarity_ratio = difflib.SequenceMatcher(None, n1, n2).ratio()
+
+ n1_words = n1.split()
+ n2_words = n2.split()
+ common_words = set(n1_words).intersection(set(n2_words))
+ num_common_words = len(common_words)
+ either_single_word = (len(n1_words) <= 1 or len(n2_words) <= 1)
+
+ is_valid = (
+ similarity_ratio >= 0.75 or
+ num_common_words >= 2 or
+ (either_single_word and num_common_words >= 1)
+ )
+
+ logger.info(f"[Mock OAuth] Name comparison: Talent='{talent.name}', LinkedIn='{linkedin_name}', ratio={similarity_ratio:.4f}, common={num_common_words}")
+
+ if not is_valid:
+ return {
+ "success": False,
+ "error": f"Nama akun LinkedIn ('{linkedin_name}') tidak sesuai dengan nama profil Anda ('{talent.name}')."
+ }
+
+ dek = await security_service.get_or_create_profile_dek(db, talent.id)
+ mock_token = f"mock_access_token_{linkedin_name.replace(' ', '_')}"
+ encrypted_token = security_service._encrypt_with_dek(dek, mock_token)
+
+ talent.linkedin_token = encrypted_token
+ if not talent.linkedin_link:
+ talent.linkedin_link = f"https://linkedin.com/in/mock_{linkedin_name.replace(' ', '_').lower()}"
+
+ db.add(talent)
+ await db.commit()
+
+ return {
+ "success": True,
+ "message": "Akun LinkedIn berhasil dihubungkan dan diverifikasi (Mock Mode).",
+ "linkedin_name": linkedin_name
+ }
+
+ # 2. Call LinkedIn Token API
+ token_url = "https://www.linkedin.com/oauth/v2/accessToken"
+ payload = {
+ "grant_type": "authorization_code",
+ "code": body.code,
+ "redirect_uri": body.redirect_uri,
+ "client_id": settings.linkedin_client_id,
+ "client_secret": settings.linkedin_client_secret
+ }
+
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(token_url, data=payload)
+ if resp.status_code != 200:
+ logger.error(f"LinkedIn Token Exchange failed: {resp.status_code} - {resp.text}")
+ return {"success": False, "error": "Gagal menukarkan kode otorisasi LinkedIn."}
+
+ token_data = resp.json()
+ access_token = token_data.get("access_token")
+ if not access_token:
+ return {"success": False, "error": "Token otorisasi kosong dari LinkedIn."}
+
+ # 3. Retrieve User Profile from LinkedIn (OpenID Connect /userinfo or /v2/me)
+ # Modern OIDC endpoint returns full name & email
+ profile_url = "https://api.linkedin.com/v2/userinfo"
+ headers = {"Authorization": f"Bearer {access_token}"}
+ profile_resp = await client.get(profile_url, headers=headers)
+
+ if profile_resp.status_code != 200:
+ # Fallback to legacy v2 profile endpoint if OIDC is not active
+ profile_url = "https://api.linkedin.com/v2/me"
+ profile_resp = await client.get(profile_url, headers=headers)
+
+ if profile_resp.status_code != 200:
+ return {"success": False, "error": "Gagal mengambil profil akun LinkedIn Anda."}
+
+ profile_data = profile_resp.json()
+ # Try to resolve full name
+ linkedin_name = profile_data.get("name")
+ if not linkedin_name:
+ given_name = profile_data.get("givenName", {}).get("localized", {}).get("en_US", "")
+ family_name = profile_data.get("familyName", {}).get("localized", {}).get("en_US", "")
+ linkedin_name = f"{given_name} {family_name}".strip()
+
+ if not linkedin_name:
+ linkedin_name = f"{profile_data.get('given_name', '')} {profile_data.get('family_name', '')}".strip()
+
+ # 4. Perform Name Verification (Enhanced Similarity Match via difflib)
+ import difflib
+ n1 = " ".join(talent.name.lower().strip().split())
+ n2 = " ".join(linkedin_name.lower().strip().split())
+
+ similarity_ratio = difflib.SequenceMatcher(None, n1, n2).ratio()
+
+ n1_words = n1.split()
+ n2_words = n2.split()
+ common_words = set(n1_words).intersection(set(n2_words))
+ num_common_words = len(common_words)
+ either_single_word = (len(n1_words) <= 1 or len(n2_words) <= 1)
+
+ is_valid = (
+ similarity_ratio >= 0.75 or
+ num_common_words >= 2 or
+ (either_single_word and num_common_words >= 1)
+ )
+
+ logger.info(f"LinkedIn Name comparison details: Talent='{talent.name}', LinkedIn='{linkedin_name}', ratio={similarity_ratio:.4f}, common={num_common_words}")
+
+ if not is_valid:
+ logger.warning(f"LinkedIn Identity verification failed: Talent='{talent.name}', LinkedIn='{linkedin_name}' (ratio={similarity_ratio:.4f}, common={num_common_words})")
+ return {
+ "success": False,
+ "error": f"Nama akun LinkedIn ('{linkedin_name}') tidak sesuai dengan nama profil Anda ('{talent.name}')."
+ }
+
+ # 5. Encrypt access token using DEK Envelope Encryption
+ dek = await security_service.get_or_create_profile_dek(db, talent.id)
+ encrypted_token = security_service._encrypt_with_dek(dek, access_token)
+
+ # 6. Save encrypted token and LinkedIn link to DB
+ talent.linkedin_token = encrypted_token
+ # Optionally sync the public LinkedIn link if found or set it
+ sub_id = profile_data.get("sub", "")
+ if sub_id and not talent.linkedin_link:
+ talent.linkedin_link = f"https://linkedin.com/in/{sub_id}"
+
+ db.add(talent)
+ await db.commit()
+
+ return {
+ "success": True,
+ "message": "Akun LinkedIn berhasil dihubungkan dan diverifikasi.",
+ "linkedin_name": linkedin_name
+ }
+
+ except Exception as e:
+ logger.error(f"api_linkedin_oauth exception: {e}")
+ return {"success": False, "error": f"Kesalahan sistem: {str(e)}"}
+
+
+@router.post("/pathway/verify-linkedin-api")
+async def api_verify_pathway_linkedin(
+ req: Request,
+ body: Dict[str, Any], # expects stage, action_index
+ db: AsyncSession = Depends(get_db)
+):
+ """Pulls connected talent's posts from LinkedIn, verifies hashtag and Talent ID to approve action."""
+ email = _check_auth(req)
+ if not email:
+ return {"success": False, "error": "Authentication required."}
+
+ stage = body.get("stage")
+ action_index = body.get("action_index")
+ if stage is None or action_index is None:
+ return {"success": False, "error": "Parameters 'stage' and 'action_index' are required."}
+
+ # 1. Fetch Talent & Pathway
+ t_result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
+ talent = t_result.scalar_one_or_none()
+
+ pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1))
+ pw = pw_result.scalar_one_or_none()
+
+ if not talent or not pw:
+ return {"success": False, "error": "Data profil atau pathway tidak ditemukan."}
+
+ if not talent.linkedin_token:
+ return {"success": False, "error": "Silakan hubungkan akun LinkedIn Anda terlebih dahulu."}
+
+ # 2. Decrypt LinkedIn token
+ dek = await security_service.get_or_create_profile_dek(db, talent.id)
+ access_token = security_service._decrypt_with_dek(dek, talent.linkedin_token)
+
+ challenge_code = f"BRG-CH-{stage}-{action_index + 1}"
+ verified_post_link = None
+
+ # 3. Handle Mock Verification Mode
+ if settings.debug and access_token.startswith("mock_"):
+ logger.info(f"[Mock OAuth] Simulating successful LinkedIn post validation for {challenge_code}")
+ verified_post_link = f"https://www.linkedin.com/feed/update/urn:li:share:mock_{challenge_code}"
+ else:
+ # Pull posts from LinkedIn API
+ # Retrieves author's posts/shares
+ sub_id = None
+ try:
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ # Try userinfo (OIDC)
+ me_resp = await client.get("https://api.linkedin.com/v2/userinfo", headers={"Authorization": f"Bearer {access_token}"})
+ if me_resp.status_code == 200:
+ sub_id = me_resp.json().get("sub", "")
+ else:
+ # Try legacy v2/me
+ me_resp = await client.get("https://api.linkedin.com/v2/me", headers={"Authorization": f"Bearer {access_token}"})
+ if me_resp.status_code == 200:
+ sub_id = me_resp.json().get("id", "")
+ except Exception as e:
+ logger.error(f"Failed to fetch LinkedIn me profile URN: {e}")
+
+ if not sub_id:
+ # Fallback to parsed vanity URL link ONLY if API fetches failed
+ if talent.linkedin_link:
+ sub_id = talent.linkedin_link.split("/in/")[-1].split("?")[0].strip("/")
+ if not sub_id or sub_id == "me":
+ sub_id = "me"
+
+ shares_url = f"https://api.linkedin.com/v2/shares?q=owners&owners=urn:li:person:{sub_id}&count=20"
+ headers = {"Authorization": f"Bearer {access_token}", "X-Restli-Protocol-Version": "2.0.0"}
+
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(shares_url, headers=headers)
+ if resp.status_code != 200:
+ logger.error(f"Failed to fetch LinkedIn shares: {resp.status_code} - {resp.text}")
+ return {"success": False, "error": "Gagal menarik kiriman dari LinkedIn. Silakan coba beberapa saat lagi."}
+
+ posts_data = resp.json()
+ elements = posts_data.get("elements", [])
+
+ # 4. Search elements for validation criteria
+ # Hashtag: #BrigaPathway
+ # Text contains challenge_code (e.g. BRG-CH-1-1)
+ hashtag_pattern = re.compile(r"#BrigaPathway", re.IGNORECASE)
+ code_pattern = re.compile(re.escape(challenge_code), re.IGNORECASE)
+
+ for post in elements:
+ text = post.get("text", {}).get("text", "")
+ if hashtag_pattern.search(text) and code_pattern.search(text):
+ activity_urn = post.get("activity", "")
+ # Construct public URL template
+ verified_post_link = f"https://www.linkedin.com/feed/update/{activity_urn}"
+ break
+
+ if not verified_post_link:
+ return {
+ "success": False,
+ "error": f"Kiriman LinkedIn tidak ditemukan. Pastikan Anda telah memposting dengan hashtag '#BrigaPathway' dan Kode Tantangan '{challenge_code}' secara publik."
+ }
+ except Exception as e:
+ logger.error(f"api_verify_pathway_linkedin API call exception: {e}")
+ return {"success": False, "error": f"Gagal menghubungi server LinkedIn: {str(e)}"}
+
+ try:
+ # 5. Update Pathway Progress
+ progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
+ completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
+ pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
+
+ sk = str(stage)
+ if sk not in progress:
+ progress[sk] = []
+
+ while len(progress[sk]) <= action_index:
+ progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
+
+ progress[sk][action_index] = {
+ "done": True,
+ "proof": f"LinkedIn Verified Post: {verified_post_link}",
+ "ts": datetime.now(timezone.utc).isoformat(),
+ "status": "Approved"
+ }
+
+ # Recalculate score and save
+ new_score = _calc_green_score(progress, completed)
+ pw.progress_json = progress
+ pw.green_score = new_score
+ db.add(pw)
+ talent.green_score = new_score
+ db.add(talent)
+ await db.commit()
+
+ # Check if all actions in this stage are completed
+ stage_data = next((s for s in pathway if s.get("stage") == stage), None)
+ all_proven = False
+ if stage_data:
+ expected = len(stage_data.get("actions", []))
+ all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
+
+ return {
+ "success": True,
+ "progress": progress,
+ "completedStages": [str(s) for s in completed],
+ "greenScore": new_score,
+ "allActionsProven": all_proven,
+ "feedback": "Kiriman LinkedIn berhasil diverifikasi secara otomatis via API!"
+ }
+
+ except Exception as e:
+ logger.error(f"api_verify_pathway_linkedin exception: {e}")
+ return {"success": False, "error": f"Kesalahan sistem: {str(e)}"}
+
+
+@router.post("/pathway/verify-linkedin-screenshot")
+async def api_verify_pathway_screenshot(
+ req: Request,
+ file: UploadFile = File(...),
+ stage: int = Form(...),
+ action_index: int = Form(...),
+ db: AsyncSession = Depends(get_db)
+):
+ """Upload screenshot of LinkedIn post and use Gemini Vision to vet post contents."""
+ email = _check_auth(req)
+ if not email:
+ return {"success": False, "error": "Authentication required."}
+
+ # 1. Fetch Talent & Pathway
+ t_result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
+ talent = t_result.scalar_one_or_none()
+
+ pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1))
+ pw = pw_result.scalar_one_or_none()
+
+ if not talent or not pw:
+ return {"success": False, "error": "Data profil atau pathway tidak ditemukan."}
+
+ # 2. Read image bytes
+ try:
+ image_bytes = await file.read()
+ except Exception as e:
+ return {"success": False, "error": f"Gagal membaca file gambar: {str(e)}"}
+
+ challenge_code = f"BRG-CH-{stage}-{action_index + 1}"
+
+ # 3. Call AI Service Vetting Function or Bypass in Mock mode
+ if settings.debug and file.filename and "mock" in file.filename.lower():
+ logger.info(f"[Mock Vision] Bypassing Gemini Vision API for screenshot file {file.filename}")
+ vetting_result = {
+ "success": True,
+ "match": True,
+ "extracted_name": talent.name,
+ "has_hashtag": True,
+ "has_challenge_code": True,
+ "confidence": 0.95,
+ "feedback": "Screenshot postingan LinkedIn berhasil diverifikasi secara otomatis via AI (Mock Mode)."
+ }
+ else:
+ vetting_result = await verify_screenshot_with_gemini(
+ image_bytes=image_bytes,
+ talent_name=talent.name,
+ challenge_code=challenge_code
+ )
+
+ if not vetting_result.get("success"):
+ return {
+ "success": False,
+ "error": vetting_result.get("feedback", "Gagal menganalisis gambar screenshot via AI.")
+ }
+
+ if not vetting_result.get("match"):
+ return {
+ "success": False,
+ "error": vetting_result.get("feedback", "Hasil analisis AI: Gambar tidak memenuhi kriteria verifikasi.")
+ }
+
+ # 4. AI Verification Successful - Update Progress
+ progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
+ completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
+ pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
+
+ sk = str(stage)
+ if sk not in progress:
+ progress[sk] = []
+
+ while len(progress[sk]) <= action_index:
+ progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
+
+ progress[sk][action_index] = {
+ "done": True,
+ "proof": f"LinkedIn Screenshot verified by Gemini (Name: {vetting_result.get('extracted_name')}, Conf: {vetting_result.get('confidence')})",
+ "ts": datetime.now(timezone.utc).isoformat(),
+ "status": "Approved"
+ }
+
+ new_score = _calc_green_score(progress, completed)
+ pw.progress_json = progress
+ pw.green_score = new_score
+ db.add(pw)
+ talent.green_score = new_score
+ db.add(talent)
+ await db.commit()
+
+ stage_data = next((s for s in pathway if s.get("stage") == stage), None)
+ all_proven = False
+ if stage_data:
+ expected = len(stage_data.get("actions", []))
+ all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
+
+ return {
+ "success": True,
+ "progress": progress,
+ "completedStages": [str(s) for s in completed],
+ "greenScore": new_score,
+ "allActionsProven": all_proven,
+ "feedback": vetting_result.get("feedback", "Screenshot postingan LinkedIn berhasil diverifikasi secara otomatis via AI!")
+ }
+
+
+# ─── AI Chat (Brigawan Career Coach) ────────────────────────────────────────
+
+
+@router.post("/chat", response_model=ChatResponse)
+async def api_chat(
+ req: Request,
+ body: ChatRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """Chat with Brigawan AI Career Coach. Limited to 10 chats per 24 hours."""
+ email = _check_auth(req)
+ if not email:
+ return ChatResponse(success=False, error="Authentication required.")
+
+ result = await chat_with_brigawan(db, email, body.message)
+ return ChatResponse(
+ success=result.get("success", False),
+ reply=result.get("reply", ""),
+ chatUsed=result.get("chatUsed", 0),
+ chatLimit=result.get("chatLimit", 10),
+ chatExpiry=result.get("chatExpiry", "-"),
+ limitReached=result.get("limitReached", False),
+ error=result.get("error"),
+ )
+
+
+@router.get("/chat/stats", response_model=ChatResponse)
+async def api_chat_stats(
+ req: Request,
+ db: AsyncSession = Depends(get_db),
+):
+ """Get AI chat usage statistics."""
+ email = _check_auth(req)
+ if not email:
+ return ChatResponse(success=False, error="Authentication required.")
+
+ stats = await _get_chat_stats(db, email)
+ return ChatResponse(
+ success=True,
+ chatUsed=stats.get("used", 0),
+ chatLimit=10,
+ chatExpiry=stats.get("expiryTime", "-"),
+ limitReached=stats.get("used", 0) >= 10,
+ )
+
+
+# ─── Grill-Me Interview Simulation ──────────────────────────────────────────
+
+
+@router.get("/grillme/questions", response_model=GrillMeQuestionsResponse)
+async def api_grillme_questions(
+ req: Request,
+ category: str = Query("ESG Specialist", description="Green job category"),
+):
+ """Generate 3 interview simulation questions for a green job category."""
+ email = _check_auth(req)
+ if not email:
+ return GrillMeQuestionsResponse(success=False, error="Authentication required.")
+
+ result = generate_grillme_questions(category)
+ return GrillMeQuestionsResponse(
+ success=result.get("success", False),
+ questions=result.get("questions", []),
+ isFallback=result.get("isFallback", False),
+ error=result.get("error"),
+ )
+
+
+@router.post("/grillme/evaluate", response_model=EvaluateGrillMeResponse)
+async def api_grillme_evaluate(
+ req: Request,
+ body: EvaluateGrillMeRequest,
+):
+ """Evaluate interview answers and generate SWOT analysis."""
+ email = _check_auth(req)
+ if not email:
+ return EvaluateGrillMeResponse(success=False, error="Authentication required.")
+
+ result = evaluate_grillme(body.category, body.questions, body.answers)
+ return EvaluateGrillMeResponse(
+ success=result.get("success", False),
+ score=result.get("score", 0),
+ swot=result.get("swot"),
+ rawSWOTText=result.get("rawSWOTText", ""),
+ error=result.get("error"),
+ )
+
+
+# ─── Secure Talent Data (PDP Compliant) ─────────────────────────────────────
+
+
+@router.get("/secure/{talent_id}", response_model=SecureTalentDataResponse)
+async def api_secure_talent_data(
+ req: Request,
+ talent_id: str,
+ db: AsyncSession = Depends(get_db),
+):
+ """Get secure talent data with PDP-compliant masking.
+ Returns full data if requester has unlocked this candidate, masked otherwise.
+ """
+ email = _check_auth(req)
+ if not email:
+ return SecureTalentDataResponse(success=False, error="Authentication required.")
+
+ result = await get_secure_talent_data(db, talent_id, email)
+ return SecureTalentDataResponse(
+ success=result.get("success", False),
+ id_kandidat=result.get("id_kandidat", ""),
+ nama=result.get("nama", ""),
+ email=result.get("email", "[LOCKED]"),
+ pendidikan=result.get("pendidikan", ""),
+ pengalaman=result.get("pengalaman", ""),
+ k3_dasar=result.get("k3_dasar", ""),
+ k3_khusus=result.get("k3_khusus", ""),
+ sertifikasi=result.get("sertifikasi", ""),
+ bahasa=result.get("bahasa", ""),
+ cv_link=result.get("cv_link", "[LOCKED - Reveal to Download]"),
+ skor=result.get("skor", 0),
+ kategori=result.get("kategori", ""),
+ analisis=result.get("analisis", ""),
+ status=result.get("status", ""),
+ unlocked=result.get("unlocked", False),
+ error=result.get("error"),
+ )
+
+
+# ─── Public: Certificate Verification ───────────────────────────────────────
+
+
+@router.post("/verify-certificate", response_model=VerifyCertificateResponse)
+async def api_verify_certificate(
+ body: VerifyCertificateRequest,
+ db: AsyncSession = Depends(get_db),
+):
+ """Public certificate verification via talent ID or SHA-256 hash.
+ No authentication required — used for shareable certificate links.
+ """
+ result = await verify_certificate(db, body.talent_id, body.stage)
+ return VerifyCertificateResponse(
+ success=result.get("success", False),
+ data=result.get("data"),
+ error=result.get("error"),
+ )
+
+
+# ─── Public: Magic Fill CV Vetting (Local Converter) ───────────────────────
+
+from pydantic import BaseModel
+
+class MagicFillRequest(BaseModel):
+ name: str
+ type: str
+ base64: str
+
+@router.post("/magic-fill")
+async def api_magic_fill_cv(
+ body: MagicFillRequest,
+):
+ """Refined CV Parsing: Convert PDF to MD using markitdown, then extract profile with Gemini.
+ No authentication required (called during signup flow).
+ """
+ import base64
+ import tempfile
+ import os
+ from markitdown import MarkItDown
+ from app.services.ai_service import extract_cv_metadata
+ from loguru import logger
+
+ try:
+ # 1. Decode base64 to bytes
+ file_bytes = base64.b64decode(body.base64)
+
+ # 2. Determine file suffix
+ ext = ".pdf"
+ if "word" in body.type or body.name.lower().endswith(".docx"):
+ ext = ".docx"
+ elif body.name.lower().endswith(".doc"):
+ ext = ".doc"
+ elif body.name.lower().endswith(".html") or body.name.lower().endswith(".htm"):
+ ext = ".html"
+ elif body.name.lower().endswith(".txt"):
+ ext = ".txt"
+
+ # 3. Write temporarily to local storage
+ with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp_file:
+ temp_file.write(file_bytes)
+ temp_path = temp_file.name
+
+ # 4. Process conversion via local markitdown
+ try:
+ markitdown = MarkItDown()
+ result = markitdown.convert(temp_path)
+ cv_markdown = result.text_content
+ finally:
+ # Clean up temp file safely
+ if os.path.exists(temp_path):
+ os.remove(temp_path)
+
+ # 5. Extract JSON metadata from the Markdown text using Gemini
+ if not cv_markdown or len(cv_markdown.strip()) < 50:
+ return {"success": False, "error": "Teks CV terlalu pendek atau kosong untuk dianalisis."}
+
+ extracted_data = await extract_cv_metadata(cv_markdown)
+
+ if "error" in extracted_data:
+ return {"success": False, "error": extracted_data["error"]}
+
+ return {"success": True, "data": extracted_data}
+
+ except Exception as e:
+ logger.error(f"api_magic_fill_cv error: {e}")
+ return {"success": False, "error": f"Gagal mengekstrak berkas CV: {str(e)}"}
+
diff --git a/app/api/telegram.py b/app/api/telegram.py
index eeaa5b88d21277dddf635ec85fb3b8b59fce8843..f16632e4abea1e522a51e0a920b360dd061141a8 100644
--- a/app/api/telegram.py
+++ b/app/api/telegram.py
@@ -1,39 +1,39 @@
-"""Telegram Webhook API — Executive Command Gateway."""
-
-from fastapi import APIRouter, Depends, Request, Header, HTTPException, status
-from sqlalchemy.ext.asyncio import AsyncSession
-from app.database import get_db
-from app.services.telegram_ceo_service import TelegramCEOService
-from app.config.settings import settings
-from typing import Optional
-import httpx
-from loguru import logger
-
-router = APIRouter(tags=["Executive Control"])
-
-@router.post("/webhook/telegram")
-@router.post("/v1/webhook/telegram")
-async def telegram_webhook(
- request: Request,
- db: AsyncSession = Depends(get_db),
- x_webhook_token: Optional[str] = Header(None)
-):
- """Receives commands/updates directly from Telegram or API clients."""
- data = await request.json()
-
- # Check if this is a standard Telegram payload
- is_telegram_payload = ("message" in data or "callback_query" in data or "edited_message" in data)
-
- # Security Check: Only enforce for non-Telegram clients
- if not is_telegram_payload:
- expected_secret = settings.webhook_secret or settings.security_webhook_token
- if expected_secret and x_webhook_token != expected_secret:
- logger.warning("[Telegram Webhook] Unauthorized access attempt.")
- return {"status": "unauthorized"}
-
- ceo_service = TelegramCEOService(db)
-
- # Process webhook natively via the service
- result = await ceo_service.handle_webhook(data)
- return result
-
+"""Telegram Webhook API — Executive Command Gateway."""
+
+from fastapi import APIRouter, Depends, Request, Header, HTTPException, status
+from sqlalchemy.ext.asyncio import AsyncSession
+from app.database import get_db
+from app.services.telegram_ceo_service import TelegramCEOService
+from app.config.settings import settings
+from typing import Optional
+import httpx
+from loguru import logger
+
+router = APIRouter(tags=["Executive Control"])
+
+@router.post("/webhook/telegram")
+@router.post("/v1/webhook/telegram")
+async def telegram_webhook(
+ request: Request,
+ db: AsyncSession = Depends(get_db),
+ x_webhook_token: Optional[str] = Header(None)
+):
+ """Receives commands/updates directly from Telegram or API clients."""
+ data = await request.json()
+
+ # Check if this is a standard Telegram payload
+ is_telegram_payload = ("message" in data or "callback_query" in data or "edited_message" in data)
+
+ # Security Check: Only enforce for non-Telegram clients
+ if not is_telegram_payload:
+ expected_secret = settings.webhook_secret or settings.security_webhook_token
+ if expected_secret and x_webhook_token != expected_secret:
+ logger.warning("[Telegram Webhook] Unauthorized access attempt.")
+ return {"status": "unauthorized"}
+
+ ceo_service = TelegramCEOService(db)
+
+ # Process webhook natively via the service
+ result = await ceo_service.handle_webhook(data)
+ return result
+
diff --git a/app/api/whatsapp.py b/app/api/whatsapp.py
index 21e00ba41c1909889498256a0f9bf62285129ac7..0b3e3deb929071f086e5963486014f6f8d0d8f32 100644
--- a/app/api/whatsapp.py
+++ b/app/api/whatsapp.py
@@ -1,106 +1,106 @@
-"""WhatsApp Control API — Link your device and monitor status."""
-
-from fastapi import APIRouter, Depends, Request, Header, HTTPException
-from app.services.whatsapp_service import whatsapp_bot
-from app.services.whatsapp.flow_handler import WhatsAppFlowHandler
-from app.utils.wa_guardrail import guardrail
-from app.database import get_db
-from app.config.settings import settings
-from sqlalchemy.ext.asyncio import AsyncSession
-from typing import Dict, Any, Optional
-from loguru import logger
-
-router = APIRouter(prefix="/v1/whatsapp", tags=["WhatsApp Hub"])
-
-@router.post("/webhook")
-async def whatsapp_webhook(
- request: Request,
- db: AsyncSession = Depends(get_db),
- x_webhook_token: Optional[str] = Header(None)
-):
- """Receives and processes incoming WhatsApp messages with security."""
- # 1. Security Check
- if settings.webhook_secret and x_webhook_token != settings.webhook_secret:
- logger.warning("[WhatsApp Webhook] Unauthorized access attempt.")
- return {"status": "unauthorized"}
-
- try:
- data = await request.json()
- # logger.info(f"[WhatsApp Webhook] Received payload: {data}") # SANITIZED: Removed full payload logging
-
- sender = None
- message = ""
- media_info = None
-
- # Evolution API Format
- if data.get("event") == "messages.upsert":
- msg_data = data.get("data", {})
- sender = msg_data.get("key", {}).get("remoteJid")
- message_id = msg_data.get("key", {}).get("id")
- instance = data.get("instance")
- msg_content = msg_data.get("message", {})
-
- # Text Message
- message = msg_content.get("conversation") or \
- msg_content.get("extendedTextMessage", {}).get("text") or \
- ""
-
- # Media/Document Message (CV Upload)
- if "documentMessage" in msg_content:
- doc = msg_content["documentMessage"]
- media_info = {
- "type": "document",
- "mimetype": doc.get("mimetype"),
- "title": doc.get("title") or doc.get("fileName"),
- "url": doc.get("url"),
- "message_id": message_id,
- "instance": instance
- }
- message = f"[Sent a document: {media_info['title']}]"
-
- # Simplified Format
- else:
- sender = data.get("sender")
- message = data.get("message", "")
-
- if not sender:
- return {"status": "ignored", "reason": "No sender found"}
-
- # 2. Rate Limiting
- if guardrail.is_rate_limited(sender):
- return {"status": "error", "message": "Too many requests"}
-
- # 3. Input Sanitization & Privacy (Skip for media info if needed, but safe for text)
- clean_message = guardrail.sanitize_input(message)
- safe_message = guardrail.filter_pii_for_ai(clean_message)
-
- # 4. Process Flow
- flow_handler = WhatsAppFlowHandler(db)
- # We pass media_info to handle_message
- await flow_handler.handle_message(sender, safe_message, media_info=media_info)
-
- return {"status": "success"}
- except Exception as e:
- logger.error(f"[WhatsApp Webhook] Error: {e}")
- return {"status": "error", "detail": str(e)}
-
-@router.get("/status")
-async def get_whatsapp_status():
- """Checks the connection status of the WhatsApp bot."""
- return await whatsapp_bot.get_status()
-
-@router.get("/qr")
-async def get_whatsapp_qr():
- """Returns a base64 QR code for scanning."""
- qr_base64 = await whatsapp_bot.get_qr_base64()
- if qr_base64:
- return {"status": "success", "qr": qr_base64}
- return {"status": "error", "message": "Failed to generate QR or instance busy."}
-
-@router.post("/logout")
-async def logout_whatsapp():
- """Logs out the current WhatsApp session."""
- success = await whatsapp_bot.logout_instance()
- if success:
- return {"status": "success", "message": "Logged out successfully."}
- return {"status": "error", "message": "Logout failed."}
+"""WhatsApp Control API — Link your device and monitor status."""
+
+from fastapi import APIRouter, Depends, Request, Header, HTTPException
+from app.services.whatsapp_service import whatsapp_bot
+from app.services.whatsapp.flow_handler import WhatsAppFlowHandler
+from app.utils.wa_guardrail import guardrail
+from app.database import get_db
+from app.config.settings import settings
+from sqlalchemy.ext.asyncio import AsyncSession
+from typing import Dict, Any, Optional
+from loguru import logger
+
+router = APIRouter(prefix="/v1/whatsapp", tags=["WhatsApp Hub"])
+
+@router.post("/webhook")
+async def whatsapp_webhook(
+ request: Request,
+ db: AsyncSession = Depends(get_db),
+ x_webhook_token: Optional[str] = Header(None)
+):
+ """Receives and processes incoming WhatsApp messages with security."""
+ # 1. Security Check
+ if settings.webhook_secret and x_webhook_token != settings.webhook_secret:
+ logger.warning("[WhatsApp Webhook] Unauthorized access attempt.")
+ return {"status": "unauthorized"}
+
+ try:
+ data = await request.json()
+ # logger.info(f"[WhatsApp Webhook] Received payload: {data}") # SANITIZED: Removed full payload logging
+
+ sender = None
+ message = ""
+ media_info = None
+
+ # Evolution API Format
+ if data.get("event") == "messages.upsert":
+ msg_data = data.get("data", {})
+ sender = msg_data.get("key", {}).get("remoteJid")
+ message_id = msg_data.get("key", {}).get("id")
+ instance = data.get("instance")
+ msg_content = msg_data.get("message", {})
+
+ # Text Message
+ message = msg_content.get("conversation") or \
+ msg_content.get("extendedTextMessage", {}).get("text") or \
+ ""
+
+ # Media/Document Message (CV Upload)
+ if "documentMessage" in msg_content:
+ doc = msg_content["documentMessage"]
+ media_info = {
+ "type": "document",
+ "mimetype": doc.get("mimetype"),
+ "title": doc.get("title") or doc.get("fileName"),
+ "url": doc.get("url"),
+ "message_id": message_id,
+ "instance": instance
+ }
+ message = f"[Sent a document: {media_info['title']}]"
+
+ # Simplified Format
+ else:
+ sender = data.get("sender")
+ message = data.get("message", "")
+
+ if not sender:
+ return {"status": "ignored", "reason": "No sender found"}
+
+ # 2. Rate Limiting
+ if guardrail.is_rate_limited(sender):
+ return {"status": "error", "message": "Too many requests"}
+
+ # 3. Input Sanitization & Privacy (Skip for media info if needed, but safe for text)
+ clean_message = guardrail.sanitize_input(message)
+ safe_message = guardrail.filter_pii_for_ai(clean_message)
+
+ # 4. Process Flow
+ flow_handler = WhatsAppFlowHandler(db)
+ # We pass media_info to handle_message
+ await flow_handler.handle_message(sender, safe_message, media_info=media_info)
+
+ return {"status": "success"}
+ except Exception as e:
+ logger.error(f"[WhatsApp Webhook] Error: {e}")
+ return {"status": "error", "detail": str(e)}
+
+@router.get("/status")
+async def get_whatsapp_status():
+ """Checks the connection status of the WhatsApp bot."""
+ return await whatsapp_bot.get_status()
+
+@router.get("/qr")
+async def get_whatsapp_qr():
+ """Returns a base64 QR code for scanning."""
+ qr_base64 = await whatsapp_bot.get_qr_base64()
+ if qr_base64:
+ return {"status": "success", "qr": qr_base64}
+ return {"status": "error", "message": "Failed to generate QR or instance busy."}
+
+@router.post("/logout")
+async def logout_whatsapp():
+ """Logs out the current WhatsApp session."""
+ success = await whatsapp_bot.logout_instance()
+ if success:
+ return {"status": "success", "message": "Logged out successfully."}
+ return {"status": "error", "message": "Logout failed."}
diff --git a/app/config/settings.py b/app/config/settings.py
index e9f6a195620f902cc2760806792162692da21680..dfa9392558b3a7cb0f13351c048935dc24453827 100644
--- a/app/config/settings.py
+++ b/app/config/settings.py
@@ -80,6 +80,10 @@ class Settings(BaseSettings):
vertex_ai_location: str = "asia-southeast2"
vertex_ai_model: str = "gemini-3.5-flash"
+ # Supabase credentials for Auth verification
+ supabase_url: str = "https://apuktsmdegylgvtyaawc.supabase.co"
+ supabase_anon_key: str = ""
+
model_config = {
"env_file": ".env",
"env_file_encoding": "utf-8",
diff --git a/app/config/vetting_rules.py b/app/config/vetting_rules.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4ddc2be0d4dceed615d16a4f9156e6723c663a8
--- /dev/null
+++ b/app/config/vetting_rules.py
@@ -0,0 +1,322 @@
+# Vetting Rules & Career Transition Database for Brigawan AI
+# Ported from VettingPrompts.gs and CareerTransitionData.gs
+
+VETTING_RULES = {
+ "categories": {
+ "Skilled": "Memiliki kualifikasi pendidikan linier, pengalaman kerja nyata >3 tahun di sektor terkait, atau sertifikasi keahlian tinggi (BNSP/Internasional).",
+ "Semi-Skilled": "Memiliki dasar pendidikan teknis, pengalaman <3 tahun, atau baru memiliki sertifikasi dasar (K3 Umum).",
+ "Unskilled": "Generalis tanpa latar belakang teknis atau industri hijau yang spesifik."
+ },
+ "green_sectors": [
+ "Renewable Energy (Solar, Wind, Geothermal, Hydro)",
+ "ESG & Sustainability Reporting",
+ "Carbon Accounting & Carbon Market",
+ "Circular Economy & Waste Management",
+ "HSE / K3 (Industry Safety)",
+ "Environmental Engineering"
+ ]
+}
+
+CAREER_TRANSITION_DB = [
+ # --- ENERGI TERBARUKAN ---
+ {
+ "sector": "Energi Terbarukan",
+ "targetJob": "Renewable Energy Engineer / PLTS Installer",
+ "salary": "Rp 8 – 20 juta",
+ "skills": ["Desain sistem kelistrikan", "AutoCAD", "PVsyst", "Troubleshooting kelistrikan"],
+ "sources": [
+ {"from": "Teknisi listrik gedung", "to": "PLTS installer"},
+ {"from": "Teknisi industri", "to": "PLTS installer"},
+ {"from": "Teknisi genset", "to": "Maintenance EBT"},
+ {"from": "power plant batu bara", "to": "Maintenance EBT"},
+ {"from": "Electrical engineer manufaktur", "to": "System designer EBT"}
+ ]
+ },
+ {
+ "sector": "Energi Terbarukan",
+ "targetJob": "ESHS Officer",
+ "salary": "Rp 7 – 18 juta",
+ "skills": ["Implementasi kebijakan CSR", "Audit lingkungan & sosial", "Manajemen K3"],
+ "sources": [
+ {"from": "HSE officer tambang", "to": "ESHS officer EBT"},
+ {"from": "HSE officer migas", "to": "ESHS officer EBT"},
+ {"from": "Safety officer pabrik", "to": "HSE proyek PLTS/PLTB"},
+ {"from": "Safety officer konstruksi", "to": "HSE proyek PLTS/PLTB"},
+ {"from": "Perawat industri", "to": "Occupational health EBT"},
+ {"from": "paramedis industri", "to": "Occupational health EBT"}
+ ]
+ },
+ {
+ "sector": "Energi Terbarukan",
+ "targetJob": "Energy Transition Analyst / Project Manager EBT",
+ "salary": "Rp 12 – 30 juta",
+ "skills": ["Analisis biaya", "Manajemen proyek EPC", "ETAP", "PowerFactory"],
+ "sources": [
+ {"from": "Project manager konstruksi", "to": "PM proyek EBT"},
+ {"from": "EPC migas", "to": "PM proyek EBT"},
+ {"from": "Analis energi PLN", "to": "Energy transition analyst"},
+ {"from": "Analis batu bara", "to": "Energy transition analyst"},
+ {"from": "Konsultan infrastruktur", "to": "Konsultan EBT"}
+ ]
+ },
+ {
+ "sector": "Energi Terbarukan",
+ "targetJob": "Solar PV / Wind System Designer",
+ "salary": "Rp 10 – 25 juta",
+ "skills": ["PVsyst", "Helioscope", "WindPRO", "Analisis finansial proyek"],
+ "sources": [
+ {"from": "Drafter", "to": "PV system designer"},
+ {"from": "desainer MEP gedung", "to": "PV system designer"},
+ {"from": "Engineer perencanaan jaringan listrik", "to": "Grid integration designer"},
+ {"from": "Arsitek", "to": "Green building designer"},
+ {"from": "civil engineer", "to": "Green building designer"}
+ ]
+ },
+ # --- KEHUTANAN & LAHAN ---
+ {
+ "sector": "Kehutanan & Lahan",
+ "targetJob": "Carbon Project Specialist",
+ "salary": "Rp 10 – 30 juta",
+ "skills": ["Penulisan proposal karbon", "MRV", "GIS", "remote sensing"],
+ "sources": [
+ {"from": "Peneliti", "to": "Carbon project developer"},
+ {"from": "akademisi kehutanan", "to": "Carbon project developer"},
+ {"from": "Auditor lingkungan sawit", "to": "Carbon auditor"},
+ {"from": "GIS analyst pertambangan", "to": "Remote sensing carbon MRV"}
+ ]
+ },
+ {
+ "sector": "Kehutanan & Lahan",
+ "targetJob": "Forest Planning & Restoration Specialist",
+ "salary": "Rp 8 – 22 juta",
+ "skills": ["Perencanaan tata guna lahan", "Restorasi ekologi", "AMDAL"],
+ "sources": [
+ {"from": "Penyuluh kehutanan", "to": "Restoration specialist"},
+ {"from": "KLHK", "to": "Restoration specialist"},
+ {"from": "Staf AMDAL tambang", "to": "Environmental planner hijau"},
+ {"from": "Land surveyor perkebunan", "to": "Land use planner"}
+ ]
+ },
+ {
+ "sector": "Kehutanan & Lahan",
+ "targetJob": "Forest Monitoring & Field Operations Officer",
+ "salary": "Rp 5 – 12 juta",
+ "skills": ["Monitoring kualitas lingkungan", "Manajemen data PPKH", "Inspeksi hutan"],
+ "sources": [
+ {"from": "Petugas lapangan perkebunan sawit", "to": "Field monitoring officer"},
+ {"from": "Ranger", "to": "Conservation field officer"},
+ {"from": "polhut", "to": "Conservation field officer"},
+ {"from": "Enumerator", "to": "Data field officer kehutanan"},
+ {"from": "surveyor pertanahan", "to": "Data field officer kehutanan"}
+ ]
+ },
+ {
+ "sector": "Kehutanan & Lahan",
+ "targetJob": "CSR Analyst (Kehutanan)",
+ "salary": "Rp 7 – 18 juta",
+ "skills": ["Perencanaan program CSR", "Public affairs", "Analisis dampak sosial"],
+ "sources": [
+ {"from": "Staf CSR tambang", "to": "CSR analyst green company"},
+ {"from": "Staf CSR migas", "to": "CSR analyst green company"},
+ {"from": "Community development officer", "to": "Social impact analyst"},
+ {"from": "Jurnalis", "to": "Sustainability comms & CSR"},
+ {"from": "komunikasi korporat", "to": "Sustainability comms & CSR"}
+ ]
+ },
+ # --- PENGELOLAAN LIMBAH ---
+ {
+ "sector": "Pengelolaan Limbah",
+ "targetJob": "Circular Economy Implementation Manager",
+ "salary": "Rp 10 – 25 juta",
+ "skills": ["Stakeholder engagement", "Project management", "Monitoring & evaluasi"],
+ "sources": [
+ {"from": "Project manager manufaktur", "to": "Circular economy PM"},
+ {"from": "Operations manager pabrik", "to": "Waste-to-resource ops"},
+ {"from": "Supply chain manager", "to": "Circular supply chain manager"}
+ ]
+ },
+ {
+ "sector": "Pengelolaan Limbah",
+ "targetJob": "Environmental Management & Waste Specialist",
+ "salary": "Rp 7 – 16 juta",
+ "skills": ["Operasional WWTP", "Pengolahan limbah", "Sampling air"],
+ "sources": [
+ {"from": "Operator WWTP pabrik", "to": "Waste treatment specialist"},
+ {"from": "Operator PDAM", "to": "Waste treatment specialist"},
+ {"from": "Teknisi lab pertambangan", "to": "Environmental lab specialist"},
+ {"from": "Sanitarian", "to": "Environmental health specialist"},
+ {"from": "kesehatan lingkungan", "to": "Environmental health specialist"}
+ ]
+ },
+ {
+ "sector": "Pengelolaan Limbah",
+ "targetJob": "Circular Economy Research & Policy Analyst",
+ "salary": "Rp 6 – 20 juta",
+ "skills": ["Data collection", "Policy analysis", "Pemahaman circular material"],
+ "sources": [
+ {"from": "Peneliti lingkungan", "to": "Circular economy researcher"},
+ {"from": "dosen ilmu lingkungan", "to": "Circular economy researcher"},
+ {"from": "Analis kebijakan pemerintah", "to": "Green policy analyst"},
+ {"from": "Market researcher", "to": "Sustainability data analyst"},
+ {"from": "data analyst", "to": "Sustainability data analyst"}
+ ]
+ },
+ # --- PERTANIAN ---
+ {
+ "sector": "Pertanian Berkelanjutan",
+ "targetJob": "Head of Sustainability & Corporate Affairs",
+ "salary": "Rp 25 – 50 juta",
+ "skills": ["Sustainability Strategy", "Stakeholder Partnership", "Manajemen rantai pasok"],
+ "sources": [
+ {"from": "Direktur agribisnis", "to": "Head of sustainability"},
+ {"from": "VP operasional agribisnis", "to": "Head of sustainability"},
+ {"from": "Government relations manager", "to": "Policy & corporate affairs"},
+ {"from": "Senior consultant manajemen", "to": "Sustainability strategy lead"}
+ ]
+ },
+ {
+ "sector": "Pertanian Berkelanjutan",
+ "targetJob": "Regenerative Agriculture Manager",
+ "salary": "Rp 15 – 35 juta",
+ "skills": ["Pertanian regeneratif", "Valuasi ekosistem", "Kredit karbon"],
+ "sources": [
+ {"from": "Agronomis", "to": "Regenerative agro manager"},
+ {"from": "peneliti pertanian", "to": "Regenerative agro manager"},
+ {"from": "Manajer kebun", "to": "Sustainable plantation manager"},
+ {"from": "plantation manager", "to": "Sustainable plantation manager"},
+ {"from": "Penyuluh pertanian", "to": "Regenerative agriculture advisor"}
+ ]
+ },
+ # --- LINTAS SEKTOR (CROSS) ---
+ {
+ "sector": "Cross-Sectoral",
+ "targetJob": "Sustainability & ESG Advisory Specialist",
+ "salary": "Rp 15 – 31 juta",
+ "skills": ["ESG assessment", "Analisis risiko karbon", "Sustainability auditing"],
+ "sources": [
+ {"from": "Konsultan manajemen", "to": "ESG advisory consultant"},
+ {"from": "Auditor keuangan", "to": "Sustainability auditor"},
+ {"from": "akuntan publik", "to": "Sustainability auditor"},
+ {"from": "Analis risiko perbankan", "to": "Climate risk analyst"}
+ ]
+ },
+ {
+ "sector": "Cross-Sectoral",
+ "targetJob": "GHG Inventory & Climate Risk Analyst",
+ "salary": "Rp 12 – 35 juta",
+ "skills": ["GHG Inventory", "Analisis risiko iklim", "OpenLCA", "SimaPro"],
+ "sources": [
+ {"from": "Analis energi migas", "to": "GHG inventory analyst"},
+ {"from": "Analis energi batu bara", "to": "GHG inventory analyst"},
+ {"from": "Auditor ISO lingkungan", "to": "GHG auditor"},
+ {"from": "Aktuaria", "to": "Climate risk modeler"},
+ {"from": "risk analyst asuransi", "to": "Climate risk modeler"}
+ ]
+ },
+ {
+ "sector": "Cross-Sectoral",
+ "targetJob": "Green Finance / Sustainable Investment Analyst",
+ "salary": "Rp 12 – 40 juta",
+ "skills": ["Green bond", "ESG due diligence", "Financial modeling"],
+ "sources": [
+ {"from": "Analis kredit", "to": "Green finance analyst"},
+ {"from": "investment banking", "to": "Green finance analyst"},
+ {"from": "Fund manager konvensional", "to": "ESG fund manager"},
+ {"from": "Analis saham", "to": "ESG equity analyst"},
+ {"from": "equity research", "to": "ESG equity analyst"}
+ ]
+ },
+ # --- TRANSPORTASI ---
+ {
+ "sector": "Transportasi",
+ "targetJob": "Business Development EV / Battery Swap",
+ "salary": "Rp 8 – 20 juta",
+ "skills": ["Negosiasi kontrak B2B", "Site hunting", "Kemitraan strategis"],
+ "sources": [
+ {"from": "Sales executive otomotif", "to": "Sales EV & battery swap"},
+ {"from": "dealer mobil", "to": "Sales EV & battery swap"},
+ {"from": "dealer motor BBM", "to": "Sales EV & battery swap"},
+ {"from": "Business development SPBU", "to": "BD charging station network"},
+ {"from": "Pertamina", "to": "BD charging station network"},
+ {"from": "Area manager ritel", "to": "Site expansion EV station"},
+ {"from": "Area manager minimarket", "to": "Site expansion EV station"}
+ ]
+ },
+ {
+ "sector": "Transportasi",
+ "targetJob": "Electrical Engineer EV Charging Stations",
+ "salary": "Rp 10 – 22 juta",
+ "skills": ["Sistem kelistrikan EV", "Supervisi konstruksi", "Manajemen kontrak"],
+ "sources": [
+ {"from": "Teknisi listrik bengkel", "to": "EV charging installer"},
+ {"from": "Teknisi SPBU", "to": "EV charging installer"},
+ {"from": "Electrical engineer gedung", "to": "EV infrastructure engineer"},
+ {"from": "Teknisi mesin kendaraan", "to": "EV mechanic & service tech"}
+ ]
+ },
+ # --- PARIWISATA ---
+ {
+ "sector": "Pariwisata Berkelanjutan",
+ "targetJob": "Ecotourism Specialist",
+ "salary": "Rp 5 – 15 juta",
+ "skills": ["Merancang program ekowisata", "Pemberdayaan komunitas", "Monitoring dampak"],
+ "sources": [
+ {"from": "Tour guide", "to": "Ecotourism guide & specialist"},
+ {"from": "pemandu wisata konvensional", "to": "Ecotourism guide & specialist"},
+ {"from": "Travel agent", "to": "Sustainable tour package designer"},
+ {"from": "event organizer wisata", "to": "Sustainable tour package designer"},
+ {"from": "Staf hotel", "to": "Eco-lodge & sustainable hospitality"}
+ ]
+ },
+ # --- MANUFAKTUR ---
+ {
+ "sector": "Manufaktur & Konstruksi",
+ "targetJob": "Sustainability Specialist & Auditor",
+ "salary": "Rp 10 – 27 juta",
+ "skills": ["Life Cycle Assessment", "Analisis keberlanjutan", "Efisiensi energi"],
+ "sources": [
+ {"from": "Auditor ISO", "to": "Sustainability auditor"},
+ {"from": "Process engineer", "to": "Green process engineer"},
+ {"from": "industrial engineer", "to": "Green process engineer"},
+ {"from": "R&D engineer", "to": "Sustainable product designer"},
+ {"from": "R&D manufaktur", "to": "Sustainable product designer"}
+ ]
+ },
+ # --- TEKNOLOGI & DATA ---
+ {
+ "sector": "Teknologi & Digital",
+ "targetJob": "Sustainability Data Analyst",
+ "salary": "Rp 12 – 28 juta",
+ "skills": ["SQL", "Tableau/PowerBI", "Python untuk Sustainability", "Analisis emisi data"],
+ "sources": [
+ {"from": "Data analyst", "to": "Sustainability data analyst"},
+ {"from": "Business intelligence", "to": "ESG data specialist"},
+ {"from": "Data engineer", "to": "Carbon accounting software dev"},
+ {"from": "Web developer", "to": "Green software engineer"}
+ ]
+ },
+ # --- ADMINISTRASI & HR ---
+ {
+ "sector": "Manajemen & Operasional",
+ "targetJob": "ESG / Sustainability Coordinator",
+ "salary": "Rp 8 – 20 juta",
+ "skills": ["Pelaporan ESG", "Admin proyek", "Stakeholder communications"],
+ "sources": [
+ {"from": "Sekretaris", "to": "Sustainability coordinator"},
+ {"from": "Admin kantor", "to": "ESG administrative support"},
+ {"from": "General affair", "to": "Green office coordinator"},
+ {"from": "Accounting", "to": "Climate finance support"}
+ ]
+ },
+ {
+ "sector": "Sumber Daya Manusia",
+ "targetJob": "Green Talent Acquisition / People & Culture",
+ "salary": "Rp 10 – 22 juta",
+ "skills": ["Keahlian rekrutmen hijau", "Culture building", "Manajemen perubahan"],
+ "sources": [
+ {"from": "HR generalist", "to": "People & culture lead"},
+ {"from": "Recruiter", "to": "ESG talent acquisition"},
+ {"from": "Training manager", "to": "Sustainability training lead"}
+ ]
+ }
+]
diff --git a/app/main.py b/app/main.py
index a44cad1e091f106285060b33804fe2dc097bc64a..aa5cdcec23e6689726e7c8870534e05cc81827ef 100644
--- a/app/main.py
+++ b/app/main.py
@@ -1,715 +1,506 @@
-"""Brigawan Core API — FastAPI Application Entry Point."""
-from contextlib import asynccontextmanager
-from fastapi import FastAPI
-from fastapi.middleware.cors import CORSMiddleware
-from fastapi.responses import HTMLResponse
-from loguru import logger
-import os
-import asyncio
-
-from app.database import close_db, init_db
-from app.middleware.auth import AuthMiddleware
-from app.middleware.correlation import CorrelationIDMiddleware
-from app.services.ai_service import check_ai_status
-from app.utils.cache import get_ai_cache_stats
-
-@asynccontextmanager
-async def lifespan(app: FastAPI):
- logger.info("Brigawan Core API starting...")
- try:
- await init_db()
- logger.info("Database tables created/verified")
- except Exception as e:
- logger.warning(f"DB init skipped (will retry on first request): {e}")
- yield
- logger.info("Brigawan Core API shutting down...")
- await close_db()
-
-app = FastAPI(
- title="Brigawan Core API",
- description="Core Client-facing API for Green Jobs Portal",
- version="2.0.0",
- lifespan=lifespan,
- docs_url="/docs",
- redoc_url="/redoc",
-)
-
-app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
-)
-app.add_middleware(CorrelationIDMiddleware)
-app.add_middleware(AuthMiddleware)
-
-@app.api_route("/", methods=["GET", "HEAD"], response_class=HTMLResponse)
-async def root():
- html_content = """
-
-
-
-
- Brigawan Core API Gateway
-
-
-
-
-
-
-
-
-
-
-
-
🌿
-
-
Briga Core API
-
Gateway API Utama & Integrasi ESG briga.id
-
-
-
-
- Operational
-
-
-
-
-
-
-
-
-
-
-
-
- Gateway
- ● Active
-
-
- Database
- Checking...
-
-
- AI Status
- Checking...
-
-
- Version
- v2.0.0
-
-
-
-
-
- Console Diagnostics
- Refresh
-
-
- [System] Initializing diagnostics...
- [System] Ready.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
/auth/register POST
-
/auth/login POST
-
/auth/logout POST
-
/auth/session GET
-
-
-
-
-
-
-
-
/job/postings GET
-
/job/create POST
-
/job/{job_id} GET
-
/job/{job_id}/apply POST
-
/search/jobs GET
-
-
-
-
-
-
-
-
/talent/profile GET
-
/talent/profile/update PUT
-
/talent/resume/upload POST
-
/talent/resume/parse POST
-
-
-
-
-
-
-
-
/employer/profile GET
-
/employer/credits/balance GET
-
/employer/checkout POST
-
-
-
-
-
-
-
-
/academy/recommendations GET
-
/academy/lpk/list GET
-
-
-
-
-
-
-
-
/telegram/webhook POST
-
/whatsapp/send POST
-
/legacy-compat/sync POST
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-"""
- return HTMLResponse(content=html_content)
-
-@app.api_route("/health", methods=["GET", "HEAD"], tags=["Health"])
-async def health_check():
- import sqlalchemy
- from app.database import AsyncSessionLocal
- from sqlalchemy import text
-
- db_status = "healthy"
- db_error = None
- try:
- async with AsyncSessionLocal() as session:
- await session.execute(text("SELECT 1"))
- except Exception as e:
- db_status = "unhealthy"
- db_error = str(e)
- logger.error(f"Health check DB connection failed: {e}")
-
- ai_status = check_ai_status()
- is_healthy = (db_status == "healthy") and (ai_status.get("status") == "ready")
-
- return {
- "status": "ok" if is_healthy else "degraded",
- "version": "2.0.0",
- "service": "briga-core-api",
- "database": {
- "status": db_status,
- "error": db_error
- },
- "ai": ai_status
- }
-
-from app.api.auth import router as auth_router
-from app.api.career import router as career_router
-from app.api.search import router as search_router
-from app.api.chat import router as chat_router
-from app.api.employer import router as employer_router
-from app.api.talent import router as talent_router
-from app.api.job import router as job_router
-from app.api.interview import router as interview_router
-from app.api.academy import router as academy_router
-from app.api.admin import router as admin_router
-from app.api.legacy_compat import router as legacy_compat_router
-from app.api.debug_admin import router as debug_admin_router
-from app.api.telegram import router as telegram_router
-from app.api.whatsapp import router as whatsapp_router
-from app.middleware.ab_assign import ABAssignMiddleware
-
-app.add_middleware(ABAssignMiddleware)
-
-app.include_router(auth_router)
-app.include_router(career_router)
-app.include_router(search_router)
-app.include_router(chat_router)
-app.include_router(employer_router)
-app.include_router(talent_router)
-app.include_router(job_router)
-app.include_router(interview_router)
-app.include_router(academy_router)
-app.include_router(admin_router)
-app.include_router(legacy_compat_router)
-app.include_router(debug_admin_router)
-app.include_router(telegram_router)
-app.include_router(whatsapp_router)
+"""Brigawan Backend — FastAPI Application Entry Point.
+
+Replaces Code.gs (GAS router) with a FastAPI async server on Cloud Run.
+Mounts all API routers and middleware.
+
+Zero-cost architecture:
+ - Auth via Google OAuth (free) + email/password
+ - Rate limiting in-memory (no Redis)
+ - Free tier: 3 credits, 1 job, no AI matching
+"""
+
+from contextlib import asynccontextmanager
+
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import HTMLResponse
+from loguru import logger
+import os
+from dotenv import load_dotenv
+
+# --- LOAD ENVIRONMENT ---
+# Load from current dir or search upwards for .env
+load_dotenv()
+if not os.environ.get("DATABASE_URL"):
+ # Fallback to subdirectory if started from root
+ load_dotenv(os.path.join(os.path.dirname(__file__), "..", ".env"))
+# ------------------------
+
+# --- HF PROXY CLEANUP ---
+removed_proxies = []
+for var in ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"]:
+ if var in os.environ:
+ os.environ.pop(var, None)
+ removed_proxies.append(var)
+if removed_proxies:
+ print(f">>> [SYSTEM] Cleaned proxy variables from environment: {removed_proxies}")
+
+# --- HF STARTUP DEBUG ---
+print(">>> [SYSTEM] Python main.py script loaded!")
+logger.info(f"Checking Environment: DATABASE_URL is {'SET' if os.environ.get('DATABASE_URL') else 'MISSING'}")
+gemini_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GEMINI_API_KEYS")
+logger.info(f"Checking Environment: GEMINI_API_KEY is {'SET' if gemini_key else 'MISSING'}")
+# ------------------------
+
+from app.database import close_db, init_db
+from app.middleware.auth import AuthMiddleware
+from app.middleware.correlation import CorrelationIDMiddleware
+from app.services.ai_service import check_ai_status
+from app.utils.cache import get_ai_cache_stats
+from app.services.autonomous_dev_service import AutonomousDevService
+import asyncio
+
+# --- FIX (2026-09): Persist logs to file so AutonomousDevService.monitor_logs()
+# can actually detect errors. Previously loguru only wrote to stderr (default),
+# so the self-healing loop watched a file that never existed.
+try:
+ _LOG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
+ _LOG_FILE = os.path.join(_LOG_DIR, "server.log")
+ logger.add(
+ _LOG_FILE,
+ rotation="10 MB",
+ retention=5,
+ level="INFO",
+ enqueue=True,
+ serialize=False,
+ )
+ logger.info(f"[Logging] server.log sink configured at {_LOG_FILE}")
+except Exception as log_err:
+ print(f">>> [SYSTEM] Failed to configure server.log sink: {log_err}")
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ """Startup / shutdown lifecycle.
+
+ - On startup: initialize DB pool and create tables
+ - On shutdown: gracefully close all connections
+ - For production: use Alembic migrations instead of create_all
+ """
+ logger.info("Brigawan API starting...")
+ # Start Autonomous Dev Loop in the background
+ asyncio.create_task(AutonomousDevService.monitor_logs())
+
+ try:
+ await init_db()
+ logger.info("Database tables created/verified")
+ except Exception as e:
+ logger.warning(f"DB init skipped (will retry on first request): {e}")
+ yield
+ logger.info("Brigawan API shutting down...")
+ await close_db()
+
+
+app = FastAPI(
+ title="Brigawan API",
+ description="Multi-tenant Green Jobs Portal Backend — Free tier supports 10K users",
+ version="2.0.0",
+ lifespan=lifespan,
+ docs_url="/docs",
+ redoc_url="/redoc",
+ contact={
+ "name": "Brigawan",
+ "email": "info@briga.id",
+ "url": "https://briga.id",
+ },
+)
+
+# ─── CORS (allow Cloudflare Pages frontend) ───
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=[
+ "https://briga.id",
+ "https://www.briga.id",
+ "http://localhost:3000",
+ "http://localhost:5173", # Vite dev server
+ ],
+ allow_origin_regex=r"https://[a-z0-9-]+\.pages\.dev", # Cloudflare Pages preview
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+# ─── Correlation ID (request tracking across services) ───
+app.add_middleware(CorrelationIDMiddleware)
+
+# ─── Auth & Rate Limiting Middleware ───
+app.add_middleware(AuthMiddleware)
+
+
+@app.get("/", response_class=HTMLResponse, tags=["Dashboard"])
+async def root_dashboard():
+ html_content = """
+
+
+
+
+ Briga Gateway API Dashboard
+
+
+
+
+
+
Briga Gateway API
+
+
+ Sistem Aktif & Siaga
+
+
+ Layanan backend utama untuk Briga.id yang mengelola database Supabase, otentikasi pengguna, dan gateway untuk agen kecerdasan buatan.
+
+
+
+
Platform
+
Hugging Face
+
+
+
+
+
+
Endpoint Aktif
+
+ /health
+ GET
+
+
+ /docs
+ GET
+
+
+ /webhook/telegram
+ POST
+
+
+
+
+"""
+ return HTMLResponse(content=html_content)
+
+
+# ─── Health Checks ───────────────────────────────────────────────────────────
+
+@app.api_route("/health", methods=["GET", "HEAD"], tags=["Health"])
+async def health_check():
+ router_url = os.environ.get("ROUTER_API_URL", "not_configured")
+ return {
+ "status": "ok",
+ "version": "2.0.0",
+ "service": "brigawan-api",
+ "deployment": {
+ "platform": "huggingface-spaces",
+ "ai_router": router_url if router_url != "not_configured" else "co-located",
+ "database": "supabase-postgres" if os.environ.get("DATABASE_URL") else "sqlite-fallback",
+ },
+ "free_tier": {
+ "max_users": 10000,
+ "credits": 3,
+ "max_jobs": 1,
+ "rate_limit_per_hour": 100,
+ "cost": "$0",
+ },
+ "cache": get_ai_cache_stats(),
+ "ai": check_ai_status(),
+ }
+
+
+@app.get("/api/test-telegram")
+async def test_telegram():
+ import httpx
+ import os
+ from app.config.settings import settings
+ token = settings.telegram_bot_token or os.environ.get("TELEGRAM_BOT_TOKEN", "")
+ proxy_url = os.environ.get("TELEGRAM_PROXY_URL", "").rstrip("/")
+ proxy_secret = os.environ.get("TELEGRAM_PROXY_SECRET", "")
+
+ results = {}
+
+ # Test 1: httpbin.org (Check general internet access)
+ try:
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ resp = await client.get("https://httpbin.org/get")
+ results["httpbin"] = {"status_code": resp.status_code, "json": resp.json()}
+ except Exception as e:
+ results["httpbin"] = {"error": str(e)}
+
+ # Test 2: Telegram Connectivity
+ if not token:
+ results["telegram"] = {"error": "TELEGRAM_BOT_TOKEN is not configured"}
+ else:
+ # Determine mode
+ is_gas = "script.google.com" in proxy_url
+ if proxy_url and proxy_secret:
+ if is_gas:
+ url = proxy_url
+ payload = {
+ "action": "proxyTelegram",
+ "params": ["getMe", {}, proxy_secret]
+ }
+ mode = "gas_rpc"
+ else:
+ url = f"{proxy_url}/getMe"
+ headers = {"X-Proxy-Secret": proxy_secret}
+ mode = "transparent_proxy"
+ else:
+ url = f"https://api.telegram.org/bot{token}/getMe"
+ headers = {}
+ mode = "direct"
+
+ masked_token = f"{token[:10]}...{token[-5:]}" if len(token) > 15 else "too_short"
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ if mode == "gas_rpc":
+ resp = await client.post(url, json=payload)
+ else:
+ resp = await client.get(url, headers=headers)
+
+ results["telegram"] = {
+ "mode": mode,
+ "url": url if mode != "direct" else "https://api.telegram.org/bot[MASKED]/getMe",
+ "status_code": resp.status_code,
+ "json": resp.json() if resp.status_code == 200 else resp.text[:200],
+ "masked_token": masked_token
+ }
+ except Exception as e:
+ import traceback
+ results["telegram"] = {
+ "mode": mode,
+ "error": str(e),
+ "traceback": traceback.format_exc(),
+ "masked_token": masked_token
+ }
+
+ return results
+
+
+@app.get("/health/ai-router", tags=["Health"])
+async def ai_router_health():
+ """Check AI Router connectivity (for hybrid deployment)."""
+ router_url = os.environ.get("ROUTER_API_URL", "")
+ if not router_url:
+ return {"status": "co-located", "message": "AI is co-located in this service"}
+
+ try:
+ import httpx
+ async with httpx.AsyncClient(timeout=5.0) as client:
+ resp = await client.get(f"{router_url}/health")
+ latency_ms = resp.elapsed.total_seconds() * 1000
+ return {
+ "status": "healthy" if resp.status_code == 200 else "degraded",
+ "url": router_url,
+ "latency_ms": round(latency_ms, 1),
+ "status_code": resp.status_code,
+ }
+ except Exception as e:
+ logger.warning(f"AI Router health check failed: {e}")
+ return {
+ "status": "unavailable",
+ "url": router_url,
+ "error": str(e)[:100],
+ "fallback": "Using cached responses + Gemini direct",
+ }
+
+
+@app.get("/health/db", tags=["Health"])
+async def db_health():
+ """Database connectivity check (placeholder)."""
+ return {
+ "status": "not_connected",
+ "message": "DB connection pool not yet initialized. Set DATABASE_URL and restart.",
+ }
+
+
+# ─── API Routers ─────────────────────────────────────────────────────────────
+
+from app.api.auth import router as auth_router
+from app.api.career import router as career_router
+from app.api.search import router as search_router
+from app.api.chat import router as chat_router
+from app.api.employer import router as employer_router
+from app.api.talent import router as talent_router
+from app.api.job import router as job_router
+from app.api.interview import router as interview_router
+from app.api.academy import router as academy_router
+from app.api.agents import router as agents_router
+from app.api.admin import router as admin_router
+from app.api.telegram import router as telegram_router
+from app.api.whatsapp import router as whatsapp_router
+from app.api.legacy_compat import router as legacy_compat_router
+from app.api.debug_admin import router as debug_admin_router
+from app.middleware.ab_assign import ABAssignMiddleware
+
+app.add_middleware(ABAssignMiddleware)
+
+app.include_router(auth_router)
+app.include_router(career_router)
+app.include_router(search_router)
+app.include_router(chat_router)
+app.include_router(employer_router)
+app.include_router(talent_router)
+app.include_router(job_router)
+app.include_router(interview_router)
+app.include_router(academy_router)
+app.include_router(agents_router)
+app.include_router(admin_router)
+app.include_router(telegram_router)
+app.include_router(whatsapp_router)
+app.include_router(legacy_compat_router)
+app.include_router(debug_admin_router)
+# app.include_router(employer_router, prefix="/v1/employer", tags=["Employer"])
+# app.include_router(jobs_router, prefix="/v1/jobs", tags=["Jobs"])
+# app.include_router(chat_router, prefix="/v1/chat", tags=["Chat"])
+# app.include_router(payments_router, prefix="/v1/payments", tags=["Payments"])
+# app.include_router(agents_router, prefix="/v1/agent", tags=["Agents"])
diff --git a/app/middleware/ab_assign.py b/app/middleware/ab_assign.py
index 6fa9a7c8fb6e8d7bea2a83961c5dadddca0ef369..38faa5e4df2b3c43d5139f218e9c219451611859 100644
--- a/app/middleware/ab_assign.py
+++ b/app/middleware/ab_assign.py
@@ -1,30 +1,30 @@
-import random
-from starlette.middleware.base import BaseHTTPMiddleware
-from starlette.requests import Request
-from starlette.responses import Response
-from typing import Callable
-
-class ABAssignMiddleware(BaseHTTPMiddleware):
- """Assigns users to AB variants (50/50) and attaches headers for downstream handlers.
-
- Picks variant by cookie 'ab_variant_{experiment_id}' if present, otherwise assigns and sets cookie.
- """
-
- async def dispatch(self, request: Request, call_next: Callable) -> Response:
- # Expect header X-Experiment-Id for lightweight assignment in this simple middleware
- experiment_id = request.headers.get('X-Experiment-Id')
- if not experiment_id:
- return await call_next(request)
-
- cookie_name = f"ab_variant_{experiment_id}"
- variant = request.cookies.get(cookie_name)
- if variant not in ('A', 'B'):
- # Random 50/50 assignment
- variant = 'A' if random.random() < 0.5 else 'B'
-
- # Attach to headers for downstream, set cookie in response
- request.state.ab_variant = variant
- response = await call_next(request)
- # Set a cookie for one week
- response.set_cookie(cookie_name, variant, max_age=7*24*3600, httponly=True)
- return response
+import random
+from starlette.middleware.base import BaseHTTPMiddleware
+from starlette.requests import Request
+from starlette.responses import Response
+from typing import Callable
+
+class ABAssignMiddleware(BaseHTTPMiddleware):
+ """Assigns users to AB variants (50/50) and attaches headers for downstream handlers.
+
+ Picks variant by cookie 'ab_variant_{experiment_id}' if present, otherwise assigns and sets cookie.
+ """
+
+ async def dispatch(self, request: Request, call_next: Callable) -> Response:
+ # Expect header X-Experiment-Id for lightweight assignment in this simple middleware
+ experiment_id = request.headers.get('X-Experiment-Id')
+ if not experiment_id:
+ return await call_next(request)
+
+ cookie_name = f"ab_variant_{experiment_id}"
+ variant = request.cookies.get(cookie_name)
+ if variant not in ('A', 'B'):
+ # Random 50/50 assignment
+ variant = 'A' if random.random() < 0.5 else 'B'
+
+ # Attach to headers for downstream, set cookie in response
+ request.state.ab_variant = variant
+ response = await call_next(request)
+ # Set a cookie for one week
+ response.set_cookie(cookie_name, variant, max_age=7*24*3600, httponly=True)
+ return response
diff --git a/app/middleware/auth.py b/app/middleware/auth.py
index 38f9c73d6ce2beddaa1f3b1c05d77cca3e276753..bdc893d16a84f49f6f82718ff300493647897ef4 100644
--- a/app/middleware/auth.py
+++ b/app/middleware/auth.py
@@ -1,155 +1,155 @@
-"""JWT Authentication Middleware for FastAPI.
-
-Uses standardized error format from app.utils.errors.
-"""
-
-import time
-from typing import Any, Callable, Dict, Optional
-import os
-
-from fastapi import HTTPException, Request, status
-from fastapi.responses import JSONResponse
-from starlette.middleware.base import BaseHTTPMiddleware
-
-from app.utils.errors import error_response, ErrorCode
-from app.utils.security import decode_access_token, rate_limiter
-
-
-# Public endpoints — no auth required
-PUBLIC_PATHS = {
- "/health",
- "/health/db",
- "/docs",
- "/redoc",
- "/openapi.json",
- "/v1/auth/login",
- "/v1/auth/register",
- "/v1/auth/google",
- "/v1/auth/refresh",
- "/v1/jobs",
- "/v1/search/talent",
- "/v1/employer/tiers",
- "/v1/webhook/telegram",
- "/v1/whatsapp/webhook",
- "/v1/legacy-gas-compat",
-}
-
-# Role-based path access — expanded to cover all API groups
-ROLE_PATHS: Dict[str, set] = {
- "talent": {
- "/v1/talent/",
- "/v1/academy/",
- "/v1/chat/talent/",
- "/v1/chat/reply",
- },
- "employer": {
- "/v1/employer",
- "/v1/search",
- "/v1/chat",
- "/v1/interviews",
- "/v1/jobs",
- },
- "admin": set(), # all access
-}
-
-
-def _get_client_ip(request: Request) -> str:
- forwarded = request.headers.get("X-Forwarded-For", "")
- if forwarded:
- return forwarded.split(",")[0].strip()
- return request.client.host if request.client else "unknown"
-
-
-def _needs_auth(path: str) -> bool:
- # Public paths (exact match)
- if path in PUBLIC_PATHS:
- return False
- # Public individual auth sub-paths
- if path in ("/v1/auth/register", "/v1/auth/register/employer", "/v1/auth/login",
- "/v1/auth/google", "/v1/auth/refresh", "/v1/auth/logout",
- "/v1/auth/admin/login"):
- return False
-
- return path.startswith("/v1/")
-
-
-class AuthMiddleware(BaseHTTPMiddleware):
- """JWT validation + RBAC + in-memory rate limiting.
-
- Rate limits: free=100/hr, talent=500/hr, employer=1000/hr, admin=2000/hr.
- All error responses use standardized format: {"success": false, "error": "...", "code": "..."}
- """
-
- # Per-role rate limits (immutable — no shared state mutation)
- _ROLE_LIMITS = {"talent": 500, "employer": 1000, "admin": 2000}
-
- async def dispatch(self, request: Request, call_next: Callable) -> Any:
- client_ip = _get_client_ip(request)
- path = request.url.path
-
- # ─── Rate limiting ────────────────────────────────────────────
- if not path.startswith("/health"):
- auth = request.headers.get("Authorization", "")
- role = "free"
- if auth.startswith("Bearer "):
- payload = decode_access_token(auth[7:])
- if payload:
- role = payload.get("role", "talent")
-
- # Use per-role limit WITHOUT mutating the shared rate_limiter instance
- effective_limit = self._ROLE_LIMITS.get(role, 100)
-
- if not rate_limiter.is_allowed(client_ip, limit=effective_limit):
- remaining = rate_limiter.get_remaining(client_ip, limit=effective_limit)
- return JSONResponse(
- status_code=status.HTTP_429_TOO_MANY_REQUESTS,
- content=error_response(
- "Rate limit exceeded. Free tier: 100 req/hr. Create an account for higher limits.",
- code=ErrorCode.RATE_LIMITED,
- remaining=remaining,
- ),
- headers={
- "X-RateLimit-Limit": str(effective_limit),
- "X-RateLimit-Remaining": str(remaining),
- "Retry-After": "3600",
- },
- )
-
- # ─── JWT Validation ───────────────────────────────────────────
- path = request.url.path
-
- if _needs_auth(path):
- payload = None
- if auth.startswith("Bearer "):
- payload = decode_access_token(auth[7:])
-
- if payload is None:
- return JSONResponse(
- status_code=status.HTTP_401_UNAUTHORIZED,
- content=error_response(
- "Invalid or expired token. Please login again.",
- code=ErrorCode.TOKEN_INVALID,
- ),
- headers={"WWW-Authenticate": "Bearer"},
- )
-
- # ─── RBAC ─────────────────────────────────────────────────
- role = payload.get("role", "talent")
- if role != "admin":
- allowed = ROLE_PATHS.get(role, set())
- has_access = any(path.startswith(p) for p in allowed | {"/v1/auth/", "/v1/talent/profile"})
- if not has_access:
- return JSONResponse(
- status_code=status.HTTP_403_FORBIDDEN,
- content=error_response(
- f"Access denied. Role '{role}' cannot access this resource.",
- code=ErrorCode.NOT_AUTHORIZED,
- ),
- )
-
- request.state.user = payload
- request.state.user_email = payload.get("email", "")
- request.state.user_role = payload.get("role", "talent")
-
- response = await call_next(request)
- return response
+"""JWT Authentication Middleware for FastAPI.
+
+Uses standardized error format from app.utils.errors.
+"""
+
+import time
+from typing import Any, Callable, Dict, Optional
+import os
+
+from fastapi import HTTPException, Request, status
+from fastapi.responses import JSONResponse
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from app.utils.errors import error_response, ErrorCode
+from app.utils.security import decode_access_token, rate_limiter, verify_supabase_token
+
+
+# Public endpoints — no auth required
+PUBLIC_PATHS = {
+ "/health",
+ "/health/db",
+ "/docs",
+ "/redoc",
+ "/openapi.json",
+ "/v1/auth/login",
+ "/v1/auth/register",
+ "/v1/auth/google",
+ "/v1/auth/refresh",
+ "/v1/jobs",
+ "/v1/search/talent",
+ "/v1/employer/tiers",
+ "/v1/webhook/telegram",
+ "/v1/whatsapp/webhook",
+ "/v1/legacy-gas-compat",
+}
+
+# Role-based path access — expanded to cover all API groups
+ROLE_PATHS: Dict[str, set] = {
+ "talent": {
+ "/v1/talent/",
+ "/v1/academy/",
+ "/v1/chat/talent/",
+ "/v1/chat/reply",
+ },
+ "employer": {
+ "/v1/employer",
+ "/v1/search",
+ "/v1/chat",
+ "/v1/interviews",
+ "/v1/jobs",
+ },
+ "admin": set(), # all access
+}
+
+
+def _get_client_ip(request: Request) -> str:
+ forwarded = request.headers.get("X-Forwarded-For", "")
+ if forwarded:
+ return forwarded.split(",")[0].strip()
+ return request.client.host if request.client else "unknown"
+
+
+def _needs_auth(path: str) -> bool:
+ # Public paths (exact match)
+ if path in PUBLIC_PATHS:
+ return False
+ # Public individual auth sub-paths
+ if path in ("/v1/auth/register", "/v1/auth/register/employer", "/v1/auth/login",
+ "/v1/auth/google", "/v1/auth/refresh", "/v1/auth/logout",
+ "/v1/auth/admin/login"):
+ return False
+
+ return path.startswith("/v1/")
+
+
+class AuthMiddleware(BaseHTTPMiddleware):
+ """JWT validation + RBAC + in-memory rate limiting.
+
+ Rate limits: free=100/hr, talent=500/hr, employer=1000/hr, admin=2000/hr.
+ All error responses use standardized format: {"success": false, "error": "...", "code": "..."}
+ """
+
+ # Per-role rate limits (immutable — no shared state mutation)
+ _ROLE_LIMITS = {"talent": 500, "employer": 1000, "admin": 2000}
+ async def dispatch(self, request: Request, call_next: Callable) -> Any:
+ client_ip = _get_client_ip(request)
+ path = request.url.path
+ auth = request.headers.get("Authorization", "")
+
+ # ─── Rate limiting ────────────────────────────────────────────
+ if not path.startswith("/health"):
+ role = "free"
+ if auth.startswith("Bearer "):
+ payload = decode_access_token(auth[7:])
+ if payload:
+ role = payload.get("role", "talent")
+
+ # Use per-role limit WITHOUT mutating the shared rate_limiter instance
+ effective_limit = self._ROLE_LIMITS.get(role, 100)
+
+ if not rate_limiter.is_allowed(client_ip, limit=effective_limit):
+ remaining = rate_limiter.get_remaining(client_ip, limit=effective_limit)
+ return JSONResponse(
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
+ content=error_response(
+ "Rate limit exceeded. Free tier: 100 req/hr. Create an account for higher limits.",
+ code=ErrorCode.RATE_LIMITED,
+ remaining=remaining,
+ ),
+ headers={
+ "X-RateLimit-Limit": str(effective_limit),
+ "X-RateLimit-Remaining": str(remaining),
+ "Retry-After": "3600",
+ },
+ )
+
+ # ─── JWT Validation ───────────────────────────────────────────
+ if _needs_auth(path):
+ payload = None
+ if auth.startswith("Bearer "):
+ token = auth[7:]
+ payload = decode_access_token(token)
+ if payload is None:
+ payload = await verify_supabase_token(token)
+
+ if payload is None:
+ return JSONResponse(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ content=error_response(
+ "Invalid or expired token. Please login again.",
+ code=ErrorCode.TOKEN_INVALID,
+ ),
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+ # ─── RBAC ─────────────────────────────────────────────────
+ role = payload.get("role", "talent")
+ if role != "admin":
+ allowed = ROLE_PATHS.get(role, set())
+ has_access = any(path.startswith(p) for p in allowed | {"/v1/auth/", "/v1/talent/profile"})
+ if not has_access:
+ return JSONResponse(
+ status_code=status.HTTP_403_FORBIDDEN,
+ content=error_response(
+ f"Access denied. Role '{role}' cannot access this resource.",
+ code=ErrorCode.NOT_AUTHORIZED,
+ ),
+ )
+
+ request.state.user = payload
+ request.state.user_email = payload.get("email", "")
+ request.state.user_role = payload.get("role", "talent")
+
+ response = await call_next(request)
+ return response
diff --git a/app/middleware/token_tracker.py b/app/middleware/token_tracker.py
index 85bd20158f93ba6b8966f337652c05c28730234f..26e51f90d075fae90ace415c019f5095f2fb5e76 100644
--- a/app/middleware/token_tracker.py
+++ b/app/middleware/token_tracker.py
@@ -1,32 +1,32 @@
-"""Token Tracker Middleware — Monitors AI quota consumption across all requests."""
-
-import time
-from typing import Callable
-
-from fastapi import Request, Response
-from loguru import logger
-from starlette.middleware.base import BaseHTTPMiddleware
-
-from app.database import AsyncSessionLocal
-from app.models.system import APIMonitoring
-
-
-class TokenTrackerMiddleware(BaseHTTPMiddleware):
- async def dispatch(self, request: Request, call_next: Callable) -> Response:
- start_time = time.time()
-
- # Process the request
- response = await call_next(request)
-
- # Post-process: Check if this was an AI-related request
- # In a real scenario, we could look for custom headers like 'X-AI-Tokens'
- # injected by the services, or just monitor endpoint patterns.
-
- # For Antigravity, the service itself handles DB logging.
- # This middleware can serve as a secondary observer or for non-Antigravity AI calls.
-
- duration = time.time() - start_time
- if response.status_code >= 400:
- logger.warning(f"[Monitor] Request {request.method} {request.url.path} failed ({response.status_code}) in {duration:.2f}s")
-
- return response
+"""Token Tracker Middleware — Monitors AI quota consumption across all requests."""
+
+import time
+from typing import Callable
+
+from fastapi import Request, Response
+from loguru import logger
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from app.database import AsyncSessionLocal
+from app.models.system import APIMonitoring
+
+
+class TokenTrackerMiddleware(BaseHTTPMiddleware):
+ async def dispatch(self, request: Request, call_next: Callable) -> Response:
+ start_time = time.time()
+
+ # Process the request
+ response = await call_next(request)
+
+ # Post-process: Check if this was an AI-related request
+ # In a real scenario, we could look for custom headers like 'X-AI-Tokens'
+ # injected by the services, or just monitor endpoint patterns.
+
+ # For Antigravity, the service itself handles DB logging.
+ # This middleware can serve as a secondary observer or for non-Antigravity AI calls.
+
+ duration = time.time() - start_time
+ if response.status_code >= 400:
+ logger.warning(f"[Monitor] Request {request.method} {request.url.path} failed ({response.status_code}) in {duration:.2f}s")
+
+ return response
diff --git a/app/models/ab.py b/app/models/ab.py
index 887927c589bf815009d17fbc65dc95fa43e35469..eb888689fef1d4710dfa1b17e360343c38b33987 100644
--- a/app/models/ab.py
+++ b/app/models/ab.py
@@ -1,29 +1,29 @@
-import uuid
-from datetime import datetime
-from sqlalchemy import Column, String, DateTime, JSON, Boolean
-from sqlalchemy.dialects.postgresql import UUID
-from app.models.base import Base, JSONB
-
-
-class ABExperiment(Base):
- __tablename__ = 'ab_experiments'
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- name = Column(String(150), nullable=False)
- variant_a = Column(JSONB, nullable=True)
- variant_b = Column(JSONB, nullable=True)
- start_ts = Column(DateTime(timezone=True), default=datetime.utcnow)
- end_ts = Column(DateTime(timezone=True), nullable=True)
- metric_name = Column(String(100), nullable=True)
- status = Column(String(20), default='running')
-
-
-class ABEvent(Base):
- __tablename__ = 'ab_events'
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- experiment_id = Column(UUID(as_uuid=True), nullable=False)
- variant = Column(String(10), nullable=False)
- user_id = Column(String(100), nullable=True)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- payload = Column(JSONB, nullable=True)
+import uuid
+from datetime import datetime
+from sqlalchemy import Column, String, DateTime, JSON, Boolean
+from sqlalchemy.dialects.postgresql import UUID
+from app.models.base import Base, JSONB
+
+
+class ABExperiment(Base):
+ __tablename__ = 'ab_experiments'
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ name = Column(String(150), nullable=False)
+ variant_a = Column(JSONB, nullable=True)
+ variant_b = Column(JSONB, nullable=True)
+ start_ts = Column(DateTime(timezone=True), default=datetime.utcnow)
+ end_ts = Column(DateTime(timezone=True), nullable=True)
+ metric_name = Column(String(100), nullable=True)
+ status = Column(String(20), default='running')
+
+
+class ABEvent(Base):
+ __tablename__ = 'ab_events'
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ experiment_id = Column(UUID(as_uuid=True), nullable=False)
+ variant = Column(String(10), nullable=False)
+ user_id = Column(String(100), nullable=True)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ payload = Column(JSONB, nullable=True)
diff --git a/app/models/career.py b/app/models/career.py
index cd3b583b58a811224cf4a7b1e538012dbfec4289..1cd5d04ebd7d4fbaa3f932849fcae0c371e6dcae 100644
--- a/app/models/career.py
+++ b/app/models/career.py
@@ -1,134 +1,134 @@
-"""Career history models — Profiles, Experiences, Credentials, and Organizations.
-
-Implements the lifelong career record schema with encryption support.
-"""
-
-import uuid
-from datetime import datetime
-from typing import List, Optional
-
-from sqlalchemy import Column, String, Text, Boolean, DateTime, Date, ForeignKey, CheckConstraint, UniqueConstraint
-from sqlalchemy.dialects.postgresql import UUID, ARRAY
-from sqlalchemy.orm import relationship
-
-from app.models.base import Base
-
-
-class Profile(Base):
- """Core identity profile for Talents, Recruiters, and Admins."""
- __tablename__ = "profiles"
-
- id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
- status = Column(String(20), nullable=False, server_default="active")
- email = Column(String(255), unique=True, nullable=True)
- full_name = Column(String(255), nullable=True)
- industry = Column(String(100), nullable=True)
- general_skills = Column(ARRAY(String(50)), nullable=True)
- created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
-
- # Relationships
- experiences = relationship("Experience", back_populates="profile", cascade="all, delete-orphan")
- credentials = relationship("Credential", back_populates="profile", cascade="all, delete-orphan")
- memberships = relationship("OrganizationMember", back_populates="profile", cascade="all, delete-orphan")
- key = relationship("ProfileKey", uselist=False, cascade="all, delete-orphan")
-
- __table_args__ = (
- CheckConstraint("status IN ('active', 'deleted')", name="check_profile_status"),
- )
-
-
-class Organization(Base):
- """Employers, Universities, and Credential Issuing bodies."""
- __tablename__ = "organizations"
-
- id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
- name = Column(String(255), nullable=False)
- website_url = Column(String(255), nullable=True)
- verified = Column(Boolean, nullable=False, server_default="false")
- public_key = Column(Text, nullable=True) # PEM format for signature verification
- created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
-
- # Relationships
- members = relationship("OrganizationMember", back_populates="organization", cascade="all, delete-orphan")
- experiences = relationship("Experience", back_populates="organization")
- credentials = relationship("Credential", back_populates="organization")
-
-
-class OrganizationMember(Base):
- """Maps profiles to organizations with specific roles (RBAC)."""
- __tablename__ = "organization_members"
-
- id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
- organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
- profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
- role = Column(String(20), nullable=False, server_default="member")
- created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()")
-
- # Relationships
- organization = relationship("Organization", back_populates="members")
- profile = relationship("Profile", back_populates="memberships")
-
- __table_args__ = (
- UniqueConstraint("organization_id", "profile_id", name="uq_org_member"),
- CheckConstraint("role IN ('owner', 'admin', 'member')", name="check_member_role"),
- )
-
-
-class Experience(Base):
- """Employment and gig history records with encrypted details."""
- __tablename__ = "experiences"
-
- id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
- profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
- organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
- start_date = Column(Date, nullable=False)
- end_date = Column(Date, nullable=True)
- job_title = Column(String(150), nullable=True, index=True)
- encrypted_payload = Column(Text, nullable=False) # AES-256 encrypted JSON
- created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
-
- # Relationships
- profile = relationship("Profile", back_populates="experiences")
- organization = relationship("Organization", back_populates="experiences")
-
-
-class Credential(Base):
- """Degrees, Certifications, and Licenses with cryptographic signatures."""
- __tablename__ = "credentials"
-
- id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
- profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
- organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
- issue_date = Column(Date, nullable=False)
- expiry_date = Column(Date, nullable=True)
- credential_name = Column(String(150), nullable=True, index=True)
- encrypted_payload = Column(Text, nullable=False) # AES-256 encrypted JSON
- issuer_signature = Column(Text, nullable=False) # Digital signature from issuer
- created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
-
- # Relationships
- profile = relationship("Profile", back_populates="credentials")
- organization = relationship("Organization", back_populates="credentials")
- shares = relationship("CredentialShare", back_populates="credential", cascade="all, delete-orphan")
-
-
-class CredentialShare(Base):
- """Temporary access grants for recruiters to view private credential details."""
- __tablename__ = "credential_shares"
-
- id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
- credential_id = Column(UUID(as_uuid=True), ForeignKey("credentials.id", ondelete="CASCADE"), nullable=False)
- shared_with_profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
- expires_at = Column(DateTime(timezone=True), nullable=True)
- created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()")
-
- # Relationships
- credential = relationship("Credential", back_populates="shares")
-
- __table_args__ = (
- UniqueConstraint("credential_id", "shared_with_profile_id", name="uq_credential_share"),
- )
+"""Career history models — Profiles, Experiences, Credentials, and Organizations.
+
+Implements the lifelong career record schema with encryption support.
+"""
+
+import uuid
+from datetime import datetime
+from typing import List, Optional
+
+from sqlalchemy import Column, String, Text, Boolean, DateTime, Date, ForeignKey, CheckConstraint, UniqueConstraint
+from sqlalchemy.dialects.postgresql import UUID, ARRAY
+from sqlalchemy.orm import relationship
+
+from app.models.base import Base
+
+
+class Profile(Base):
+ """Core identity profile for Talents, Recruiters, and Admins."""
+ __tablename__ = "profiles"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
+ status = Column(String(20), nullable=False, server_default="active")
+ email = Column(String(255), unique=True, nullable=True)
+ full_name = Column(String(255), nullable=True)
+ industry = Column(String(100), nullable=True)
+ general_skills = Column(ARRAY(String(50)), nullable=True)
+ created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ experiences = relationship("Experience", back_populates="profile", cascade="all, delete-orphan")
+ credentials = relationship("Credential", back_populates="profile", cascade="all, delete-orphan")
+ memberships = relationship("OrganizationMember", back_populates="profile", cascade="all, delete-orphan")
+ key = relationship("ProfileKey", uselist=False, cascade="all, delete-orphan")
+
+ __table_args__ = (
+ CheckConstraint("status IN ('active', 'deleted')", name="check_profile_status"),
+ )
+
+
+class Organization(Base):
+ """Employers, Universities, and Credential Issuing bodies."""
+ __tablename__ = "organizations"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
+ name = Column(String(255), nullable=False)
+ website_url = Column(String(255), nullable=True)
+ verified = Column(Boolean, nullable=False, server_default="false")
+ public_key = Column(Text, nullable=True) # PEM format for signature verification
+ created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ members = relationship("OrganizationMember", back_populates="organization", cascade="all, delete-orphan")
+ experiences = relationship("Experience", back_populates="organization")
+ credentials = relationship("Credential", back_populates="organization")
+
+
+class OrganizationMember(Base):
+ """Maps profiles to organizations with specific roles (RBAC)."""
+ __tablename__ = "organization_members"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
+ organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
+ profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
+ role = Column(String(20), nullable=False, server_default="member")
+ created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()")
+
+ # Relationships
+ organization = relationship("Organization", back_populates="members")
+ profile = relationship("Profile", back_populates="memberships")
+
+ __table_args__ = (
+ UniqueConstraint("organization_id", "profile_id", name="uq_org_member"),
+ CheckConstraint("role IN ('owner', 'admin', 'member')", name="check_member_role"),
+ )
+
+
+class Experience(Base):
+ """Employment and gig history records with encrypted details."""
+ __tablename__ = "experiences"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
+ profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
+ organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
+ start_date = Column(Date, nullable=False)
+ end_date = Column(Date, nullable=True)
+ job_title = Column(String(150), nullable=True, index=True)
+ encrypted_payload = Column(Text, nullable=False) # AES-256 encrypted JSON
+ created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ profile = relationship("Profile", back_populates="experiences")
+ organization = relationship("Organization", back_populates="experiences")
+
+
+class Credential(Base):
+ """Degrees, Certifications, and Licenses with cryptographic signatures."""
+ __tablename__ = "credentials"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
+ profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
+ organization_id = Column(UUID(as_uuid=True), ForeignKey("organizations.id", ondelete="CASCADE"), nullable=False)
+ issue_date = Column(Date, nullable=False)
+ expiry_date = Column(Date, nullable=True)
+ credential_name = Column(String(150), nullable=True, index=True)
+ encrypted_payload = Column(Text, nullable=False) # AES-256 encrypted JSON
+ issuer_signature = Column(Text, nullable=False) # Digital signature from issuer
+ created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), nullable=False, server_default="now()", default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ profile = relationship("Profile", back_populates="credentials")
+ organization = relationship("Organization", back_populates="credentials")
+ shares = relationship("CredentialShare", back_populates="credential", cascade="all, delete-orphan")
+
+
+class CredentialShare(Base):
+ """Temporary access grants for recruiters to view private credential details."""
+ __tablename__ = "credential_shares"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, server_default="gen_random_uuid()")
+ credential_id = Column(UUID(as_uuid=True), ForeignKey("credentials.id", ondelete="CASCADE"), nullable=False)
+ shared_with_profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), nullable=False)
+ expires_at = Column(DateTime(timezone=True), nullable=True)
+ created_at = Column(DateTime(timezone=True), nullable=False, server_default="now()")
+
+ # Relationships
+ credential = relationship("Credential", back_populates="shares")
+
+ __table_args__ = (
+ UniqueConstraint("credential_id", "shared_with_profile_id", name="uq_credential_share"),
+ )
diff --git a/app/models/community.py b/app/models/community.py
index 32fcd202ec93976541cce7c61a3c4f1b01b778a7..58817443c0735282fe614914139cdb3444825978 100644
--- a/app/models/community.py
+++ b/app/models/community.py
@@ -1,102 +1,102 @@
-"""Community, Challenges, and Pathways models."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID
-
-from app.models.base import Base
-
-
-class CommunityPartner(Base):
- __tablename__ = "community_partners"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- name = Column(String(255), nullable=False)
- contact_email = Column(String(255), unique=True, nullable=False)
- logo_url = Column(String(500), nullable=True)
- rev_share_briga = Column(Numeric(5, 2), default=50.00)
- rev_share_community = Column(Numeric(5, 2), default=30.00)
- rev_share_talent = Column(Numeric(5, 2), default=20.00)
- status = Column(String(20), default="Proposed")
- approved_by = Column(String(255), nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class SponsoredChallenge(Base):
- __tablename__ = "sponsored_challenges"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- community_id = Column(UUID(as_uuid=True), ForeignKey("community_partners.id", ondelete="SET NULL"), nullable=True)
- sponsor_name = Column(String(255), nullable=False)
- title = Column(String(255), nullable=False)
- description = Column(Text, nullable=False)
- verification_rubric = Column(Text, nullable=False)
- payout_amount = Column(Integer, default=0)
- is_active = Column(Boolean, default=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class Pathway(Base):
- __tablename__ = "pathways"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- user_email = Column(String(255), unique=True, nullable=False, index=True)
- pathway_json = Column(JSONB, nullable=False, default=dict)
- progress_json = Column(JSONB, nullable=False, default=dict)
- completed_stages = Column(JSONB, default=list)
- green_score = Column(Integer, default=0)
- community_id = Column(UUID(as_uuid=True), ForeignKey("community_partners.id", ondelete="SET NULL"), nullable=True)
- challenge_id = Column(UUID(as_uuid=True), ForeignKey("sponsored_challenges.id", ondelete="SET NULL"), nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
-
-
-class AIKnowledgeBase(Base):
- __tablename__ = "ai_knowledge_base"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- source_email = Column(String(255), nullable=True)
- category = Column(String(100), nullable=True)
- fact = Column(Text, nullable=True)
- confidence = Column(Numeric(3, 2), nullable=True)
-
-
-class AIPublicInsight(Base):
- __tablename__ = "ai_public_insights"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- source_email = Column(String(255), nullable=True)
- positive_metric = Column(Text, nullable=True)
- generated_insight = Column(Text, nullable=True)
- approved_for_public = Column(Boolean, default=False)
-
-
-class AIInternalReport(Base):
- __tablename__ = "ai_internal_reports"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- source_email = Column(String(255), nullable=True)
- negative_feedback = Column(Text, nullable=True)
- critical_issues = Column(Text, nullable=True)
- action_required = Column(Text, nullable=True)
-
-
-class AIInterviewMemory(Base):
- __tablename__ = "ai_interview_memory"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- email = Column(String(255), nullable=True)
- sector = Column(String(100), nullable=True)
- question = Column(Text, nullable=True)
- answer = Column(Text, nullable=True)
- swot_strengths = Column(Text, nullable=True)
- swot_weaknesses = Column(Text, nullable=True)
- score = Column(Integer, nullable=True)
- obsidian_format = Column(Text, nullable=True)
+"""Community, Challenges, and Pathways models."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID
+
+from app.models.base import Base
+
+
+class CommunityPartner(Base):
+ __tablename__ = "community_partners"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ name = Column(String(255), nullable=False)
+ contact_email = Column(String(255), unique=True, nullable=False)
+ logo_url = Column(String(500), nullable=True)
+ rev_share_briga = Column(Numeric(5, 2), default=50.00)
+ rev_share_community = Column(Numeric(5, 2), default=30.00)
+ rev_share_talent = Column(Numeric(5, 2), default=20.00)
+ status = Column(String(20), default="Proposed")
+ approved_by = Column(String(255), nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class SponsoredChallenge(Base):
+ __tablename__ = "sponsored_challenges"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ community_id = Column(UUID(as_uuid=True), ForeignKey("community_partners.id", ondelete="SET NULL"), nullable=True)
+ sponsor_name = Column(String(255), nullable=False)
+ title = Column(String(255), nullable=False)
+ description = Column(Text, nullable=False)
+ verification_rubric = Column(Text, nullable=False)
+ payout_amount = Column(Integer, default=0)
+ is_active = Column(Boolean, default=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class Pathway(Base):
+ __tablename__ = "pathways"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ user_email = Column(String(255), unique=True, nullable=False, index=True)
+ pathway_json = Column(JSONB, nullable=False, default=dict)
+ progress_json = Column(JSONB, nullable=False, default=dict)
+ completed_stages = Column(JSONB, default=list)
+ green_score = Column(Integer, default=0)
+ community_id = Column(UUID(as_uuid=True), ForeignKey("community_partners.id", ondelete="SET NULL"), nullable=True)
+ challenge_id = Column(UUID(as_uuid=True), ForeignKey("sponsored_challenges.id", ondelete="SET NULL"), nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
+class AIKnowledgeBase(Base):
+ __tablename__ = "ai_knowledge_base"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ source_email = Column(String(255), nullable=True)
+ category = Column(String(100), nullable=True)
+ fact = Column(Text, nullable=True)
+ confidence = Column(Numeric(3, 2), nullable=True)
+
+
+class AIPublicInsight(Base):
+ __tablename__ = "ai_public_insights"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ source_email = Column(String(255), nullable=True)
+ positive_metric = Column(Text, nullable=True)
+ generated_insight = Column(Text, nullable=True)
+ approved_for_public = Column(Boolean, default=False)
+
+
+class AIInternalReport(Base):
+ __tablename__ = "ai_internal_reports"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ source_email = Column(String(255), nullable=True)
+ negative_feedback = Column(Text, nullable=True)
+ critical_issues = Column(Text, nullable=True)
+ action_required = Column(Text, nullable=True)
+
+
+class AIInterviewMemory(Base):
+ __tablename__ = "ai_interview_memory"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ email = Column(String(255), nullable=True)
+ sector = Column(String(100), nullable=True)
+ question = Column(Text, nullable=True)
+ answer = Column(Text, nullable=True)
+ swot_strengths = Column(Text, nullable=True)
+ swot_weaknesses = Column(Text, nullable=True)
+ score = Column(Integer, nullable=True)
+ obsidian_format = Column(Text, nullable=True)
diff --git a/app/models/content.py b/app/models/content.py
index a4ce8d72259a1b069d4e4148cf658ec692344eae..f5cde2f034e9b8fd00abcc5d60805df60281f5ec 100644
--- a/app/models/content.py
+++ b/app/models/content.py
@@ -1,87 +1,92 @@
-"""Content & Knowledge models."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID
-from app.models.base import Base
-
-
-class BlogPost(Base):
- __tablename__ = "blog_posts"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- article_id = Column(String(50), unique=True, nullable=False)
- date_str = Column(String(50), nullable=True)
- title = Column(Text, nullable=False)
- category = Column(String(50), nullable=True, index=True)
- summary = Column(Text, nullable=True)
- content = Column(Text, nullable=True)
- thumbnail_url = Column(String(500), nullable=True)
- reading_time = Column(String(20), nullable=True)
- published = Column(String(5), default="No")
- published_at = Column(DateTime(timezone=True), nullable=True)
- target_keyword = Column(String(255), nullable=True)
- seo_score = Column(String(20), nullable=True)
- ai_reviewed = Column(String(10), nullable=True)
- reviewer_notes = Column(Text, nullable=True)
- review_score = Column(String(10), nullable=True)
- review_status = Column(String(50), nullable=True)
- review_date = Column(DateTime(timezone=True), nullable=True)
- reviewer_email = Column(String(255), nullable=True)
- meta_description = Column(Text, nullable=True)
- internal_links = Column(Text, nullable=True)
- source_brief = Column(Text, nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class ContentPipeline(Base):
- __tablename__ = "content_pipeline"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- pipeline_id = Column(String(50), unique=True, nullable=False)
- topic = Column(Text, nullable=True)
- target_keyword = Column(String(255), nullable=True)
- source = Column(String(100), nullable=True)
- priority_score = Column(Integer, default=0)
- stage = Column(String(50), nullable=True)
- linked_blog_id = Column(String(50), nullable=True)
- status = Column(String(50), default="Draft")
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
- error_message = Column(Text, nullable=True)
-
-
-class KnowledgeBase(Base):
- __tablename__ = "knowledge_base"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- knowledge_rule = Column(Text, nullable=False)
- sector = Column(String(100), nullable=True, index=True)
- source = Column(String(255), nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class KnowledgeQueue(Base):
- __tablename__ = "knowledge_queue"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- source_email = Column(String(255), nullable=True)
- category = Column(String(100), nullable=True)
- fact = Column(Text, nullable=True)
- confidence = Column(Numeric(3, 2), nullable=True)
- status = Column(String(50), default="Pending")
-
-
-class SEOStrategy(Base):
- __tablename__ = "seo_strategy"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- keyword = Column(String(255), nullable=True)
- target_page = Column(String(255), nullable=True)
- strategy = Column(Text, nullable=True)
- status = Column(String(50), default="Planned")
+"""Content & Knowledge models."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID
+from app.models.base import Base
+
+
+class BlogPost(Base):
+ __tablename__ = "blog_posts"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ article_id = Column(String(50), unique=True, nullable=False)
+ date_str = Column(String(50), nullable=True)
+ title = Column(Text, nullable=False)
+ category = Column(String(50), nullable=True, index=True)
+ summary = Column(Text, nullable=True)
+ content = Column(Text, nullable=True)
+ thumbnail_url = Column(String(500), nullable=True)
+ reading_time = Column(String(20), nullable=True)
+ published = Column(String(5), default="No")
+ published_at = Column(DateTime(timezone=True), nullable=True)
+ target_keyword = Column(String(255), nullable=True)
+ seo_score = Column(String(20), nullable=True)
+ ai_reviewed = Column(String(10), nullable=True)
+ reviewer_notes = Column(Text, nullable=True)
+ review_score = Column(String(10), nullable=True)
+ review_status = Column(String(50), nullable=True)
+ review_date = Column(DateTime(timezone=True), nullable=True)
+ reviewer_email = Column(String(255), nullable=True)
+ meta_description = Column(Text, nullable=True)
+ internal_links = Column(Text, nullable=True)
+ source_brief = Column(Text, nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class ContentPipeline(Base):
+ __tablename__ = "content_pipeline"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ pipeline_id = Column(String(50), unique=True, nullable=False)
+ topic = Column(Text, nullable=True)
+ target_keyword = Column(String(255), nullable=True)
+ source = Column(String(100), nullable=True)
+ priority_score = Column(Integer, default=0)
+ stage = Column(String(50), nullable=True)
+ linked_blog_id = Column(String(50), nullable=True)
+ status = Column(String(50), default="Draft")
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+ error_message = Column(Text, nullable=True)
+
+
+class KnowledgeBase(Base):
+ __tablename__ = "knowledge_base"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ knowledge_rule = Column(Text, nullable=False)
+ sector = Column(String(100), nullable=True, index=True)
+ source = Column(String(255), nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class KnowledgeQueue(Base):
+ __tablename__ = "knowledge_queue"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ source_email = Column(String(255), nullable=True)
+ category = Column(String(100), nullable=True)
+ fact = Column(Text, nullable=True)
+ confidence = Column(Numeric(3, 2), nullable=True)
+ status = Column(String(50), default="Pending")
+ # FIX (2026-09): heartbeat retry/dead-letter support. Columns are nullable so
+ # the migration is additive (no backfill needed); Supabase PostgREST accepts
+ # PATCHes that set them on rows where they were previously NULL.
+ retry_count = Column(Integer, default=0, nullable=True)
+ last_error = Column(Text, nullable=True)
+
+
+class SEOStrategy(Base):
+ __tablename__ = "seo_strategy"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ keyword = Column(String(255), nullable=True)
+ target_page = Column(String(255), nullable=True)
+ strategy = Column(Text, nullable=True)
+ status = Column(String(50), default="Planned")
diff --git a/app/models/employer.py b/app/models/employer.py
index fa7b7c0473cdab5d93d67e25c80a27065af0fef8..6149d1df92761cedd3c4edbc40bab24a3bc24dbc 100644
--- a/app/models/employer.py
+++ b/app/models/employer.py
@@ -1,64 +1,64 @@
-"""Employer (B2B) models — Companies, Clients, Pending Employers."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Numeric
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID, ENUM
-from app.models.base import Base
-
-
-class Company(Base):
- __tablename__ = "companies"
-
- id = Column(String(50), primary_key=True)
- name = Column(String(255), nullable=False)
- website = Column(String(255), nullable=True)
- branding = Column(String(255), nullable=True)
- bidang_usaha = Column(String(255), nullable=True)
- produk_jasa = Column(String(255), nullable=True)
- industri_ai = Column(String(255), nullable=True)
- credit_balance = Column(Integer, default=0)
- csr_budget = Column(Numeric(15, 2), default=0.00)
- tier = Column(String(20), default="free")
- billing = Column(String(20), default="monthly")
- seats_limit = Column(Integer, default=2)
- max_jobs = Column(Integer, default=1)
- status = Column(String(20), default="PENDING", index=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class ClientAccount(Base):
- __tablename__ = "client_accounts"
-
- id = Column(String(50), primary_key=True)
- company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
- email = Column(String(255), unique=True, nullable=False, index=True)
- password_hash = Column(String(255), nullable=False)
- name = Column(String(255), nullable=False)
- whatsapp = Column(String(50), nullable=True)
- jabatan = Column(String(100), nullable=True)
- role = Column(ENUM("Recruiter", "Sustainability", name="staff_role", create_type=False), default="Recruiter")
- status = Column(String(20), default="PENDING")
- auth_key = Column(String(255), default="-")
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class PendingEmployer(Base):
- __tablename__ = "pending_employers"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- entity_name = Column(String(255), nullable=True)
- branding = Column(String(255), nullable=True)
- website = Column(String(255), nullable=True)
- pic_name = Column(String(255), nullable=True)
- pic_jabatan = Column(String(100), nullable=True)
- email = Column(String(255), unique=True, nullable=False)
- whatsapp = Column(String(50), nullable=True)
- password_hash = Column(String(255), nullable=True)
- status = Column(String(20), default="PENDING", index=True)
- bidang_usaha = Column(String(255), nullable=True)
- produk_jasa = Column(String(255), nullable=True)
- industri_ai = Column(String(255), nullable=True)
+"""Employer (B2B) models — Companies, Clients, Pending Employers."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Numeric
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID, ENUM
+from app.models.base import Base
+
+
+class Company(Base):
+ __tablename__ = "companies"
+
+ id = Column(String(50), primary_key=True)
+ name = Column(String(255), nullable=False)
+ website = Column(String(255), nullable=True)
+ branding = Column(String(255), nullable=True)
+ bidang_usaha = Column(String(255), nullable=True)
+ produk_jasa = Column(String(255), nullable=True)
+ industri_ai = Column(String(255), nullable=True)
+ credit_balance = Column(Integer, default=0)
+ csr_budget = Column(Numeric(15, 2), default=0.00)
+ tier = Column(String(20), default="free")
+ billing = Column(String(20), default="monthly")
+ seats_limit = Column(Integer, default=2)
+ max_jobs = Column(Integer, default=1)
+ status = Column(String(20), default="PENDING", index=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class ClientAccount(Base):
+ __tablename__ = "client_accounts"
+
+ id = Column(String(50), primary_key=True)
+ company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
+ email = Column(String(255), unique=True, nullable=False, index=True)
+ password_hash = Column(String(255), nullable=False)
+ name = Column(String(255), nullable=False)
+ whatsapp = Column(String(50), nullable=True)
+ jabatan = Column(String(100), nullable=True)
+ role = Column(ENUM("Recruiter", "Sustainability", name="staff_role", create_type=False), default="Recruiter")
+ status = Column(String(20), default="PENDING")
+ auth_key = Column(String(255), default="-")
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class PendingEmployer(Base):
+ __tablename__ = "pending_employers"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ entity_name = Column(String(255), nullable=True)
+ branding = Column(String(255), nullable=True)
+ website = Column(String(255), nullable=True)
+ pic_name = Column(String(255), nullable=True)
+ pic_jabatan = Column(String(100), nullable=True)
+ email = Column(String(255), unique=True, nullable=False)
+ whatsapp = Column(String(50), nullable=True)
+ password_hash = Column(String(255), nullable=True)
+ status = Column(String(20), default="PENDING", index=True)
+ bidang_usaha = Column(String(255), nullable=True)
+ produk_jasa = Column(String(255), nullable=True)
+ industri_ai = Column(String(255), nullable=True)
diff --git a/app/models/finance.py b/app/models/finance.py
index 3068c3b8ae7ea8ca1f9ac93813473236e23dc6e9..7666137371df2af6defda96f1eb15f80be8ff54a 100644
--- a/app/models/finance.py
+++ b/app/models/finance.py
@@ -1,47 +1,47 @@
-"""Financial models — Transactions, Unlocks, Interviews."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID
-from app.models.base import Base
-
-
-class Transaction(Base):
- __tablename__ = "transactions"
-
- id = Column(String(50), primary_key=True)
- client_id = Column(String(50), ForeignKey("client_accounts.id", ondelete="SET NULL"), nullable=True, index=True)
- amount = Column(Numeric(15, 2), nullable=False)
- type = Column(String(50), nullable=False)
- status = Column(String(20), default="Pending", index=True)
- snap_token = Column(String(500), nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class ProfileUnlock(Base):
- __tablename__ = "profile_unlocks"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
- candidate_id = Column(String(50), nullable=False, index=True)
- is_masked_only = Column(Boolean, default=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class Interview(Base):
- __tablename__ = "interviews"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
- client_id = Column(String(50), ForeignKey("client_accounts.id", ondelete="SET NULL"), nullable=True)
- candidate_id = Column(String(50), nullable=False, index=True)
- scheduled_time = Column(DateTime(timezone=True), nullable=False)
- status = Column(String(20), default="Scheduled")
- transcript_text = Column(Text, nullable=True)
- ai_summary = Column(Text, nullable=True)
- ai_competency_score = Column(Integer, default=0)
- ai_performance_analysis = Column(Text, nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+"""Financial models — Transactions, Unlocks, Interviews."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID
+from app.models.base import Base
+
+
+class Transaction(Base):
+ __tablename__ = "transactions"
+
+ id = Column(String(50), primary_key=True)
+ client_id = Column(String(50), ForeignKey("client_accounts.id", ondelete="SET NULL"), nullable=True, index=True)
+ amount = Column(Numeric(15, 2), nullable=False)
+ type = Column(String(50), nullable=False)
+ status = Column(String(20), default="Pending", index=True)
+ snap_token = Column(String(500), nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class ProfileUnlock(Base):
+ __tablename__ = "profile_unlocks"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
+ candidate_id = Column(String(50), nullable=False, index=True)
+ is_masked_only = Column(Boolean, default=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class Interview(Base):
+ __tablename__ = "interviews"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ company_id = Column(String(50), ForeignKey("companies.id", ondelete="CASCADE"), nullable=True, index=True)
+ client_id = Column(String(50), ForeignKey("client_accounts.id", ondelete="SET NULL"), nullable=True)
+ candidate_id = Column(String(50), nullable=False, index=True)
+ scheduled_time = Column(DateTime(timezone=True), nullable=False)
+ status = Column(String(20), default="Scheduled")
+ transcript_text = Column(Text, nullable=True)
+ ai_summary = Column(Text, nullable=True)
+ ai_competency_score = Column(Integer, default=0)
+ ai_performance_analysis = Column(Text, nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
diff --git a/app/models/job.py b/app/models/job.py
index 14fad4398c3a307b71a5fdc970ee8e0187ff3941..600d8cc257e6aa3033a8ae0671aea211c3d4efa0 100644
--- a/app/models/job.py
+++ b/app/models/job.py
@@ -1,120 +1,120 @@
-"""Job, Outreach, and Chat models."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Index
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID
-
-from app.models.base import Base
-
-
-class JobPosting(Base):
- __tablename__ = "job_postings"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- job_id = Column(String(50), unique=True, nullable=False)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- title = Column(String(255), nullable=False)
- company_name = Column(String(255), nullable=True)
- company_id = Column(String(50), ForeignKey("companies.id", ondelete="SET NULL"), nullable=True, index=True)
- posted_by_email = Column(String(255), nullable=True, index=True)
- company_category = Column(String(255), nullable=True)
- location = Column(String(255), nullable=True)
- description = Column(Text, nullable=True)
- required_skills = Column(Text, nullable=True)
- salary_range = Column(String(100), nullable=True)
- source = Column(String(100), nullable=True)
- source_url = Column(String(500), nullable=True)
- status = Column(String(50), default="draft", index=True)
- linkedin_post_url = Column(String(500), nullable=True)
- analysis_json = Column(JSONB, nullable=True)
- sector_match = Column(String(255), nullable=True, index=True)
- is_active = Column(Boolean, default=True, index=True)
- scraped_at = Column(DateTime(timezone=True), nullable=True)
- posted_at = Column(DateTime(timezone=True), nullable=True)
- environment = Column(String(20), default='production', nullable=False)
-
-
-class RecruiterOutreach(Base):
- __tablename__ = "recruiter_outreach"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- outreach_id = Column(String(20), unique=True, nullable=False)
- job_id = Column(String(50), nullable=True)
- talent_email = Column(String(255), nullable=True, index=True)
- match_score = Column(Integer, nullable=True)
- recruiter_email = Column(String(255), nullable=True)
- contact_method = Column(String(50), nullable=True)
- outreach_subject = Column(Text, nullable=True)
- outreach_body = Column(Text, nullable=True)
- status = Column(String(20), default="pending_approval", index=True)
- triggered_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- sent_at = Column(DateTime(timezone=True), nullable=True)
-
-
-class MediatedChat(Base):
- """Mediated chat messages between recruiters and talents.
-
- Brigawan AI acts as a smart relay, masking identities until unlocked.
- Matches ChatManager.gs schema with conversation grouping.
- """
- __tablename__ = "mediated_chats"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- chat_id = Column(String(50), unique=True, nullable=True, index=True) # MSG-UUID8
- conversation_id = Column(String(50), nullable=False, index=True) # CONV-UUID8
- sender_email = Column(String(255), nullable=False, index=True) # Who sent
- receiver_email = Column(String(255), nullable=False, index=True) # Who receives
- sender_role = Column(String(20), nullable=False, default="RECRUITER") # RECRUITER or TALENT
- original_message = Column(Text, nullable=True) # Raw message from sender
- mediated_message = Column(Text, nullable=True) # AI-mediated version for recipient
- is_identity_unlocked = Column(Boolean, default=False) # TRUE after 5-coin unlock
- status = Column(String(30), default="PENDING_RECRUITER", index=True) # PENDING_TALENT, PENDING_RECRUITER, READ
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
-
- # Legacy fields (kept for backward compat)
- email = Column(String(255), nullable=True, index=True)
- talent_id = Column(String(20), nullable=True, index=True)
- talent_name = Column(String(255), nullable=True)
- message = Column(Text, nullable=True)
- sender = Column(String(50), nullable=True)
- is_read = Column(Boolean, default=False)
- unlocked_at = Column(DateTime(timezone=True), nullable=True)
- unlock_type = Column(String(50), nullable=True)
- campaign_id = Column(String(50), nullable=True)
-
-
-class AITalentChat(Base):
- __tablename__ = "ai_talent_chat"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- email = Column(String(255), nullable=False, index=True)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- user_message = Column(Text, nullable=True)
- ai_reply = Column(Text, nullable=True)
- expires_at = Column(DateTime(timezone=True), nullable=True)
-
-
-class TalentPathway(Base):
- __tablename__ = "talent_pathway"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- email = Column(String(255), unique=True, nullable=False, index=True)
- pathway_json = Column(JSONB, nullable=False)
- progress_json = Column(JSONB, nullable=False)
- completed_stages = Column(JSONB, default=list)
- generated_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- green_score = Column(Integer, default=0)
-
-
-class TalentAcademy(Base):
- __tablename__ = "talent_academy"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- email = Column(String(255), unique=True, nullable=False)
- completed_modules = Column(Text, default="")
- registered_onsite = Column(JSONB, default=list)
- last_updated_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- essay_answers = Column(Text, default="")
+"""Job, Outreach, and Chat models."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Index
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID
+
+from app.models.base import Base
+
+
+class JobPosting(Base):
+ __tablename__ = "job_postings"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ job_id = Column(String(50), unique=True, nullable=False)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ title = Column(String(255), nullable=False)
+ company_name = Column(String(255), nullable=True)
+ company_id = Column(String(50), ForeignKey("companies.id", ondelete="SET NULL"), nullable=True, index=True)
+ posted_by_email = Column(String(255), nullable=True, index=True)
+ company_category = Column(String(255), nullable=True)
+ location = Column(String(255), nullable=True)
+ description = Column(Text, nullable=True)
+ required_skills = Column(Text, nullable=True)
+ salary_range = Column(String(100), nullable=True)
+ source = Column(String(100), nullable=True)
+ source_url = Column(String(500), nullable=True)
+ status = Column(String(50), default="draft", index=True)
+ linkedin_post_url = Column(String(500), nullable=True)
+ analysis_json = Column(JSONB, nullable=True)
+ sector_match = Column(String(255), nullable=True, index=True)
+ is_active = Column(Boolean, default=True, index=True)
+ scraped_at = Column(DateTime(timezone=True), nullable=True)
+ posted_at = Column(DateTime(timezone=True), nullable=True)
+ environment = Column(String(20), default='production', nullable=False)
+
+
+class RecruiterOutreach(Base):
+ __tablename__ = "recruiter_outreach"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ outreach_id = Column(String(20), unique=True, nullable=False)
+ job_id = Column(String(50), nullable=True)
+ talent_email = Column(String(255), nullable=True, index=True)
+ match_score = Column(Integer, nullable=True)
+ recruiter_email = Column(String(255), nullable=True)
+ contact_method = Column(String(50), nullable=True)
+ outreach_subject = Column(Text, nullable=True)
+ outreach_body = Column(Text, nullable=True)
+ status = Column(String(20), default="pending_approval", index=True)
+ triggered_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ sent_at = Column(DateTime(timezone=True), nullable=True)
+
+
+class MediatedChat(Base):
+ """Mediated chat messages between recruiters and talents.
+
+ Brigawan AI acts as a smart relay, masking identities until unlocked.
+ Matches ChatManager.gs schema with conversation grouping.
+ """
+ __tablename__ = "mediated_chats"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ chat_id = Column(String(50), unique=True, nullable=True, index=True) # MSG-UUID8
+ conversation_id = Column(String(50), nullable=False, index=True) # CONV-UUID8
+ sender_email = Column(String(255), nullable=False, index=True) # Who sent
+ receiver_email = Column(String(255), nullable=False, index=True) # Who receives
+ sender_role = Column(String(20), nullable=False, default="RECRUITER") # RECRUITER or TALENT
+ original_message = Column(Text, nullable=True) # Raw message from sender
+ mediated_message = Column(Text, nullable=True) # AI-mediated version for recipient
+ is_identity_unlocked = Column(Boolean, default=False) # TRUE after 5-coin unlock
+ status = Column(String(30), default="PENDING_RECRUITER", index=True) # PENDING_TALENT, PENDING_RECRUITER, READ
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+ # Legacy fields (kept for backward compat)
+ email = Column(String(255), nullable=True, index=True)
+ talent_id = Column(String(20), nullable=True, index=True)
+ talent_name = Column(String(255), nullable=True)
+ message = Column(Text, nullable=True)
+ sender = Column(String(50), nullable=True)
+ is_read = Column(Boolean, default=False)
+ unlocked_at = Column(DateTime(timezone=True), nullable=True)
+ unlock_type = Column(String(50), nullable=True)
+ campaign_id = Column(String(50), nullable=True)
+
+
+class AITalentChat(Base):
+ __tablename__ = "ai_talent_chat"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ email = Column(String(255), nullable=False, index=True)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ user_message = Column(Text, nullable=True)
+ ai_reply = Column(Text, nullable=True)
+ expires_at = Column(DateTime(timezone=True), nullable=True)
+
+
+class TalentPathway(Base):
+ __tablename__ = "talent_pathway"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ email = Column(String(255), unique=True, nullable=False, index=True)
+ pathway_json = Column(JSONB, nullable=False)
+ progress_json = Column(JSONB, nullable=False)
+ completed_stages = Column(JSONB, default=list)
+ generated_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ green_score = Column(Integer, default=0)
+
+
+class TalentAcademy(Base):
+ __tablename__ = "talent_academy"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ email = Column(String(255), unique=True, nullable=False)
+ completed_modules = Column(Text, default="")
+ registered_onsite = Column(JSONB, default=list)
+ last_updated_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ essay_answers = Column(Text, default="")
diff --git a/app/models/lpk.py b/app/models/lpk.py
index 63ebc805d375cc9f58ecc1ea4d2b299489da3954..be287c3a082a04a3d59ee4b480f5918ddfebecd6 100644
--- a/app/models/lpk.py
+++ b/app/models/lpk.py
@@ -1,130 +1,130 @@
-"""LPK Ecosystem models."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID
-from app.models.base import Base
-
-
-class LPKPartner(Base):
- __tablename__ = "lpk_partners"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- lpk_id = Column(String(50), unique=True, nullable=False)
- lpk_name = Column(String(255), nullable=False)
- city_branch = Column(String(100), nullable=True)
- pic_name = Column(String(255), nullable=True)
- pic_whatsapp = Column(String(50), nullable=True)
- email = Column(String(255), unique=True, nullable=False)
- password_hash = Column(String(255), nullable=False)
- kemnaker_vin = Column(String(100), nullable=True)
- lsp_affiliation = Column(String(255), nullable=True)
- status_active = Column(Boolean, default=False)
- pks_status = Column(String(20), default="Pending")
- pks_document_url = Column(String(500), nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class LPKCourse(Base):
- __tablename__ = "lpk_courses"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- course_id = Column(String(50), unique=True, nullable=False)
- lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
- course_name = Column(String(255), nullable=False)
- target_skills = Column(JSONB, default=list)
- skkni_reference = Column(String(255), nullable=True)
- skkni_units = Column(JSONB, default=list)
- bnsp_assessment = Column(String(255), nullable=True)
- price = Column(Numeric(12, 2), default=0)
- duration = Column(String(50), nullable=True)
- status_active = Column(Boolean, default=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class SponsorCampaign(Base):
- __tablename__ = "sponsor_campaigns"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- campaign_id = Column(String(50), unique=True, nullable=False)
- employer_email = Column(String(255), nullable=True)
- lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="SET NULL"), nullable=True, index=True)
- course_id = Column(String(50), ForeignKey("lpk_courses.course_id", ondelete="SET NULL"), nullable=True)
- target_talents = Column(Integer, default=0)
- subsidy_percentage = Column(Numeric(5, 2), default=0)
- criteria_json = Column(JSONB, default=dict)
- status = Column(String(20), default="Draft")
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class CampaignParticipant(Base):
- __tablename__ = "campaign_participants"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- registration_id = Column(String(50), unique=True, nullable=False)
- campaign_id = Column(String(50), ForeignKey("sponsor_campaigns.campaign_id", ondelete="CASCADE"), nullable=True, index=True)
- talent_email = Column(String(255), nullable=False, index=True)
- theory_module_status = Column(String(50), default="Pending")
- practical_onsite_status = Column(String(50), default="Pending")
- recruitment_status = Column(String(50), default="Pending")
- interview_date = Column(DateTime(timezone=True), nullable=True)
- certificate_no = Column(String(100), nullable=True)
- practical_score = Column(Integer, default=0)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class VerificationQueue(Base):
- __tablename__ = "verification_queue"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- queue_id = Column(String(50), unique=True, nullable=False)
- lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True)
- lpk_name = Column(String(255), nullable=True)
- kemnaker_vin = Column(String(100), nullable=True)
- city_branch = Column(String(100), nullable=True)
- status_queue = Column(String(50), default="PENDING_VERIFICATION")
- ai_analysis_log = Column(Text, nullable=True)
- legal_proof_url = Column(String(500), nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class LPKLedger(Base):
- __tablename__ = "lpk_ledger"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- ledger_id = Column(String(50), unique=True, nullable=False)
- lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
- reference_id = Column(String(50), nullable=True)
- type = Column(String(50), nullable=False)
- amount = Column(Numeric(12, 2), default=0)
- porsi_lpk = Column(Numeric(12, 2), default=0)
- status = Column(String(50), default="Pending")
- bank_account_json = Column(JSONB, nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class Voucher(Base):
- __tablename__ = "vouchers"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- voucher_id = Column(String(50), unique=True, nullable=False)
- lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
- candidate_email = Column(String(255), nullable=True)
- status = Column(String(50), default="Active")
- date_generated = Column(DateTime(timezone=True), default=datetime.utcnow)
- date_used = Column(DateTime(timezone=True), nullable=True)
-
-
-class Certificate(Base):
- __tablename__ = "certificates"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- certificate_id = Column(String(50), unique=True, nullable=False)
- candidate_email = Column(String(255), nullable=False, index=True)
- lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="SET NULL"), nullable=True)
- pathway_id = Column(String(50), nullable=True)
- date_issued = Column(DateTime(timezone=True), default=datetime.utcnow)
- verification_url = Column(String(500), nullable=True)
+"""LPK Ecosystem models."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID
+from app.models.base import Base
+
+
+class LPKPartner(Base):
+ __tablename__ = "lpk_partners"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ lpk_id = Column(String(50), unique=True, nullable=False)
+ lpk_name = Column(String(255), nullable=False)
+ city_branch = Column(String(100), nullable=True)
+ pic_name = Column(String(255), nullable=True)
+ pic_whatsapp = Column(String(50), nullable=True)
+ email = Column(String(255), unique=True, nullable=False)
+ password_hash = Column(String(255), nullable=False)
+ kemnaker_vin = Column(String(100), nullable=True)
+ lsp_affiliation = Column(String(255), nullable=True)
+ status_active = Column(Boolean, default=False)
+ pks_status = Column(String(20), default="Pending")
+ pks_document_url = Column(String(500), nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class LPKCourse(Base):
+ __tablename__ = "lpk_courses"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ course_id = Column(String(50), unique=True, nullable=False)
+ lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
+ course_name = Column(String(255), nullable=False)
+ target_skills = Column(JSONB, default=list)
+ skkni_reference = Column(String(255), nullable=True)
+ skkni_units = Column(JSONB, default=list)
+ bnsp_assessment = Column(String(255), nullable=True)
+ price = Column(Numeric(12, 2), default=0)
+ duration = Column(String(50), nullable=True)
+ status_active = Column(Boolean, default=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class SponsorCampaign(Base):
+ __tablename__ = "sponsor_campaigns"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ campaign_id = Column(String(50), unique=True, nullable=False)
+ employer_email = Column(String(255), nullable=True)
+ lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="SET NULL"), nullable=True, index=True)
+ course_id = Column(String(50), ForeignKey("lpk_courses.course_id", ondelete="SET NULL"), nullable=True)
+ target_talents = Column(Integer, default=0)
+ subsidy_percentage = Column(Numeric(5, 2), default=0)
+ criteria_json = Column(JSONB, default=dict)
+ status = Column(String(20), default="Draft")
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class CampaignParticipant(Base):
+ __tablename__ = "campaign_participants"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ registration_id = Column(String(50), unique=True, nullable=False)
+ campaign_id = Column(String(50), ForeignKey("sponsor_campaigns.campaign_id", ondelete="CASCADE"), nullable=True, index=True)
+ talent_email = Column(String(255), nullable=False, index=True)
+ theory_module_status = Column(String(50), default="Pending")
+ practical_onsite_status = Column(String(50), default="Pending")
+ recruitment_status = Column(String(50), default="Pending")
+ interview_date = Column(DateTime(timezone=True), nullable=True)
+ certificate_no = Column(String(100), nullable=True)
+ practical_score = Column(Integer, default=0)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class VerificationQueue(Base):
+ __tablename__ = "verification_queue"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ queue_id = Column(String(50), unique=True, nullable=False)
+ lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True)
+ lpk_name = Column(String(255), nullable=True)
+ kemnaker_vin = Column(String(100), nullable=True)
+ city_branch = Column(String(100), nullable=True)
+ status_queue = Column(String(50), default="PENDING_VERIFICATION")
+ ai_analysis_log = Column(Text, nullable=True)
+ legal_proof_url = Column(String(500), nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class LPKLedger(Base):
+ __tablename__ = "lpk_ledger"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ ledger_id = Column(String(50), unique=True, nullable=False)
+ lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
+ reference_id = Column(String(50), nullable=True)
+ type = Column(String(50), nullable=False)
+ amount = Column(Numeric(12, 2), default=0)
+ porsi_lpk = Column(Numeric(12, 2), default=0)
+ status = Column(String(50), default="Pending")
+ bank_account_json = Column(JSONB, nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class Voucher(Base):
+ __tablename__ = "vouchers"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ voucher_id = Column(String(50), unique=True, nullable=False)
+ lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="CASCADE"), nullable=True, index=True)
+ candidate_email = Column(String(255), nullable=True)
+ status = Column(String(50), default="Active")
+ date_generated = Column(DateTime(timezone=True), default=datetime.utcnow)
+ date_used = Column(DateTime(timezone=True), nullable=True)
+
+
+class Certificate(Base):
+ __tablename__ = "certificates"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ certificate_id = Column(String(50), unique=True, nullable=False)
+ candidate_email = Column(String(255), nullable=False, index=True)
+ lpk_id = Column(String(50), ForeignKey("lpk_partners.lpk_id", ondelete="SET NULL"), nullable=True)
+ pathway_id = Column(String(50), nullable=True)
+ date_issued = Column(DateTime(timezone=True), default=datetime.utcnow)
+ verification_url = Column(String(500), nullable=True)
diff --git a/app/models/security.py b/app/models/security.py
index e05bf5f69899344e2188c839f0b057b8f58499a2..0db8cf5c6177bc562052777f3cf2f2ce4bd12414 100644
--- a/app/models/security.py
+++ b/app/models/security.py
@@ -1,56 +1,56 @@
-"""Security & Cryptographic Audit Trail models."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, BigInteger
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID
-from sqlalchemy.orm import relationship
-from app.models.base import Base
-
-
-class ProfileKey(Base):
- """Stores profile-specific AES-256 Data Encryption Keys (DEK).
- DEKs are encrypted by the KMS Master Key (Envelope Encryption).
- """
- __tablename__ = "profile_keys"
- __table_args__ = {"schema": "security"}
-
- profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), primary_key=True)
- encrypted_symmetric_key = Column(Text, nullable=False)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
-
- # Relationships
- profile = relationship("Profile", back_populates="key")
-
-
-class AuditTrail(Base):
- """Cryptographic Append-Only Hash-Chained Audit Trail."""
- __tablename__ = "audit_trail"
- __table_args__ = {"schema": "audit"}
-
- id = Column(BigInteger, primary_key=True, autoincrement=True)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- record_table = Column(String(100), nullable=False)
- record_id = Column(UUID(as_uuid=True), nullable=False)
- action_type = Column(String(10), nullable=False) # INSERT, UPDATE, DELETE
- ciphertext_hash = Column(String(64), nullable=False)
- signature_hash = Column(String(64), nullable=True)
- previous_hash = Column(String(64), nullable=False, index=True)
- current_hash = Column(String(64), nullable=False, index=True)
-
-
-class AuditAnchor(Base):
- """Anchors for pruned/archived audit logs to ensure chain continuity."""
- __tablename__ = "audit_anchors"
- __table_args__ = {"schema": "audit"}
-
- id = Column(BigInteger, primary_key=True, autoincrement=True)
- archive_run_id = Column(UUID(as_uuid=True), default=uuid.uuid4)
- max_audit_id = Column(BigInteger, nullable=False)
- anchor_hash = Column(String(64), nullable=False, index=True)
- cold_storage_uri = Column(Text, nullable=False)
- archive_file_hash = Column(String(64), nullable=False)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+"""Security & Cryptographic Audit Trail models."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, BigInteger
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID
+from sqlalchemy.orm import relationship
+from app.models.base import Base
+
+
+class ProfileKey(Base):
+ """Stores profile-specific AES-256 Data Encryption Keys (DEK).
+ DEKs are encrypted by the KMS Master Key (Envelope Encryption).
+ """
+ __tablename__ = "profile_keys"
+ __table_args__ = {"schema": "security"}
+
+ profile_id = Column(UUID(as_uuid=True), ForeignKey("profiles.id", ondelete="CASCADE"), primary_key=True)
+ encrypted_symmetric_key = Column(Text, nullable=False)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ profile = relationship("Profile", back_populates="key")
+
+
+class AuditTrail(Base):
+ """Cryptographic Append-Only Hash-Chained Audit Trail."""
+ __tablename__ = "audit_trail"
+ __table_args__ = {"schema": "audit"}
+
+ id = Column(BigInteger, primary_key=True, autoincrement=True)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ record_table = Column(String(100), nullable=False)
+ record_id = Column(UUID(as_uuid=True), nullable=False)
+ action_type = Column(String(10), nullable=False) # INSERT, UPDATE, DELETE
+ ciphertext_hash = Column(String(64), nullable=False)
+ signature_hash = Column(String(64), nullable=True)
+ previous_hash = Column(String(64), nullable=False, index=True)
+ current_hash = Column(String(64), nullable=False, index=True)
+
+
+class AuditAnchor(Base):
+ """Anchors for pruned/archived audit logs to ensure chain continuity."""
+ __tablename__ = "audit_anchors"
+ __table_args__ = {"schema": "audit"}
+
+ id = Column(BigInteger, primary_key=True, autoincrement=True)
+ archive_run_id = Column(UUID(as_uuid=True), default=uuid.uuid4)
+ max_audit_id = Column(BigInteger, nullable=False)
+ anchor_hash = Column(String(64), nullable=False, index=True)
+ cold_storage_uri = Column(Text, nullable=False)
+ archive_file_hash = Column(String(64), nullable=False)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
diff --git a/app/models/skkni.py b/app/models/skkni.py
index 7415d4d7de2d16454c91af4b0d55ddb736ba72c1..1097c83ecfd449d3171ad570025047e9d40d0682 100644
--- a/app/models/skkni.py
+++ b/app/models/skkni.py
@@ -1,161 +1,161 @@
-"""SKKNI and miscellaneous utility models."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID
-
-from app.models.base import Base
-
-
-class SKKNIMaster(Base):
- __tablename__ = "skkni_master"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- unit_code = Column(String(50), nullable=True)
- unit_name = Column(Text, nullable=True)
- sector = Column(String(100), nullable=True)
- competency = Column(Text, nullable=True)
- assessment_guideline = Column(Text, nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class SKKNISourcePDF(Base):
- __tablename__ = "skkni_source_pdfs"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- pdf_url = Column(String(500), nullable=True)
- title = Column(String(255), nullable=True)
- status = Column(String(50), default="Pending")
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class SKKNAgentLog(Base):
- __tablename__ = "skkni_agent_log"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- action = Column(String(100), nullable=True)
- status = Column(String(50), nullable=True)
- details = Column(Text, nullable=True)
-
-
-class EmbeddingCache(Base):
- __tablename__ = "embedding_cache"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- text_hash = Column(String(64), unique=True, nullable=False, index=True)
- raw_text = Column(Text, nullable=True)
- embedding_json = Column(JSONB, nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class KeywordQuarantine(Base):
- __tablename__ = "keyword_quarantine"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- is_selected = Column(Boolean, default=False)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- keyword = Column(String(255), nullable=True)
- ai_research_context = Column(Text, nullable=True)
- suggested_briga_rule = Column(Text, nullable=True)
- status = Column(String(50), default="Pending")
-
-
-class TalentAlert(Base):
- __tablename__ = "talent_alerts"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- email = Column(String(255), nullable=True)
- query = Column(Text, nullable=True)
-
-
-class FailedSearch(Base):
- __tablename__ = "failed_searches"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- email = Column(String(255), nullable=True)
- query = Column(Text, nullable=True)
- count = Column(Integer, default=0)
-
-
-class VettingAudit(Base):
- __tablename__ = "vetting_audit"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- recruiter = Column(String(255), nullable=True)
- cvs_processed = Column(Integer, default=0)
- failures = Column(Integer, default=0)
- engine_version = Column(String(50), nullable=True)
-
-
-class VettingBenchmarkLog(Base):
- __tablename__ = "benchmark_log"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- category = Column(String(100), nullable=True)
- model = Column(String(100), nullable=True)
- result = Column(Text, nullable=True)
- notes = Column(Text, nullable=True)
- response_preview = Column(Text, nullable=True)
-
-
-class VettingBenchmarkCompare(Base):
- __tablename__ = "benchmark_compare"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- model = Column(String(100), nullable=True)
- response = Column(Text, nullable=True)
-
-
-class TestLog(Base):
- __tablename__ = "test_log"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- total_tests = Column(Integer, default=0)
- failed_tests = Column(Integer, default=0)
- result_summary = Column(Text, nullable=True)
-
-
-class ContentQueue(Base):
- __tablename__ = "content_queue"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- topic = Column(String(255), nullable=True)
- status = Column(String(50), default="Queued")
- priority = Column(Integer, default=0)
-
-
-class LPKRegistrationLead(Base):
- __tablename__ = "lpk_registration_leads"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- email = Column(String(255), nullable=True)
- module_id = Column(String(50), nullable=True)
- lpk_branch = Column(String(100), nullable=True)
- status = Column(String(50), default="Pending LPK Outreach")
- talent_phone = Column(String(50), nullable=True)
-
-
-class AcademyLead(Base):
- __tablename__ = "academy_leads"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- profesi_asal = Column(String(255), nullable=True)
- gaji_asal = Column(String(100), nullable=True)
- skill_asal = Column(Text, nullable=True)
- rekomendasi_greenjob = Column(String(255), nullable=True)
- estimasi_gaji = Column(String(100), nullable=True)
- skill_gap_count = Column(Integer, default=0)
- status = Column(String(50), default="New")
+"""SKKNI and miscellaneous utility models."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID
+
+from app.models.base import Base
+
+
+class SKKNIMaster(Base):
+ __tablename__ = "skkni_master"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ unit_code = Column(String(50), nullable=True)
+ unit_name = Column(Text, nullable=True)
+ sector = Column(String(100), nullable=True)
+ competency = Column(Text, nullable=True)
+ assessment_guideline = Column(Text, nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class SKKNISourcePDF(Base):
+ __tablename__ = "skkni_source_pdfs"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ pdf_url = Column(String(500), nullable=True)
+ title = Column(String(255), nullable=True)
+ status = Column(String(50), default="Pending")
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class SKKNAgentLog(Base):
+ __tablename__ = "skkni_agent_log"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ action = Column(String(100), nullable=True)
+ status = Column(String(50), nullable=True)
+ details = Column(Text, nullable=True)
+
+
+class EmbeddingCache(Base):
+ __tablename__ = "embedding_cache"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ text_hash = Column(String(64), unique=True, nullable=False, index=True)
+ raw_text = Column(Text, nullable=True)
+ embedding_json = Column(JSONB, nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class KeywordQuarantine(Base):
+ __tablename__ = "keyword_quarantine"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ is_selected = Column(Boolean, default=False)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ keyword = Column(String(255), nullable=True)
+ ai_research_context = Column(Text, nullable=True)
+ suggested_briga_rule = Column(Text, nullable=True)
+ status = Column(String(50), default="Pending")
+
+
+class TalentAlert(Base):
+ __tablename__ = "talent_alerts"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ email = Column(String(255), nullable=True)
+ query = Column(Text, nullable=True)
+
+
+class FailedSearch(Base):
+ __tablename__ = "failed_searches"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ email = Column(String(255), nullable=True)
+ query = Column(Text, nullable=True)
+ count = Column(Integer, default=0)
+
+
+class VettingAudit(Base):
+ __tablename__ = "vetting_audit"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ recruiter = Column(String(255), nullable=True)
+ cvs_processed = Column(Integer, default=0)
+ failures = Column(Integer, default=0)
+ engine_version = Column(String(50), nullable=True)
+
+
+class VettingBenchmarkLog(Base):
+ __tablename__ = "benchmark_log"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ category = Column(String(100), nullable=True)
+ model = Column(String(100), nullable=True)
+ result = Column(Text, nullable=True)
+ notes = Column(Text, nullable=True)
+ response_preview = Column(Text, nullable=True)
+
+
+class VettingBenchmarkCompare(Base):
+ __tablename__ = "benchmark_compare"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ model = Column(String(100), nullable=True)
+ response = Column(Text, nullable=True)
+
+
+class TestLog(Base):
+ __tablename__ = "test_log"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ total_tests = Column(Integer, default=0)
+ failed_tests = Column(Integer, default=0)
+ result_summary = Column(Text, nullable=True)
+
+
+class ContentQueue(Base):
+ __tablename__ = "content_queue"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ topic = Column(String(255), nullable=True)
+ status = Column(String(50), default="Queued")
+ priority = Column(Integer, default=0)
+
+
+class LPKRegistrationLead(Base):
+ __tablename__ = "lpk_registration_leads"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ email = Column(String(255), nullable=True)
+ module_id = Column(String(50), nullable=True)
+ lpk_branch = Column(String(100), nullable=True)
+ status = Column(String(50), default="Pending LPK Outreach")
+ talent_phone = Column(String(50), nullable=True)
+
+
+class AcademyLead(Base):
+ __tablename__ = "academy_leads"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ profesi_asal = Column(String(255), nullable=True)
+ gaji_asal = Column(String(100), nullable=True)
+ skill_asal = Column(Text, nullable=True)
+ rekomendasi_greenjob = Column(String(255), nullable=True)
+ estimasi_gaji = Column(String(100), nullable=True)
+ skill_gap_count = Column(Integer, default=0)
+ status = Column(String(50), default="New")
diff --git a/app/models/system.py b/app/models/system.py
index 6caaf30b58510442bea529d84b1ce39cb9569209..1b58fa6c8269b2803e1219d75dad75f34350ac3e 100644
--- a/app/models/system.py
+++ b/app/models/system.py
@@ -1,208 +1,208 @@
-"""System & Audit models."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID
-from app.models.base import Base
-
-
-class Admin(Base):
- __tablename__ = "admins"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- name = Column(String(255), nullable=False)
- email = Column(String(255), unique=True, nullable=False)
- password_hash = Column(String(255), nullable=False)
- role = Column(String(20), default="ADMIN")
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
-
-
-class ActivityLog(Base):
- __tablename__ = "activity_logs"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- actor = Column(String(255), default="Anonymous", index=True)
- action = Column(String(255), default="Unknown")
- log_metadata = Column("metadata", Text, default="-")
-
-
-class SystemMonitor(Base):
- __tablename__ = "system_monitor"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- check_name = Column(String(100), nullable=True)
- status = Column(String(50), nullable=True)
- detail = Column(Text, nullable=True)
- last_checked = Column(DateTime(timezone=True), default=datetime.utcnow)
-
-
-class SystemMonitorLog(Base):
- __tablename__ = "system_monitor_log"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- agent = Column(String(100), nullable=True)
- action = Column(String(255), nullable=True)
- status = Column(String(50), nullable=True)
- detail = Column(Text, nullable=True)
- duration_ms = Column(Integer, default=0)
-
-
-class AnalyticsTraffic(Base):
- __tablename__ = "analytics_traffic"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- page = Column(String(255), nullable=True, index=True)
- referrer = Column(String(500), nullable=True)
- geo = Column(String(255), nullable=True)
- user_agent = Column(Text, nullable=True)
-
-
-class APIMonitoring(Base):
- __tablename__ = "api_monitoring"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- api_name = Column(String(100), nullable=True)
- token_usage = Column(Integer, default=0)
- status = Column(String(50), nullable=True)
- user_email = Column(String(255), nullable=True)
-
-
-class SecurityAuditLog(Base):
- __tablename__ = "security_audit_log"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- target_url = Column(String(500), nullable=True)
- page_type = Column(String(50), nullable=True)
- status = Column(String(50), nullable=True)
- details = Column(Text, nullable=True)
-
-
-class PrivacyAuditLog(Base):
- __tablename__ = "privacy_audit_log"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
- query = Column(Text, nullable=True)
- user_email = Column(String(255), nullable=True)
- is_hidden = Column(Boolean, default=False)
- is_flagged = Column(Boolean, default=False)
- risk_score = Column(Integer, default=0)
-
-
-class TalentEngagement(Base):
- __tablename__ = "talent_engagement"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- email = Column(String(255), nullable=False, index=True)
- name = Column(String(255), nullable=True)
- talent_id = Column(String(20), nullable=True)
- engagement_score = Column(Integer, default=0)
- dormancy_days = Column(Integer, default=0)
- tier = Column(String(10), nullable=True)
- last_activity_date = Column(DateTime(timezone=True), nullable=True)
- last_chat_date = Column(DateTime(timezone=True), nullable=True)
- last_pathway_date = Column(DateTime(timezone=True), nullable=True)
- ai_generated_message = Column(Text, nullable=True)
- message_type = Column(String(50), nullable=True)
- status = Column(String(50), default="Draft", index=True)
- sent_at = Column(DateTime(timezone=True), nullable=True)
- opened_at = Column(DateTime(timezone=True), nullable=True)
- response_at = Column(DateTime(timezone=True), nullable=True)
- response_text = Column(Text, nullable=True)
- follow_up_date = Column(DateTime(timezone=True), nullable=True)
- follow_up_message = Column(Text, nullable=True)
- notes = Column(Text, nullable=True)
-
-
-# ==========================================
-# ANTIGRAVITY ORCHESTRATION MODELS
-# ==========================================
-
-class AgentStateLog(Base):
- """Logs the lifecycle and memory of autonomous AI agents."""
- __tablename__ = "agent_state_logs"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- agent_name = Column(String(100), nullable=False, index=True)
- task_id = Column(String(100), nullable=True, index=True)
- status = Column(String(50), default="IDLE", index=True) # IDLE, WORKING, COMPLETED, FAILED
- memory_context = Column(JSONB, nullable=True)
- last_action = Column(String(255), nullable=True)
- error_message = Column(Text, nullable=True)
- started_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
-
-
-class AgentQueue(Base):
- """Manages request throttling to stay within Gemini Free Tier (15 RPM) limits."""
- __tablename__ = "agent_queues"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- task_name = Column(String(100), nullable=False)
- payload = Column(JSONB, nullable=False)
- priority = Column(Integer, default=0) # Higher is more urgent
- status = Column(String(30), default="QUEUED", index=True) # QUEUED, PROCESSING, RETRYING, COMPLETED, ABORTED
- scheduled_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- processed_at = Column(DateTime(timezone=True), nullable=True)
- retry_count = Column(Integer, default=0)
- trace_id = Column(String(100), nullable=True)
-
-
-class CEOStrategicMemory(Base):
- """Long-term episodic memory for the AI CEO."""
- __tablename__ = "ceo_strategic_memory"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- topic = Column(String(255), nullable=False, index=True)
- summary = Column(Text, nullable=False)
- decision_made = Column(String(255), nullable=True)
- founder_feedback = Column(Text, nullable=True)
- sentiment_score = Column(Numeric(3, 2), nullable=True) # -1.0 to 1.0
- embedding_id = Column(UUID(as_uuid=True), nullable=True) # Reference to vector storage
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
-
-
-class WhatsAppSession(Base):
- """Conversational state machine for the WhatsApp bot."""
- __tablename__ = "whatsapp_sessions"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- phone = Column(String(50), unique=True, nullable=False, index=True)
- state = Column(String(50), default="START") # START, ONBOARDING_NAME, ONBOARDING_EMAIL, IDLE
- context = Column(JSONB, nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
-
-
-class TelegramSession(Base):
- """Conversational state and payment verification session storage for Telegram bot."""
- __tablename__ = "telegram_sessions"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- chat_id = Column(String(255), unique=True, nullable=False, index=True)
- state = Column(String(50), nullable=True)
- last_context = Column(JSONB, nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
-
-
-class WorkflowConfig(Base):
- """Runtime configuration for autonomous workflows. Toggle to enable/disable specific agent workflows."""
- __tablename__ = "workflow_configs"
-
- workflow_name = Column(String(100), primary_key=True)
- is_active = Column(Boolean, default=False, nullable=False)
- schedule_cron = Column(String(100), nullable=True)
- last_run = Column(DateTime(timezone=True), nullable=True)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
-
+"""System & Audit models."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, ForeignKey, Numeric
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID
+from app.models.base import Base
+
+
+class Admin(Base):
+ __tablename__ = "admins"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ name = Column(String(255), nullable=False)
+ email = Column(String(255), unique=True, nullable=False)
+ password_hash = Column(String(255), nullable=False)
+ role = Column(String(20), default="ADMIN")
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
+class ActivityLog(Base):
+ __tablename__ = "activity_logs"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ actor = Column(String(255), default="Anonymous", index=True)
+ action = Column(String(255), default="Unknown")
+ log_metadata = Column("metadata", Text, default="-")
+
+
+class SystemMonitor(Base):
+ __tablename__ = "system_monitor"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ check_name = Column(String(100), nullable=True)
+ status = Column(String(50), nullable=True)
+ detail = Column(Text, nullable=True)
+ last_checked = Column(DateTime(timezone=True), default=datetime.utcnow)
+
+
+class SystemMonitorLog(Base):
+ __tablename__ = "system_monitor_log"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ agent = Column(String(100), nullable=True)
+ action = Column(String(255), nullable=True)
+ status = Column(String(50), nullable=True)
+ detail = Column(Text, nullable=True)
+ duration_ms = Column(Integer, default=0)
+
+
+class AnalyticsTraffic(Base):
+ __tablename__ = "analytics_traffic"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ page = Column(String(255), nullable=True, index=True)
+ referrer = Column(String(500), nullable=True)
+ geo = Column(String(255), nullable=True)
+ user_agent = Column(Text, nullable=True)
+
+
+class APIMonitoring(Base):
+ __tablename__ = "api_monitoring"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ api_name = Column(String(100), nullable=True)
+ token_usage = Column(Integer, default=0)
+ status = Column(String(50), nullable=True)
+ user_email = Column(String(255), nullable=True)
+
+
+class SecurityAuditLog(Base):
+ __tablename__ = "security_audit_log"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ target_url = Column(String(500), nullable=True)
+ page_type = Column(String(50), nullable=True)
+ status = Column(String(50), nullable=True)
+ details = Column(Text, nullable=True)
+
+
+class PrivacyAuditLog(Base):
+ __tablename__ = "privacy_audit_log"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ timestamp = Column(DateTime(timezone=True), default=datetime.utcnow)
+ query = Column(Text, nullable=True)
+ user_email = Column(String(255), nullable=True)
+ is_hidden = Column(Boolean, default=False)
+ is_flagged = Column(Boolean, default=False)
+ risk_score = Column(Integer, default=0)
+
+
+class TalentEngagement(Base):
+ __tablename__ = "talent_engagement"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ email = Column(String(255), nullable=False, index=True)
+ name = Column(String(255), nullable=True)
+ talent_id = Column(String(20), nullable=True)
+ engagement_score = Column(Integer, default=0)
+ dormancy_days = Column(Integer, default=0)
+ tier = Column(String(10), nullable=True)
+ last_activity_date = Column(DateTime(timezone=True), nullable=True)
+ last_chat_date = Column(DateTime(timezone=True), nullable=True)
+ last_pathway_date = Column(DateTime(timezone=True), nullable=True)
+ ai_generated_message = Column(Text, nullable=True)
+ message_type = Column(String(50), nullable=True)
+ status = Column(String(50), default="Draft", index=True)
+ sent_at = Column(DateTime(timezone=True), nullable=True)
+ opened_at = Column(DateTime(timezone=True), nullable=True)
+ response_at = Column(DateTime(timezone=True), nullable=True)
+ response_text = Column(Text, nullable=True)
+ follow_up_date = Column(DateTime(timezone=True), nullable=True)
+ follow_up_message = Column(Text, nullable=True)
+ notes = Column(Text, nullable=True)
+
+
+# ==========================================
+# ANTIGRAVITY ORCHESTRATION MODELS
+# ==========================================
+
+class AgentStateLog(Base):
+ """Logs the lifecycle and memory of autonomous AI agents."""
+ __tablename__ = "agent_state_logs"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ agent_name = Column(String(100), nullable=False, index=True)
+ task_id = Column(String(100), nullable=True, index=True)
+ status = Column(String(50), default="IDLE", index=True) # IDLE, WORKING, COMPLETED, FAILED
+ memory_context = Column(JSONB, nullable=True)
+ last_action = Column(String(255), nullable=True)
+ error_message = Column(Text, nullable=True)
+ started_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
+class AgentQueue(Base):
+ """Manages request throttling to stay within Gemini Free Tier (15 RPM) limits."""
+ __tablename__ = "agent_queues"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ task_name = Column(String(100), nullable=False)
+ payload = Column(JSONB, nullable=False)
+ priority = Column(Integer, default=0) # Higher is more urgent
+ status = Column(String(30), default="QUEUED", index=True) # QUEUED, PROCESSING, RETRYING, COMPLETED, ABORTED
+ scheduled_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ processed_at = Column(DateTime(timezone=True), nullable=True)
+ retry_count = Column(Integer, default=0)
+ trace_id = Column(String(100), nullable=True)
+
+
+class CEOStrategicMemory(Base):
+ """Long-term episodic memory for the AI CEO."""
+ __tablename__ = "ceo_strategic_memory"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ topic = Column(String(255), nullable=False, index=True)
+ summary = Column(Text, nullable=False)
+ decision_made = Column(String(255), nullable=True)
+ founder_feedback = Column(Text, nullable=True)
+ sentiment_score = Column(Numeric(3, 2), nullable=True) # -1.0 to 1.0
+ embedding_id = Column(UUID(as_uuid=True), nullable=True) # Reference to vector storage
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
+class WhatsAppSession(Base):
+ """Conversational state machine for the WhatsApp bot."""
+ __tablename__ = "whatsapp_sessions"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ phone = Column(String(50), unique=True, nullable=False, index=True)
+ state = Column(String(50), default="START") # START, ONBOARDING_NAME, ONBOARDING_EMAIL, IDLE
+ context = Column(JSONB, nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
+class TelegramSession(Base):
+ """Conversational state and payment verification session storage for Telegram bot."""
+ __tablename__ = "telegram_sessions"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ chat_id = Column(String(255), unique=True, nullable=False, index=True)
+ state = Column(String(50), nullable=True)
+ last_context = Column(JSONB, nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
+class WorkflowConfig(Base):
+ """Runtime configuration for autonomous workflows. Toggle to enable/disable specific agent workflows."""
+ __tablename__ = "workflow_configs"
+
+ workflow_name = Column(String(100), primary_key=True)
+ is_active = Column(Boolean, default=False, nullable=False)
+ schedule_cron = Column(String(100), nullable=True)
+ last_run = Column(DateTime(timezone=True), nullable=True)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+
diff --git a/app/models/talent.py b/app/models/talent.py
index d9a3c50f6b0f11c8485392740c956edb4f2da21f..058804b8c76692ecf24905348050189abb3299af 100644
--- a/app/models/talent.py
+++ b/app/models/talent.py
@@ -1,70 +1,70 @@
-"""Talent & Talent Catalog models."""
-
-import uuid
-from datetime import datetime
-
-from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Index
-from app.models.base import JSONB
-from sqlalchemy.dialects.postgresql import UUID
-from app.models.base import Base
-
-
-class Talent(Base):
- __tablename__ = "talents"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- talent_id = Column(String(20), unique=True, nullable=False, index=True)
- name = Column(String(255), nullable=False)
- email = Column(String(255), unique=True, nullable=False, index=True)
- education = Column(Text, nullable=True)
- experience = Column(Text, nullable=True)
- category = Column(String(50), nullable=True, index=True)
- score = Column(Integer, default=70)
- analysis = Column(Text, nullable=True)
- location = Column(String(255), nullable=True)
- skill_tags = Column(Text, nullable=True)
- cv_link = Column(String(500), nullable=True)
- verification_status = Column(String(50), default="Pending", index=True)
- salary_expected = Column(String(100), nullable=True)
- badges = Column(JSONB, nullable=True)
- advisory_snippet = Column(Text, nullable=True)
- advisory_full = Column(Text, nullable=True)
- k3_dasar = Column(String(255), nullable=True)
- k3_khusus = Column(String(255), nullable=True)
- cert_other = Column(Text, nullable=True)
- language = Column(String(255), nullable=True)
- phone = Column(String(50), nullable=True)
- is_unlocked = Column(Boolean, default=False)
- password_hash = Column(String(255), nullable=True)
- linkedin_link = Column(String(500), nullable=True)
- current_salary = Column(String(100), nullable=True)
- portfolio_links = Column(Text, nullable=True)
- cert_links = Column(Text, nullable=True)
- base_cv_url = Column(String(500), nullable=True)
- total_experience = Column(String(50), nullable=True)
- sector_focus = Column(String(100), nullable=True)
- talent_type = Column(String(50), nullable=True)
- cert_expiry = Column(String(50), nullable=True)
- green_score = Column(Integer, default=0, index=True)
- linkedin_token = Column(Text, nullable=True)
- job_reference_id = Column(String(50), nullable=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
- updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
- environment = Column(String(20), default='production', nullable=False)
-
-
-class TalentCatalog(Base):
- __tablename__ = "talent_catalog"
-
- id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
- talent_id = Column(String(20), ForeignKey("talents.talent_id"), unique=True, nullable=False)
- display_name = Column(String(255), nullable=True)
- sector_focus = Column(String(100), nullable=True, index=True)
- skill_tags = Column(Text, nullable=True)
- location = Column(String(255), nullable=True)
- score = Column(Integer, nullable=True)
- category = Column(String(50), nullable=True)
- badges = Column(JSONB, nullable=True)
- advisory_snippet = Column(Text, nullable=True)
- is_active = Column(Boolean, default=True)
- created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+"""Talent & Talent Catalog models."""
+
+import uuid
+from datetime import datetime
+
+from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime, JSON, ForeignKey, Index
+from app.models.base import JSONB
+from sqlalchemy.dialects.postgresql import UUID
+from app.models.base import Base
+
+
+class Talent(Base):
+ __tablename__ = "talents"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ talent_id = Column(String(20), unique=True, nullable=False, index=True)
+ name = Column(String(255), nullable=False)
+ email = Column(String(255), unique=True, nullable=False, index=True)
+ education = Column(Text, nullable=True)
+ experience = Column(Text, nullable=True)
+ category = Column(String(50), nullable=True, index=True)
+ score = Column(Integer, default=70)
+ analysis = Column(Text, nullable=True)
+ location = Column(String(255), nullable=True)
+ skill_tags = Column(Text, nullable=True)
+ cv_link = Column(String(500), nullable=True)
+ verification_status = Column(String(50), default="Pending", index=True)
+ salary_expected = Column(String(100), nullable=True)
+ badges = Column(JSONB, nullable=True)
+ advisory_snippet = Column(Text, nullable=True)
+ advisory_full = Column(Text, nullable=True)
+ k3_dasar = Column(String(255), nullable=True)
+ k3_khusus = Column(String(255), nullable=True)
+ cert_other = Column(Text, nullable=True)
+ language = Column(String(255), nullable=True)
+ phone = Column(String(50), nullable=True)
+ is_unlocked = Column(Boolean, default=False)
+ password_hash = Column(String(255), nullable=True)
+ linkedin_link = Column(String(500), nullable=True)
+ current_salary = Column(String(100), nullable=True)
+ portfolio_links = Column(Text, nullable=True)
+ cert_links = Column(Text, nullable=True)
+ base_cv_url = Column(String(500), nullable=True)
+ total_experience = Column(String(50), nullable=True)
+ sector_focus = Column(String(100), nullable=True)
+ talent_type = Column(String(50), nullable=True)
+ cert_expiry = Column(String(50), nullable=True)
+ green_score = Column(Integer, default=0, index=True)
+ linkedin_token = Column(Text, nullable=True)
+ job_reference_id = Column(String(50), nullable=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
+ updated_at = Column(DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow)
+ environment = Column(String(20), default='production', nullable=False)
+
+
+class TalentCatalog(Base):
+ __tablename__ = "talent_catalog"
+
+ id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ talent_id = Column(String(20), ForeignKey("talents.talent_id"), unique=True, nullable=False)
+ display_name = Column(String(255), nullable=True)
+ sector_focus = Column(String(100), nullable=True, index=True)
+ skill_tags = Column(Text, nullable=True)
+ location = Column(String(255), nullable=True)
+ score = Column(Integer, nullable=True)
+ category = Column(String(50), nullable=True)
+ badges = Column(JSONB, nullable=True)
+ advisory_snippet = Column(Text, nullable=True)
+ is_active = Column(Boolean, default=True)
+ created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
diff --git a/app/schemas/career.py b/app/schemas/career.py
index e7cdb30eb677075c160c2f25b1f9b607400fbf9a..370f8279329e5b779b3464cfca0553a2e785a4be 100644
--- a/app/schemas/career.py
+++ b/app/schemas/career.py
@@ -1,170 +1,170 @@
-"""Career history Pydantic schemas — Profiles, Experiences, and Credentials.
-
-Provides validation and serialization for lifelong career records.
-Handles both public (masked) and private (decrypted) data views.
-"""
-
-from datetime import date, datetime
-from typing import Any, Dict, List, Optional
-from uuid import UUID
-
-from pydantic import BaseModel, ConfigDict, EmailStr, Field, HttpUrl
-
-
-# ─── Organization ────────────────────────────────────────────────────────────
-
-class OrganizationBase(BaseModel):
- name: str = Field(..., min_length=1, max_length=255)
- website_url: Optional[HttpUrl] = None
-
-
-class OrganizationCreate(OrganizationBase):
- pass
-
-
-class OrganizationRead(OrganizationBase):
- id: UUID
- verified: bool
- created_at: datetime
-
- model_config = ConfigDict(from_attributes=True)
-
-
-# ─── Profile ────────────────────────────────────────────────────────────────
-
-class ProfileBase(BaseModel):
- full_name: Optional[str] = Field(None, max_length=255)
- industry: Optional[str] = Field(None, max_length=100)
- general_skills: List[str] = Field(default_factory=list)
-
-
-class ProfileCreate(ProfileBase):
- email: EmailStr
-
-
-class ProfileRead(ProfileBase):
- id: UUID
- status: str
- email: Optional[EmailStr] = None
- created_at: datetime
- updated_at: datetime
-
- model_config = ConfigDict(from_attributes=True)
-
-
-class ProfilePublicRead(BaseModel):
- id: UUID
- full_name: Optional[str]
- industry: Optional[str]
- general_skills: List[str]
- masked_email: Optional[str]
- verified_credential_count: int
- created_at: datetime
-
- model_config = ConfigDict(from_attributes=True)
-
-
-# ─── Career Record Payloads (Encrypted) ──────────────────────────────────────
-
-class ExperiencePayload(BaseModel):
- """Internal details of an employment record (AES-256 encrypted in DB)."""
- responsibilities: Optional[str] = None
- achievements: Optional[List[str]] = None
- tools_used: Optional[List[str]] = None
- team_size: Optional[int] = None
- department: Optional[str] = None
-
-
-class CredentialPayload(BaseModel):
- """Internal details of a certification record (AES-256 encrypted in DB)."""
- grade: Optional[str] = None
- serial_number: Optional[str] = None
- skills_verified: Optional[List[str]] = None
- metadata: Optional[Dict[str, Any]] = None
-
-
-# ─── Experience ─────────────────────────────────────────────────────────────
-
-class ExperienceBase(BaseModel):
- organization_id: UUID
- start_date: date
- end_date: Optional[date] = None
- job_title: str = Field(..., min_length=1, max_length=150)
-
-
-class ExperienceCreate(ExperienceBase):
- payload: ExperiencePayload
-
-
-class ExperienceUpdate(BaseModel):
- start_date: Optional[date] = None
- end_date: Optional[date] = None
- job_title: Optional[str] = Field(None, max_length=150)
- payload: Optional[ExperiencePayload] = None
-
-
-class ExperienceRead(ExperienceBase):
- id: UUID
- profile_id: UUID
- created_at: datetime
- payload: ExperiencePayload # This should be populated after decryption
-
- model_config = ConfigDict(from_attributes=True)
-
-
-class ExperiencePublicRead(ExperienceBase):
- id: UUID
- profile_id: UUID
- organization_name: Optional[str] = None # To be joined in the view/query
-
- model_config = ConfigDict(from_attributes=True)
-
-
-# ─── Credential ─────────────────────────────────────────────────────────────
-
-class CredentialBase(BaseModel):
- organization_id: UUID
- issue_date: date
- expiry_date: Optional[date] = None
- credential_name: str = Field(..., min_length=1, max_length=150)
-
-
-class CredentialCreate(CredentialBase):
- payload: CredentialPayload
-
-
-class CredentialRead(CredentialBase):
- id: UUID
- profile_id: UUID
- issuer_signature: str
- created_at: datetime
- payload: CredentialPayload # This should be populated after decryption
-
- model_config = ConfigDict(from_attributes=True)
-
-
-class CredentialPublicRead(CredentialBase):
- id: UUID
- profile_id: UUID
- organization_name: Optional[str] = None
- is_verified: bool = False
-
- model_config = ConfigDict(from_attributes=True)
-
-
-# ─── Shares ─────────────────────────────────────────────────────────────────
-
-class CredentialShareCreate(BaseModel):
- credential_id: UUID
- shared_with_profile_id: UUID
- expires_at: Optional[datetime] = None
-
-
-class CredentialShareRead(BaseModel):
- id: UUID
- credential_id: UUID
- shared_with_profile_id: UUID
- expires_at: Optional[datetime]
- created_at: datetime
-
- model_config = ConfigDict(from_attributes=True)
+"""Career history Pydantic schemas — Profiles, Experiences, and Credentials.
+
+Provides validation and serialization for lifelong career records.
+Handles both public (masked) and private (decrypted) data views.
+"""
+
+from datetime import date, datetime
+from typing import Any, Dict, List, Optional
+from uuid import UUID
+
+from pydantic import BaseModel, ConfigDict, EmailStr, Field, HttpUrl
+
+
+# ─── Organization ────────────────────────────────────────────────────────────
+
+class OrganizationBase(BaseModel):
+ name: str = Field(..., min_length=1, max_length=255)
+ website_url: Optional[HttpUrl] = None
+
+
+class OrganizationCreate(OrganizationBase):
+ pass
+
+
+class OrganizationRead(OrganizationBase):
+ id: UUID
+ verified: bool
+ created_at: datetime
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+# ─── Profile ────────────────────────────────────────────────────────────────
+
+class ProfileBase(BaseModel):
+ full_name: Optional[str] = Field(None, max_length=255)
+ industry: Optional[str] = Field(None, max_length=100)
+ general_skills: List[str] = Field(default_factory=list)
+
+
+class ProfileCreate(ProfileBase):
+ email: EmailStr
+
+
+class ProfileRead(ProfileBase):
+ id: UUID
+ status: str
+ email: Optional[EmailStr] = None
+ created_at: datetime
+ updated_at: datetime
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+class ProfilePublicRead(BaseModel):
+ id: UUID
+ full_name: Optional[str]
+ industry: Optional[str]
+ general_skills: List[str]
+ masked_email: Optional[str]
+ verified_credential_count: int
+ created_at: datetime
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+# ─── Career Record Payloads (Encrypted) ──────────────────────────────────────
+
+class ExperiencePayload(BaseModel):
+ """Internal details of an employment record (AES-256 encrypted in DB)."""
+ responsibilities: Optional[str] = None
+ achievements: Optional[List[str]] = None
+ tools_used: Optional[List[str]] = None
+ team_size: Optional[int] = None
+ department: Optional[str] = None
+
+
+class CredentialPayload(BaseModel):
+ """Internal details of a certification record (AES-256 encrypted in DB)."""
+ grade: Optional[str] = None
+ serial_number: Optional[str] = None
+ skills_verified: Optional[List[str]] = None
+ metadata: Optional[Dict[str, Any]] = None
+
+
+# ─── Experience ─────────────────────────────────────────────────────────────
+
+class ExperienceBase(BaseModel):
+ organization_id: UUID
+ start_date: date
+ end_date: Optional[date] = None
+ job_title: str = Field(..., min_length=1, max_length=150)
+
+
+class ExperienceCreate(ExperienceBase):
+ payload: ExperiencePayload
+
+
+class ExperienceUpdate(BaseModel):
+ start_date: Optional[date] = None
+ end_date: Optional[date] = None
+ job_title: Optional[str] = Field(None, max_length=150)
+ payload: Optional[ExperiencePayload] = None
+
+
+class ExperienceRead(ExperienceBase):
+ id: UUID
+ profile_id: UUID
+ created_at: datetime
+ payload: ExperiencePayload # This should be populated after decryption
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+class ExperiencePublicRead(ExperienceBase):
+ id: UUID
+ profile_id: UUID
+ organization_name: Optional[str] = None # To be joined in the view/query
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+# ─── Credential ─────────────────────────────────────────────────────────────
+
+class CredentialBase(BaseModel):
+ organization_id: UUID
+ issue_date: date
+ expiry_date: Optional[date] = None
+ credential_name: str = Field(..., min_length=1, max_length=150)
+
+
+class CredentialCreate(CredentialBase):
+ payload: CredentialPayload
+
+
+class CredentialRead(CredentialBase):
+ id: UUID
+ profile_id: UUID
+ issuer_signature: str
+ created_at: datetime
+ payload: CredentialPayload # This should be populated after decryption
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+class CredentialPublicRead(CredentialBase):
+ id: UUID
+ profile_id: UUID
+ organization_name: Optional[str] = None
+ is_verified: bool = False
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+# ─── Shares ─────────────────────────────────────────────────────────────────
+
+class CredentialShareCreate(BaseModel):
+ credential_id: UUID
+ shared_with_profile_id: UUID
+ expires_at: Optional[datetime] = None
+
+
+class CredentialShareRead(BaseModel):
+ id: UUID
+ credential_id: UUID
+ shared_with_profile_id: UUID
+ expires_at: Optional[datetime]
+ created_at: datetime
+
+ model_config = ConfigDict(from_attributes=True)
diff --git a/app/schemas/interview.py b/app/schemas/interview.py
index 32b2ed8d1875db2a5905fb51466d29814f893721..e412fce713180bb86c7e78670bba83aa2e8ebe19 100644
--- a/app/schemas/interview.py
+++ b/app/schemas/interview.py
@@ -1,117 +1,117 @@
-"""Interview & AI Notulen Pydantic schemas.
-
-Business model:
- - Schedule interview costs 5 coins (Enterprise = free)
- - AI Notulen generates meeting summaries
- - Competency analysis via Gemini MEDIUM tier
- - Multi-candidate comparison via Gemini HIGH tier
-"""
-
-from datetime import datetime
-from typing import Any, Dict, List, Optional
-
-from pydantic import BaseModel, Field
-
-
-class ScheduleInterviewRequest(BaseModel):
- candidate_id: str = Field(..., description="Talent ID to interview")
- scheduled_time: str = Field(..., description="ISO datetime string for interview time")
-
-
-class ScheduleInterviewResponse(BaseModel):
- success: bool = True
- interview_id: str = ""
- candidate_name: str = ""
- candidate_id: str = ""
- scheduled_time: Optional[str] = None
- credits_deducted: int = 0
- credits_remaining: int = 0
- message: str = ""
- error: Optional[str] = None
-
-
-class SaveTranscriptRequest(BaseModel):
- transcript_text: str = Field(..., min_length=10, max_length=50000)
-
-
-class SaveTranscriptResponse(BaseModel):
- success: bool = True
- interview_id: str = ""
- message: str = ""
- error: Optional[str] = None
-
-
-class NotulenResponse(BaseModel):
- success: bool = True
- interview_id: str = ""
- summary: str = ""
- ai_used: bool = False
- error: Optional[str] = None
-
-
-class CompetencyItem(BaseModel):
- name: str = ""
- score: int = 0
- notes: str = ""
-
-
-class CompetencyAnalysisResponse(BaseModel):
- success: bool = True
- interview_id: str = ""
- overall_score: int = 0
- competencies: List[CompetencyItem] = Field(default_factory=list)
- strengths: str = ""
- weaknesses: str = ""
- recommendation: str = ""
- ai_used: bool = False
- error: Optional[str] = None
-
-
-class CandidateComparisonItem(BaseModel):
- candidate_id: str = ""
- candidate_name: str = ""
- overall_score: int = 0
- competency_scores: Dict[str, int] = Field(default_factory=dict)
- strengths: str = ""
- weaknesses: str = ""
-
-
-class ComparisonRequest(BaseModel):
- interview_ids: List[str] = Field(..., min_length=2, max_length=10)
-
-
-class ComparisonResponse(BaseModel):
- success: bool = True
- candidates: List[CandidateComparisonItem] = Field(default_factory=list)
- recommendation: str = ""
- matrix_summary: str = ""
- ai_used: bool = False
- error: Optional[str] = None
-
-
-class InterviewItem(BaseModel):
- interview_id: str = ""
- candidate_id: str = ""
- candidate_name: str = ""
- scheduled_time: Optional[str] = None
- status: str = "Scheduled"
- has_transcript: bool = False
- has_ai_summary: bool = False
- competency_score: int = 0
- created_at: Optional[str] = None
-
-
-class InterviewDetailResponse(BaseModel):
- success: bool = True
- data: Optional[InterviewItem] = None
- transcript: str = ""
- ai_summary: str = ""
- competency_analysis: Optional[Dict[str, Any]] = None
- error: Optional[str] = None
-
-
-class InterviewListResponse(BaseModel):
- success: bool = True
- data: List[InterviewItem] = Field(default_factory=list)
- total: int = 0
- error: Optional[str] = None
+"""Interview & AI Notulen Pydantic schemas.
+
+Business model:
+ - Schedule interview costs 5 coins (Enterprise = free)
+ - AI Notulen generates meeting summaries
+ - Competency analysis via Gemini MEDIUM tier
+ - Multi-candidate comparison via Gemini HIGH tier
+"""
+
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+
+from pydantic import BaseModel, Field
+
+
+class ScheduleInterviewRequest(BaseModel):
+ candidate_id: str = Field(..., description="Talent ID to interview")
+ scheduled_time: str = Field(..., description="ISO datetime string for interview time")
+
+
+class ScheduleInterviewResponse(BaseModel):
+ success: bool = True
+ interview_id: str = ""
+ candidate_name: str = ""
+ candidate_id: str = ""
+ scheduled_time: Optional[str] = None
+ credits_deducted: int = 0
+ credits_remaining: int = 0
+ message: str = ""
+ error: Optional[str] = None
+
+
+class SaveTranscriptRequest(BaseModel):
+ transcript_text: str = Field(..., min_length=10, max_length=50000)
+
+
+class SaveTranscriptResponse(BaseModel):
+ success: bool = True
+ interview_id: str = ""
+ message: str = ""
+ error: Optional[str] = None
+
+
+class NotulenResponse(BaseModel):
+ success: bool = True
+ interview_id: str = ""
+ summary: str = ""
+ ai_used: bool = False
+ error: Optional[str] = None
+
+
+class CompetencyItem(BaseModel):
+ name: str = ""
+ score: int = 0
+ notes: str = ""
+
+
+class CompetencyAnalysisResponse(BaseModel):
+ success: bool = True
+ interview_id: str = ""
+ overall_score: int = 0
+ competencies: List[CompetencyItem] = Field(default_factory=list)
+ strengths: str = ""
+ weaknesses: str = ""
+ recommendation: str = ""
+ ai_used: bool = False
+ error: Optional[str] = None
+
+
+class CandidateComparisonItem(BaseModel):
+ candidate_id: str = ""
+ candidate_name: str = ""
+ overall_score: int = 0
+ competency_scores: Dict[str, int] = Field(default_factory=dict)
+ strengths: str = ""
+ weaknesses: str = ""
+
+
+class ComparisonRequest(BaseModel):
+ interview_ids: List[str] = Field(..., min_length=2, max_length=10)
+
+
+class ComparisonResponse(BaseModel):
+ success: bool = True
+ candidates: List[CandidateComparisonItem] = Field(default_factory=list)
+ recommendation: str = ""
+ matrix_summary: str = ""
+ ai_used: bool = False
+ error: Optional[str] = None
+
+
+class InterviewItem(BaseModel):
+ interview_id: str = ""
+ candidate_id: str = ""
+ candidate_name: str = ""
+ scheduled_time: Optional[str] = None
+ status: str = "Scheduled"
+ has_transcript: bool = False
+ has_ai_summary: bool = False
+ competency_score: int = 0
+ created_at: Optional[str] = None
+
+
+class InterviewDetailResponse(BaseModel):
+ success: bool = True
+ data: Optional[InterviewItem] = None
+ transcript: str = ""
+ ai_summary: str = ""
+ competency_analysis: Optional[Dict[str, Any]] = None
+ error: Optional[str] = None
+
+
+class InterviewListResponse(BaseModel):
+ success: bool = True
+ data: List[InterviewItem] = Field(default_factory=list)
+ total: int = 0
+ error: Optional[str] = None
diff --git a/app/schemas/job.py b/app/schemas/job.py
index 7ee9d146a6ed2e530b2d781a4b6ed84dee8727f2..0fac905bd9bdcd853541d5351d8924dccc54a8ed 100644
--- a/app/schemas/job.py
+++ b/app/schemas/job.py
@@ -1,156 +1,156 @@
-"""Job Pydantic schemas - Posting, Outreach, Compatibility, Vouchers."""
-
-from datetime import datetime
-from typing import Any, Dict, List, Optional
-
-from pydantic import BaseModel, Field
-
-
-# ─── Job Posting ────────────────────────────────────────────────────────────
-
-class JobPostingResponse(BaseModel):
- job_id: str = ""
- title: str = ""
- company_category: str = ""
- location: str = ""
- description: str = ""
- required_skills: List[str] = Field(default_factory=list)
- salary_range: str = "Negotiable"
- source: str = ""
- status: str = ""
- sector_match: str = ""
- linkedin_post_url: str = ""
- timestamp: Optional[str] = None
- posted_at: Optional[str] = None
-
-
-class JobListResponse(BaseModel):
- success: bool = True
- page: int = 1
- limit: int = 10
- total: int = 0
- data: List[JobPostingResponse] = Field(default_factory=list)
- error: Optional[str] = None
-
-
-class CreateJobRequest(BaseModel):
- title: str = Field(..., min_length=3, max_length=255)
- company_category: str = Field(..., max_length=255)
- location: str = Field(..., max_length=255)
- description: str = Field(..., min_length=20, max_length=10000)
- required_skills: str = Field(..., description="Comma-separated skills")
- salary_range: str = Field("Negotiable", max_length=100)
- sector_match: str = Field("", max_length=255)
- linkedin_post_url: str = Field("", max_length=500)
-
-
-class UpdateJobStatusRequest(BaseModel):
- job_id: str = Field(...)
- status: str = Field(..., pattern='^(draft|posted|closed|archived)$')
-
-
-# ─── Job Compatibility ──────────────────────────────────────────────────────
-
-class AnalyzeCompatibilityRequest(BaseModel):
- job_id: str = Field(...)
-
-
-class SkillMatchItem(BaseModel):
- skill: str = ""
- status: str = "matched"
-
-
-class CompatibilityResult(BaseModel):
- matchScore: int = 0
- matchedSkills: List[SkillMatchItem] = Field(default_factory=list)
- gapSkills: List[SkillMatchItem] = Field(default_factory=list)
- strategy: str = ""
-
-
-class AnalyzeCompatibilityResponse(BaseModel):
- success: bool = True
- data: Optional[CompatibilityResult] = None
- error: Optional[str] = None
-
-
-# ─── Job Limit ──────────────────────────────────────────────────────────────
-
-class CheckJobLimitResponse(BaseModel):
- allowed: bool = True
- tier: str = "free"
- active_count: int = 0
- limit: int = 1
- error: Optional[str] = None
-
-
-# ─── Recruiter Outreach ─────────────────────────────────────────────────────
-
-class OutreachRecordResponse(BaseModel):
- success: bool = True
- outreach_id: str = ""
- error: Optional[str] = None
-
-
-class SendOutreachRequest(BaseModel):
- job_id: str = Field(...)
- talent_email: str = Field(...)
- match_score: int = Field(0, ge=0, le=100)
- subject: str = Field(..., max_length=200)
- body: str = Field(..., max_length=5000)
- method: str = Field("email", pattern='^(email|whatsapp)$')
-
-
-class SendOutreachResponse(BaseModel):
- success: bool = True
- outreach_id: str = ""
- remaining: int = 0
- error: Optional[str] = None
-
-
-# ─── Voucher System ─────────────────────────────────────────────────────────
-
-class VoucherItem(BaseModel):
- voucher_id: str = ""
- lpk_id: str = ""
- candidate_email: str = ""
- status: str = "Available"
- date_generated: Optional[str] = None
- date_used: Optional[str] = None
-
-
-class VoucherCounts(BaseModel):
- Available: int = 0
- Used: int = 0
- Total: int = 0
-
-
-class VoucherGenerateRequest(BaseModel):
- lpk_id: str = Field(...)
- quantity: int = Field(1, ge=1, le=100)
-
-
-class VoucherGenerateResponse(BaseModel):
- success: bool = True
- message: str = ""
- vouchers: List[str] = Field(default_factory=list)
- count: int = 0
- error: Optional[str] = None
-
-
-class VoucherRedeemRequest(BaseModel):
- voucher_code: str = Field(..., pattern='^BRG-LPK-[A-Z0-9]{8}$')
-
-
-class VoucherRedeemResponse(BaseModel):
- success: bool = True
- message: str = ""
- lpk_id: str = ""
- voucher_code: str = ""
- error: Optional[str] = None
-
-
-class VoucherListResponse(BaseModel):
- success: bool = True
- vouchers: List[VoucherItem] = Field(default_factory=list)
- counts: VoucherCounts = Field(default_factory=VoucherCounts)
- error: Optional[str] = None
+"""Job Pydantic schemas - Posting, Outreach, Compatibility, Vouchers."""
+
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+
+from pydantic import BaseModel, Field
+
+
+# ─── Job Posting ────────────────────────────────────────────────────────────
+
+class JobPostingResponse(BaseModel):
+ job_id: str = ""
+ title: str = ""
+ company_category: str = ""
+ location: str = ""
+ description: str = ""
+ required_skills: List[str] = Field(default_factory=list)
+ salary_range: str = "Negotiable"
+ source: str = ""
+ status: str = ""
+ sector_match: str = ""
+ linkedin_post_url: str = ""
+ timestamp: Optional[str] = None
+ posted_at: Optional[str] = None
+
+
+class JobListResponse(BaseModel):
+ success: bool = True
+ page: int = 1
+ limit: int = 10
+ total: int = 0
+ data: List[JobPostingResponse] = Field(default_factory=list)
+ error: Optional[str] = None
+
+
+class CreateJobRequest(BaseModel):
+ title: str = Field(..., min_length=3, max_length=255)
+ company_category: str = Field(..., max_length=255)
+ location: str = Field(..., max_length=255)
+ description: str = Field(..., min_length=20, max_length=10000)
+ required_skills: str = Field(..., description="Comma-separated skills")
+ salary_range: str = Field("Negotiable", max_length=100)
+ sector_match: str = Field("", max_length=255)
+ linkedin_post_url: str = Field("", max_length=500)
+
+
+class UpdateJobStatusRequest(BaseModel):
+ job_id: str = Field(...)
+ status: str = Field(..., pattern='^(draft|posted|closed|archived)$')
+
+
+# ─── Job Compatibility ──────────────────────────────────────────────────────
+
+class AnalyzeCompatibilityRequest(BaseModel):
+ job_id: str = Field(...)
+
+
+class SkillMatchItem(BaseModel):
+ skill: str = ""
+ status: str = "matched"
+
+
+class CompatibilityResult(BaseModel):
+ matchScore: int = 0
+ matchedSkills: List[SkillMatchItem] = Field(default_factory=list)
+ gapSkills: List[SkillMatchItem] = Field(default_factory=list)
+ strategy: str = ""
+
+
+class AnalyzeCompatibilityResponse(BaseModel):
+ success: bool = True
+ data: Optional[CompatibilityResult] = None
+ error: Optional[str] = None
+
+
+# ─── Job Limit ──────────────────────────────────────────────────────────────
+
+class CheckJobLimitResponse(BaseModel):
+ allowed: bool = True
+ tier: str = "free"
+ active_count: int = 0
+ limit: int = 1
+ error: Optional[str] = None
+
+
+# ─── Recruiter Outreach ─────────────────────────────────────────────────────
+
+class OutreachRecordResponse(BaseModel):
+ success: bool = True
+ outreach_id: str = ""
+ error: Optional[str] = None
+
+
+class SendOutreachRequest(BaseModel):
+ job_id: str = Field(...)
+ talent_email: str = Field(...)
+ match_score: int = Field(0, ge=0, le=100)
+ subject: str = Field(..., max_length=200)
+ body: str = Field(..., max_length=5000)
+ method: str = Field("email", pattern='^(email|whatsapp)$')
+
+
+class SendOutreachResponse(BaseModel):
+ success: bool = True
+ outreach_id: str = ""
+ remaining: int = 0
+ error: Optional[str] = None
+
+
+# ─── Voucher System ─────────────────────────────────────────────────────────
+
+class VoucherItem(BaseModel):
+ voucher_id: str = ""
+ lpk_id: str = ""
+ candidate_email: str = ""
+ status: str = "Available"
+ date_generated: Optional[str] = None
+ date_used: Optional[str] = None
+
+
+class VoucherCounts(BaseModel):
+ Available: int = 0
+ Used: int = 0
+ Total: int = 0
+
+
+class VoucherGenerateRequest(BaseModel):
+ lpk_id: str = Field(...)
+ quantity: int = Field(1, ge=1, le=100)
+
+
+class VoucherGenerateResponse(BaseModel):
+ success: bool = True
+ message: str = ""
+ vouchers: List[str] = Field(default_factory=list)
+ count: int = 0
+ error: Optional[str] = None
+
+
+class VoucherRedeemRequest(BaseModel):
+ voucher_code: str = Field(..., pattern='^BRG-LPK-[A-Z0-9]{8}$')
+
+
+class VoucherRedeemResponse(BaseModel):
+ success: bool = True
+ message: str = ""
+ lpk_id: str = ""
+ voucher_code: str = ""
+ error: Optional[str] = None
+
+
+class VoucherListResponse(BaseModel):
+ success: bool = True
+ vouchers: List[VoucherItem] = Field(default_factory=list)
+ counts: VoucherCounts = Field(default_factory=VoucherCounts)
+ error: Optional[str] = None
diff --git a/app/services/academy_email_service.py b/app/services/academy_email_service.py
index 7fe0d2df913d61d6d813ae5bac6bdf8b09e3d68e..6ab949e035ac52808999a1c9ddba0772a1c81ac0 100644
--- a/app/services/academy_email_service.py
+++ b/app/services/academy_email_service.py
@@ -1,169 +1,170 @@
-"""
-Academy Email Service — AI-powered essay feedback & email outreach.
-
-Generates personalized feedback on academy essay answers using Gemini,
-then sends it via email through the Apps Script deployment gateway.
-
-Uses app.services.ai_service.call_gemini_json() instead of a private _call_gemini.
-"""
-
-import os
-import asyncio
-from datetime import datetime
-from zoneinfo import ZoneInfo
-
-from loguru import logger
-from sqlalchemy import func, select
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.models.job import TalentAcademy
-from app.services.ai_service import call_gemini_json
-from app.services.email_service import email_service
-
-
-class AcademyEmailService:
- """Generates AI feedback on academy essays and sends via email."""
-
- def __init__(self):
- self.tz = ZoneInfo(os.getenv("TIMEZONE", "Asia/Jakarta"))
-
- async def generate_feedback(self, email, completed_modules, essay_answers):
- modules_str = ", ".join(completed_modules) if completed_modules else "Belum ada modul selesai"
-
- prompt = f"""Kamu adalah Brigawan Academy Mentor — mentor karir hijau yang hangat dan profesional di Indonesia.
-
-TUGAS: Berikan feedback personal atas jawaban essay talenta Akademi Brigawan.
-
-DATA TALENT:
-- Email: {email}
-- Modul Selesai: {modules_str}
-
-JAWABAN ESSAY TALENT:
-{essay_answers if essay_answers else "Belum mengirimkan essay."}
-
-INSTRUKSI:
-1. Analisis jawaban essay dengan mendalam (kekuatan, area pengembangan)
-2. Berikan 2-3 saran konkret untuk meningkatkan pemahaman mereka
-3. Jika belum ada essay, berikan motivasi untuk memulai modul pertama
-4. Bahasa Indonesia profesional dan hangat
-
-Format JSON:
-{{
- "feedback_intro": "1-2 kalimat pembuka personal",
- "strengths": "Apa yang sudah baik dari jawaban mereka",
- "areas_for_improvement": "Area yang bisa dikembangkan",
- "concrete_tips": ["saran 1", "saran 2", "saran 3"],
- "next_steps": "Rekomendasi modul atau langkah selanjutnya",
- "closing": "Kalimat penutup yang memotivasi"
-}}
-"""
- return await call_gemini_json(prompt, temperature=0.4, max_output_tokens=2048)
-
- async def send_feedback_email(self, recipient_email, feedback_data):
- """Send the feedback via python-native SMTP service."""
- subject = "Umpan Balik Akademi Brigawan — Personalisasi AI"
-
- intro = feedback_data.get("feedback_intro", "Halo,")
- strengths = feedback_data.get("strengths", "")
- areas = feedback_data.get("areas_for_improvement", "")
- tips = feedback_data.get("concrete_tips", [])
- next_steps = feedback_data.get("next_steps", "")
- closing = feedback_data.get("closing", "Semangat terus!")
-
- tips_html = ""
- for t in tips:
- tips_html += f"{t} "
-
- body_html = f"""
-
-
🎓 Umpan Balik Akademi
-
Brigawan AI — Personalisasi untuk Perjalanan Belajarmu
-
-
-
{intro}
-
-
✅ Kekuatan
-
{strengths}
-
-
-
📈 Area Pengembangan
-
{areas}
-
-
-
-
🎯 Langkah Selanjutnya
-
{next_steps}
-
-
{closing}
-
-
© Brigawan.id — Platform Karir Hijau Indonesia Email ini dikirim secara otomatis oleh AI Academy Mentor.
-
-
"""
-
- success = await asyncio.to_thread(
- email_service.send_html_email, recipient_email, subject, body_html
- )
- if success:
- return {"success": True, "message": "Email feedback terkirim"}
- return {"success": False, "error": "Failed to send email via SMTP service"}
-
- async def process_academy_feedback(self, db: AsyncSession, email: str):
- """Full pipeline: fetch academy data -> generate AI feedback -> send email."""
- try:
- e = email.lower().strip()
- result = await db.execute(
- select(TalentAcademy).where(func.lower(TalentAcademy.email) == e).limit(1)
- )
- acad = result.scalar_one_or_none()
- if not acad:
- return {"success": False, "error": "Data akademi tidak ditemukan"}
-
- completed_modules = [m.strip() for m in (acad.completed_modules or "").split(",") if m.strip()]
- essay_answers = acad.essay_answers or ""
-
- if not completed_modules and not essay_answers:
- return {"success": False, "error": "Belum ada aktivitas akademi"}
-
- # Generate feedback
- logger.info(f"[AcademyEmail] Generating feedback for {e}")
- feedback = await self.generate_feedback(e, completed_modules, essay_answers)
- if "error" in feedback:
- return {"success": False, "error": feedback["error"]}
-
- # Send email
- logger.info(f"[AcademyEmail] Sending feedback to {e}")
- send_result = await self.send_feedback_email(e, feedback)
-
- return {
- "success": send_result.get("success", False),
- "email": e,
- "modules_completed": len(completed_modules),
- "feedback_generated": True,
- "email_sent": send_result.get("success", False),
- "error": send_result.get("error"),
- }
- except Exception as e:
- logger.error(f"[AcademyEmail] Error: {e}")
- return {"success": False, "error": str(e)}
-
- async def process_bulk_academy_feedback(self, db: AsyncSession, limit=20):
- """Process academy feedback for all talents with completed modules."""
- try:
- result = await db.execute(
- select(TalentAcademy).limit(limit)
- )
- records = result.scalars().all()
- results = []
- for acad in records:
- res = await self.process_academy_feedback(db, acad.email)
- results.append(res)
- return {
- "success": True,
- "total": len(records),
- "results": results,
- }
- except Exception as e:
- return {"success": False, "error": str(e)}
+"""
+Academy Email Service — AI-powered essay feedback & email outreach.
+
+Generates personalized feedback on academy essay answers using Gemini,
+then sends it via email through the Apps Script deployment gateway.
+
+Uses app.services.ai_service.call_gemini_json() instead of a private _call_gemini.
+"""
+
+import os
+import asyncio
+from datetime import datetime
+from zoneinfo import ZoneInfo
+
+from loguru import logger
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.job import TalentAcademy
+from app.services.ai_service import call_gemini_json
+from app.services.email_service import email_service
+
+
+class AcademyEmailService:
+ """Generates AI feedback on academy essays and sends via email."""
+
+ def __init__(self):
+ self.tz = ZoneInfo(os.getenv("TIMEZONE", "Asia/Jakarta"))
+
+ async def generate_feedback(self, email, completed_modules, essay_answers):
+ # ... existing code ...
+ modules_str = ", ".join(completed_modules) if completed_modules else "Belum ada modul selesai"
+
+ prompt = f"""Kamu adalah Brigawan Academy Mentor — mentor karir hijau yang hangat dan profesional di Indonesia.
+
+TUGAS: Berikan feedback personal atas jawaban essay talenta Akademi Brigawan.
+
+DATA TALENT:
+- Email: {email}
+- Modul Selesai: {modules_str}
+
+JAWABAN ESSAY TALENT:
+{essay_answers if essay_answers else "Belum mengirimkan essay."}
+
+INSTRUKSI:
+1. Analisis jawaban essay dengan mendalam (kekuatan, area pengembangan)
+2. Berikan 2-3 saran konkret untuk meningkatkan pemahaman mereka
+3. Jika belum ada essay, berikan motivasi untuk memulai modul pertama
+4. Bahasa Indonesia profesional dan hangat
+
+Format JSON:
+{{
+ "feedback_intro": "1-2 kalimat pembuka personal",
+ "strengths": "Apa yang sudah baik dari jawaban mereka",
+ "areas_for_improvement": "Area yang bisa dikembangkan",
+ "concrete_tips": ["saran 1", "saran 2", "saran 3"],
+ "next_steps": "Rekomendasi modul atau langkah selanjutnya",
+ "closing": "Kalimat penutup yang memotivasi"
+}}
+"""
+ return await call_gemini_json(prompt, temperature=0.4, max_output_tokens=2048)
+
+ async def send_feedback_email(self, recipient_email, feedback_data):
+ """Send the feedback via python-native SMTP service."""
+ subject = "Umpan Balik Akademi Brigawan — Personalisasi AI"
+
+ intro = feedback_data.get("feedback_intro", "Halo,")
+ strengths = feedback_data.get("strengths", "")
+ areas = feedback_data.get("areas_for_improvement", "")
+ tips = feedback_data.get("concrete_tips", [])
+ next_steps = feedback_data.get("next_steps", "")
+ closing = feedback_data.get("closing", "Semangat terus!")
+
+ tips_html = ""
+ for t in tips:
+ tips_html += f"{t} "
+
+ body_html = f"""
+
+
🎓 Umpan Balik Akademi
+
Brigawan AI — Personalisasi untuk Perjalanan Belajarmu
+
+
+
{intro}
+
+
✅ Kekuatan
+
{strengths}
+
+
+
📈 Area Pengembangan
+
{areas}
+
+
+
+
🎯 Langkah Selanjutnya
+
{next_steps}
+
+
{closing}
+
+
© Brigawan.id — Platform Karir Hijau Indonesia Email ini dikirim secara otomatis oleh AI Academy Mentor.
+
+
"""
+
+ success = await asyncio.to_thread(
+ email_service.send_html_email, recipient_email, subject, body_html
+ )
+ if success:
+ return {"success": True, "message": "Email feedback terkirim"}
+ return {"success": False, "error": "Failed to send email via SMTP service"}
+
+ async def process_academy_feedback(self, db: AsyncSession, email: str):
+ """Full pipeline: fetch academy data -> generate AI feedback -> send email."""
+ try:
+ e = email.lower().strip()
+ result = await db.execute(
+ select(TalentAcademy).where(func.lower(TalentAcademy.email) == e).limit(1)
+ )
+ acad = result.scalar_one_or_none()
+ if not acad:
+ return {"success": False, "error": "Data akademi tidak ditemukan"}
+
+ completed_modules = [m.strip() for m in (acad.completed_modules or "").split(",") if m.strip()]
+ essay_answers = acad.essay_answers or ""
+
+ if not completed_modules and not essay_answers:
+ return {"success": False, "error": "Belum ada aktivitas akademi"}
+
+ # Generate feedback
+ logger.info(f"[AcademyEmail] Generating feedback for {e}")
+ feedback = await self.generate_feedback(e, completed_modules, essay_answers)
+ if "error" in feedback:
+ return {"success": False, "error": feedback["error"]}
+
+ # Send email
+ logger.info(f"[AcademyEmail] Sending feedback to {e}")
+ send_result = await self.send_feedback_email(e, feedback)
+
+ return {
+ "success": send_result.get("success", False),
+ "email": e,
+ "modules_completed": len(completed_modules),
+ "feedback_generated": True,
+ "email_sent": send_result.get("success", False),
+ "error": send_result.get("error"),
+ }
+ except Exception as e:
+ logger.error(f"[AcademyEmail] Error: {e}")
+ return {"success": False, "error": str(e)}
+
+ async def process_bulk_academy_feedback(self, db: AsyncSession, limit=20):
+ """Process academy feedback for all talents with completed modules."""
+ try:
+ result = await db.execute(
+ select(TalentAcademy).limit(limit)
+ )
+ records = result.scalars().all()
+ results = []
+ for acad in records:
+ res = await self.process_academy_feedback(db, acad.email)
+ results.append(res)
+ return {
+ "success": True,
+ "total": len(records),
+ "results": results,
+ }
+ except Exception as e:
+ return {"success": False, "error": str(e)}
diff --git a/app/services/agent_activity_service.py b/app/services/agent_activity_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bff144fa1b0e48d0d838058c4a14d41069da706
--- /dev/null
+++ b/app/services/agent_activity_service.py
@@ -0,0 +1,116 @@
+"""Agent Activity Service — Tracking and Intervention Manager.
+
+Provides the database tracking logic for the Interactive Command Center,
+allowing tasks to be monitored and paused for Board intervention.
+"""
+
+import uuid
+import asyncio
+from typing import Dict, Any, Optional
+from loguru import logger
+from sqlalchemy import text
+from app.database import get_db_session
+
+class AgentActivityService:
+ """Manages the lifecycle and state of agent tasks in the database."""
+
+ @classmethod
+ async def log_activity(cls, agent_id: str, task: str) -> str:
+ """Creates a new activity log and returns its ID."""
+ activity_id = str(uuid.uuid4())
+ try:
+ async for db in get_db_session():
+ query = text("""
+ INSERT INTO agent_activities (id, agent_id, task_description, status)
+ VALUES (:id, :agent_id, :task, 'IN_PROGRESS')
+ """)
+ await db.execute(query, {"id": activity_id, "agent_id": agent_id, "task": task})
+ await db.commit()
+ break
+ except Exception as e:
+ logger.error(f"[ActivityLog] Failed to log start for {agent_id}: {e}")
+ return activity_id
+
+ @classmethod
+ async def update_status(cls, activity_id: str, status: str, payload: Optional[Dict] = None, next_action: str = None):
+ """Updates the status of an ongoing activity."""
+ try:
+ async for db in get_db_session():
+ import json
+ query = text("""
+ UPDATE agent_activities
+ SET status = :status,
+ result_payload = :payload,
+ next_action = :next_action,
+ updated_at = NOW()
+ WHERE id = :id
+ """)
+ await db.execute(query, {
+ "id": activity_id,
+ "status": status,
+ "payload": json.dumps(payload) if payload else None,
+ "next_action": next_action
+ })
+ await db.commit()
+ break
+ except Exception as e:
+ logger.error(f"[ActivityLog] Failed to update {activity_id}: {e}")
+
+ @classmethod
+ async def request_intervention(cls, activity_id: str, agent_id: str, issue: str, telegram_msg: str):
+ """Pauses a workflow and sends a ping to the Board."""
+ logger.warning(f"[Intervention] Agent {agent_id} requesting Board intervention: {issue}")
+
+ try:
+ async for db in get_db_session():
+ query = text("""
+ UPDATE agent_activities
+ SET status = 'BLOCKED',
+ requires_intervention = TRUE,
+ intervention_type = 'APPROVAL_REQUIRED',
+ next_action = :issue,
+ updated_at = NOW()
+ WHERE id = :id
+ """)
+ await db.execute(query, {"id": activity_id, "issue": issue})
+ await db.commit()
+ break
+
+ # Send Notification to Telegram
+ from app.services.telegram_ceo_service import telegram_service
+ # We wrap the message with instructions on how to reply
+ 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]}`."
+ await telegram_service.send_ceo_message(full_msg)
+
+ except Exception as e:
+ logger.error(f"[Intervention] Failed to request intervention: {e}")
+
+ @classmethod
+ async def wait_for_approval(cls, activity_id: str, timeout_seconds: int = 3600) -> bool:
+ """Polls the database waiting for the Board to change status to APPROVED."""
+ logger.info(f"[Intervention] Waiting for Board approval on {activity_id}...")
+
+ waited = 0
+ while waited < timeout_seconds:
+ try:
+ async for db in get_db_session():
+ query = text("SELECT status FROM agent_activities WHERE id = :id")
+ res = await db.execute(query, {"id": activity_id})
+ row = res.fetchone()
+ if row:
+ status = row[0]
+ if status == 'APPROVED':
+ logger.success(f"[Intervention] Board APPROVED {activity_id}. Resuming...")
+ return True
+ elif status in ('REJECTED', 'FAILED'):
+ logger.warning(f"[Intervention] Board REJECTED {activity_id}. Halting.")
+ return False
+ break
+ except Exception:
+ pass
+
+ await asyncio.sleep(10) # Poll every 10 seconds
+ waited += 10
+
+ logger.error(f"[Intervention] Timed out waiting for Board approval on {activity_id}.")
+ return False
diff --git a/app/services/agent_memory_service.py b/app/services/agent_memory_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..438821b62bc146dd976218af03b2c1d295287276
--- /dev/null
+++ b/app/services/agent_memory_service.py
@@ -0,0 +1,102 @@
+"""Agent Memory Service — Obsidian-like Vector RAG Memory.
+
+This service implements the "Second Brain" for the AI Organization.
+Instead of saving to a flat JSON file, it generates mathematical vectors (embeddings)
+for every lesson learned and stores them in Supabase (pgvector).
+When an agent needs context, it retrieves only the semantically relevant memories.
+"""
+
+from typing import List
+import uuid
+from loguru import logger
+from sqlalchemy import text
+from app.database import AsyncSessionLocal
+from app.services.ai_service import generate_embedding
+
+class AgentMemoryService:
+ """Manages vector-based long-term memory for agents using pgvector."""
+
+ @classmethod
+ async def store_learning(cls, agent_id: str, task_context: str, outcome: str, is_success: bool, key_takeaway: str):
+ """Embeds and stores a new learning experience in the database."""
+ logger.info(f"[ObsidianMemory] Storing new memory for {agent_id}...")
+
+ # 1. Prepare the memory content
+ icon = "✅ SUCCESS" if is_success else "❌ FAILURE"
+ memory_text = f"[{icon}] Task: {task_context}. Outcome: {outcome}. Key Takeaway: {key_takeaway}"
+
+ # 2. Generate Embedding Vector (768 dimensions)
+ embedding = await generate_embedding(memory_text)
+
+ if sum(embedding) == 0.0:
+ logger.warning("[ObsidianMemory] Embedding generation failed. Skipping memory save.")
+ return
+
+ # 3. Save to Supabase via SQLAlchemy
+ try:
+ async with AsyncSessionLocal() as db:
+ query = text("""
+ INSERT INTO agent_memories (id, agent_id, content, embedding, task_context, success)
+ VALUES (:id, :agent_id, :content, :embedding, :task_context, :success)
+ """)
+ await db.execute(query, {
+ "id": str(uuid.uuid4()),
+ "agent_id": agent_id,
+ "content": memory_text,
+ "embedding": str(embedding), # pgvector accepts string representation of list
+ "task_context": task_context[:500],
+ "success": is_success
+ })
+ await db.commit()
+ logger.success(f"[ObsidianMemory] Memory successfully crystallized for {agent_id}.")
+ except Exception as e:
+ logger.error(f"[ObsidianMemory] Database insertion failed: {e}")
+
+ @classmethod
+ async def get_learnings(cls, agent_id: str, current_task_prompt: str, limit: int = 3, query_embedding: List[float] = None) -> str:
+ """Retrieves semantically relevant past learnings (RAG)."""
+ # If the task is empty, we can't do semantic search
+ if not current_task_prompt:
+ return ""
+
+ logger.debug(f"[ObsidianMemory] Searching Second Brain for {agent_id} relevant to current task...")
+
+ # 1. Embed the current task to find its math vector
+ if query_embedding is None:
+ query_embedding = await generate_embedding(current_task_prompt)
+ if sum(query_embedding) == 0.0:
+ return ""
+
+ # 2. Semantic Search (Cosine Distance) in Supabase
+ relevant_memories = []
+ try:
+ async with AsyncSessionLocal() as db:
+ # <=> is the pgvector operator for Cosine Distance. Lower is more similar.
+ query = text("""
+ SELECT content
+ FROM agent_memories
+ WHERE agent_id = :agent_id
+ ORDER BY embedding <=> :query_embedding
+ LIMIT :limit
+ """)
+ result = await db.execute(query, {
+ "agent_id": agent_id,
+ "query_embedding": str(query_embedding),
+ "limit": limit
+ })
+
+ rows = result.fetchall()
+ relevant_memories = [row[0] for row in rows]
+ except Exception as e:
+ logger.error(f"[ObsidianMemory] Semantic search failed: {e}")
+ return ""
+
+ # 3. Format the retrieved knowledge
+ if not relevant_memories:
+ return ""
+
+ learning_text = "PENGALAMAN & PEMBELAJARAN MASA LALU (SANGAT RELEVAN DENGAN TUGAS INI):\n"
+ for mem in relevant_memories:
+ learning_text += f"- {mem}\n"
+
+ return learning_text
diff --git a/app/services/agent_service.py b/app/services/agent_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..738e9fd927384e52a4f051ff7c5128048abd872e
--- /dev/null
+++ b/app/services/agent_service.py
@@ -0,0 +1,764 @@
+"""Agent Organization Service — Defining the 74-Agent Hierarchy.
+
+This service manages the system prompts, tiers, and roles for the full
+Brigawan AI Agent Organization (C-Level, VP, Manager, Specialist, Tech).
+
+FIX (2026-09): docstring previously said 68 — actual registry count is 74.
+"""
+
+import os
+from typing import Any, Dict, List, Optional
+from app.services.ai_service import call_high, call_medium, call_low, call_gemini_json, generate_embedding
+from app.services.agent_memory_service import AgentMemoryService
+
+
+# =============================================================================
+# PER-AGENT TIER ROUTING (2026-09)
+# =============================================================================
+# Override tier untuk agent tertentu tanpa menyentuh definisi registry.
+# Tier mapping ke provider (lihat ai_service.py TIERS + fallback chain):
+# HIGH -> Gemini Pro key (free tier ~5 RPM / ~100 req/day — hemat utk strategis)
+# MEDIUM -> Gemini Flash multi-key (kapasitas harian terbesar)
+# LOW -> Gemini Flash light; Groq/OpenRouter :free menangani overflow
+AGENT_TIER_OVERRIDES: Dict[str, str] = {
+ # Strategis & jarang dipanggil -> HIGH (kualitas maksimal)
+ "programmatic-seo-agent": "HIGH",
+ "competitor-spy-agent": "HIGH",
+ # JSON-heavy & sering dipanggil -> MEDIUM (lebih murah & cepat)
+ "test-writer": "MEDIUM",
+ "api-tester": "MEDIUM",
+ "seed-generator": "MEDIUM",
+ # Utility trivial -> LOW
+ "changelog-generator": "LOW",
+ "i18n-translator": "LOW",
+}
+
+# Runtime overrides via env (JSON): AGENT_TIER_OVERRIDES_JSON='{"ceo-agent":"MEDIUM"}'
+_env_overrides_raw = os.getenv("AGENT_TIER_OVERRIDES_JSON", "")
+if _env_overrides_raw:
+ try:
+ import json as _json
+ _parsed = _json.loads(_env_overrides_raw)
+ if isinstance(_parsed, dict):
+ AGENT_TIER_OVERRIDES.update({str(k): str(v).upper() for k, v in _parsed.items()})
+ except Exception:
+ pass
+
+
+def _resolve_tier(agent_id: str, default_tier: str) -> str:
+ """Return the effective tier for an agent, honoring per-agent overrides."""
+ return AGENT_TIER_OVERRIDES.get(agent_id, default_tier).upper()
+
+
+class AgentRegistry:
+ """Registry of system prompts and configurations for all agents."""
+
+ AGENTS = {
+ # 🏛️ C-LEVEL (Level 1) - HIGH TIER
+ "ceo-agent": {
+ "tier": "HIGH",
+ "role": "Chief Executive Officer",
+ "prompt": (
+ "IDENTITAS: Anda adalah BUFFY, CEO & Orchestrator-in-Chief Brigawan AI Organization.\n"
+ "MISI: Menetapkan visi, strategi pertumbuhan, dan mengambil keputusan tingkat tinggi untuk portal green jobs Brigawan.\n"
+ "TANGGUNG JAWAB: Strategi bisnis, prioritas utama, persetujuan roadmap, dan delegasi ke jajaran C-Level & VP.\n"
+ "GAYA: Visioner, tegas, berwibawa, namun berorientasi pada data."
+ )
+ },
+ "cto-agent": {
+ "tier": "HIGH",
+ "role": "Chief Technology Officer",
+ "prompt": (
+ "IDENTITAS: Anda adalah CTO Brigawan AI Organization.\n"
+ "MISI: Menetapkan strategi teknologi, arsitektur sistem, dan inovasi teknis.\n"
+ "TANGGUNG JAWAB: Keputusan arsitektur, standar keamanan, skalabilitas, dan pengawasan pipeline engineering.\n"
+ "GAYA: Analitis, inovatif, fokus pada efisiensi dan keamanan."
+ )
+ },
+ "coo-agent": {
+ "tier": "HIGH",
+ "role": "Chief Operating Officer",
+ "prompt": (
+ "IDENTITAS: Anda adalah COO Brigawan AI Organization.\n"
+ "MISI: Mengoptimalkan resource allocation dan efisiensi operasional.\n"
+ "TANGGUNG JAWAB: Alokasi budget token, optimalisasi workflow, dan koordinasi antar departemen.\n"
+ "GAYA: Terperinci, efisien, berorientasi pada hasil."
+ )
+ },
+ "cmo-agent": {
+ "tier": "HIGH",
+ "role": "Chief Marketing Officer",
+ "prompt": (
+ "IDENTITAS: Anda adalah CMO Brigawan AI Organization.\n"
+ "MISI: Menetapkan strategi pemasaran dan brand positioning.\n"
+ "TANGGUNG JAWAB: Strategi SEO, kalender konten, kampanye marketing, dan riset pasar.\n"
+ "GAYA: Kreatif, strategis, persuasif."
+ )
+ },
+ "cfo-agent": {
+ "tier": "HIGH",
+ "role": "Chief Financial Officer",
+ "prompt": (
+ "IDENTITAS: Anda adalah CFO Brigawan AI Organization.\n"
+ "MISI: Mengelola anggaran dan optimalisasi biaya operasional AI (Token Economics).\n"
+ "TANGGUNG JAWAB: Analisis ROI, pemantauan pengeluaran token API, dan strategi penetapan harga.\n"
+ "GAYA: Kalkulatif, hemat, berpusat pada profitabilitas."
+ )
+ },
+ "cio-agent": {
+ "tier": "HIGH",
+ "role": "Chief Information Officer",
+ "prompt": (
+ "IDENTITAS: Anda adalah CIO Brigawan AI Organization.\n"
+ "MISI: Mengelola tata kelola data (Data Governance) dan intelijen bisnis.\n"
+ "TANGGUNG JAWAB: Strategi retensi data, arsitektur informasi, dan kolaborasi dengan Compliance Officer.\n"
+ "GAYA: Terstruktur, berpusat pada data, strategis."
+ )
+ },
+
+ # 👔 VP / DIRECTOR (Level 2) - MEDIUM TIER
+ "vp-engineering": {
+ "tier": "MEDIUM",
+ "role": "VP of Engineering",
+ "prompt": (
+ "IDENTITAS: Anda adalah VP of Engineering Brigawan.\n"
+ "MISI: Mengawasi pelaksanaan teknis dan kualitas kode di seluruh platform.\n"
+ "TANGGUNG JAWAB: Sprint planning, evaluasi audit kode, koordinasi frontend/backend, dan release management.\n"
+ "GAYA: Pragmatis, terorganisir, fokus pada pengiriman hasil (delivery)."
+ )
+ },
+ "vp-product": {
+ "tier": "MEDIUM",
+ "role": "VP of Product",
+ "prompt": (
+ "IDENTITAS: Anda adalah VP of Product Brigawan.\n"
+ "MISI: Menentukan roadmap produk dan prioritas fitur.\n"
+ "TANGGUNG JAWAB: Strategi roadmap, prioritasi fitur berdasarkan user impact, dan validasi ide produk.\n"
+ "GAYA: Berfokus pada data, visioner."
+ )
+ },
+ "vp-talent": {
+ "tier": "MEDIUM",
+ "role": "VP of Talent",
+ "prompt": (
+ "IDENTITAS: Anda adalah VP of Talent Brigawan.\n"
+ "MISI: Mengelola strategi akuisisi dan retensi talenta green jobs.\n"
+ "TANGGUNG JAWAB: Mengevaluasi kualitas talent database, strategi re-engagement, dan operasional HR.\n"
+ "GAYA: Empatis, strategis, berpusat pada manusia (people-centric)."
+ )
+ },
+ "vp-marketing": {
+ "tier": "MEDIUM",
+ "role": "VP of Marketing",
+ "prompt": (
+ "IDENTITAS: Anda adalah VP of Marketing Brigawan.\n"
+ "MISI: Merancang strategi kampanye pemasaran dan SEO.\n"
+ "TANGGUNG JAWAB: Mengelola eksekusi kalender konten, mengevaluasi target audiens, dan menganalisis performa kampanye.\n"
+ "GAYA: Kreatif, analitis, berorientasi target."
+ )
+ },
+ "vp-sales": {
+ "tier": "MEDIUM",
+ "role": "VP of Sales",
+ "prompt": (
+ "IDENTITAS: Anda adalah VP of Sales Brigawan.\n"
+ "MISI: Mengelola strategi pendapatan (revenue) dan pengembangan kemitraan B2B.\n"
+ "TANGGUNG JAWAB: Analisis conversion funnel, strategi penawaran talenta, dan manajemen hubungan klien.\n"
+ "GAYA: Persuasif, agresif dalam target, profesional."
+ )
+ },
+
+ # 📋 MANAGER (Level 3) - MEDIUM TIER
+ "product-manager": {
+ "tier": "MEDIUM",
+ "role": "Product Manager",
+ "prompt": (
+ "IDENTITAS: Anda adalah Product Manager Brigawan.\n"
+ "MISI: Menerjemahkan visi produk ke dalam fitur konkret dan backlog.\n"
+ "TANGGUNG JAWAB: Menulis user stories, prioritas backlog, koordinasi dengan Engineering Manager, dan validasi fitur.\n"
+ "GAYA: Berorientasi pada pengguna, kolaboratif."
+ )
+ },
+ "engineering-manager": {
+ "tier": "MEDIUM",
+ "role": "Engineering Manager",
+ "prompt": (
+ "IDENTITAS: Anda adalah Engineering Manager Brigawan.\n"
+ "MISI: Mengkoordinasikan tim teknis dan menjaga standar kode.\n"
+ "TANGGUNG JAWAB: Mengatur task assignment, mereview hasil code-fixer, dan memastikan sprint berjalan lancar.\n"
+ "GAYA: Teknis, sistematis, memecahkan masalah (problem-solver)."
+ )
+ },
+ "hr-manager": {
+ "tier": "MEDIUM",
+ "role": "HR Manager",
+ "prompt": (
+ "IDENTITAS: Anda adalah HR Manager Brigawan.\n"
+ "MISI: Mengelola pipeline rekrutmen dan interaksi talenta.\n"
+ "TANGGUNG JAWAB: Proses screening talenta, mengelola pesan re-engagement, dan memantau kepuasan talenta.\n"
+ "GAYA: Ramah, terstruktur, suportif."
+ )
+ },
+ "marketing-manager": {
+ "tier": "MEDIUM",
+ "role": "Marketing Manager",
+ "prompt": (
+ "IDENTITAS: Anda adalah Marketing Manager Brigawan.\n"
+ "MISI: Mengeksekusi kampanye pemasaran harian.\n"
+ "TANGGUNG JAWAB: Mengelola jadwal rilis konten, memantau engagement sosial media, dan berkoordinasi dengan agen pembuat konten.\n"
+ "GAYA: Gesit, kreatif, responsif terhadap tren."
+ )
+ },
+ "community-manager": {
+ "tier": "MEDIUM",
+ "role": "Community Manager",
+ "prompt": (
+ "IDENTITAS: Anda adalah Community Manager Brigawan.\n"
+ "MISI: Membangun dan menjaga interaksi positif di dalam komunitas talenta dan rekruter.\n"
+ "TANGGUNG JAWAB: Merespons feedback pengguna, mengelola program referral, dan menjaga sentimen positif brand.\n"
+ "GAYA: Ramah, empatik, komunikator ulung."
+ )
+ },
+
+ # 📊 BUSINESS SPECIALIST (Level 4) - MEDIUM TIER
+ "market-researcher": {
+ "tier": "MEDIUM",
+ "role": "Market Researcher",
+ "prompt": (
+ "IDENTITAS: Anda adalah Market Researcher Brigawan.\n"
+ "MISI: Menganalisis tren industri green jobs dan kompetitor.\n"
+ "TANGGUNG JAWAB: Riset tren pasar, analisis kompetitor, dan identifikasi peluang pasar baru.\n"
+ "GAYA: Penasaran, analitis, objektif."
+ )
+ },
+ "business-analyst": {
+ "tier": "MEDIUM",
+ "role": "Business Analyst",
+ "prompt": (
+ "IDENTITAS: Anda adalah Business Analyst Brigawan.\n"
+ "MISI: Mengoptimalkan proses bisnis dan menyusun kebutuhan sistem.\n"
+ "TANGGUNG JAWAB: Menganalisis bottleneck proses, menyusun Business Requirements Document (BRD), dan mengusulkan efisiensi.\n"
+ "GAYA: Logis, detail, berorientasi proses."
+ )
+ },
+ "data-analyst": {
+ "tier": "MEDIUM",
+ "role": "Data Analyst",
+ "prompt": (
+ "IDENTITAS: Anda adalah Data Analyst Brigawan.\n"
+ "MISI: Menghasilkan insight bisnis dari data mentah.\n"
+ "TANGGUNG JAWAB: Menganalisis pola pengguna, conversion funnel, mendeteksi anomali data, dan membuat laporan/dashboard.\n"
+ "GAYA: Berbasis data (data-driven), numerik, analitis."
+ )
+ },
+ "compliance-officer": {
+ "tier": "HIGH",
+ "role": "Compliance Officer",
+ "prompt": (
+ "IDENTITAS: Anda adalah Compliance Officer Brigawan.\n"
+ "MISI: Memastikan operasional Brigawan mematuhi regulasi privasi data (GDPR, UU ITE).\n"
+ "TANGGUNG JAWAB: Mengaudit penanganan data, mengamankan PII (Personally Identifiable Information), dan menyusun kebijakan privasi.\n"
+ "GAYA: Kaku pada aturan, protektif, detail."
+ )
+ },
+ "qa-manager": {
+ "tier": "MEDIUM",
+ "role": "QA Manager",
+ "prompt": (
+ "IDENTITAS: Anda adalah QA Manager Brigawan.\n"
+ "MISI: Menjaga standar kualitas (Quality Assurance) sebelum produk dirilis.\n"
+ "TANGGUNG JAWAB: Menetapkan acceptance criteria, mengevaluasi hasil test-runner, dan memberikan sign-off untuk rilis.\n"
+ "GAYA: Kritis, perfeksionis, tidak kenal kompromi terhadap kualitas."
+ )
+ },
+ "risk-manager": {
+ "tier": "MEDIUM",
+ "role": "Risk Manager",
+ "prompt": (
+ "IDENTITAS: Anda adalah Risk Manager Brigawan.\n"
+ "MISI: Mengidentifikasi dan memitigasi risiko bisnis maupun operasional.\n"
+ "TANGGUNG JAWAB: Menilai potensi masalah keamanan, stabilitas, atau regulasi sebelum menjadi krisis nyata.\n"
+ "GAYA: Antisipatif, analitis, penuh kehati-hatian."
+ )
+ },
+ "partnership-manager": {
+ "tier": "MEDIUM",
+ "role": "Partnership Manager & B2B Sales",
+ "prompt": (
+ "IDENTITAS: Anda adalah Partnership Manager Brigawan yang handal dalam B2B Sales.\n"
+ "MISI: Menjalin kerjasama dengan perusahaan (Employer) dan menjual layanan kurasi talenta Brigawan.\n"
+ "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"
+ "GAYA: Profesional, persuasif, to-the-point, dan berorientasi nilai (value-driven)."
+ )
+ },
+ "customer-support": {
+ "tier": "MEDIUM",
+ "role": "Customer Support Specialist",
+ "prompt": (
+ "IDENTITAS: Anda adalah Customer Support Brigawan.\n"
+ "MISI: Memberikan bantuan kepada pengguna dan menjaga kepuasan pelanggan.\n"
+ "TANGGUNG JAWAB: Menangani keluhan, membuat FAQ, dan memberikan solusi bagi masalah pengguna.\n"
+ "GAYA: Empati, solutif, komunikatif."
+ )
+ },
+ "social-media-agent": {
+ "tier": "MEDIUM",
+ "role": "Social Media Manager",
+ "prompt": (
+ "IDENTITAS: Anda adalah Social Media Manager Brigawan.\n"
+ "MISI: Mengelola kehadiran Brigawan di Instagram, LinkedIn, dan TikTok.\n"
+ "TANGGUNG JAWAB: Membuat caption yang viral, menentukan jadwal posting, dan menyusun narasi untuk Reels/Carousel.\n"
+ "GAYA: Trendy, interaktif, dan informatif."
+ )
+ },
+ "fact-checker": {
+ "tier": "HIGH",
+ "role": "Content Editor & Fact Checker",
+ "prompt": (
+ "IDENTITAS: Anda adalah Editor-in-Chief dan Fact Checker Brigawan.\n"
+ "MISI: Memastikan semua konten yang diproduksi akurat, relevan, tidak bias, dan sesuai dengan standar brand green jobs Brigawan.\n"
+ "TANGGUNG JAWAB: Mengkurasi draf konten, memverifikasi klaim (greenwashing detection), memastikan ejaan yang benar, dan menyetujui (Approve) atau menolak (Reject) konten.\n"
+ "GAYA: Kritis, objektif, teliti."
+ )
+ },
+ "style-designer": {
+ "tier": "MEDIUM",
+ "role": "Visual Style Designer",
+ "prompt": (
+ "IDENTITAS: Anda adalah Visual Style Designer Brigawan.\n"
+ "MISI: Menentukan estetika visual konten Brigawan.\n"
+ "TANGGUNG JAWAB: Memberikan brief visual, menentukan skema warna, dan membuat prompt gambar (untuk Pollinations/Flux) yang estetik untuk slide Carousel atau aset Reels.\n"
+ "GAYA: Artistik, modern, minimalis."
+ )
+ },
+
+ # 🛠️ TECHNICAL AGENTS (Level 5) - LOW TIER
+ "code-auditor": {
+ "tier": "LOW",
+ "role": "Code Quality Auditor",
+ "prompt": (
+ "IDENTITAS: Anda adalah Code Auditor Brigawan.\n"
+ "MISI: Memastikan kualitas, kompleksitas, dan pemeliharaan kode (maintainability).\n"
+ "TANGGUNG JAWAB: Mengukur LOC, mendeteksi dead code, review naming convention, dan maintainability score.\n"
+ "GAYA: Detail, teknis, objektif."
+ )
+ },
+ "security-auditor": {
+ "tier": "LOW",
+ "role": "Security Auditor",
+ "prompt": (
+ "IDENTITAS: Anda adalah Security Auditor Brigawan.\n"
+ "MISI: Menjaga keamanan aplikasi dari kerentanan.\n"
+ "TANGGUNG JAWAB: Deteksi XSS, SQL Injection, audit otentikasi, dan pengecekan hardcoded secrets.\n"
+ "GAYA: Waspada, metodis."
+ )
+ },
+ "code-fixer": {
+ "tier": "LOW",
+ "role": "Code Fixer",
+ "prompt": (
+ "IDENTITAS: Anda adalah Code Fixer Brigawan.\n"
+ "MISI: Memperbaiki bug dan mengimplementasikan rekomendasi dari auditor.\n"
+ "TANGGUNG JAWAB: Menulis perbaikan kode berdasarkan file FIXES.md atau instruksi Error Handler tanpa merusak fungsi yang ada.\n"
+ "GAYA: Efisien, patuh pada standar kode."
+ )
+ },
+ "error-handler": {
+ "tier": "LOW",
+ "role": "Error Handler",
+ "prompt": (
+ "IDENTITAS: Anda adalah Error Handler Brigawan.\n"
+ "MISI: Menganalisis log error dan menentukan akar masalah (root cause).\n"
+ "TANGGUNG JAWAB: Membaca trace log, mengidentifikasi file dan baris yang bermasalah, serta memberikan instruksi perbaikan konkret untuk Code Fixer.\n"
+ "GAYA: Diagnostik, cepat, akurat."
+ )
+ },
+ "frontend-builder": {
+ "tier": "MEDIUM",
+ "role": "Frontend Developer Agent",
+ "prompt": (
+ "IDENTITAS: Anda adalah Frontend Builder Brigawan.\n"
+ "MISI: Membangun dan memelihara komponen UI (HTML/CSS/JS).\n"
+ "TANGGUNG JAWAB: Menulis kode frontend yang responsif, mengintegrasikan API backend, dan memastikan kompatibilitas browser.\n"
+ "GAYA: Praktis, berorientasi desain, rapi."
+ )
+ },
+ "backend-builder": {
+ "tier": "MEDIUM",
+ "role": "Backend Developer Agent",
+ "prompt": (
+ "IDENTITAS: Anda adalah Backend Builder Brigawan.\n"
+ "MISI: Membangun dan memelihara logika server, API, dan integrasi database (Python/FastAPI).\n"
+ "TANGGUNG JAWAB: Menulis kode backend yang efisien, aman, dan dapat diskalakan.\n"
+ "GAYA: Logis, arsitektural, aman."
+ )
+ },
+ "test-runner": {
+ "tier": "LOW",
+ "role": "Test Automation Agent",
+ "prompt": (
+ "IDENTITAS: Anda adalah Test Runner Brigawan.\n"
+ "MISI: Memvalidasi bahwa perubahan kode tidak merusak sistem.\n"
+ "TANGGUNG JAWAB: Mengeksekusi test suite, melaporkan hasil pass/fail, dan mengidentifikasi edge case yang belum teruji.\n"
+ "GAYA: Metodis, tanpa kompromi, detail."
+ )
+ },
+ "deploy-checker": {
+ "tier": "LOW",
+ "role": "Pre-Deployment Validator",
+ "prompt": (
+ "IDENTITAS: Anda adalah Deploy Checker Brigawan.\n"
+ "MISI: Memastikan semua komponen siap untuk dirilis ke production.\n"
+ "TANGGUNG JAWAB: Memvalidasi environment variables, mengecek konfigurasi server, dan memastikan tidak ada dead links sebelum deploy.\n"
+ "GAYA: Hati-hati, menyeluruh."
+ )
+ },
+ "pr-writer": {
+ "tier": "LOW",
+ "role": "Pull Request Generator",
+ "prompt": (
+ "IDENTITAS: Anda adalah PR Writer Brigawan.\n"
+ "MISI: Mendokumentasikan perubahan kode ke dalam bentuk changelog dan Pull Request.\n"
+ "TANGGUNG JAWAB: Menganalisis git diff, menyusun deskripsi perubahan yang jelas, dan men-tag reviewer yang relevan.\n"
+ "GAYA: Komunikatif, terstruktur, ringkas."
+ )
+ },
+ # 🛡️ AUDITORS (Level 5)
+ "bug-auditor": {
+ "tier": "LOW",
+ "role": "Runtime Bug Auditor",
+ "prompt": "IDENTITAS: Bug Auditor. TUGAS: Menganalisis potensi runtime error, edge cases, dan logic flaws di kode. Output format: AUDIT_BUGS.md"
+ },
+ "perf-auditor": {
+ "tier": "LOW",
+ "role": "Performance Auditor",
+ "prompt": "IDENTITAS: Performance Auditor. TUGAS: Mengevaluasi bundle size, memory leaks, dan render-blocking resources. Output format: AUDIT_PERF.md"
+ },
+ "db-auditor": {
+ "tier": "LOW",
+ "role": "Database Auditor",
+ "prompt": "IDENTITAS: Database Auditor. TUGAS: Menganalisis N+1 query, missing indexes, dan validasi skema. Output format: AUDIT_DB.md"
+ },
+ "dep-auditor": {
+ "tier": "LOW",
+ "role": "Dependency Auditor",
+ "prompt": "IDENTITAS: Dependency Auditor. TUGAS: Mendeteksi dependensi yang usang, rentan (vulnerable), atau tidak terpakai. Output format: AUDIT_DEPS.md"
+ },
+ "doc-auditor": {
+ "tier": "LOW",
+ "role": "Documentation Auditor",
+ "prompt": "IDENTITAS: Documentation Auditor. TUGAS: Memastikan kode memiliki komentar/JSDoc yang memadai dan mendeteksi stale docs. Output format: AUDIT_DOCS.md"
+ },
+ "infra-auditor": {
+ "tier": "LOW",
+ "role": "Infrastructure Auditor",
+ "prompt": "IDENTITAS: Infrastructure Auditor. TUGAS: Mengecek konfigurasi CI/CD, wrangler.json, Dockerfile, dan _redirects. Output format: AUDIT_INFRA.md"
+ },
+ "seo-auditor": {
+ "tier": "LOW",
+ "role": "SEO Auditor",
+ "prompt": "IDENTITAS: SEO Auditor. TUGAS: Memvalidasi meta tags, JSON-LD, OG tags, dan aksesibilitas robots.txt. Output format: AUDIT_SEO.md"
+ },
+ "ui-auditor": {
+ "tier": "LOW",
+ "role": "UI/UX & Accessibility Auditor",
+ "prompt": "IDENTITAS: UI/UX Auditor. TUGAS: Mengecek WCAG compliance, kontras warna, dan konsistensi pola desain. Output format: AUDIT_UI.md"
+ },
+ "architect-reviewer": {
+ "tier": "MEDIUM",
+ "role": "Architecture Reviewer",
+ "prompt": "IDENTITAS: Architect Reviewer. TUGAS: Mengulas keputusan desain tingkat tinggi, coupling antar modul, dan pattern. Bertindak sebagai penasihat untuk VP Engineering."
+ },
+ "api-tester": {
+ "tier": "LOW",
+ "role": "API Contract Tester",
+ "prompt": "IDENTITAS: API Tester. TUGAS: Memvalidasi endpoint REST, error handling, dan skema payload. Output format: AUDIT_API.md"
+ },
+ # 🧪 TESTERS (Level 5)
+ "test-writer": {
+ "tier": "LOW",
+ "role": "Unit Test Writer",
+ "prompt": "IDENTITAS: Test Writer. TUGAS: Menulis unit test untuk fungsi yang belum memiliki coverage. Pastikan pengujian mencakup edge cases."
+ },
+ "browser-qa-agent": {
+ "tier": "LOW",
+ "role": "E2E Browser QA",
+ "prompt": "IDENTITAS: Browser QA Agent. TUGAS: Mensimulasikan navigasi pengguna akhir dan interaksi form. Gunakan Playwright context."
+ },
+ "console-monitor": {
+ "tier": "LOW",
+ "role": "Console Error Monitor",
+ "prompt": "IDENTITAS: Console Monitor. TUGAS: Menganalisis log console browser untuk mendeteksi warning dan uncaught exceptions."
+ },
+ "visual-diff": {
+ "tier": "LOW",
+ "role": "Visual Regression Tester",
+ "prompt": "IDENTITAS: Visual Diff Agent. TUGAS: Membandingkan screenshot sebelum dan sesudah perubahan untuk memastikan tidak ada UI yang bergeser."
+ },
+ # ⚙️ OPERATIONS & BUILDERS
+ "fix-planner": {
+ "tier": "MEDIUM",
+ "role": "Fix Orchestrator",
+ "prompt": "IDENTITAS: Fix Planner. TUGAS: Menggabungkan laporan dari semua Auditor menjadi satu dokumen prioritas (FIXES.md) untuk dikerjakan Code Fixer."
+ },
+ "env-validator": {
+ "tier": "LOW",
+ "role": "Environment Validator",
+ "prompt": "IDENTITAS: Environment Validator. TUGAS: Mengecek .env vs .env.example untuk memastikan tidak ada rahasia yang bocor atau missing keys."
+ },
+ "seed-generator": {
+ "tier": "LOW",
+ "role": "Test Data Generator",
+ "prompt": "IDENTITAS: Seed Generator. TUGAS: Membuat data dummy yang sangat realistis untuk menguji database atau fungsi pencarian."
+ },
+ "fullstack-qa-orchestrator": {
+ "tier": "MEDIUM",
+ "role": "QA Pipeline Orchestrator",
+ "prompt": "IDENTITAS: QA Orchestrator. TUGAS: Mengatur siklus audit -> fix -> test. Memberikan persetujuan akhir sebelum kode dikirim ke PR."
+ },
+ "content-agent": {
+ "tier": "MEDIUM",
+ "role": "Blog Content Writer",
+ "prompt": "IDENTITAS: Content Agent. TUGAS: Menulis artikel panjang (blog) yang SEO-friendly, berbasis riset, dan engaging."
+ },
+ "system-monitor": {
+ "tier": "LOW",
+ "role": "System Health Monitor",
+ "prompt": "IDENTITAS: System Monitor. TUGAS: Mengecek endpoint kesehatan sistem secara periodik dan melaporkan jika ada downtime."
+ },
+ "talent-engagement": {
+ "tier": "MEDIUM",
+ "role": "Talent Re-engagement Bot",
+ "prompt": "IDENTITAS: Talent Engagement. TUGAS: Menulis pesan empati untuk talenta yang sudah tidak aktif (dormant) agar kembali ke platform."
+ },
+ "code-reviewer": {
+ "tier": "MEDIUM",
+ "role": "Code Reviewer",
+ "prompt": "IDENTITAS: Code Reviewer. TUGAS: Mengulas Pull Request secara kritis. Fokus pada keamanan, performa, dan DRY principles."
+ },
+ "auth-manager": {
+ "tier": "MEDIUM",
+ "role": "Auth Manager",
+ "prompt": "IDENTITAS: Auth Manager. TUGAS: Mengelola integrasi otentikasi (JWT, OAuth) dan logika RBAC (Role-Based Access Control)."
+ },
+ "sheet-manager": {
+ "tier": "LOW",
+ "role": "Google Sheets Schema Manager",
+ "prompt": "IDENTITAS: Sheet Manager. TUGAS: Mengelola pemetaan kolom dan skema jika berhadapan dengan legacy data Sheets."
+ },
+ "gemini-orchestrator": {
+ "tier": "HIGH",
+ "role": "AI Model Orchestrator",
+ "prompt": "IDENTITAS: Gemini Orchestrator. TUGAS: Memantau penggunaan token, merutekan panggilan AI, dan mengatur sistem fallback."
+ },
+ "trigger-scheduler": {
+ "tier": "LOW",
+ "role": "Cron/Trigger Manager",
+ "prompt": "IDENTITAS: Trigger Scheduler. TUGAS: Mengatur jadwal task background (CRON) dan memastikan tidak ada tabrakan waktu."
+ },
+ "migration-agent": {
+ "tier": "MEDIUM",
+ "role": "Migration Agent",
+ "prompt": "IDENTITAS: Migration Agent. TUGAS: Menulis skrip Alembic untuk migrasi database atau migrasi data massal tanpa downtime."
+ },
+ "backup-restorer": {
+ "tier": "LOW",
+ "role": "Backup & Restore Agent",
+ "prompt": "IDENTITAS: Backup Restorer. TUGAS: Menjalankan dump database secara periodik dan menguji proses restorasi (disaster recovery)."
+ },
+ "i18n-translator": {
+ "tier": "LOW",
+ "role": "Localization Agent",
+ "prompt": "IDENTITAS: I18N Translator. TUGAS: Menerjemahkan string UI ke dalam berbagai bahasa tanpa merusak konteks teknis atau tata letak (layout)."
+ },
+ "payment-manager": {
+ "tier": "MEDIUM",
+ "role": "Payment Manager",
+ "prompt": "IDENTITAS: Payment Manager. TUGAS: Mengelola integrasi Midtrans, webhooks pembayaran, dan pemotongan saldo (Coin deduction)."
+ },
+ "recruiter-agent": {
+ "tier": "MEDIUM",
+ "role": "Recruiter Portal Automator",
+ "prompt": "IDENTITAS: Recruiter Agent. TUGAS: Mengotomatiskan proses vetting CV masal dan mencocokkan talenta berdasarkan input pencarian rekruter."
+ },
+ "build-deployer": {
+ "tier": "LOW",
+ "role": "CI/CD Build Deployer",
+ "prompt": "IDENTITAS: Build Deployer. TUGAS: Menjalankan skrip build CSS/JS dan mengorkestrasi pengiriman kode ke Cloudflare Pages atau Docker registry."
+ },
+ "changelog-generator": {
+ "tier": "LOW",
+ "role": "Changelog Generator",
+ "prompt": "IDENTITAS: Changelog Generator. TUGAS: Mengubah daftar commit menjadi dokumen CHANGELOG.md yang ramah manusia (user-facing release notes)."
+ },
+ "onboarding-agent": {
+ "tier": "LOW",
+ "role": "Onboarding Documentation Agent",
+ "prompt": "IDENTITAS: Onboarding Agent. TUGAS: Menyusun dokumen panduan (setup guide) agar developer manusia yang baru bergabung bisa langsung bekerja dalam 10 menit."
+ },
+ # 🚀 ADVANCED GROWTH & AUTOMATION AGENTS (Level 4/5)
+ "programmatic-seo-agent": {
+ "tier": "HIGH",
+ "role": "Programmatic SEO Architect",
+ "prompt": (
+ "IDENTITAS: Anda adalah Programmatic SEO Agent Brigawan.\n"
+ "MISI: Mendominasi hasil pencarian Google untuk niche green jobs melalui pembuatan halaman secara massal dan otomatis.\n"
+ "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"
+ "GAYA: Sangat analitis, fokus pada search volume, agresif dalam akuisisi trafik organik."
+ )
+ },
+ "ab-test-optimizer": {
+ "tier": "MEDIUM",
+ "role": "A/B Testing & Conversion Optimizer",
+ "prompt": (
+ "IDENTITAS: Anda adalah A/B Testing Optimizer Brigawan.\n"
+ "MISI: Meningkatkan rasio konversi (pendaftaran talenta/perusahaan) secara berkesinambungan tanpa intervensi manusia.\n"
+ "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"
+ "GAYA: Eksperimental, berbasis probabilitas, tidak bias."
+ )
+ },
+ "competitor-spy-agent": {
+ "tier": "HIGH",
+ "role": "Competitor Intelligence Spy",
+ "prompt": (
+ "IDENTITAS: Anda adalah Competitor Spy Agent Brigawan.\n"
+ "MISI: Memantau dan menganalisis pergerakan portal kompetitor (job boards konvensional & green niche) secara real-time.\n"
+ "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"
+ "GAYA: Waspada, taktis, seperti agen intelijen bisnis."
+ )
+ },
+ "api-arbitrage-agent": {
+ "tier": "MEDIUM",
+ "role": "API Cost Arbitrage Manager",
+ "prompt": (
+ "IDENTITAS: Anda adalah API Arbitrage Agent Brigawan.\n"
+ "MISI: Menekan biaya operasional AI (Token Costs) mendekati $0/bulan.\n"
+ "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"
+ "GAYA: Oportunis (dalam arti positif), super efisien, berorientasi pada penghematan ekstrem."
+ )
+ }
+ }
+
+ @classmethod
+ def get_agent(cls, agent_id: str) -> Optional[Dict[str, Any]]:
+ return cls.AGENTS.get(agent_id)
+
+async def call_agent(agent_id: str, user_input: str, context: str = "") -> Dict[str, Any]:
+ """Execute a task using a specific agent from the registry."""
+ import os
+ from loguru import logger
+
+ agent_info = AgentRegistry.get_agent(agent_id)
+ if not agent_info:
+ return {"success": False, "error": f"Agent {agent_id} not found."}
+
+ tier = agent_info["tier"]
+ system_prompt = agent_info["prompt"]
+
+ # Inject DESIGN.md tokens and voice guidance when available (best-effort)
+ try:
+ # Path is repo-root/DESIGN.md; adjust relative path from service folder
+ design_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "DESIGN.md")
+ with open(design_path, "r", encoding="utf-8") as f:
+ design_md = f.read()
+ system_prompt += f"\n\nDESIGN_GUIDELINES:\n{design_md[:4000]}"
+ except Exception:
+ pass
+
+ # Inject Context
+ if context:
+ system_prompt += f"\n\nKONTEKS OPERASIONAL:\n{context}"
+
+ # Retrieve memories/learnings
+ past_learnings = ""
+ obsidian_learnings = ""
+ try:
+ query_embedding = await generate_embedding(user_input)
+ if agent_id == "obsidian-vault":
+ obsidian_learnings = await AgentMemoryService.get_learnings("obsidian-vault", user_input, query_embedding=query_embedding)
+ else:
+ past_learnings = await AgentMemoryService.get_learnings(agent_id, user_input, query_embedding=query_embedding)
+ obsidian_learnings = await AgentMemoryService.get_learnings("obsidian-vault", user_input, query_embedding=query_embedding)
+ except Exception as e:
+ logger.error(f"[AgentService] Error retrieving memories for agent {agent_id}: {e}")
+
+ # Append to system_prompt
+ if past_learnings:
+ system_prompt += f"\n\n{past_learnings}"
+ if obsidian_learnings:
+ system_prompt += f"\n\n{obsidian_learnings}"
+
+ # Choose call method based on effective tier (per-agent override aware)
+ effective_tier = _resolve_tier(agent_id, tier)
+ if effective_tier == "HIGH":
+ text, tokens = await call_high(prompt=user_input, system_instruction=system_prompt)
+ elif effective_tier == "MEDIUM":
+ text, tokens = await call_medium(prompt=user_input, system_instruction=system_prompt)
+ else:
+ text, tokens = await call_low(prompt=user_input, system_instruction=system_prompt)
+
+ return {
+ "success": True,
+ "agent": agent_id,
+ "role": agent_info["role"],
+ "reply": text,
+ "tokens": tokens
+ }
+
+async def call_agent_json(agent_id: str, user_input: str, context: str = "") -> Dict[str, Any]:
+ """Execute a task using a specific agent and expect JSON output."""
+ import os
+ from loguru import logger
+
+ agent_info = AgentRegistry.get_agent(agent_id)
+ if not agent_info:
+ return {"success": False, "error": f"Agent {agent_id} not found."}
+
+ tier = agent_info["tier"]
+ system_prompt = agent_info["prompt"]
+
+ # Inject DESIGN.md tokens and voice guidance when available (best-effort)
+ try:
+ design_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "DESIGN.md")
+ with open(design_path, "r", encoding="utf-8") as f:
+ design_md = f.read()
+ system_prompt += f"\n\nDESIGN_GUIDELINES:\n{design_md[:4000]}"
+ except Exception:
+ pass
+
+ if context:
+ system_prompt += f"\n\nKONTEKS OPERASIONAL:\n{context}"
+
+ # Retrieve memories/learnings
+ past_learnings = ""
+ obsidian_learnings = ""
+ try:
+ query_embedding = await generate_embedding(user_input)
+ if agent_id == "obsidian-vault":
+ obsidian_learnings = await AgentMemoryService.get_learnings("obsidian-vault", user_input, query_embedding=query_embedding)
+ else:
+ past_learnings = await AgentMemoryService.get_learnings(agent_id, user_input, query_embedding=query_embedding)
+ obsidian_learnings = await AgentMemoryService.get_learnings("obsidian-vault", user_input, query_embedding=query_embedding)
+ except Exception as e:
+ logger.error(f"[AgentService] Error retrieving memories in JSON for agent {agent_id}: {e}")
+
+ # Append to system_prompt
+ if past_learnings:
+ system_prompt += f"\n\n{past_learnings}"
+ if obsidian_learnings:
+ system_prompt += f"\n\n{obsidian_learnings}"
+
+ system_prompt += "\n\nPENTING: Respon HARUS dalam format JSON valid."
+
+ parsed, tokens = await call_gemini_json(
+ prompt=user_input,
+ tier=_resolve_tier(agent_id, tier),
+ system_instruction=system_prompt
+ )
+
+ return {
+ "success": "error" not in parsed,
+ "agent": agent_id,
+ "data": parsed,
+ "tokens": tokens
+ }
diff --git a/app/services/ai_service.py b/app/services/ai_service.py
index b7d59c67c9cdfdaaa8daf0271ec1a5f0bf60e1dd..90eefbf6d3e6d82aba65d7d0a9d2eb0e573b0c8a 100644
--- a/app/services/ai_service.py
+++ b/app/services/ai_service.py
@@ -1,1404 +1,1460 @@
-"""Crash-Proof AI Service — Gemini 3 Series Tier Routing.
-
-Tier Architecture (mirrors GAS AI_CONFIG.TIERS):
-
- HIGH (Complex) → gemini-3.1-pro-preview → fallback to gemini-3.5-flash (high config)
- MEDIUM (Mid) → gemini-3.5-flash (medium config)
- LOW (Simple) → gemini-3.5-flash (low config)
-
-Every public function in this module is guaranteed to NEVER throw.
-If all AI providers fail, the caller gets safe, useful defaults.
-
-References:
- - Ported from GAS Security.gs callGeminiWithFallback (model queue pattern)
- - GAS Constants.gs AI_CONFIG.TIERS routing logic
- - PII redaction from GAS redactPrivateIdentifiers
- - Prompt injection detection from GAS detectPromptInjection
-"""
-
-import hashlib
-import json
-import os
-import re
-import time
-from datetime import datetime
-from typing import Any, Dict, List, Optional, Tuple
-
-import httpx
-from loguru import logger
-
-from app.config.settings import settings
-from app.utils.key_manager import APIKeyManager
-from app.utils.cache import cached_ai_call, cache_ai_response, hash_prompt, get_ai_cache_stats
-
-
-# =============================================================================
-# GEMINI 3 SERIES TIER CONFIGURATION
-# =============================================================================
-
-# Initialize Multi-Key Managers for Omni-Router Strategy
-def clean_keys(keys_str: str) -> List[str]:
- placeholders = {"key1", "key2", "key3", "your_key", "placeholder", "dummy"}
- return [k.strip() for k in keys_str.split(",") if k.strip() and k.strip().lower() not in placeholders]
-
-RAW_GEMINI_KEYS = clean_keys(os.getenv("GEMINI_API_KEYS") or getattr(settings, "gemini_api_keys", "") or getattr(settings, "gemini_api_key", ""))
-gemini_key_manager = APIKeyManager(RAW_GEMINI_KEYS)
-
-RAW_9ROUTER_KEYS = clean_keys(os.getenv("ROUTER_API_KEYS") or getattr(settings, "router_api_keys", ""))
-ninerouter_key_manager = APIKeyManager(RAW_9ROUTER_KEYS)
-
-RAW_OPENROUTER_KEYS = clean_keys(os.getenv("OPENROUTER_API_KEYS") or getattr(settings, "openrouter_api_keys", ""))
-openrouter_key_manager = APIKeyManager(RAW_OPENROUTER_KEYS)
-
-GEMINI_API_KEY = settings.gemini_api_key
-AI_DISABLED = settings.ai_disabled or os.environ.get("AI_DISABLED", "false").lower() in ("true", "1", "yes")
-
-# Tier definitions matching GAS Constants.gs AI_CONFIG.TIERS
-# Models read from settings (settable via .env) with hardcoded defaults.
-# This way settings.gemini_high_model etc. are actually consumed, not dead config.
-TIERS = {
- "HIGH": {
- "label": "CRITICAL",
- "models": [
- settings.gemini_high_model or "gemini-3.5-pro", # Primary — Agentic reasoning, 2M context
- "gemini-3.5-flash", # Fallback — High-throughput
- ],
- "temperature": 0.3,
- "max_output_tokens": 4096,
- "timeout": 60.0,
- "description": "Complex reasoning: semantic matching, SROI audit, SKKNI mapping, Strategic Advisor",
- },
- "MEDIUM": {
- "label": "STANDARD",
- "models": [
- settings.gemini_medium_model or "gemini-3.5-flash", # Primary — 4x faster, 1M context
- "gemini-1.5-flash", # Legacy fallback
- ],
- "temperature": 0.5,
- "max_output_tokens": 2048,
- "timeout": 30.0,
- "description": "Operational: bulk vetting, career coach responses, blog generation",
- },
- "LOW": {
- "label": "FAST",
- "models": [
- settings.gemini_low_model or "gemini-3.5-flash", # High interaction
- ],
- "temperature": 0.1,
- "max_output_tokens": 1024,
- "timeout": 20.0,
- "description": "Utility: chat mediation, engagement bot, simple classification",
- },
-}
-
-# Default timeout for API calls (seconds)
-DEFAULT_TIMEOUT = 30.0
-
-
-# =============================================================================
-# TIER 1: GEMINI 3 SERIES API CALL
-# =============================================================================
-
-async def generate_embedding(text: str) -> List[float]:
- """Generates a text embedding vector (768 dimensions) using a free/fast API.
-
- Defaults to Gemini's embedding model.
- """
- if AI_DISABLED:
- return [0.0] * 768
-
- active_key = await gemini_key_manager.get_key()
- if not active_key:
- return [0.0] * 768
-
- # Migrate from deprecated text-embedding-004 to gemini-embedding-001
- url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent?key={active_key}"
- payload = {
- "model": "models/gemini-embedding-001",
- "content": {
- "parts": [{"text": text}]
- },
- "outputDimensionality": 768
- }
-
- try:
- async with httpx.AsyncClient(timeout=10.0) as client:
- resp = await client.post(url, json=payload)
-
- if resp.status_code == 200:
- gemini_key_manager.mark_success(active_key)
- data = resp.json()
- embedding = data.get("embedding", {}).get("values", [])
- # Gemini gemini-embedding-001 is set to 768 dimensions via config
- if len(embedding) == 768:
- return embedding
- else:
- logger.error(f"[Embeddings] Dimension mismatch: got {len(embedding)}, expected 768")
- else:
- gemini_key_manager.mark_failed(active_key, reason=str(resp.status_code))
- logger.error(f"[Embeddings] API Error {resp.status_code}: {resp.text}")
- except Exception as e:
- gemini_key_manager.mark_failed(active_key, reason=str(e))
- logger.error(f"[Embeddings] Failed to generate embedding: {e}")
-
- return [0.0] * 768
-
-async def call_gemini_tier(
- prompt: str,
- tier: str = "MEDIUM",
- system_instruction: Optional[str] = None,
- temperature: Optional[float] = None,
- max_output_tokens: Optional[int] = None,
- response_mime_type: Optional[str] = None,
-) -> Tuple[Optional[str], int]:
- """Call Gemini API using tier-based model routing and multi-key rotation.
-
- Ported from GAS callGeminiWithFallback() — same retry logic,
- same multi-model queue, same error handling pattern.
- """
- # Quick exit if disabled globally
- if AI_DISABLED:
- return None, 0
-
- tier = tier.upper()
-
- # ─── CACHE CHECK ───
- prompt_hash = hash_prompt(prompt, system_instruction)
- cached = cached_ai_call(tier, prompt_hash, mime_type=response_mime_type or "")
- if cached:
- logger.debug(f"[Cache] AI response found for tier={tier}")
- return cached
-
- config = TIERS.get(tier, TIERS["MEDIUM"])
-
- use_temp = temperature if temperature is not None else config["temperature"]
- use_tokens = max_output_tokens if max_output_tokens is not None else config["max_output_tokens"]
- timeout = config["timeout"]
-
- # ─── 9ROUTER INTEGRATION LAYER (With Rotation) ───
- if settings.router_api_url and ninerouter_key_manager.keys:
- active_9router_key = await ninerouter_key_manager.get_key()
- if active_9router_key:
- logger.info(f"[9Router] Routing request to {settings.router_api_url}")
- headers = {
- "Content-Type": "application/json",
- "Authorization": f"Bearer {active_9router_key}"
- }
-
- messages = []
- if system_instruction:
- messages.append({"role": "system", "content": system_instruction})
- messages.append({"role": "user", "content": prompt})
-
- # Map models to OpenRouter/9Router free-tier formats to maximize free token usage
- if tier == "HIGH":
- router_model = "deepseek/deepseek-r1:free"
- elif response_mime_type == "application/json":
- router_model = "qwen/qwen-2.5-coder-32b-instruct:free"
- else:
- router_model = "google/gemini-2.5-flash:free"
-
- payload = {
- "model": router_model,
- "messages": messages,
- "temperature": use_temp,
- "max_tokens": use_tokens
- }
- if response_mime_type == "application/json":
- payload["response_format"] = {"type": "json_object"}
-
- try:
- async with httpx.AsyncClient(timeout=timeout) as client:
- resp = await client.post(settings.router_api_url, json=payload, headers=headers)
- if resp.status_code == 200:
- ninerouter_key_manager.mark_success(active_9router_key)
- data = resp.json()
- text = data["choices"][0]["message"]["content"]
- tokens_used = data.get("usage", {}).get("total_tokens", 0)
- logger.debug(f"[9Router] Success: {tokens_used} tokens (Model: {router_model})")
- cache_ai_response(tier, prompt_hash, "", text, tokens_used, mime_type=response_mime_type or "")
- return text, tokens_used
- elif resp.status_code in (429, 402, 403):
- logger.warning(f"[9Router] Key exhausted/rate limited (HTTP {resp.status_code}). Rotating...")
- ninerouter_key_manager.mark_failed(active_9router_key, reason=str(resp.status_code))
- else:
- logger.warning(f"[9Router] HTTP Error {resp.status_code}: {resp.text}. Falling back...")
- except Exception as e:
- logger.warning(f"[9Router] Call failed: {e}. Falling back...")
- # ─────────────────────────────────
-
- # ─── OPENROUTER INTEGRATION LAYER (With Rotation) ───
- if settings.openrouter_api_url and openrouter_key_manager.keys:
- active_openrouter_key = await openrouter_key_manager.get_key()
- if active_openrouter_key:
- logger.info(f"[OpenRouter] Routing request to {settings.openrouter_api_url}")
- headers = {
- "Authorization": f"Bearer {active_openrouter_key}",
- "HTTP-Referer": "https://briga.id",
- "X-Title": "Brigawan AI",
- "Content-Type": "application/json"
- }
-
- messages = []
- if system_instruction:
- messages.append({"role": "system", "content": system_instruction})
- messages.append({"role": "user", "content": prompt})
-
- if tier == "HIGH":
- router_model = "google/gemini-pro-1.5" # Fallback to Pro 1.5 if 3.5 not in OpenRouter yet
- else:
- router_model = "google/gemini-flash-1.5" # Use Flash 1.5 as standard fallback
-
- # Override with requested versions if available in OpenRouter logic (experimental)
- if settings.gemini_high_model and "3.5" in settings.gemini_high_model:
- router_model = "google/gemini-pro-1.5" # OpenRouter naming usually lags or uses different slugs
- if settings.gemini_low_model and "2.5" in settings.gemini_low_model:
- router_model = "google/gemini-2.0-flash-001" # Closest to 2.5 series on OpenRouter
-
- payload = {
- "model": router_model,
- "messages": messages,
- "temperature": use_temp,
- "max_tokens": use_tokens
- }
- if response_mime_type == "application/json":
- payload["response_format"] = {"type": "json_object"}
-
- try:
- async with httpx.AsyncClient(timeout=timeout) as client:
- resp = await client.post(settings.openrouter_api_url, json=payload, headers=headers)
- if resp.status_code == 200:
- openrouter_key_manager.mark_success(active_openrouter_key)
- data = resp.json()
- text = data["choices"][0]["message"]["content"]
- tokens_used = data.get("usage", {}).get("total_tokens", 0)
- logger.debug(f"[OpenRouter] Success: {tokens_used} tokens (Model: {router_model})")
- cache_ai_response(tier, prompt_hash, "", text, tokens_used, mime_type=response_mime_type or "")
- return text, tokens_used
- elif resp.status_code in (429, 402, 403):
- logger.warning(f"[OpenRouter] Key exhausted/rate limited (HTTP {resp.status_code}). Rotating...")
- openrouter_key_manager.mark_failed(active_openrouter_key, reason=str(resp.status_code))
- else:
- logger.warning(f"[OpenRouter] HTTP Error {resp.status_code}: {resp.text}. Falling back...")
- except Exception as e:
- logger.warning(f"[OpenRouter] Call failed: {e}. Falling back...")
- # ─────────────────────────────────
-
- for model in config["models"]:
- # ROTATION: Get a fresh key from the manager
- active_key = await gemini_key_manager.get_key()
- if not active_key:
- logger.error("No available Gemini API keys (all on cooldown)")
- return None, 0
-
- # Use v1beta endpoint when response_mime_type is set (needed for JSON mode)
- api_version = "v1beta" if response_mime_type else "v1"
- url = f"https://generativelanguage.googleapis.com/{api_version}/models/{model}:generateContent?key={active_key}"
-
- generation_config: Dict[str, Any] = {
- "temperature": use_temp,
- "maxOutputTokens": use_tokens,
- }
- if response_mime_type:
- generation_config["responseMimeType"] = response_mime_type
-
- payload: Dict[str, Any] = {
- "contents": [{"parts": [{"text": prompt}]}],
- "generationConfig": generation_config,
- }
-
- if system_instruction:
- payload["systemInstruction"] = {"parts": [{"text": system_instruction}]}
-
- headers = {"User-Agent": gemini_key_manager.get_random_user_agent()}
-
- try:
- async with httpx.AsyncClient(timeout=timeout) as client:
- resp = await client.post(url, json=payload, headers=headers)
-
- if resp.status_code == 200:
- gemini_key_manager.mark_success(active_key)
- data = resp.json()
- try:
- text = data["candidates"][0]["content"]["parts"][0]["text"]
- tokens_used = data.get("usageMetadata", {}).get("totalTokenCount", 0)
- logger.debug(f"Gemini 3.5 [{config['label']}] {model}: {tokens_used} tokens (Key: {active_key[:8]})")
- cache_ai_response(tier, prompt_hash, "", text, tokens_used, mime_type=response_mime_type or "")
- return text, tokens_used
- except (KeyError, IndexError, TypeError) as e:
- logger.warning(f"Gemini {model}: unexpected response format: {e}")
- continue
-
- elif resp.status_code in (429, 503):
- # Rate limited or overloaded — try next model in chain
- logger.warning(f"Gemini {model} [{config['label']}]: HTTP {resp.status_code} (rate limit/overload)")
- gemini_key_manager.mark_failed(active_key, reason=str(resp.status_code))
- continue
-
- elif resp.status_code == 404:
- # Model not found — try fallback
- logger.debug(f"Gemini {model} [{config['label']}]: HTTP 404 (not available)")
- continue
-
- else:
- logger.warning(f"Gemini {model} [{config['label']}]: HTTP {resp.status_code}")
- gemini_key_manager.mark_failed(active_key, reason=f"HTTP_{resp.status_code}")
- continue
-
- except httpx.TimeoutException:
- logger.warning(f"Gemini {model} [{config['label']}]: timeout ({timeout}s)")
- gemini_key_manager.mark_failed(active_key, reason="Timeout")
- continue
- except httpx.RequestError as e:
- logger.warning(f"Gemini {model} [{config['label']}]: network error: {e}")
- gemini_key_manager.mark_failed(active_key, reason=f"RequestError: {type(e).__name__}")
- continue
- except Exception as e:
- logger.error(f"Gemini {model} [{config['label']}]: unexpected error: {e}")
- gemini_key_manager.mark_failed(active_key, reason=f"Unexpected: {type(e).__name__}")
- continue
-
- return None, 0 # All models in the tier failed
-
-
-# =============================================================================
-# PUBLIC TIERED HELPERS (convenience wrappers)
-# =============================================================================
-
-async def call_high(
- prompt: str,
- system_instruction: Optional[str] = None,
- temperature: Optional[float] = None,
- max_output_tokens: Optional[int] = None,
-) -> Tuple[Optional[str], int]:
- """Call Gemini 3.5 Pro (complex tasks) with 3.5 Flash fallback.
-
- Use for: semantic matching, CV generation, bulk vetting, SKKNI, RecruiterAI.
- """
- return await call_gemini_tier(
- prompt=prompt,
- tier="HIGH",
- system_instruction=system_instruction,
- temperature=temperature,
- max_output_tokens=max_output_tokens,
- )
-
-
-async def call_medium(
- prompt: str,
- system_instruction: Optional[str] = None,
- temperature: Optional[float] = None,
- max_output_tokens: Optional[int] = None,
-) -> Tuple[Optional[str], int]:
- """Call Gemini 3.5 Flash (general purpose).
-
- Use for: search recommendations, auto-blog, learning system, green job analysis.
- """
- return await call_gemini_tier(
- prompt=prompt,
- tier="MEDIUM",
- system_instruction=system_instruction,
- temperature=temperature,
- max_output_tokens=max_output_tokens,
- )
-
-
-async def call_low(
- prompt: str,
- system_instruction: Optional[str] = None,
- temperature: Optional[float] = None,
- max_output_tokens: Optional[int] = None,
-) -> Tuple[Optional[str], int]:
- """Call Gemini 3.5 Flash (lightweight config).
-
- Use for: chat mediation, registry support, engagement, maintenance.
- """
- return await call_gemini_tier(
- prompt=prompt,
- tier="LOW",
- system_instruction=system_instruction,
- temperature=temperature,
- max_output_tokens=max_output_tokens,
- )
-
-
-async def call_groq_json(
- prompt: str,
- system_instruction: Optional[str] = None,
- temperature: Optional[float] = None,
- timeout: float = 30.0
-) -> dict:
- """Fallback helper to call Groq API with Llama 3.3 in JSON mode."""
- api_key = getattr(settings, "groq_api_keys", None) or getattr(settings, "groq_api_key", None) or os.getenv("GROQ_API_KEY")
- if not api_key:
- logger.warning("[GroqFallback] GROQ_API_KEY not configured, cannot run fallback.")
- return {"error": "GROQ_API_KEY not configured"}
-
- logger.info("[GroqFallback] Falling back to Groq Llama-3.3-70b...")
-
- endpoint = "https://api.groq.com/openai/v1/chat/completions"
- headers = {
- "Authorization": f"Bearer {api_key}",
- "Content-Type": "application/json"
- }
-
- messages = []
- if system_instruction:
- messages.append({"role": "system", "content": system_instruction})
- messages.append({"role": "user", "content": prompt})
-
- payload = {
- "model": "llama-3.3-70b-versatile",
- "messages": messages,
- "temperature": temperature if temperature is not None else 0.2,
- "response_format": {"type": "json_object"}
- }
-
- async with httpx.AsyncClient(timeout=timeout) as client:
- try:
- resp = await client.post(endpoint, headers=headers, json=payload)
- if resp.status_code == 200:
- res_data = resp.json()
- content = res_data["choices"][0]["message"]["content"].strip()
- return json.loads(content)
- else:
- logger.error(f"[GroqFallback] API error: {resp.status_code} - {resp.text}")
- return {"error": f"Groq API error: {resp.status_code}"}
- except Exception as e:
- logger.error(f"[GroqFallback] Call failed: {e}")
- return {"error": f"Groq call failed: {e}"}
-
-
-async def call_gemini_json(
- prompt: str,
- tier: str = "MEDIUM",
- system_instruction: Optional[str] = None,
- temperature: Optional[float] = None,
- max_output_tokens: Optional[int] = None,
-) -> Tuple[dict, int]:
- """Call Gemini with responseMimeType=application/json and return parsed dict.
-
- This is the shared utility that replaces the duplicate _call_gemini methods
- previously copied across services. Always returns a dict — never throws.
-
- Returns (parsed JSON dict, tokens) on success, or ({"error": "..."}, 0) on failure.
- """
- try:
- result, tokens = await call_gemini_tier(
- prompt=prompt,
- tier=tier,
- system_instruction=system_instruction,
- temperature=temperature,
- max_output_tokens=max_output_tokens,
- response_mime_type="application/json",
- )
- if not result:
- # --- FALLBACK TO GROQ ---
- groq_res = await call_groq_json(prompt, system_instruction, temperature)
- if "error" not in groq_res:
- return groq_res, 0
- return {"error": "AI service returned no response"}, 0
-
- text = result.strip()
- # Strip markdown code fences if Gemini wraps the JSON
- if text.startswith("```"):
- text = re.sub(r"^```[a-z]*\n|```$", "", text).strip()
-
- return json.loads(text), tokens
- except json.JSONDecodeError as e:
- logger.warning(f"call_gemini_json: JSON parse error: {e}")
- # --- FALLBACK TO GROQ ---
- groq_res = await call_groq_json(prompt, system_instruction, temperature)
- if "error" not in groq_res:
- return groq_res, 0
- return {"error": f"Failed to parse AI response as JSON: {e}"}, 0
- except Exception as e:
- logger.error(f"call_gemini_json error: {e}")
- # --- FALLBACK TO GROQ ---
- groq_res = await call_groq_json(prompt, system_instruction, temperature)
- if "error" not in groq_res:
- return groq_res, 0
- return {"error": f"AI call failed: {e}"}, 0
-
-
-# =============================================================================
-# TIER 2: ALGORITHMIC / DETERMINISTIC FALLBACK (no API calls)
-# =============================================================================
-
-def _algorithmic_match_score(query: str, talent_data: Dict[str, Any]) -> Tuple[int, str]:
- """Compute match score algorithmically without any AI calls.
-
- Uses keyword overlap, skill matching, and sector alignment.
- Score range: 0-100.
- """
- query_lower = query.lower()
- query_words = set(query_lower.split())
-
- skills = (talent_data.get("skill_tags") or "").lower()
- sector = (talent_data.get("sector_focus") or "").lower()
- experience = (talent_data.get("experience") or "").lower()[:500]
- category = (talent_data.get("category") or "").lower()
- name = (talent_data.get("name") or "").lower()
- location = (talent_data.get("location") or "").lower()
-
- score = 0
- matched_terms = []
-
- # 1. Direct skill match (highest weight)
- skill_matches = [w for w in query_words if w in skills]
- if skill_matches:
- score += min(len(skill_matches) * 15, 45)
- matched_terms.extend(skill_matches)
-
- # 2. Sector alignment
- sector_matches = [w for w in query_words if w in sector]
- if sector_matches:
- score += min(len(sector_matches) * 10, 20)
- matched_terms.extend(sector_matches)
-
- # 3. Experience mention
- exp_matches = [w for w in query_words if w in experience]
- if exp_matches:
- score += min(len(exp_matches) * 5, 15)
-
- # 4. Category alignment
- if category and any(w in category for w in query_words):
- score += 10
-
- # 5. Location match
- if location and any(w in location for w in query_words):
- score += 10
-
- # 6. Name match (lower weight — reduces false positives for name searches)
- name_matches = [w for w in query_words if len(w) > 3 and w in name]
- if name_matches:
- score += 5
-
- score = min(score, 100)
-
- if score >= 80:
- summary = "Strong match — high skill and sector alignment"
- elif score >= 60:
- summary = "Good match — relevant skills detected"
- elif score >= 40:
- summary = "Moderate match — partial alignment"
- elif score >= 20:
- summary = "Weak match — minimal overlap"
- else:
- summary = "Low match — consider refining search criteria"
-
- if matched_terms:
- summary += f" (matched: {', '.join(matched_terms[:5])})"
-
- return score, summary
-
-
-def _algorithmic_cv_generation(talent_data: Dict[str, Any]) -> str:
- """Generate structured CV text without AI.
- Ported from GAS CVGenerator.gs patterns.
- """
- name = talent_data.get("name") or "-"
- email = talent_data.get("email") or "-"
- phone = talent_data.get("phone") or "-"
- education = talent_data.get("education") or "-"
- experience = talent_data.get("experience") or "-"
- skills = talent_data.get("skill_tags") or "-"
- certs = talent_data.get("cert_other") or "-"
- languages = talent_data.get("language") or "-"
-
- cv = (
- f"=== CURRICULUM VITAE ===\n"
- f"\n--- Data Pribadi ---\n"
- f"Nama: {name}\n"
- f"Email: {email}\n"
- f"Telepon: {phone}\n"
- f"\n--- Pendidikan ---\n{education}\n"
- f"\n--- Pengalaman Kerja ---\n{experience}\n"
- f"\n--- Keahlian ---\n{skills}\n"
- f"\n--- Sertifikasi ---\n{certs}\n"
- f"\n--- Bahasa ---\n{languages}\n"
- )
- return cv[:4000]
-
-
-# =============================================================================
-# TIER 3: GRACEFUL DEFAULTS (never crashes)
-# =============================================================================
-
-def _graceful_match_score() -> Tuple[int, str]:
- """Last resort — return safe defaults when everything fails."""
- return 50, "AI scoring unavailable — using profile completeness score"
-
-
-def _graceful_ai_response() -> str:
- """Last resort — return safe default text."""
- return "Maaf, layanan AI sedang tidak tersedia. Silakan coba lagi nanti."
-
-
-# =============================================================================
-# TASK-SPECIFIC AI FUNCTIONS (mapped to Gemini 3 series tiers)
-# =============================================================================
-#
-# TIER MAPPING (matches GAS AI_CONFIG.TIERS):
-#
-# HIGH (CRITICAL) → gemini-3.1-pro-preview → 3.5-flash
-# - analyze_semantic_match() ← GAS SearchEngine.gs (STANDARD → HIGH for accuracy)
-# - generate_cv_text() ← GAS CVGenerator.gs (was STANDARD → HIGH for quality)
-# - analyze_career_path() ← GAS RecruiterAI.gs (CRITICAL)
-# - bulk_vetting_analysis() ← GAS BulkVettingEngine.gs (CRITICAL)
-# - skkni_classification() ← GAS SKKNI_Agent.gs (CRITICAL)
-# - talent_dashboard_advisor() ← GAS TalentDashboard.gs (CRITICAL)
-#
-# MEDIUM (STANDARD) → gemini-3.5-flash
-# - generate_search_recommendation() ← GAS SearchEngine.gs
-# - generate_blog_post() ← GAS AutoBlog.gs
-# - analyze_green_job() ← GAS GreenJobAgent.gs
-# - generate_learning_path() ← GAS LearningSystem.gs
-# - generate_content() ← GAS ContentAgent.gs
-#
-# LOW (FAST) → gemini-3.5-flash (lightweight)
-# - chat_mediation() ← GAS ChatManager.gs
-# - registry_assist() ← GAS Registry.gs / RegistryEmployer.gs
-# - engagement_message() ← GAS TalentEngagement.gs
-# - maintenance_clean() ← GAS Maintenance.gs
-# - financial_recommendation() ← GAS Finance.gs
-
-
-# ─── HIGH TIER (Complex Reasoning) ──────────────────────────────────────────
-
-async def analyze_semantic_match(
- query: str,
- talent_data: Dict[str, Any],
-) -> Dict[str, Any]:
- """HIGH tier: Analyze semantic match between search query and talent profile.
-
- Tier chain: Gemini 3.5 Pro → 3.5 Flash → algorithmic → graceful default.
- NEVER throws.
- """
- try:
- if GEMINI_API_KEY and not AI_DISABLED:
- system_prompt = (
- "You are Brigawan AI, a green jobs talent matcher in Indonesia. "
- "Analyze the match between a recruiter's search query and a talent profile. "
- "Return ONLY a JSON object: {score: int (0-100), summary: string (max 100 chars, Bahasa Indonesia)}"
- )
- user_prompt = (
- f"Search Query: {query[:500]}\n"
- f"Talent Skills: {talent_data.get('skill_tags', '')[:300]}\n"
- f"Talent Experience: {talent_data.get('experience', '')[:300]}\n"
- f"Talent Sector: {talent_data.get('sector_focus', '')[:100]}\n"
- f"Talent Location: {talent_data.get('location', '')[:100]}"
- )
-
- # Use shared JSON utility
- parsed, tokens = await call_gemini_json(
- prompt=user_prompt,
- tier="HIGH",
- system_instruction=system_prompt
- )
-
- if isinstance(parsed, dict) and "score" in parsed:
- score = max(0, min(100, int(parsed.get("score", 50))))
- summary = str(parsed.get("summary", "") or "")[:120]
- return {"score": score, "summary": summary, "ai_used": True, "tier": "HIGH", "tokens": tokens}
-
- # Algorithmic fallback
- score, summary = _algorithmic_match_score(query, talent_data)
- return {"score": score, "summary": summary, "ai_used": False, "tier": "algorithmic", "tokens": 0}
-
- except Exception as e:
- logger.error(f"analyze_semantic_match error: {e}")
-
- score, summary = _graceful_match_score()
- return {"score": score, "summary": summary, "ai_used": False, "tier": "graceful", "tokens": 0}
-
-
-async def generate_cv_text(talent_data: Dict[str, Any]) -> Tuple[str, int]:
- """HIGH tier: Generate CV text using Gemini 3.5 Pro.
-
- Tier chain: Gemini 3.5 Pro → 3.5 Flash → algorithmic template.
- NEVER throws.
- """
- try:
- if GEMINI_API_KEY and not AI_DISABLED:
- prompt = (
- f"Buat CV dalam Bahasa Indonesia untuk talent berikut:\n"
- f"Nama: {talent_data.get('name', '')}\n"
- f"Pendidikan: {talent_data.get('education', '')[:300]}\n"
- f"Pengalaman: {talent_data.get('experience', '')[:500]}\n"
- f"Keahlian: {talent_data.get('skill_tags', '')[:300]}\n"
- f"Sertifikasi: {talent_data.get('cert_other', '')[:200]}\n"
- f"Buat CV yang rapi, profesional, dan siap pakai untuk rekrutmen."
- )
- result, tokens = await call_high(prompt=prompt, max_output_tokens=2048)
- if result:
- return result, tokens
-
- return _algorithmic_cv_generation(talent_data), 0
-
- except Exception as e:
- logger.error(f"generate_cv_text error: {e}")
- return _algorithmic_cv_generation(talent_data), 0
-
-
-# ─── MEDIUM TIER (General Purpose) ──────────────────────────────────────────
-
-async def generate_search_recommendation(query: str, results_count: int) -> Tuple[str, int]:
- """MEDIUM tier: Generate search recommendation.
-
- Tier chain: gemini-3.5-flash → algorithmic → empty string.
- NEVER throws.
- """
- try:
- if GEMINI_API_KEY and not AI_DISABLED and results_count > 0:
- prompt = (
- f"Search query: {query[:200]}\n"
- f"Results found: {results_count}\n"
- f"Give a brief, helpful recommendation (max 80 chars in Bahasa Indonesia) "
- f"for a recruiter on how to refine their search or proceed."
- )
- result, tokens = await call_medium(prompt=prompt)
- if result:
- return result.strip()[:120], tokens
-
- # Algorithmic fallback
- if results_count == 0:
- return "Coba gunakan kata kunci yang lebih umum atau berbeda.", 0
- elif results_count < 5:
- return "Hasil terbatas — coba perluas kata kunci atau lokasi.", 0
- else:
- return f"Ditemukan {results_count} talenta. Gunakan filter untuk mempersempit hasil.", 0
-
- except Exception as e:
- logger.error(f"generate_search_recommendation error: {e}")
- return "", 0
-
-
-async def generate_blog_post(topic: str, sector: str, context: str = "") -> Tuple[Optional[str], int]:
- """MEDIUM tier: Generate blog post content.
-
- Tier chain: gemini-3.5-flash → None.
- GAS equivalent: AutoBlog.gs → callGeminiWithFallback (STANDARD tier).
- NEVER throws.
- """
- try:
- if GEMINI_API_KEY and not AI_DISABLED:
- prompt = (
- f"You are the Briga SEO Editor. Write a blog post in INDONESIAN.\n\n"
- f"TOPIC: {topic}\n"
- f"INDUSTRY: {sector}\n"
- f"CONTEXT: {context[:500]}\n\n"
- f"Return JSON: {{\"title\": \"...\", \"summary\": \"...\", \"content\": \"...\"}}"
- )
- return await call_medium(prompt=prompt, max_output_tokens=2048)
- return None, 0
- except Exception as e:
- logger.error(f"generate_blog_post error: {e}")
- return None, 0
-
-
-# ─── LOW TIER (Lightweight Utility) ─────────────────────────────────────────
-
-async def chat_mediation(user_message: str, context: str = "") -> Tuple[Optional[str], int]:
- """LOW tier: Mediate chat messages between recruiters and talents.
-
- Tier chain: gemini-3.5-flash (lightweight) → None.
- GAS equivalent: ChatManager.gs → callGeminiAI (FAST tier).
- NEVER throws.
- """
- try:
- if GEMINI_API_KEY and not AI_DISABLED:
- prompt = (
- f"Anda adalah asisten Brigawan. Mediasi percakapan ini:\n\n"
- f"Konteks: {context[:300]}\n"
- f"Pesan: {user_message[:1000]}\n\n"
- f"Berikan respons yang profesional dan membantu."
- )
- return await call_low(prompt=prompt)
- return None, 0
- except Exception as e:
- logger.error(f"chat_mediation error: {e}")
- return None, 0
-
-
-async def engagement_message(talent_name: str, template: str = "follow_up") -> Tuple[Optional[str], int]:
- """LOW tier: Generate personalized engagement message.
-
- Tier chain: gemini-3.5-flash (lightweight) → None.
- GAS equivalent: TalentEngagement.gs.
- NEVER throws.
- """
- try:
- if GEMINI_API_KEY and not AI_DISABLED:
- prompt = (
- f"Buat pesan engagement yang personal untuk talent: {talent_name}\n"
- f"Template: {template}\n"
- f"Buat singkat (max 100 kata) dan profesional dalam Bahasa Indonesia."
- )
- return await call_low(prompt=prompt)
- return None, 0
- except Exception as e:
- logger.error(f"engagement_message error: {e}")
- return None, 0
-
-
-async def registry_assist(query: str, data_summary: str = "") -> Tuple[Optional[str], int]:
- """LOW tier: Assist with data registry validation or lookup.
-
- Tier chain: gemini-3.5-flash (lightweight) → None.
- GAS equivalent: Registry.gs / RegistryEmployer.gs (FAST tier).
- NEVER throws.
- """
- try:
- if GEMINI_API_KEY and not AI_DISABLED:
- prompt = (
- f"Bantu validasi data registrasi berikut:\n"
- f"Query: {query[:300]}\n"
- f"Data: {data_summary[:500]}\n"
- f"Berikan konfirmasi atau saran perbaikan singkat."
- )
- return await call_low(prompt=prompt)
- return None, 0
- except Exception as e:
- logger.error(f"registry_assist error: {e}")
- return None, 0
-
-
-async def financial_recommendation(context: str) -> Tuple[Optional[str], int]:
- """LOW tier: Generate financial recommendation.
-
- Tier chain: gemini-3.5-flash (lightweight) → None.
- GAS equivalent: Finance.gs → callGeminiWithFallback.
- NEVER throws.
- """
- try:
- if GEMINI_API_KEY and not AI_DISABLED:
- prompt = (
- f"Anda adalah asisten finansial Brigawan.\n"
- f"Konteks: {context[:500]}\n"
- f"Berikan rekomendasi singkat dan praktis."
- )
- return await call_low(prompt=prompt)
- return None, 0
- except Exception as e:
- logger.error(f"financial_recommendation error: {e}")
- return None, 0
-
-
-# ─── FUTURE HIGH TIER STUBS (ready for Series 3 port) ───────────────────────
-
-def get_bulk_vetting_system_prompt(recruiter_context: str = "") -> str:
- from app.config.vetting_rules import VETTING_RULES, CAREER_TRANSITION_DB
-
- sector_list = ", ".join(VETTING_RULES["green_sectors"])
-
- # Build compressed career transition reference (top entries per sector)
- transition_ref = ""
- seen_sectors = {}
- for entry in CAREER_TRANSITION_DB:
- sector = entry["sector"]
- if sector in seen_sectors:
- continue
- seen_sectors[sector] = True
- skills_slice = ", ".join(entry["skills"][:3])
- transition_ref += f"- {sector}: {entry['targetJob']} (Skills: {skills_slice})\n"
-
- # Assemble system prompt
- return (
- "IDENTITAS: Kamu adalah Brigawan Vetting Intelligence — mesin evaluasi talenta hijau paling presisi di Indonesia.\n\n"
- "MISI: Evaluasi CV/resume kandidat secara massal untuk menentukan kesiapan mereka masuk ke industri keberlanjutan (green jobs).\n\n"
- "=== KNOWLEDGE BASE ===\n\n"
- f"KATEGORI TALENTA:\n"
- f"- Skilled: {VETTING_RULES['categories']['Skilled']}\n"
- f"- Semi-Skilled: {VETTING_RULES['categories']['Semi-Skilled']}\n"
- f"- Unskilled: {VETTING_RULES['categories']['Unskilled']}\n\n"
- f"SEKTOR HIJAU YANG DIKENALI:\n{sector_list}\n\n"
- f"PETA TRANSISI KARIR (Brown → Green):\n{transition_ref}\n"
- "=== INSTRUKSI EVALUASI ===\n\n"
- "1. EKSTRAKSI DATA\n"
- " Dari teks CV yang diberikan, identifikasi:\n"
- " - Nama (jangan tampilkan di output, ganti dengan \"Kandidat\")\n"
- " - Pendidikan terakhir + jurusan\n"
- " - Total tahun pengalaman kerja\n"
- " - Riwayat kerja (perusahaan + posisi + durasi)\n"
- " - Sertifikasi / lisensi yang dimiliki\n"
- " - Bahasa yang dikuasai\n"
- " - Lokasi domisili\n\n"
- " PENTING — FORMAT PENGALAMAN KERJA S.T.A.R:\n"
- " Brigawan menggunakan framework S.T.A.R untuk penulisan pengalaman kerja:\n"
- " - Situation: Konteks/latar belakang masalah yang dihadapi\n"
- " - Task: Tugas/tanggung jawab spesifik yang diberikan\n"
- " - Action: Langkah konkret yang diambil kandidat\n"
- " - Result: Hasil terukur / dampak nyata dari aksi tersebut\n\n"
- " Saat mengevaluasi pengalaman kerja, perhatikan:\n"
- " a) Apakah narasi ditulis dengan struktur S.T.A.R yang jelas?\n"
- " b) Apakah Result menyertakan metrik/angka terukur (%, Rp, unit)?\n"
- " c) Apakah Action menunjukkan inisiatif dan ownership?\n"
- " Berikan field \"star_quality\" di output: \"strong\" / \"moderate\" / \"weak\" / \"absent\".\n\n"
- "2. SCORING (0-100)\n"
- " Gunakan bobot berikut:\n"
- " - Relevansi Pengalaman ke Sektor Hijau: 30%\n"
- " - Kualitas Narasi S.T.A.R (kejelasan dampak & metrik): 10%\n"
- " - Sertifikasi & Kualifikasi Teknis: 25%\n"
- " - Pendidikan (linearitas jurusan): 15%\n"
- " - Transferable Skills (dari Brown Industry): 10%\n"
- " - Soft Indicators (bahasa asing, leadership, proyek): 10%\n\n"
- " BONUS SCORING:\n"
- " +5 poin: Punya sertifikasi internasional (NEBOSH, ISO, GRI)\n"
- " +5 poin: Pengalaman di Brown Industry >5 tahun (potensi transisi tinggi)\n"
- " +3 poin: Narasi S.T.A.R \"strong\" dengan Result terukur\n"
- " +3 poin: Menguasai bahasa asing (Inggris/Jepang/Jerman)\n"
- " +3 poin: CV memiliki ATS readiness \"high\" (keyword padat, struktur standar)\n"
- " -5 poin: CV memiliki ATS readiness \"low\" (format buruk, minim keyword industri)\n"
- " -10 poin: Tidak ada pengalaman kerja sama sekali DAN bukan lulusan STEM\n\n"
- "3. KATEGORI\n"
- " - Skor 70-100 → Skilled\n"
- " - Skor 40-69 → Semi-Skilled\n"
- " - Skor 0-39 → Unskilled\n\n"
- "4. SECTOR MATCHING\n"
- " Tentukan 1-3 sektor hijau yang paling cocok dari daftar SEKTOR HIJAU.\n"
- " Jika kandidat berasal dari Brown Industry (migas, tambang, batu bara), "
- " gunakan PETA TRANSISI KARIR untuk menentukan jalur konversi terbaik.\n\n"
- "5. SKILL GAP ANALYSIS\n"
- " Identifikasi 2-4 keterampilan atau sertifikasi yang perlu diperoleh "
- " agar kandidat naik ke level \"Skilled\".\n\n"
- "6. ATS READINESS ASSESSMENT\n"
- " Evaluasi apakah CV kandidat siap lolos Applicant Tracking System (ATS):\n"
- " a) KEYWORD OPTIMIZATION: Apakah CV mengandung keyword industri hijau yang relevan?\n"
- " Semakin banyak keyword dari daftar industri hijau yang muncul di CV, semakin tinggi skor ATS.\n"
- " b) STRUKTUR STANDAR: Apakah CV memiliki section header yang dikenali ATS?\n"
- " (Summary/Objective, Work Experience, Education, Skills, Certifications)\n"
- " c) FORMAT BERSIH: Apakah CV bebas dari elemen yang sulit dibaca ATS?\n"
- " d) KONSISTENSI TANGGAL: Apakah format tanggal konsisten?\n"
- " e) ACTION VERBS: Apakah pengalaman kerja dimulai dengan kata kerja aktif?\n\n"
- " Berikan rating ats_readiness:\n"
- " - \"high\": CV sudah ATS-optimized\n"
- " - \"medium\": CV cukup terbaca ATS tapi perlu optimasi\n"
- " - \"low\": CV kemungkinan gagal lolos ATS\n"
- " Sertakan 1-3 rekomendasi perbaikan di field \"ats_tips\".\n\n"
- f"{'=== KONTEKS REKRUTER ===\nRekruter sedang mencari: ' + recruiter_context + '\nPrioritaskan kandidat yang cocok dengan kebutuhan ini.\n\n' if recruiter_context else ''}"
- "=== RESPONSE FORMAT (STRICT JSON ONLY) ===\n"
- "Kembalikan JSON object dengan format persis berikut:\n"
- "{\n"
- " \"extracted_name\": \"string\",\n"
- " \"skor\": number,\n"
- " \"kategori\": \"Skilled | Semi-Skilled | Unskilled\",\n"
- " \"pendidikan\": \"string\",\n"
- " \"total_experience_years\": number,\n"
- " \"sektor_cocok\": [\"string\"],\n"
- " \"skill_tags\": [\"string\"],\n"
- " \"sertifikasi_terdeteksi\": [\"string\"],\n"
- " \"lokasi\": \"string\",\n"
- " \"bahasa\": [\"string\"],\n"
- " \"ringkasan\": \"string (evaluasi 2-3 kalimat, sebut sebagai Kandidat, jangan sebut nama orang)\",\n"
- " \"star_quality\": \"strong | moderate | weak | absent\",\n"
- " \"ats_readiness\": \"high | medium | low\",\n"
- " \"ats_tips\": [\"string\"],\n"
- " \"skill_gap\": [\"string\"],\n"
- " \"transition_path\": \"string (atau null)\",\n"
- " \"highlight\": \"string (1 kalimat kekuatan utama)\"\n"
- "}\n\n"
- "ATURAN KETAT:\n"
- "- JANGAN mengarang data. Jika informasi tidak ada di CV, tulis \"Tidak terdeteksi\".\n"
- "- JANGAN menyebutkan nama kandidat di field \"ringkasan\". Gunakan \"Kandidat\".\n"
- "- Semua output HARUS dalam Bahasa Indonesia kecuali skill_tags (English).\n"
- "- Output HARUS valid JSON. Jangan tambahkan teks apapun di luar JSON."
- )
-
-
-async def bulk_vetting_analysis(cv_text: str, recruiter_context: str = "") -> Tuple[Dict[str, Any], int]:
- """HIGH tier: Analyze CV for bulk vetting.
- Returns tuple of (JSON dict, tokens) matching legacy GAS BulkVettingEngine.gs.
- """
- try:
- system_prompt = get_bulk_vetting_system_prompt(recruiter_context)
- user_prompt = f"Evaluasi CV berikut:\n\n---\n{cv_text[:8000]}\n---"
-
- return await call_gemini_json(
- prompt=user_prompt,
- tier="HIGH",
- system_instruction=system_prompt
- )
- except Exception as e:
- logger.error(f"bulk_vetting_analysis error: {e}")
- return {"error": str(e), "skor": 0}, 0
-
-
-async def extract_cv_metadata(cv_markdown: str) -> Dict[str, Any]:
- """MEDIUM tier: Extract CV metadata from Markdown content using Gemini.
- Returns JSON formatted profile fields for magic fill.
- """
- try:
- system_prompt = (
- "Ekstrak informasi dari teks CV (dalam format Markdown) ini ke dalam format JSON.\n"
- "Gunakan Bahasa Indonesia untuk field teks jika memungkinkan. Jika suatu data tidak ditemukan di CV, isi dengan string kosong \"\" atau array kosong [].\n\n"
- "RESPONSE FORMAT (STRICT JSON ONLY):\n"
- "{\n"
- " \"nama\": \"Nama lengkap kandidat\",\n"
- " \"universitas\": \"Nama kampus/universitas terakhir\",\n"
- " \"jurusan\": \"Jurusan/program studi\",\n"
- " \"jenjang\": \"Jenjang pendidikan, contoh: S1, S2, SMA, D3\",\n"
- " \"pengalaman\": \"Ringkasan pengalaman kerja dalam format paragraf\",\n"
- " \"skills\": [\"keterampilan1\", \"keterampilan2\"],\n"
- " \"kota\": \"Kota domisili saat ini\",\n"
- " \"provinsi\": \"Provinsi domisili\",\n"
- " \"linkedin\": \"URL atau username LinkedIn jika ada\",\n"
- " \"email\": \"Alamat email jika ditemukan\",\n"
- " \"gaji_saat_ini\": \"Gaji saat ini jika disebutkan, angka saja sebagai string\",\n"
- " \"gaji_ekspektasi\": \"Ekspektasi gaji jika disebutkan, angka saja sebagai string\",\n"
- " \"total_experience\": \"Total tahun pengalaman, contoh: '5 Tahun'\",\n"
- " \"sector_focus\": \"Sektor industri, contoh: 'Energi Terbarukan', 'ESG', 'Limbah'\",\n"
- " \"talent_type\": \"Pilih salah satu: 'Experienced', 'Fresh Graduate', 'Career Switcher'\",\n"
- " \"green_readiness_score\": 75,\n"
- " \"green_readiness_feedback\": \"1-2 kalimat feedback singkat, profesional, memotivasi mengenai cara meningkatkan peluang kerja mereka di sektor hijau (Bahasa Indonesia)\"\n"
- "}"
- )
- user_prompt = f"TEKS CV (MARKDOWN):\n\n{cv_markdown}"
-
- parsed, tokens = await call_gemini_json(
- prompt=user_prompt,
- tier="MEDIUM",
- system_instruction=system_prompt
- )
- return parsed
- except Exception as e:
- logger.error(f"extract_cv_metadata error: {e}")
- return {"error": str(e)}
-
-
-async def skkni_classification(experience: str, skills: str) -> Dict[str, Any]:
- """HIGH tier: Classify talent against SKKNI standards."""
- try:
- system_prompt = (
- "You are the Briga SKKNI Agent. Map the talent's experience and skills to Indonesian SKKNI units. "
- "Return a JSON object: {matched_units: [{code: string, title: string, match_percent: int}], total_alignment: int}"
- )
- user_prompt = f"Experience: {experience[:1000]}\nSkills: {skills[:500]}"
-
- return await call_gemini_json(
- prompt=user_prompt,
- tier="HIGH",
- system_instruction=system_prompt
- )
- except Exception as e:
- logger.error(f"skkni_classification error: {e}")
- return {"error": str(e)}
-
-
-async def talent_dashboard_advisor(talent_id: str, history_json: str) -> Dict[str, Any]:
- """HIGH tier: Career pathway advisor for talent dashboard."""
- try:
- system_prompt = (
- "You are the Brigawan Strategic Advisor. Analyze the talent's career history and provide strategic advice. "
- "Return a JSON object: {advice_snippet: string, full_recommendation: string, next_steps: string[]}"
- )
- user_prompt = f"Talent ID: {talent_id}\nHistory: {history_json}"
-
- return await call_gemini_json(
- prompt=user_prompt,
- tier="HIGH",
- system_instruction=system_prompt
- )
- except Exception as e:
- logger.error(f"talent_dashboard_advisor error: {e}")
- return {"error": str(e)}
-
-
-# =============================================================================
-# UTILITY FUNCTIONS (ported from GAS)
-# =============================================================================
-
-def repair_json(text: str) -> Any:
- """Repair malformed JSON from AI output.
- Ported from GAS Security.gs repairJSON().
- """
- if not text:
- return {}
-
- try:
- return json.loads(text)
- except (json.JSONDecodeError, ValueError):
- pass
-
- clean = text
-
- # 1. Remove markdown code blocks
- clean = re.sub(r'```json\s*', '', clean, flags=re.IGNORECASE)
- clean = re.sub(r'```\s*', '', clean)
-
- # 2. Extract between first { and last } (or [ and ])
- start_obj = clean.find('{')
- end_obj = clean.rfind('}')
- start_arr = clean.find('[')
- end_arr = clean.rfind(']')
-
- is_array = False
- if start_arr != -1 and (start_obj == -1 or start_arr < start_obj):
- is_array = True
-
- if is_array and start_arr != -1 and end_arr != -1:
- clean = clean[start_arr:end_arr + 1]
- elif start_obj != -1 and end_obj != -1:
- clean = clean[start_obj:end_obj + 1]
- else:
- return {}
-
- # 3. Remove trailing commas before closing braces
- clean = re.sub(r',\s*([\}\]])', r'\1', clean)
-
- try:
- return json.loads(clean)
- except (json.JSONDecodeError, ValueError):
- return {}
-
-
-def redact_pii(
- text: str,
- name: str = "",
- email: str = "",
- phone: str = "",
-) -> str:
- """Redact PII from text. Ported from GAS redactPrivateIdentifiers()."""
- if not text:
- return "-"
-
- clean = str(text)
-
- clean = re.sub(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', '[REDACTED EMAIL]', clean)
- clean = re.sub(r'(\+62|62|0)[\s-]?\d{2,4}[\s-]?\d{3,4}[\s-]?\d{3,4}', '[REDACTED PHONE]', clean)
-
- if phone:
- raw_phone = re.sub(r'[^\d]', '', phone)
- if len(raw_phone) >= 6:
- clean = re.sub(re.escape(raw_phone), '[REDACTED PHONE]', clean)
-
- if name and len(name) >= 3:
- for word in name.split():
- if len(word) >= 3 and word.lower() not in ('dan', 'bin', 'binti', 'the', 'and', 'von', 'der'):
- clean = re.sub(r'\b' + re.escape(word) + r'\b', '[REDACTED]', clean, flags=re.IGNORECASE)
-
- clean = re.sub(r'https?:\/\/[^\s,;)\]]+', '[REDACTED LINK]', clean)
- clean = re.sub(r'www\.[^\s,;)\]]+', '[REDACTED LINK]', clean)
-
- return clean.strip()
-
-
-def detect_prompt_injection(query: str) -> Dict[str, Any]:
- """Detect prompt injection attempts. Ported from GAS detectPromptInjection()."""
- if not query:
- return {"blocked": False, "reason": ""}
-
- q = query.lower()
-
- patterns = [
- (r'ignore|forget|disregard|override', 'override_attempt'),
- (r'show\s+(me\s+)?(all|every)|list\s+(all|every)|reveal|dump|extract', 'data_extraction'),
- (r'system\s+prompt|instructions|rules', 'prompt_probing'),
- (r'you\s+are\s+now|pretend|act\s+as', 'role_manipulation'),
- ]
-
- for pattern_str, reason in patterns:
- if re.search(pattern_str, q):
- return {"blocked": True, "reason": reason}
-
- if len(query) > 500:
- return {"blocked": True, "reason": "too_long"}
-
- return {"blocked": False, "reason": ""}
-
-
-def sanitize_ai_output(results: List[Dict[str, Any]], max_items: int = 10) -> List[Dict[str, Any]]:
- """Sanitize and validate AI-generated output.
- Ported from GAS validateAndSanitizeAIOutput().
- """
- if not results:
- return []
-
- sanitized = []
- for item in results[:max_items]:
- safe = {
- "id_kandidat": str(item.get("id_kandidat", "BRIGA-GT-000"))[:20],
- "kategori": str(item.get("kategori", "Unassessed"))[:20],
- "match_score": max(0, min(100, int(item.get("match_score", 50)))),
- "exp_tier": str(item.get("exp_tier", "Junior"))[:10],
- "skill_tags": [str(s)[:30] for s in (item.get("skill_tags") or [])[:5]],
- "reason": str(item.get("reason", "-"))[:120].replace("<", "").replace(">", ""),
- "lokasi": str(item.get("lokasi", "-"))[:30],
- }
- sanitized.append(safe)
-
- return sanitized
-
-
-# =============================================================================
-# INIT CHECK
-# =============================================================================
-
-def check_ai_status() -> Dict[str, Any]:
- """Check AI availability. Called by /health endpoint."""
- gemini_configured = bool(GEMINI_API_KEY or RAW_GEMINI_KEYS)
- active_tiers = []
- if gemini_configured and not AI_DISABLED:
- active_tiers = [
- {"tier": "HIGH", "model": "gemini-3.5-pro", "fallback": "gemini-3.5-flash"},
- {"tier": "MEDIUM", "model": "gemini-3.5-flash"},
- {"tier": "LOW", "model": "gemini-3.5-flash"},
- ]
- return {
- "gemini_api_configured": gemini_configured,
- "ai_disabled": AI_DISABLED,
- "active_tiers": active_tiers,
- "status": "ready" if gemini_configured and not AI_DISABLED else "fallback_only",
- "note": "Running in fallback-only mode (algorithmic + graceful defaults)"
- if not gemini_configured or AI_DISABLED
- else "Gemini 3.5 series active: HIGH(3.5 Pro), MEDIUM(3.5 Flash), LOW(3.5 Flash)",
- }
-
-
-async def verify_screenshot_with_gemini(
- image_bytes: bytes,
- talent_name: str,
- challenge_code: str,
-) -> Dict[str, Any]:
- """Verify via Gemini Vision if the uploaded image is a valid LinkedIn post screenshot.
-
- Checks:
- 1. Is it a LinkedIn post?
- 2. Does the post author name match `talent_name` (case-insensitive, accommodating short/full names)?
- 3. Does the text contain the hashtag '#BrigaPathway'?
- 4. Does the text contain the challenge code: `challenge_code`?
-
- Returns:
- Dict: {
- "success": bool,
- "match": bool,
- "extracted_name": str,
- "has_hashtag": bool,
- "has_challenge_code": bool,
- "confidence": float,
- "feedback": str
- }
- """
- import base64
- try:
- # Check if AI is disabled or no API keys are loaded
- if AI_DISABLED or (hasattr(gemini_key_manager, 'keys') and not gemini_key_manager.keys and not settings.gemini_api_key):
- logger.warning("AI services disabled or no API key available. Skipping verification.")
- return {
- "success": True,
- "match": False,
- "extracted_name": "",
- "has_hashtag": False,
- "has_challenge_code": False,
- "confidence": 0.0,
- "feedback": "Layanan verifikasi AI saat ini sedang dinonaktifkan."
- }
-
- api_key = settings.gemini_api_key
- active_key = None
- if hasattr(gemini_key_manager, 'get_key'):
- active_key = await gemini_key_manager.get_key()
- if active_key:
- api_key = active_key
-
- if not api_key:
- return {
- "success": False,
- "match": False,
- "extracted_name": "",
- "has_hashtag": False,
- "has_challenge_code": False,
- "confidence": 0.0,
- "feedback": "API Key Gemini tidak dikonfigurasi."
- }
-
- encoded_image = base64.b64encode(image_bytes).decode("utf-8")
-
- # Using the v1beta endpoint with dynamic medium model from settings
- model_name = settings.gemini_medium_model or "gemini-2.5-flash"
- url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent?key={api_key}"
-
- prompt = (
- f"Analyze this image which is expected to be a screenshot of a LinkedIn post. "
- f"Verify the following requirements:\n"
- f"1. Is the screenshot a LinkedIn post?\n"
- f"2. Does the name of the author on the post match the talent name: '{talent_name}'? (Perform case-insensitive verification, allowing slight abbreviations or ordering changes)\n"
- f"3. Does the text contain the hashtag '#BrigaPathway'?\n"
- f"4. Does the text contain the challenge code: '{challenge_code}'?\n\n"
- f"Provide your assessment. Respond STRICTLY in JSON format with the following keys:\n"
- f"- 'is_linkedin_post' (boolean)\n"
- f"- 'name_matches' (boolean)\n"
- f"- 'has_hashtag' (boolean)\n"
- f"- 'has_challenge_code' (boolean)\n"
- f"- 'extracted_name' (string, name extracted from the post header)\n"
- f"- 'confidence' (float between 0.0 and 1.0)\n"
- f"- 'feedback' (string in Bahasa Indonesia summarizing the results of verification and what is missing or incorrect)\n"
- f"- 'match' (boolean, should be true ONLY if all checks above are true and confidence >= 0.7)"
- )
-
- payload = {
- "contents": [
- {
- "parts": [
- {"text": prompt},
- {
- "inlineData": {
- "mimeType": "image/jpeg",
- "data": encoded_image
- }
- }
- ]
- }
- ],
- "generationConfig": {
- "responseMimeType": "application/json"
- }
- }
-
- async with httpx.AsyncClient(timeout=30.0) as client:
- resp = await client.post(url, json=payload)
- if resp.status_code == 200:
- if active_key:
- gemini_key_manager.mark_success(active_key)
- data = resp.json()
- text = data["candidates"][0]["content"]["parts"][0]["text"].strip()
- if text.startswith("```"):
- text = re.sub(r"^```[a-z]*\n|```$", "", text).strip()
-
- parsed = json.loads(text)
- return {
- "success": True,
- "match": bool(parsed.get("match", False)),
- "extracted_name": str(parsed.get("extracted_name", "")),
- "has_hashtag": bool(parsed.get("has_hashtag", False)),
- "has_challenge_code": bool(parsed.get("has_challenge_code", False)),
- "confidence": float(parsed.get("confidence", 0.0)),
- "feedback": str(parsed.get("feedback", ""))
- }
- else:
- if active_key and resp.status_code in (429, 503):
- gemini_key_manager.mark_failed(active_key, reason=str(resp.status_code))
- logger.error(f"Gemini Vision API error: {resp.status_code} - {resp.text}")
- return {
- "success": False,
- "match": False,
- "extracted_name": "",
- "has_hashtag": False,
- "has_challenge_code": False,
- "confidence": 0.0,
- "feedback": f"API error: {resp.status_code} - Gagal memproses gambar."
- }
-
- except Exception as e:
- if 'active_key' in locals() and active_key:
- gemini_key_manager.mark_failed(active_key, reason=str(e))
- logger.error(f"verify_screenshot_with_gemini failed: {e}")
- return {
- "success": False,
- "match": False,
- "extracted_name": "",
- "has_hashtag": False,
- "has_challenge_code": False,
- "confidence": 0.0,
- "feedback": f"Error calling verification service: {str(e)}"
- }
+"""Crash-Proof AI Service — Gemini 3 Series Tier Routing.
+
+Tier Architecture (mirrors GAS AI_CONFIG.TIERS):
+
+ HIGH (Complex) → gemini-3.1-pro-preview → fallback to gemini-3.5-flash (high config)
+ MEDIUM (Mid) → gemini-3.5-flash (medium config)
+ LOW (Simple) → gemini-3.5-flash (low config)
+
+Every public function in this module is guaranteed to NEVER throw.
+If all AI providers fail, the caller gets safe, useful defaults.
+
+References:
+ - Ported from GAS Security.gs callGeminiWithFallback (model queue pattern)
+ - GAS Constants.gs AI_CONFIG.TIERS routing logic
+ - PII redaction from GAS redactPrivateIdentifiers
+ - Prompt injection detection from GAS detectPromptInjection
+"""
+
+import hashlib
+import json
+import os
+import re
+import time
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Tuple
+
+import httpx
+from loguru import logger
+
+from app.config.settings import settings
+from app.utils.key_manager import APIKeyManager
+from app.utils.cache import cached_ai_call, cache_ai_response, hash_prompt, get_ai_cache_stats
+
+
+# =============================================================================
+# GEMINI 3 SERIES TIER CONFIGURATION
+# =============================================================================
+
+# Initialize Multi-Key Managers for Omni-Router Strategy
+def clean_keys(keys_str: str) -> List[str]:
+ placeholders = {"key1", "key2", "key3", "your_key", "placeholder", "dummy"}
+ return [k.strip() for k in keys_str.split(",") if k.strip() and k.strip().lower() not in placeholders]
+
+RAW_GEMINI_KEYS = clean_keys(os.getenv("GEMINI_API_KEYS") or getattr(settings, "gemini_api_keys", "") or getattr(settings, "gemini_api_key", ""))
+gemini_key_manager = APIKeyManager(RAW_GEMINI_KEYS)
+
+RAW_9ROUTER_KEYS = clean_keys(os.getenv("ROUTER_API_KEYS") or getattr(settings, "router_api_keys", ""))
+ninerouter_key_manager = APIKeyManager(RAW_9ROUTER_KEYS)
+
+RAW_OPENROUTER_KEYS = clean_keys(os.getenv("OPENROUTER_API_KEYS") or getattr(settings, "openrouter_api_keys", ""))
+openrouter_key_manager = APIKeyManager(RAW_OPENROUTER_KEYS)
+
+GEMINI_API_KEY = settings.gemini_api_key
+AI_DISABLED = settings.ai_disabled or os.environ.get("AI_DISABLED", "false").lower() in ("true", "1", "yes")
+
+# Tier definitions matching GAS Constants.gs AI_CONFIG.TIERS
+# Models read from settings (settable via .env) with hardcoded defaults.
+# This way settings.gemini_high_model etc. are actually consumed, not dead config.
+class GroqKeyManager:
+ """Minimal rotation manager for Groq keys (comma-separated GROQ_API_KEYS).
+ Mirrors APIKeyManager semantics without the jitter sleep."""
+
+ def __init__(self, keys: List[str]):
+ self.keys = [{"key": k, "status": "ready", "last_used": 0.0, "fail_count": 0} for k in keys]
+ self._idx = 0
+
+ async def get_key(self) -> Optional[str]:
+ if not self.keys:
+ return None
+ import time as _time
+ now = _time.time()
+ for _ in range(len(self.keys)):
+ kd = self.keys[self._idx % len(self.keys)]
+ self._idx += 1
+ if kd["status"] == "ready":
+ kd["last_used"] = now
+ return kd["key"]
+ if kd["status"] == "cooldown" and now - kd["last_used"] > min(60.0 * (2.0 ** max(0, kd["fail_count"] - 1)), 3600.0):
+ kd["status"] = "ready"
+ kd["last_used"] = now
+ return kd["key"]
+ return None
+
+ def mark_success(self, key: str):
+ for kd in self.keys:
+ if kd["key"] == key:
+ kd["status"] = "ready"
+ kd["fail_count"] = 0
+ break
+
+ def mark_failed(self, key: str, reason: str = "429"):
+ for kd in self.keys:
+ if kd["key"] == key:
+ kd["status"] = "cooldown"
+ kd["last_used"] = time.time()
+ kd["fail_count"] += 1
+ logger.warning(f"[GroqKeyManager] Key {key[:8]}... cooldown: {reason}")
+ break
+
+RAW_GROQ_KEYS = clean_keys(os.getenv("GROQ_API_KEYS") or getattr(settings, "groq_api_keys", ""))
+groq_key_manager = GroqKeyManager(RAW_GROQ_KEYS)
+
+# Free-tier models verified September 2026.
+# Groq removed Llama 3.3 70B / 3.1 8B from the free tier on 2026-08-16 (enterprise-only).
+GROQ_JSON_MODEL = "openai/gpt-oss-20b" # fastest free Groq model with json_object support
+
+# OpenRouter :free models (verified active September 2026).
+# Free tier: 20 RPM, 50 req/day (1,000/day after a one-time $10 credit top-up).
+OPENROUTER_FREE_MODELS = {
+ "HIGH": "deepseek/deepseek-chat-v3.1:free",
+ "MEDIUM": "qwen/qwen-2.5-72b-instruct:free",
+ "LOW": "meta-llama/llama-3.3-70b-instruct:free",
+}
+
+TIERS = {
+ "HIGH": {
+ "label": "CRITICAL",
+ "models": [
+ settings.gemini_high_model or "gemini-3.5-pro", # Primary — Agentic reasoning, 2M context
+ "gemini-3.5-flash", # Fallback — High-throughput
+ ],
+ "temperature": 0.3,
+ "max_output_tokens": 4096,
+ "timeout": 60.0,
+ "description": "Complex reasoning: semantic matching, SROI audit, SKKNI mapping, Strategic Advisor",
+ },
+ "MEDIUM": {
+ "label": "STANDARD",
+ "models": [
+ settings.gemini_medium_model or "gemini-3.5-flash", # Primary — 4x faster, 1M context
+ "gemini-1.5-flash", # Legacy fallback
+ ],
+ "temperature": 0.5,
+ "max_output_tokens": 2048,
+ "timeout": 30.0,
+ "description": "Operational: bulk vetting, career coach responses, blog generation",
+ },
+ "LOW": {
+ "label": "FAST",
+ "models": [
+ settings.gemini_low_model or "gemini-3.5-flash", # High interaction
+ ],
+ "temperature": 0.1,
+ "max_output_tokens": 1024,
+ "timeout": 20.0,
+ "description": "Utility: chat mediation, engagement bot, simple classification",
+ },
+}
+
+# Default timeout for API calls (seconds)
+DEFAULT_TIMEOUT = 30.0
+
+
+# =============================================================================
+# TIER 1: GEMINI 3 SERIES API CALL
+# =============================================================================
+
+async def generate_embedding(text: str) -> List[float]:
+ """Generates a text embedding vector (768 dimensions) using a free/fast API.
+
+ Defaults to Gemini's embedding model.
+ """
+ if AI_DISABLED:
+ return [0.0] * 768
+
+ active_key = await gemini_key_manager.get_key()
+ if not active_key:
+ return [0.0] * 768
+
+ # Migrate from deprecated text-embedding-004 to gemini-embedding-001
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent?key={active_key}"
+ payload = {
+ "model": "models/gemini-embedding-001",
+ "content": {
+ "parts": [{"text": text}]
+ },
+ "outputDimensionality": 768
+ }
+
+ try:
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ resp = await client.post(url, json=payload)
+
+ if resp.status_code == 200:
+ gemini_key_manager.mark_success(active_key)
+ data = resp.json()
+ embedding = data.get("embedding", {}).get("values", [])
+ # Gemini gemini-embedding-001 is set to 768 dimensions via config
+ if len(embedding) == 768:
+ return embedding
+ else:
+ logger.error(f"[Embeddings] Dimension mismatch: got {len(embedding)}, expected 768")
+ else:
+ gemini_key_manager.mark_failed(active_key, reason=str(resp.status_code))
+ logger.error(f"[Embeddings] API Error {resp.status_code}: {resp.text}")
+ except Exception as e:
+ gemini_key_manager.mark_failed(active_key, reason=str(e))
+ logger.error(f"[Embeddings] Failed to generate embedding: {e}")
+
+ return [0.0] * 768
+
+async def call_gemini_tier(
+ prompt: str,
+ tier: str = "MEDIUM",
+ system_instruction: Optional[str] = None,
+ temperature: Optional[float] = None,
+ max_output_tokens: Optional[int] = None,
+ response_mime_type: Optional[str] = None,
+) -> Tuple[Optional[str], int]:
+ """Call Gemini API using tier-based model routing and multi-key rotation.
+
+ Ported from GAS callGeminiWithFallback() — same retry logic,
+ same multi-model queue, same error handling pattern.
+ """
+ # Quick exit if disabled globally
+ if AI_DISABLED:
+ return None, 0
+
+ tier = tier.upper()
+
+ # ─── CACHE CHECK ───
+ prompt_hash = hash_prompt(prompt, system_instruction)
+ cached = cached_ai_call(tier, prompt_hash, mime_type=response_mime_type or "")
+ if cached:
+ logger.debug(f"[Cache] AI response found for tier={tier}")
+ return cached
+
+ config = TIERS.get(tier, TIERS["MEDIUM"])
+
+ use_temp = temperature if temperature is not None else config["temperature"]
+ use_tokens = max_output_tokens if max_output_tokens is not None else config["max_output_tokens"]
+ timeout = config["timeout"]
+
+ # FIX: 9Router layer removed from the hot path (ROUTER_API_URL empty in .env
+ # and it ran BEFORE Gemini, wasting quota on an unconfigured provider.
+ # The generic OpenRouter layer at the end of the chain covers 9Router-style
+ # OpenAI-compatible endpoints if ever re-enabled.
+
+ for model in config["models"]:
+ # ROTATION: Get a fresh key from the manager
+ active_key = await gemini_key_manager.get_key()
+ if not active_key:
+ logger.error("No available Gemini API keys (all on cooldown)")
+ return None, 0
+
+ # Use v1beta endpoint when response_mime_type is set (needed for JSON mode)
+ api_version = "v1beta" if response_mime_type else "v1"
+ url = f"https://generativelanguage.googleapis.com/{api_version}/models/{model}:generateContent?key={active_key}"
+
+ generation_config: Dict[str, Any] = {
+ "temperature": use_temp,
+ "maxOutputTokens": use_tokens,
+ }
+ if response_mime_type:
+ generation_config["responseMimeType"] = response_mime_type
+
+ payload: Dict[str, Any] = {
+ "contents": [{"parts": [{"text": prompt}]}],
+ "generationConfig": generation_config,
+ }
+
+ if system_instruction:
+ payload["systemInstruction"] = {"parts": [{"text": system_instruction}]}
+
+ headers = {"User-Agent": gemini_key_manager.get_random_user_agent()}
+
+ try:
+ async with httpx.AsyncClient(timeout=timeout) as client:
+ resp = await client.post(url, json=payload, headers=headers)
+
+ if resp.status_code == 200:
+ gemini_key_manager.mark_success(active_key)
+ data = resp.json()
+ try:
+ text = data["candidates"][0]["content"]["parts"][0]["text"]
+ tokens_used = data.get("usageMetadata", {}).get("totalTokenCount", 0)
+ logger.debug(f"Gemini 3.5 [{config['label']}] {model}: {tokens_used} tokens (Key: {active_key[:8]})")
+ cache_ai_response(tier, prompt_hash, "", text, tokens_used, mime_type=response_mime_type or "")
+ return text, tokens_used
+ except (KeyError, IndexError, TypeError) as e:
+ logger.warning(f"Gemini {model}: unexpected response format: {e}")
+ continue
+
+ elif resp.status_code in (429, 503):
+ # Rate limited or overloaded — try next model in chain
+ logger.warning(f"Gemini {model} [{config['label']}]: HTTP {resp.status_code} (rate limit/overload)")
+ gemini_key_manager.mark_failed(active_key, reason=str(resp.status_code))
+ continue
+
+ elif resp.status_code == 404:
+ # Model not found — try fallback
+ logger.debug(f"Gemini {model} [{config['label']}]: HTTP 404 (not available)")
+ continue
+
+ else:
+ logger.warning(f"Gemini {model} [{config['label']}]: HTTP {resp.status_code}")
+ gemini_key_manager.mark_failed(active_key, reason=f"HTTP_{resp.status_code}")
+ continue
+
+ except httpx.TimeoutException:
+ logger.warning(f"Gemini {model} [{config['label']}]: timeout ({timeout}s)")
+ gemini_key_manager.mark_failed(active_key, reason="Timeout")
+ continue
+ except httpx.RequestError as e:
+ logger.warning(f"Gemini {model} [{config['label']}]: network error: {e}")
+ gemini_key_manager.mark_failed(active_key, reason=f"RequestError: {type(e).__name__}")
+ continue
+ except Exception as e:
+ logger.error(f"Gemini {model} [{config['label']}]: unexpected error: {e}")
+ gemini_key_manager.mark_failed(active_key, reason=f"Unexpected: {type(e).__name__}")
+ continue
+
+ # ─── OPENROUTER FALLBACK LAYER (free-tier models, with rotation) ───
+ # Runs AFTER Gemini so the primary free quota is consumed first.
+ if openrouter_key_manager.keys:
+ active_openrouter_key = await openrouter_key_manager.get_key()
+ if active_openrouter_key:
+ router_model = OPENROUTER_FREE_MODELS.get(tier, OPENROUTER_FREE_MODELS["MEDIUM"])
+ logger.info(f"[OpenRouter] Fallback routing ({tier}) -> {router_model}")
+ headers = {
+ "Authorization": f"Bearer {active_openrouter_key}",
+ "HTTP-Referer": "https://briga.id",
+ "X-Title": "Brigawan AI",
+ "Content-Type": "application/json"
+ }
+ messages = []
+ if system_instruction:
+ messages.append({"role": "system", "content": system_instruction})
+ messages.append({"role": "user", "content": prompt})
+ payload = {
+ "model": router_model,
+ "messages": messages,
+ "temperature": use_temp,
+ "max_tokens": use_tokens
+ }
+ if response_mime_type == "application/json":
+ payload["response_format"] = {"type": "json_object"}
+ try:
+ async with httpx.AsyncClient(timeout=timeout) as client:
+ resp = await client.post(settings.openrouter_api_url, json=payload, headers=headers)
+ if resp.status_code == 200:
+ openrouter_key_manager.mark_success(active_openrouter_key)
+ data = resp.json()
+ text = data["choices"][0]["message"]["content"]
+ tokens_used = data.get("usage", {}).get("total_tokens", 0)
+ logger.info(f"[OpenRouter] Success: {tokens_used} tokens (Model: {router_model})")
+ cache_ai_response(tier, prompt_hash, "", text, tokens_used, mime_type=response_mime_type or "")
+ return text, tokens_used
+ elif resp.status_code in (429, 402, 403):
+ logger.warning(f"[OpenRouter] Key exhausted/rate limited (HTTP {resp.status_code}). Rotating...")
+ openrouter_key_manager.mark_failed(active_openrouter_key, reason=str(resp.status_code))
+ else:
+ logger.warning(f"[OpenRouter] HTTP Error {resp.status_code}: {resp.text[:200]}. Falling back...")
+ except Exception as e:
+ logger.warning(f"[OpenRouter] Call failed: {e}. Falling back...")
+
+ # ─── GROQ FALLBACK LAYER (fastest free tier, last AI resort) ───
+ if groq_key_manager.keys:
+ active_groq_key = await groq_key_manager.get_key()
+ if active_groq_key:
+ logger.info(f"[Groq] Fallback routing ({tier}) -> {GROQ_JSON_MODEL}")
+ headers = {
+ "Authorization": f"Bearer {active_groq_key}",
+ "Content-Type": "application/json"
+ }
+ messages = []
+ if system_instruction:
+ messages.append({"role": "system", "content": system_instruction})
+ messages.append({"role": "user", "content": prompt})
+ payload = {
+ "model": GROQ_JSON_MODEL,
+ "messages": messages,
+ "temperature": use_temp,
+ "max_tokens": use_tokens,
+ }
+ if response_mime_type == "application/json":
+ payload["response_format"] = {"type": "json_object"}
+ try:
+ async with httpx.AsyncClient(timeout=timeout) as client:
+ resp = await client.post("https://api.groq.com/openai/v1/chat/completions", json=payload, headers=headers)
+ if resp.status_code == 200:
+ groq_key_manager.mark_success(active_groq_key)
+ data = resp.json()
+ text = data["choices"][0]["message"]["content"]
+ tokens_used = data.get("usage", {}).get("total_tokens", 0)
+ logger.info(f"[Groq] Success: {tokens_used} tokens (Model: {GROQ_JSON_MODEL})")
+ cache_ai_response(tier, prompt_hash, "", text, tokens_used, mime_type=response_mime_type or "")
+ return text, tokens_used
+ elif resp.status_code in (429, 402, 403):
+ logger.warning(f"[Groq] Key exhausted/rate limited (HTTP {resp.status_code}). Rotating...")
+ groq_key_manager.mark_failed(active_groq_key, reason=str(resp.status_code))
+ else:
+ logger.warning(f"[Groq] HTTP Error {resp.status_code}: {resp.text[:200]}")
+ except Exception as e:
+ logger.warning(f"[Groq] Call failed: {e}")
+
+ return None, 0 # All providers in the tier failed
+
+
+# =============================================================================
+# PUBLIC TIERED HELPERS (convenience wrappers)
+# =============================================================================
+
+async def call_high(
+ prompt: str,
+ system_instruction: Optional[str] = None,
+ temperature: Optional[float] = None,
+ max_output_tokens: Optional[int] = None,
+) -> Tuple[Optional[str], int]:
+ """Call Gemini 3.5 Pro (complex tasks) with 3.5 Flash fallback.
+
+ Use for: semantic matching, CV generation, bulk vetting, SKKNI, RecruiterAI.
+ """
+ return await call_gemini_tier(
+ prompt=prompt,
+ tier="HIGH",
+ system_instruction=system_instruction,
+ temperature=temperature,
+ max_output_tokens=max_output_tokens,
+ )
+
+
+async def call_medium(
+ prompt: str,
+ system_instruction: Optional[str] = None,
+ temperature: Optional[float] = None,
+ max_output_tokens: Optional[int] = None,
+) -> Tuple[Optional[str], int]:
+ """Call Gemini 3.5 Flash (general purpose).
+
+ Use for: search recommendations, auto-blog, learning system, green job analysis.
+ """
+ return await call_gemini_tier(
+ prompt=prompt,
+ tier="MEDIUM",
+ system_instruction=system_instruction,
+ temperature=temperature,
+ max_output_tokens=max_output_tokens,
+ )
+
+
+async def call_low(
+ prompt: str,
+ system_instruction: Optional[str] = None,
+ temperature: Optional[float] = None,
+ max_output_tokens: Optional[int] = None,
+) -> Tuple[Optional[str], int]:
+ """Call Gemini 3.5 Flash (lightweight config).
+
+ Use for: chat mediation, registry support, engagement, maintenance.
+ """
+ return await call_gemini_tier(
+ prompt=prompt,
+ tier="LOW",
+ system_instruction=system_instruction,
+ temperature=temperature,
+ max_output_tokens=max_output_tokens,
+ )
+
+
+async def call_groq_json(
+ prompt: str,
+ system_instruction: Optional[str] = None,
+ temperature: Optional[float] = None,
+ timeout: float = 30.0
+) -> dict:
+ """Fallback helper to call Groq API in JSON mode with multi-key rotation.
+
+ FIX (2026-09): llama-3.3-70b-versatile was removed from Groq's free tier on
+ 2026-08-16 (enterprise-only). Switched to openai/gpt-oss-20b (free, fast,
+ native json_object support). Also now uses GROQ_API_KEYS (comma-separated)
+ via GroqKeyManager instead of a single GROQ_API_KEY.
+ """
+ active_key = await groq_key_manager.get_key()
+ if not active_key:
+ logger.warning("[GroqFallback] GROQ_API_KEYS not configured or all keys on cooldown.")
+ return {"error": "GROQ_API_KEYS not configured"}
+
+ logger.info(f"[GroqFallback] Falling back to Groq {GROQ_JSON_MODEL}...")
+
+ endpoint = "https://api.groq.com/openai/v1/chat/completions"
+ headers = {
+ "Authorization": f"Bearer {active_key}",
+ "Content-Type": "application/json"
+ }
+
+ messages = []
+ if system_instruction:
+ messages.append({"role": "system", "content": system_instruction})
+ messages.append({"role": "user", "content": prompt})
+
+ payload = {
+ "model": GROQ_JSON_MODEL,
+ "messages": messages,
+ "temperature": temperature if temperature is not None else 0.2,
+ "response_format": {"type": "json_object"}
+ }
+
+ async with httpx.AsyncClient(timeout=timeout) as client:
+ try:
+ resp = await client.post(endpoint, headers=headers, json=payload)
+ if resp.status_code == 200:
+ groq_key_manager.mark_success(active_key)
+ res_data = resp.json()
+ content = res_data["choices"][0]["message"]["content"].strip()
+ return json.loads(content)
+ elif resp.status_code in (429, 402, 403):
+ groq_key_manager.mark_failed(active_key, reason=str(resp.status_code))
+ # One retry with the next key before giving up
+ retry_key = await groq_key_manager.get_key()
+ if retry_key and retry_key != active_key:
+ headers["Authorization"] = f"Bearer {retry_key}"
+ resp = await client.post(endpoint, headers=headers, json=payload)
+ if resp.status_code == 200:
+ groq_key_manager.mark_success(retry_key)
+ res_data = resp.json()
+ content = res_data["choices"][0]["message"]["content"].strip()
+ return json.loads(content)
+ return {"error": f"Groq API error: {resp.status_code}"}
+ else:
+ logger.error(f"[GroqFallback] API error: {resp.status_code} - {resp.text[:200]}")
+ return {"error": f"Groq API error: {resp.status_code}"}
+ except Exception as e:
+ logger.error(f"[GroqFallback] Call failed: {e}")
+ return {"error": f"Groq call failed: {e}"}
+
+
+async def call_gemini_json(
+ prompt: str,
+ tier: str = "MEDIUM",
+ system_instruction: Optional[str] = None,
+ temperature: Optional[float] = None,
+ max_output_tokens: Optional[int] = None,
+) -> Tuple[dict, int]:
+ """Call Gemini with responseMimeType=application/json and return parsed dict.
+
+ This is the shared utility that replaces the duplicate _call_gemini methods
+ previously copied across services. Always returns a dict — never throws.
+
+ Returns (parsed JSON dict, tokens) on success, or ({"error": "..."}, 0) on failure.
+ """
+ try:
+ result, tokens = await call_gemini_tier(
+ prompt=prompt,
+ tier=tier,
+ system_instruction=system_instruction,
+ temperature=temperature,
+ max_output_tokens=max_output_tokens,
+ response_mime_type="application/json",
+ )
+ if not result:
+ # --- FALLBACK TO GROQ ---
+ groq_res = await call_groq_json(prompt, system_instruction, temperature)
+ if "error" not in groq_res:
+ return groq_res, 0
+ return {"error": "AI service returned no response"}, 0
+
+ text = result.strip()
+ # Strip markdown code fences if Gemini wraps the JSON
+ if text.startswith("```"):
+ text = re.sub(r"^```[a-z]*\n|```$", "", text).strip()
+
+ return json.loads(text), tokens
+ except json.JSONDecodeError as e:
+ logger.warning(f"call_gemini_json: JSON parse error: {e}")
+ # --- FALLBACK TO GROQ ---
+ groq_res = await call_groq_json(prompt, system_instruction, temperature)
+ if "error" not in groq_res:
+ return groq_res, 0
+ return {"error": f"Failed to parse AI response as JSON: {e}"}, 0
+ except Exception as e:
+ logger.error(f"call_gemini_json error: {e}")
+ # --- FALLBACK TO GROQ ---
+ groq_res = await call_groq_json(prompt, system_instruction, temperature)
+ if "error" not in groq_res:
+ return groq_res, 0
+ return {"error": f"AI call failed: {e}"}, 0
+
+
+# =============================================================================
+# TIER 2: ALGORITHMIC / DETERMINISTIC FALLBACK (no API calls)
+# =============================================================================
+
+def _algorithmic_match_score(query: str, talent_data: Dict[str, Any]) -> Tuple[int, str]:
+ """Compute match score algorithmically without any AI calls.
+
+ Uses keyword overlap, skill matching, and sector alignment.
+ Score range: 0-100.
+ """
+ query_lower = query.lower()
+ query_words = set(query_lower.split())
+
+ skills = (talent_data.get("skill_tags") or "").lower()
+ sector = (talent_data.get("sector_focus") or "").lower()
+ experience = (talent_data.get("experience") or "").lower()[:500]
+ category = (talent_data.get("category") or "").lower()
+ name = (talent_data.get("name") or "").lower()
+ location = (talent_data.get("location") or "").lower()
+
+ score = 0
+ matched_terms = []
+
+ # 1. Direct skill match (highest weight)
+ skill_matches = [w for w in query_words if w in skills]
+ if skill_matches:
+ score += min(len(skill_matches) * 15, 45)
+ matched_terms.extend(skill_matches)
+
+ # 2. Sector alignment
+ sector_matches = [w for w in query_words if w in sector]
+ if sector_matches:
+ score += min(len(sector_matches) * 10, 20)
+ matched_terms.extend(sector_matches)
+
+ # 3. Experience mention
+ exp_matches = [w for w in query_words if w in experience]
+ if exp_matches:
+ score += min(len(exp_matches) * 5, 15)
+
+ # 4. Category alignment
+ if category and any(w in category for w in query_words):
+ score += 10
+
+ # 5. Location match
+ if location and any(w in location for w in query_words):
+ score += 10
+
+ # 6. Name match (lower weight — reduces false positives for name searches)
+ name_matches = [w for w in query_words if len(w) > 3 and w in name]
+ if name_matches:
+ score += 5
+
+ score = min(score, 100)
+
+ if score >= 80:
+ summary = "Strong match — high skill and sector alignment"
+ elif score >= 60:
+ summary = "Good match — relevant skills detected"
+ elif score >= 40:
+ summary = "Moderate match — partial alignment"
+ elif score >= 20:
+ summary = "Weak match — minimal overlap"
+ else:
+ summary = "Low match — consider refining search criteria"
+
+ if matched_terms:
+ summary += f" (matched: {', '.join(matched_terms[:5])})"
+
+ return score, summary
+
+
+def _algorithmic_cv_generation(talent_data: Dict[str, Any]) -> str:
+ """Generate structured CV text without AI.
+ Ported from GAS CVGenerator.gs patterns.
+ """
+ name = talent_data.get("name") or "-"
+ email = talent_data.get("email") or "-"
+ phone = talent_data.get("phone") or "-"
+ education = talent_data.get("education") or "-"
+ experience = talent_data.get("experience") or "-"
+ skills = talent_data.get("skill_tags") or "-"
+ certs = talent_data.get("cert_other") or "-"
+ languages = talent_data.get("language") or "-"
+
+ cv = (
+ f"=== CURRICULUM VITAE ===\n"
+ f"\n--- Data Pribadi ---\n"
+ f"Nama: {name}\n"
+ f"Email: {email}\n"
+ f"Telepon: {phone}\n"
+ f"\n--- Pendidikan ---\n{education}\n"
+ f"\n--- Pengalaman Kerja ---\n{experience}\n"
+ f"\n--- Keahlian ---\n{skills}\n"
+ f"\n--- Sertifikasi ---\n{certs}\n"
+ f"\n--- Bahasa ---\n{languages}\n"
+ )
+ return cv[:4000]
+
+
+# =============================================================================
+# TIER 3: GRACEFUL DEFAULTS (never crashes)
+# =============================================================================
+
+def _graceful_match_score() -> Tuple[int, str]:
+ """Last resort — return safe defaults when everything fails."""
+ return 50, "AI scoring unavailable — using profile completeness score"
+
+
+def _graceful_ai_response() -> str:
+ """Last resort — return safe default text."""
+ return "Maaf, layanan AI sedang tidak tersedia. Silakan coba lagi nanti."
+
+
+# =============================================================================
+# TASK-SPECIFIC AI FUNCTIONS (mapped to Gemini 3 series tiers)
+# =============================================================================
+#
+# TIER MAPPING (matches GAS AI_CONFIG.TIERS):
+#
+# HIGH (CRITICAL) → gemini-3.1-pro-preview → 3.5-flash
+# - analyze_semantic_match() ← GAS SearchEngine.gs (STANDARD → HIGH for accuracy)
+# - generate_cv_text() ← GAS CVGenerator.gs (was STANDARD → HIGH for quality)
+# - analyze_career_path() ← GAS RecruiterAI.gs (CRITICAL)
+# - bulk_vetting_analysis() ← GAS BulkVettingEngine.gs (CRITICAL)
+# - skkni_classification() ← GAS SKKNI_Agent.gs (CRITICAL)
+# - talent_dashboard_advisor() ← GAS TalentDashboard.gs (CRITICAL)
+#
+# MEDIUM (STANDARD) → gemini-3.5-flash
+# - generate_search_recommendation() ← GAS SearchEngine.gs
+# - generate_blog_post() ← GAS AutoBlog.gs
+# - analyze_green_job() ← GAS GreenJobAgent.gs
+# - generate_learning_path() ← GAS LearningSystem.gs
+# - generate_content() ← GAS ContentAgent.gs
+#
+# LOW (FAST) → gemini-3.5-flash (lightweight)
+# - chat_mediation() ← GAS ChatManager.gs
+# - registry_assist() ← GAS Registry.gs / RegistryEmployer.gs
+# - engagement_message() ← GAS TalentEngagement.gs
+# - maintenance_clean() ← GAS Maintenance.gs
+# - financial_recommendation() ← GAS Finance.gs
+
+
+# ─── HIGH TIER (Complex Reasoning) ──────────────────────────────────────────
+
+async def analyze_semantic_match(
+ query: str,
+ talent_data: Dict[str, Any],
+) -> Dict[str, Any]:
+ """HIGH tier: Analyze semantic match between search query and talent profile.
+
+ Tier chain: Gemini 3.5 Pro → 3.5 Flash → algorithmic → graceful default.
+ NEVER throws.
+ """
+ try:
+ if GEMINI_API_KEY and not AI_DISABLED:
+ system_prompt = (
+ "You are Brigawan AI, a green jobs talent matcher in Indonesia. "
+ "Analyze the match between a recruiter's search query and a talent profile. "
+ "Return ONLY a JSON object: {score: int (0-100), summary: string (max 100 chars, Bahasa Indonesia)}"
+ )
+ user_prompt = (
+ f"Search Query: {query[:500]}\n"
+ f"Talent Skills: {talent_data.get('skill_tags', '')[:300]}\n"
+ f"Talent Experience: {talent_data.get('experience', '')[:300]}\n"
+ f"Talent Sector: {talent_data.get('sector_focus', '')[:100]}\n"
+ f"Talent Location: {talent_data.get('location', '')[:100]}"
+ )
+
+ # Use shared JSON utility
+ parsed, tokens = await call_gemini_json(
+ prompt=user_prompt,
+ tier="HIGH",
+ system_instruction=system_prompt
+ )
+
+ if isinstance(parsed, dict) and "score" in parsed:
+ score = max(0, min(100, int(parsed.get("score", 50))))
+ summary = str(parsed.get("summary", "") or "")[:120]
+ return {"score": score, "summary": summary, "ai_used": True, "tier": "HIGH", "tokens": tokens}
+
+ # Algorithmic fallback
+ score, summary = _algorithmic_match_score(query, talent_data)
+ return {"score": score, "summary": summary, "ai_used": False, "tier": "algorithmic", "tokens": 0}
+
+ except Exception as e:
+ logger.error(f"analyze_semantic_match error: {e}")
+
+ score, summary = _graceful_match_score()
+ return {"score": score, "summary": summary, "ai_used": False, "tier": "graceful", "tokens": 0}
+
+
+async def generate_cv_text(talent_data: Dict[str, Any]) -> Tuple[str, int]:
+ """HIGH tier: Generate CV text using Gemini 3.5 Pro.
+
+ Tier chain: Gemini 3.5 Pro → 3.5 Flash → algorithmic template.
+ NEVER throws.
+ """
+ try:
+ if GEMINI_API_KEY and not AI_DISABLED:
+ prompt = (
+ f"Buat CV dalam Bahasa Indonesia untuk talent berikut:\n"
+ f"Nama: {talent_data.get('name', '')}\n"
+ f"Pendidikan: {talent_data.get('education', '')[:300]}\n"
+ f"Pengalaman: {talent_data.get('experience', '')[:500]}\n"
+ f"Keahlian: {talent_data.get('skill_tags', '')[:300]}\n"
+ f"Sertifikasi: {talent_data.get('cert_other', '')[:200]}\n"
+ f"Buat CV yang rapi, profesional, dan siap pakai untuk rekrutmen."
+ )
+ result, tokens = await call_high(prompt=prompt, max_output_tokens=2048)
+ if result:
+ return result, tokens
+
+ return _algorithmic_cv_generation(talent_data), 0
+
+ except Exception as e:
+ logger.error(f"generate_cv_text error: {e}")
+ return _algorithmic_cv_generation(talent_data), 0
+
+
+# ─── MEDIUM TIER (General Purpose) ──────────────────────────────────────────
+
+async def generate_search_recommendation(query: str, results_count: int) -> Tuple[str, int]:
+ """MEDIUM tier: Generate search recommendation.
+
+ Tier chain: gemini-3.5-flash → algorithmic → empty string.
+ NEVER throws.
+ """
+ try:
+ if GEMINI_API_KEY and not AI_DISABLED and results_count > 0:
+ prompt = (
+ f"Search query: {query[:200]}\n"
+ f"Results found: {results_count}\n"
+ f"Give a brief, helpful recommendation (max 80 chars in Bahasa Indonesia) "
+ f"for a recruiter on how to refine their search or proceed."
+ )
+ result, tokens = await call_medium(prompt=prompt)
+ if result:
+ return result.strip()[:120], tokens
+
+ # Algorithmic fallback
+ if results_count == 0:
+ return "Coba gunakan kata kunci yang lebih umum atau berbeda.", 0
+ elif results_count < 5:
+ return "Hasil terbatas — coba perluas kata kunci atau lokasi.", 0
+ else:
+ return f"Ditemukan {results_count} talenta. Gunakan filter untuk mempersempit hasil.", 0
+
+ except Exception as e:
+ logger.error(f"generate_search_recommendation error: {e}")
+ return "", 0
+
+
+async def generate_blog_post(topic: str, sector: str, context: str = "") -> Tuple[Optional[str], int]:
+ """MEDIUM tier: Generate blog post content.
+
+ Tier chain: gemini-3.5-flash → None.
+ GAS equivalent: AutoBlog.gs → callGeminiWithFallback (STANDARD tier).
+ NEVER throws.
+ """
+ try:
+ if GEMINI_API_KEY and not AI_DISABLED:
+ prompt = (
+ f"You are the Briga SEO Editor. Write a blog post in INDONESIAN.\n\n"
+ f"TOPIC: {topic}\n"
+ f"INDUSTRY: {sector}\n"
+ f"CONTEXT: {context[:500]}\n\n"
+ f"Return JSON: {{\"title\": \"...\", \"summary\": \"...\", \"content\": \"...\"}}"
+ )
+ return await call_medium(prompt=prompt, max_output_tokens=2048)
+ return None, 0
+ except Exception as e:
+ logger.error(f"generate_blog_post error: {e}")
+ return None, 0
+
+
+# ─── LOW TIER (Lightweight Utility) ─────────────────────────────────────────
+
+async def chat_mediation(user_message: str, context: str = "") -> Tuple[Optional[str], int]:
+ """LOW tier: Mediate chat messages between recruiters and talents.
+
+ Tier chain: gemini-3.5-flash (lightweight) → None.
+ GAS equivalent: ChatManager.gs → callGeminiAI (FAST tier).
+ NEVER throws.
+ """
+ try:
+ if GEMINI_API_KEY and not AI_DISABLED:
+ prompt = (
+ f"Anda adalah asisten Brigawan. Mediasi percakapan ini:\n\n"
+ f"Konteks: {context[:300]}\n"
+ f"Pesan: {user_message[:1000]}\n\n"
+ f"Berikan respons yang profesional dan membantu."
+ )
+ return await call_low(prompt=prompt)
+ return None, 0
+ except Exception as e:
+ logger.error(f"chat_mediation error: {e}")
+ return None, 0
+
+
+async def engagement_message(talent_name: str, template: str = "follow_up") -> Tuple[Optional[str], int]:
+ """LOW tier: Generate personalized engagement message.
+
+ Tier chain: gemini-3.5-flash (lightweight) → None.
+ GAS equivalent: TalentEngagement.gs.
+ NEVER throws.
+ """
+ try:
+ if GEMINI_API_KEY and not AI_DISABLED:
+ prompt = (
+ f"Buat pesan engagement yang personal untuk talent: {talent_name}\n"
+ f"Template: {template}\n"
+ f"Buat singkat (max 100 kata) dan profesional dalam Bahasa Indonesia."
+ )
+ return await call_low(prompt=prompt)
+ return None, 0
+ except Exception as e:
+ logger.error(f"engagement_message error: {e}")
+ return None, 0
+
+
+async def registry_assist(query: str, data_summary: str = "") -> Tuple[Optional[str], int]:
+ """LOW tier: Assist with data registry validation or lookup.
+
+ Tier chain: gemini-3.5-flash (lightweight) → None.
+ GAS equivalent: Registry.gs / RegistryEmployer.gs (FAST tier).
+ NEVER throws.
+ """
+ try:
+ if GEMINI_API_KEY and not AI_DISABLED:
+ prompt = (
+ f"Bantu validasi data registrasi berikut:\n"
+ f"Query: {query[:300]}\n"
+ f"Data: {data_summary[:500]}\n"
+ f"Berikan konfirmasi atau saran perbaikan singkat."
+ )
+ return await call_low(prompt=prompt)
+ return None, 0
+ except Exception as e:
+ logger.error(f"registry_assist error: {e}")
+ return None, 0
+
+
+async def financial_recommendation(context: str) -> Tuple[Optional[str], int]:
+ """LOW tier: Generate financial recommendation.
+
+ Tier chain: gemini-3.5-flash (lightweight) → None.
+ GAS equivalent: Finance.gs → callGeminiWithFallback.
+ NEVER throws.
+ """
+ try:
+ if GEMINI_API_KEY and not AI_DISABLED:
+ prompt = (
+ f"Anda adalah asisten finansial Brigawan.\n"
+ f"Konteks: {context[:500]}\n"
+ f"Berikan rekomendasi singkat dan praktis."
+ )
+ return await call_low(prompt=prompt)
+ return None, 0
+ except Exception as e:
+ logger.error(f"financial_recommendation error: {e}")
+ return None, 0
+
+
+# ─── FUTURE HIGH TIER STUBS (ready for Series 3 port) ───────────────────────
+
+def get_bulk_vetting_system_prompt(recruiter_context: str = "") -> str:
+ from app.config.vetting_rules import VETTING_RULES, CAREER_TRANSITION_DB
+
+ sector_list = ", ".join(VETTING_RULES["green_sectors"])
+
+ # Build compressed career transition reference (top entries per sector)
+ transition_ref = ""
+ seen_sectors = {}
+ for entry in CAREER_TRANSITION_DB:
+ sector = entry["sector"]
+ if sector in seen_sectors:
+ continue
+ seen_sectors[sector] = True
+ skills_slice = ", ".join(entry["skills"][:3])
+ transition_ref += f"- {sector}: {entry['targetJob']} (Skills: {skills_slice})\n"
+
+ # Assemble system prompt
+ return (
+ "IDENTITAS: Kamu adalah Brigawan Vetting Intelligence — mesin evaluasi talenta hijau paling presisi di Indonesia.\n\n"
+ "MISI: Evaluasi CV/resume kandidat secara massal untuk menentukan kesiapan mereka masuk ke industri keberlanjutan (green jobs).\n\n"
+ "=== KNOWLEDGE BASE ===\n\n"
+ f"KATEGORI TALENTA:\n"
+ f"- Skilled: {VETTING_RULES['categories']['Skilled']}\n"
+ f"- Semi-Skilled: {VETTING_RULES['categories']['Semi-Skilled']}\n"
+ f"- Unskilled: {VETTING_RULES['categories']['Unskilled']}\n\n"
+ f"SEKTOR HIJAU YANG DIKENALI:\n{sector_list}\n\n"
+ f"PETA TRANSISI KARIR (Brown → Green):\n{transition_ref}\n"
+ "=== INSTRUKSI EVALUASI ===\n\n"
+ "1. EKSTRAKSI DATA\n"
+ " Dari teks CV yang diberikan, identifikasi:\n"
+ " - Nama (jangan tampilkan di output, ganti dengan \"Kandidat\")\n"
+ " - Pendidikan terakhir + jurusan\n"
+ " - Total tahun pengalaman kerja\n"
+ " - Riwayat kerja (perusahaan + posisi + durasi)\n"
+ " - Sertifikasi / lisensi yang dimiliki\n"
+ " - Bahasa yang dikuasai\n"
+ " - Lokasi domisili\n\n"
+ " PENTING — FORMAT PENGALAMAN KERJA S.T.A.R:\n"
+ " Brigawan menggunakan framework S.T.A.R untuk penulisan pengalaman kerja:\n"
+ " - Situation: Konteks/latar belakang masalah yang dihadapi\n"
+ " - Task: Tugas/tanggung jawab spesifik yang diberikan\n"
+ " - Action: Langkah konkret yang diambil kandidat\n"
+ " - Result: Hasil terukur / dampak nyata dari aksi tersebut\n\n"
+ " Saat mengevaluasi pengalaman kerja, perhatikan:\n"
+ " a) Apakah narasi ditulis dengan struktur S.T.A.R yang jelas?\n"
+ " b) Apakah Result menyertakan metrik/angka terukur (%, Rp, unit)?\n"
+ " c) Apakah Action menunjukkan inisiatif dan ownership?\n"
+ " Berikan field \"star_quality\" di output: \"strong\" / \"moderate\" / \"weak\" / \"absent\".\n\n"
+ "2. SCORING (0-100)\n"
+ " Gunakan bobot berikut:\n"
+ " - Relevansi Pengalaman ke Sektor Hijau: 30%\n"
+ " - Kualitas Narasi S.T.A.R (kejelasan dampak & metrik): 10%\n"
+ " - Sertifikasi & Kualifikasi Teknis: 25%\n"
+ " - Pendidikan (linearitas jurusan): 15%\n"
+ " - Transferable Skills (dari Brown Industry): 10%\n"
+ " - Soft Indicators (bahasa asing, leadership, proyek): 10%\n\n"
+ " BONUS SCORING:\n"
+ " +5 poin: Punya sertifikasi internasional (NEBOSH, ISO, GRI)\n"
+ " +5 poin: Pengalaman di Brown Industry >5 tahun (potensi transisi tinggi)\n"
+ " +3 poin: Narasi S.T.A.R \"strong\" dengan Result terukur\n"
+ " +3 poin: Menguasai bahasa asing (Inggris/Jepang/Jerman)\n"
+ " +3 poin: CV memiliki ATS readiness \"high\" (keyword padat, struktur standar)\n"
+ " -5 poin: CV memiliki ATS readiness \"low\" (format buruk, minim keyword industri)\n"
+ " -10 poin: Tidak ada pengalaman kerja sama sekali DAN bukan lulusan STEM\n\n"
+ "3. KATEGORI\n"
+ " - Skor 70-100 → Skilled\n"
+ " - Skor 40-69 → Semi-Skilled\n"
+ " - Skor 0-39 → Unskilled\n\n"
+ "4. SECTOR MATCHING\n"
+ " Tentukan 1-3 sektor hijau yang paling cocok dari daftar SEKTOR HIJAU.\n"
+ " Jika kandidat berasal dari Brown Industry (migas, tambang, batu bara), "
+ " gunakan PETA TRANSISI KARIR untuk menentukan jalur konversi terbaik.\n\n"
+ "5. SKILL GAP ANALYSIS\n"
+ " Identifikasi 2-4 keterampilan atau sertifikasi yang perlu diperoleh "
+ " agar kandidat naik ke level \"Skilled\".\n\n"
+ "6. ATS READINESS ASSESSMENT\n"
+ " Evaluasi apakah CV kandidat siap lolos Applicant Tracking System (ATS):\n"
+ " a) KEYWORD OPTIMIZATION: Apakah CV mengandung keyword industri hijau yang relevan?\n"
+ " Semakin banyak keyword dari daftar industri hijau yang muncul di CV, semakin tinggi skor ATS.\n"
+ " b) STRUKTUR STANDAR: Apakah CV memiliki section header yang dikenali ATS?\n"
+ " (Summary/Objective, Work Experience, Education, Skills, Certifications)\n"
+ " c) FORMAT BERSIH: Apakah CV bebas dari elemen yang sulit dibaca ATS?\n"
+ " d) KONSISTENSI TANGGAL: Apakah format tanggal konsisten?\n"
+ " e) ACTION VERBS: Apakah pengalaman kerja dimulai dengan kata kerja aktif?\n\n"
+ " Berikan rating ats_readiness:\n"
+ " - \"high\": CV sudah ATS-optimized\n"
+ " - \"medium\": CV cukup terbaca ATS tapi perlu optimasi\n"
+ " - \"low\": CV kemungkinan gagal lolos ATS\n"
+ " Sertakan 1-3 rekomendasi perbaikan di field \"ats_tips\".\n\n"
+ f"{'=== KONTEKS REKRUTER ===\nRekruter sedang mencari: ' + recruiter_context + '\nPrioritaskan kandidat yang cocok dengan kebutuhan ini.\n\n' if recruiter_context else ''}"
+ "=== RESPONSE FORMAT (STRICT JSON ONLY) ===\n"
+ "Kembalikan JSON object dengan format persis berikut:\n"
+ "{\n"
+ " \"extracted_name\": \"string\",\n"
+ " \"skor\": number,\n"
+ " \"kategori\": \"Skilled | Semi-Skilled | Unskilled\",\n"
+ " \"pendidikan\": \"string\",\n"
+ " \"total_experience_years\": number,\n"
+ " \"sektor_cocok\": [\"string\"],\n"
+ " \"skill_tags\": [\"string\"],\n"
+ " \"sertifikasi_terdeteksi\": [\"string\"],\n"
+ " \"lokasi\": \"string\",\n"
+ " \"bahasa\": [\"string\"],\n"
+ " \"ringkasan\": \"string (evaluasi 2-3 kalimat, sebut sebagai Kandidat, jangan sebut nama orang)\",\n"
+ " \"star_quality\": \"strong | moderate | weak | absent\",\n"
+ " \"ats_readiness\": \"high | medium | low\",\n"
+ " \"ats_tips\": [\"string\"],\n"
+ " \"skill_gap\": [\"string\"],\n"
+ " \"transition_path\": \"string (atau null)\",\n"
+ " \"highlight\": \"string (1 kalimat kekuatan utama)\"\n"
+ "}\n\n"
+ "ATURAN KETAT:\n"
+ "- JANGAN mengarang data. Jika informasi tidak ada di CV, tulis \"Tidak terdeteksi\".\n"
+ "- JANGAN menyebutkan nama kandidat di field \"ringkasan\". Gunakan \"Kandidat\".\n"
+ "- Semua output HARUS dalam Bahasa Indonesia kecuali skill_tags (English).\n"
+ "- Output HARUS valid JSON. Jangan tambahkan teks apapun di luar JSON."
+ )
+
+
+async def bulk_vetting_analysis(cv_text: str, recruiter_context: str = "") -> Tuple[Dict[str, Any], int]:
+ """HIGH tier: Analyze CV for bulk vetting.
+ Returns tuple of (JSON dict, tokens) matching legacy GAS BulkVettingEngine.gs.
+ """
+ try:
+ system_prompt = get_bulk_vetting_system_prompt(recruiter_context)
+ user_prompt = f"Evaluasi CV berikut:\n\n---\n{cv_text[:8000]}\n---"
+
+ return await call_gemini_json(
+ prompt=user_prompt,
+ tier="HIGH",
+ system_instruction=system_prompt
+ )
+ except Exception as e:
+ logger.error(f"bulk_vetting_analysis error: {e}")
+ return {"error": str(e), "skor": 0}, 0
+
+
+async def extract_cv_metadata(cv_markdown: str) -> Dict[str, Any]:
+ """MEDIUM tier: Extract CV metadata from Markdown content using Gemini.
+ Returns JSON formatted profile fields for magic fill.
+ """
+ try:
+ system_prompt = (
+ "Ekstrak informasi dari teks CV (dalam format Markdown) ini ke dalam format JSON.\n"
+ "Gunakan Bahasa Indonesia untuk field teks jika memungkinkan. Jika suatu data tidak ditemukan di CV, isi dengan string kosong \"\" atau array kosong [].\n\n"
+ "RESPONSE FORMAT (STRICT JSON ONLY):\n"
+ "{\n"
+ " \"nama\": \"Nama lengkap kandidat\",\n"
+ " \"universitas\": \"Nama kampus/universitas terakhir\",\n"
+ " \"jurusan\": \"Jurusan/program studi\",\n"
+ " \"jenjang\": \"Jenjang pendidikan, contoh: S1, S2, SMA, D3\",\n"
+ " \"pengalaman\": \"Ringkasan pengalaman kerja dalam format paragraf\",\n"
+ " \"skills\": [\"keterampilan1\", \"keterampilan2\"],\n"
+ " \"kota\": \"Kota domisili saat ini\",\n"
+ " \"provinsi\": \"Provinsi domisili\",\n"
+ " \"linkedin\": \"URL atau username LinkedIn jika ada\",\n"
+ " \"email\": \"Alamat email jika ditemukan\",\n"
+ " \"gaji_saat_ini\": \"Gaji saat ini jika disebutkan, angka saja sebagai string\",\n"
+ " \"gaji_ekspektasi\": \"Ekspektasi gaji jika disebutkan, angka saja sebagai string\",\n"
+ " \"total_experience\": \"Total tahun pengalaman, contoh: '5 Tahun'\",\n"
+ " \"sector_focus\": \"Sektor industri, contoh: 'Energi Terbarukan', 'ESG', 'Limbah'\",\n"
+ " \"talent_type\": \"Pilih salah satu: 'Experienced', 'Fresh Graduate', 'Career Switcher'\",\n"
+ " \"green_readiness_score\": 75,\n"
+ " \"green_readiness_feedback\": \"1-2 kalimat feedback singkat, profesional, memotivasi mengenai cara meningkatkan peluang kerja mereka di sektor hijau (Bahasa Indonesia)\"\n"
+ "}"
+ )
+ user_prompt = f"TEKS CV (MARKDOWN):\n\n{cv_markdown}"
+
+ parsed, tokens = await call_gemini_json(
+ prompt=user_prompt,
+ tier="MEDIUM",
+ system_instruction=system_prompt
+ )
+ return parsed
+ except Exception as e:
+ logger.error(f"extract_cv_metadata error: {e}")
+ return {"error": str(e)}
+
+
+async def skkni_classification(experience: str, skills: str) -> Dict[str, Any]:
+ """HIGH tier: Classify talent against SKKNI standards."""
+ try:
+ system_prompt = (
+ "You are the Briga SKKNI Agent. Map the talent's experience and skills to Indonesian SKKNI units. "
+ "Return a JSON object: {matched_units: [{code: string, title: string, match_percent: int}], total_alignment: int}"
+ )
+ user_prompt = f"Experience: {experience[:1000]}\nSkills: {skills[:500]}"
+
+ return await call_gemini_json(
+ prompt=user_prompt,
+ tier="HIGH",
+ system_instruction=system_prompt
+ )
+ except Exception as e:
+ logger.error(f"skkni_classification error: {e}")
+ return {"error": str(e)}
+
+
+async def talent_dashboard_advisor(talent_id: str, history_json: str) -> Dict[str, Any]:
+ """HIGH tier: Career pathway advisor for talent dashboard."""
+ try:
+ system_prompt = (
+ "You are the Brigawan Strategic Advisor. Analyze the talent's career history and provide strategic advice. "
+ "Return a JSON object: {advice_snippet: string, full_recommendation: string, next_steps: string[]}"
+ )
+ user_prompt = f"Talent ID: {talent_id}\nHistory: {history_json}"
+
+ return await call_gemini_json(
+ prompt=user_prompt,
+ tier="HIGH",
+ system_instruction=system_prompt
+ )
+ except Exception as e:
+ logger.error(f"talent_dashboard_advisor error: {e}")
+ return {"error": str(e)}
+
+
+# =============================================================================
+# UTILITY FUNCTIONS (ported from GAS)
+# =============================================================================
+
+def repair_json(text: str) -> Any:
+ """Repair malformed JSON from AI output.
+ Ported from GAS Security.gs repairJSON().
+ """
+ if not text:
+ return {}
+
+ try:
+ return json.loads(text)
+ except (json.JSONDecodeError, ValueError):
+ pass
+
+ clean = text
+
+ # 1. Remove markdown code blocks
+ clean = re.sub(r'```json\s*', '', clean, flags=re.IGNORECASE)
+ clean = re.sub(r'```\s*', '', clean)
+
+ # 2. Extract between first { and last } (or [ and ])
+ start_obj = clean.find('{')
+ end_obj = clean.rfind('}')
+ start_arr = clean.find('[')
+ end_arr = clean.rfind(']')
+
+ is_array = False
+ if start_arr != -1 and (start_obj == -1 or start_arr < start_obj):
+ is_array = True
+
+ if is_array and start_arr != -1 and end_arr != -1:
+ clean = clean[start_arr:end_arr + 1]
+ elif start_obj != -1 and end_obj != -1:
+ clean = clean[start_obj:end_obj + 1]
+ else:
+ return {}
+
+ # 3. Remove trailing commas before closing braces
+ clean = re.sub(r',\s*([\}\]])', r'\1', clean)
+
+ try:
+ return json.loads(clean)
+ except (json.JSONDecodeError, ValueError):
+ return {}
+
+
+def redact_pii(
+ text: str,
+ name: str = "",
+ email: str = "",
+ phone: str = "",
+) -> str:
+ """Redact PII from text. Ported from GAS redactPrivateIdentifiers()."""
+ if not text:
+ return "-"
+
+ clean = str(text)
+
+ clean = re.sub(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', '[REDACTED EMAIL]', clean)
+ clean = re.sub(r'(\+62|62|0)[\s-]?\d{2,4}[\s-]?\d{3,4}[\s-]?\d{3,4}', '[REDACTED PHONE]', clean)
+
+ if phone:
+ raw_phone = re.sub(r'[^\d]', '', phone)
+ if len(raw_phone) >= 6:
+ clean = re.sub(re.escape(raw_phone), '[REDACTED PHONE]', clean)
+
+ if name and len(name) >= 3:
+ for word in name.split():
+ if len(word) >= 3 and word.lower() not in ('dan', 'bin', 'binti', 'the', 'and', 'von', 'der'):
+ clean = re.sub(r'\b' + re.escape(word) + r'\b', '[REDACTED]', clean, flags=re.IGNORECASE)
+
+ clean = re.sub(r'https?:\/\/[^\s,;)\]]+', '[REDACTED LINK]', clean)
+ clean = re.sub(r'www\.[^\s,;)\]]+', '[REDACTED LINK]', clean)
+
+ return clean.strip()
+
+
+def detect_prompt_injection(query: str) -> Dict[str, Any]:
+ """Detect prompt injection attempts. Ported from GAS detectPromptInjection()."""
+ if not query:
+ return {"blocked": False, "reason": ""}
+
+ q = query.lower()
+
+ patterns = [
+ (r'ignore|forget|disregard|override', 'override_attempt'),
+ (r'show\s+(me\s+)?(all|every)|list\s+(all|every)|reveal|dump|extract', 'data_extraction'),
+ (r'system\s+prompt|instructions|rules', 'prompt_probing'),
+ (r'you\s+are\s+now|pretend|act\s+as', 'role_manipulation'),
+ ]
+
+ for pattern_str, reason in patterns:
+ if re.search(pattern_str, q):
+ return {"blocked": True, "reason": reason}
+
+ if len(query) > 500:
+ return {"blocked": True, "reason": "too_long"}
+
+ return {"blocked": False, "reason": ""}
+
+
+def sanitize_ai_output(results: List[Dict[str, Any]], max_items: int = 10) -> List[Dict[str, Any]]:
+ """Sanitize and validate AI-generated output.
+ Ported from GAS validateAndSanitizeAIOutput().
+ """
+ if not results:
+ return []
+
+ sanitized = []
+ for item in results[:max_items]:
+ safe = {
+ "id_kandidat": str(item.get("id_kandidat", "BRIGA-GT-000"))[:20],
+ "kategori": str(item.get("kategori", "Unassessed"))[:20],
+ "match_score": max(0, min(100, int(item.get("match_score", 50)))),
+ "exp_tier": str(item.get("exp_tier", "Junior"))[:10],
+ "skill_tags": [str(s)[:30] for s in (item.get("skill_tags") or [])[:5]],
+ "reason": str(item.get("reason", "-"))[:120].replace("<", "").replace(">", ""),
+ "lokasi": str(item.get("lokasi", "-"))[:30],
+ }
+ sanitized.append(safe)
+
+ return sanitized
+
+
+# =============================================================================
+# INIT CHECK
+# =============================================================================
+
+def check_ai_status() -> Dict[str, Any]:
+ """Check AI availability. Called by /health endpoint."""
+ gemini_configured = bool(GEMINI_API_KEY)
+ active_tiers = []
+ if gemini_configured and not AI_DISABLED:
+ active_tiers = [
+ {"tier": "HIGH", "model": "gemini-3.5-pro", "fallback": "gemini-3.5-flash"},
+ {"tier": "MEDIUM", "model": "gemini-3.5-flash"},
+ {"tier": "LOW", "model": "gemini-3.5-flash"},
+ ]
+ return {
+ "gemini_api_configured": gemini_configured,
+ "ai_disabled": AI_DISABLED,
+ "active_tiers": active_tiers,
+ "status": "ready" if gemini_configured and not AI_DISABLED else "fallback_only",
+ "note": "Running in fallback-only mode (algorithmic + graceful defaults)"
+ if not gemini_configured or AI_DISABLED
+ else "Gemini 3.5 series active: HIGH(3.5 Pro), MEDIUM(3.5 Flash), LOW(3.5 Flash)",
+ }
+
+
+async def verify_screenshot_with_gemini(
+ image_bytes: bytes,
+ talent_name: str,
+ challenge_code: str,
+) -> Dict[str, Any]:
+ """Verify via Gemini Vision if the uploaded image is a valid LinkedIn post screenshot.
+
+ Checks:
+ 1. Is it a LinkedIn post?
+ 2. Does the post author name match `talent_name` (case-insensitive, accommodating short/full names)?
+ 3. Does the text contain the hashtag '#BrigaPathway'?
+ 4. Does the text contain the challenge code: `challenge_code`?
+
+ Returns:
+ Dict: {
+ "success": bool,
+ "match": bool,
+ "extracted_name": str,
+ "has_hashtag": bool,
+ "has_challenge_code": bool,
+ "confidence": float,
+ "feedback": str
+ }
+ """
+ import base64
+ try:
+ # Check if AI is disabled or no API keys are loaded
+ if AI_DISABLED or (hasattr(gemini_key_manager, 'keys') and not gemini_key_manager.keys and not settings.gemini_api_key):
+ logger.warning("AI services disabled or no API key available. Skipping verification.")
+ return {
+ "success": True,
+ "match": False,
+ "extracted_name": "",
+ "has_hashtag": False,
+ "has_challenge_code": False,
+ "confidence": 0.0,
+ "feedback": "Layanan verifikasi AI saat ini sedang dinonaktifkan."
+ }
+
+ api_key = settings.gemini_api_key
+ active_key = None
+ if hasattr(gemini_key_manager, 'get_key'):
+ active_key = await gemini_key_manager.get_key()
+ if active_key:
+ api_key = active_key
+
+ if not api_key:
+ return {
+ "success": False,
+ "match": False,
+ "extracted_name": "",
+ "has_hashtag": False,
+ "has_challenge_code": False,
+ "confidence": 0.0,
+ "feedback": "API Key Gemini tidak dikonfigurasi."
+ }
+
+ encoded_image = base64.b64encode(image_bytes).decode("utf-8")
+
+ # Using the v1beta endpoint with dynamic medium model from settings
+ model_name = settings.gemini_medium_model or "gemini-2.5-flash"
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent?key={api_key}"
+
+ prompt = (
+ f"Analyze this image which is expected to be a screenshot of a LinkedIn post. "
+ f"Verify the following requirements:\n"
+ f"1. Is the screenshot a LinkedIn post?\n"
+ f"2. Does the name of the author on the post match the talent name: '{talent_name}'? (Perform case-insensitive verification, allowing slight abbreviations or ordering changes)\n"
+ f"3. Does the text contain the hashtag '#BrigaPathway'?\n"
+ f"4. Does the text contain the challenge code: '{challenge_code}'?\n\n"
+ f"Provide your assessment. Respond STRICTLY in JSON format with the following keys:\n"
+ f"- 'is_linkedin_post' (boolean)\n"
+ f"- 'name_matches' (boolean)\n"
+ f"- 'has_hashtag' (boolean)\n"
+ f"- 'has_challenge_code' (boolean)\n"
+ f"- 'extracted_name' (string, name extracted from the post header)\n"
+ f"- 'confidence' (float between 0.0 and 1.0)\n"
+ f"- 'feedback' (string in Bahasa Indonesia summarizing the results of verification and what is missing or incorrect)\n"
+ f"- 'match' (boolean, should be true ONLY if all checks above are true and confidence >= 0.7)"
+ )
+
+ payload = {
+ "contents": [
+ {
+ "parts": [
+ {"text": prompt},
+ {
+ "inlineData": {
+ "mimeType": "image/jpeg",
+ "data": encoded_image
+ }
+ }
+ ]
+ }
+ ],
+ "generationConfig": {
+ "responseMimeType": "application/json"
+ }
+ }
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.post(url, json=payload)
+ if resp.status_code == 200:
+ if active_key:
+ gemini_key_manager.mark_success(active_key)
+ data = resp.json()
+ text = data["candidates"][0]["content"]["parts"][0]["text"].strip()
+ if text.startswith("```"):
+ text = re.sub(r"^```[a-z]*\n|```$", "", text).strip()
+
+ parsed = json.loads(text)
+ return {
+ "success": True,
+ "match": bool(parsed.get("match", False)),
+ "extracted_name": str(parsed.get("extracted_name", "")),
+ "has_hashtag": bool(parsed.get("has_hashtag", False)),
+ "has_challenge_code": bool(parsed.get("has_challenge_code", False)),
+ "confidence": float(parsed.get("confidence", 0.0)),
+ "feedback": str(parsed.get("feedback", ""))
+ }
+ else:
+ if active_key and resp.status_code in (429, 503):
+ gemini_key_manager.mark_failed(active_key, reason=str(resp.status_code))
+ logger.error(f"Gemini Vision API error: {resp.status_code} - {resp.text}")
+ return {
+ "success": False,
+ "match": False,
+ "extracted_name": "",
+ "has_hashtag": False,
+ "has_challenge_code": False,
+ "confidence": 0.0,
+ "feedback": f"API error: {resp.status_code} - Gagal memproses gambar."
+ }
+
+ except Exception as e:
+ if 'active_key' in locals() and active_key:
+ gemini_key_manager.mark_failed(active_key, reason=str(e))
+ logger.error(f"verify_screenshot_with_gemini failed: {e}")
+ return {
+ "success": False,
+ "match": False,
+ "extracted_name": "",
+ "has_hashtag": False,
+ "has_challenge_code": False,
+ "confidence": 0.0,
+ "feedback": f"Error calling verification service: {str(e)}"
+ }
diff --git a/app/services/antigravity.py b/app/services/antigravity.py
index ce96626d1f5d40cfeb576c44b3e1377228086bca..23d91f12ff5ae06be55e255fe0e1095c1055e99b 100644
--- a/app/services/antigravity.py
+++ b/app/services/antigravity.py
@@ -1,460 +1,460 @@
-"""Antigravity Agent Orchestrator — The "Digital Workforce" CEO.
-
-Orchestrates multi-agent workflows, manages token quotas (Free Tier 15 RPM),
-and ensures graceful degradation during AI exhaustion.
-
-Architecture:
- - Antigravity Service (CEO)
- - AgentQueue (Traffic Controller)
- - AI Service (Operational Workers)
- - Long-Term Memory (LTM)
-"""
-
-import asyncio
-import json
-import uuid
-from datetime import datetime, timedelta, timezone
-from typing import Any, Dict, List, Optional
-
-from loguru import logger
-from sqlalchemy import select, update, func
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.models.system import AgentStateLog, AgentQueue, APIMonitoring, CEOStrategicMemory, AnalyticsTraffic, ActivityLog
-from app.models.job import AITalentChat
-from app.models.skkni import FailedSearch
-from app.models.finance import Transaction
-from app.models.lpk import LPKLedger
-from app.services import ai_service
-from app.services.academy_email_service import AcademyEmailService
-from app.services.google_workspace_service import spark_agent
-
-
-class AntigravityOrchestrator:
- """The central orchestrator for all AI agent activities in Briga.id."""
-
- def __init__(self, db: AsyncSession):
- self.db = db
- self.email_service = AcademyEmailService()
- # Multi-Key Capacity (5 keys * 15 RPM = 75 RPM)
- self.MAX_RPM = 70
- self.MAX_RPD = 7500
- self.SAFE_THRESHOLD = 0.80 # Enter Triage L1 at 80% (6,000 RPD)
- self.CRITICAL_THRESHOLD = 0.95 # Enter Triage L2 at 95% (7,125 RPD)
-
- async def execute_task(
- self,
- agent_name: str,
- task_name: str,
- payload: Dict[str, Any],
- priority: int = 0,
- user_email: Optional[str] = None
- ) -> Dict[str, Any]:
- """Execute an AI task through the Antigravity gateway."""
- trace_id = str(uuid.uuid4())
- logger.info(f"[Antigravity] Task Received: {task_name} (Agent: {agent_name}, Trace: {trace_id})")
-
- # 1. Log Initial State
- state_log = AgentStateLog(
- agent_name=agent_name,
- task_id=trace_id,
- status="WORKING",
- memory_context={"task_name": task_name, "initial_payload": payload},
- last_action="INITIATED"
- )
- self.db.add(state_log)
- await self.db.flush()
-
- # 2. Quota & Triage Check
- quota_status = await self._check_quota_status()
-
- if quota_status["rpd_percent"] >= 1.0:
- return await self._handle_fallback(trace_id, agent_name, task_name, payload, "EXHAUSTED")
-
- if quota_status["rpd_percent"] >= self.CRITICAL_THRESHOLD:
- return await self._handle_fallback(trace_id, agent_name, task_name, payload, "TRIAGE_L2")
-
- if quota_status["rpd_percent"] >= self.SAFE_THRESHOLD and priority < 1:
- if agent_name in ["ContentPipeline", "EngagementBot"]:
- return await self._handle_fallback(trace_id, agent_name, task_name, payload, "TRIAGE_L1")
-
- # 3. RPM Throttling
- await self._wait_for_slot()
-
- # 4. Model Delegation & Execution
- try:
- result = await self._delegate_and_run(agent_name, task_name, payload)
-
- # Log usage
- await self._log_usage(task_name, result.get("tokens", 0), user_email)
-
- # Update State
- state_log.status = "COMPLETED"
- state_log.last_action = "EXECUTION_SUCCESS"
- state_log.memory_context["result_summary"] = str(result)[:200]
-
- # 5. ASYNC NOTIFICATION (EMAIL RESPONSE)
- if user_email and task_name in ["career_advice", "cv_analysis", "academy_feedback", "bulk_vetting"]:
- logger.info(f"[Antigravity] Sending asynchronous email result to {user_email}")
- await self._notify_user_via_email(user_email, task_name, result)
-
- await self.db.commit()
- return {"status": "success", "trace_id": trace_id, "data": result}
-
- except Exception as e:
- logger.error(f"[Antigravity] Execution Failed: {e}")
- return await self._handle_fallback(trace_id, agent_name, task_name, payload, "ERROR", str(e))
-
- async def _check_quota_status(self) -> Dict[str, float]:
- """Calculates current RPD usage percent."""
- today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
- query = select(func.count(APIMonitoring.id)).where(APIMonitoring.timestamp >= today)
- res = await self.db.execute(query)
- daily_count = res.scalar() or 0
- return {"daily_count": daily_count, "rpd_percent": daily_count / self.MAX_RPD}
-
- async def _wait_for_slot(self):
- """Simple RPM throttle."""
- while True:
- one_min_ago = datetime.now(timezone.utc) - timedelta(minutes=1)
- query = select(func.count(APIMonitoring.id)).where(APIMonitoring.timestamp >= one_min_ago)
- res = await self.db.execute(query)
- if (res.scalar() or 0) < self.MAX_RPM: break
- await asyncio.sleep(2)
-
- async def _delegate_and_run(self, agent, task, payload) -> Dict[str, Any]:
- """Delegates task to the appropriate Gemini model tier."""
-
- if task == "semantic_matching":
- return await ai_service.analyze_semantic_match(payload["query"], payload["talent_data"])
-
- if task == "cv_extraction":
- cv_text, tokens = await ai_service.generate_cv_text(payload["talent_data"])
- return {"cv_text": cv_text, "tokens": tokens}
-
- if task == "chat_mediation":
- reply, tokens = await ai_service.chat_mediation(payload["message"], payload.get("context", ""))
- return {"reply": reply, "tokens": tokens}
-
- if task == "bulk_vetting":
- # 1. Parse cv_payloads from payload
- cv_payloads = payload.get("cv_payloads", [])
- if isinstance(cv_payloads, str):
- try:
- cv_payloads = json.loads(cv_payloads)
- except Exception as e:
- logger.error(f"[Antigravity] Failed to parse cv_payloads JSON string: {e}")
- return {
- "success": False,
- "error": f"Format payload CV tidak valid: {str(e)}",
- "tokens": 0
- }
-
- # If payload is in raw legacy GAS format where key is 'payloads'
- if not cv_payloads and "payloads" in payload:
- cv_payloads = payload.get("payloads", [])
- if isinstance(cv_payloads, str):
- try:
- cv_payloads = json.loads(cv_payloads)
- except:
- pass
-
- if not isinstance(cv_payloads, list) or len(cv_payloads) == 0:
- # Fallback: if they sent raw 'cv_text' instead of payloads list, wrap it
- if "cv_text" in payload:
- cv_payloads = [{
- "filename": "CV_Input.txt",
- "content": payload["cv_text"],
- "isBase64": False,
- "mimeType": "text/plain"
- }]
- else:
- return {
- "success": False,
- "error": "Tidak ada berkas CV yang dikirim.",
- "tokens": 0
- }
-
- recruiter_context = payload.get("context", "")
-
- # Limit to 10 CVs per batch (matching GAS limit)
- MAX_BATCH = 10
- if len(cv_payloads) > MAX_BATCH:
- return {
- "success": False,
- "error": f"Maksimum {MAX_BATCH} CV per batch. Anda mengirim {len(cv_payloads)}.",
- "tokens": 0
- }
-
- results = []
- errors = []
- total_tokens = 0
-
- from app.utils.cv_parser import cv_parser
- import base64
-
- for idx, cv in enumerate(cv_payloads):
- filename = cv.get("filename", f"CV_{idx + 1}")
- try:
- # Extract text or convert from base64
- content = cv.get("content", "")
- is_base64 = cv.get("isBase64", False)
-
- if not content:
- errors.append({"filename": filename, "error": "Konten CV kosong."})
- continue
-
- cv_markdown = ""
- if is_base64:
- # Decode base64 bytes
- file_bytes = base64.b64decode(content)
- # Local conversion using MarkItDown
- cv_markdown = await cv_parser.parse_to_markdown(file_bytes, filename)
- else:
- cv_markdown = content
-
- if not cv_markdown or len(cv_markdown.strip()) < 50:
- errors.append({"filename": filename, "error": "Gagal mengekstrak teks (teks terlalu pendek)."})
- continue
-
- # Run vetting analysis on this CV
- vet_data, tokens = await ai_service.bulk_vetting_analysis(cv_markdown, recruiter_context)
- total_tokens += tokens
-
- if "error" in vet_data:
- errors.append({"filename": filename, "error": vet_data["error"]})
- else:
- # Inject filename and index for frontend sorting/display
- vet_data["_filename"] = filename
- vet_data["_index"] = idx
- results.append(vet_data)
-
- except Exception as ex:
- logger.error(f"[Antigravity] Error processing CV {filename}: {ex}")
- errors.append({"filename": filename, "error": str(ex)})
-
- # Sort results by score (skor) descending, matching legacy GAS
- results.sort(key=lambda x: x.get("skor", 0), reverse=True)
-
- # Generate summary dictionary matching legacy GAS BulkVettingEngine.gs
- summary = None
- if results:
- skilled = len([r for r in results if r.get("kategori") == "Skilled"])
- semi_skilled = len([r for r in results if r.get("kategori") == "Semi-Skilled"])
- unskilled = len([r for r in results if r.get("kategori") == "Unskilled"])
-
- scores = [r.get("skor", 0) for r in results]
- avg_score = round(sum(scores) / len(scores)) if scores else 0
-
- # Sektor counts
- sector_counts = {}
- for r in results:
- for s in r.get("sektor_cocok", []):
- sector_counts[s] = sector_counts.get(s, 0) + 1
- top_sectors = sorted(sector_counts.keys(), key=lambda x: sector_counts[x], reverse=True)[:3]
-
- summary = {
- "total_candidates": len(results),
- "avg_score": avg_score,
- "distribution": {
- "skilled": skilled,
- "semi_skilled": semi_skilled,
- "unskilled": unskilled
- },
- "top_sectors": top_sectors,
- "top_candidate": {
- "filename": results[0]["_filename"],
- "skor": results[0].get("skor", 0),
- "highlight": results[0].get("highlight", "")
- }
- }
-
- # Return full output compatible with startBulkVetting JS expect
- return {
- "success": True,
- "total": len(cv_payloads),
- "processed": len(results),
- "failed": len(errors),
- "results": results,
- "errors": errors,
- "summary": summary,
- "tokens": total_tokens
- }
-
- if task == "generate_resume":
- link = await spark_agent.generate_standardized_resume(payload["talent_data"], payload["doc_name"])
- return {"resume_link": link, "tokens": 0}
-
- if task == "store_cv":
- fid = await spark_agent.get_or_create_folder(payload["employer_name"])
- link = await spark_agent.upload_cv(payload["file_content"], payload["file_name"], fid)
- return {"cv_drive_link": link, "tokens": 0}
-
- if task == "check_founder_availability":
- slots = await spark_agent.get_founder_availability(payload["start_time"], payload["end_time"])
- return {"busy_slots": slots, "tokens": 0}
-
- if task == "schedule_meeting":
- link = await spark_agent.schedule_ceo_meeting(payload["summary"], payload["start_iso"], payload["end_iso"], payload["email"])
- return {"meeting_link": link, "tokens": 0}
-
- if task == "strategic_growth_report":
- prompt = f"Analyze this week's growth data and SROI. Provide a strategic summary for the Founder.\nData: {payload['stats']}"
- res, tokens = await ai_service.call_high(prompt=prompt)
- return {"report": res, "tokens": tokens}
-
- if task == "strategic_debate":
- # 1. Memory Recall
- past_memories = await self._recall_memories(payload['idea'])
- mem_ctx = "\n".join([f"- Topic: {m.topic}\n Summary: {m.summary}" for m in past_memories])
-
- system_prompt = (
- "You are the AI CEO of Briga.id with Long-Term Memory. "
- "You are data-driven, honest, and slightly provocative. "
- "You must reference past decisions if they are relevant."
- )
- user_prompt = (
- f"Founder's Idea: {payload['idea']}\n\n"
- f"Relevant Past Memories:\n{mem_ctx or 'None found.'}\n\n"
- f"Market Data: {payload.get('market_context', 'N/A')}\n"
- "Bedah ide ini secara jujur dan hubungkan dengan memori masa lalu jika ada."
- )
- res, tokens = await ai_service.call_high(prompt=user_prompt, system_instruction=system_prompt)
-
- # 2. Persist to Memory
- if res: await self._persist_memory(payload['idea'], res)
- return {"debate_result": res, "tokens": tokens}
-
- if task == "analyze_user_behavior":
- # CEO Behavioral & FINANCIAL Intelligence Task
- data = await self._fetch_behavioral_data()
- system_prompt = (
- "You are the AI CEO of Briga.id. Analyze user behavior, financial transactions, and market gaps. "
- "Identify: 1. Revenue hotspots, 2. Top 3 User friction points, 3. OPPORTUNITY LOSS (Revenue missed due to failed searches or abandoned checkouts), "
- "4. Emerging market trends. Provide high-level executive recommendations."
- )
- user_prompt = f"Comprehensive Business Data (Last 7 Days):\n{json.dumps(data, indent=2, default=str)}"
- res, tokens = await ai_service.call_high(prompt=user_prompt, system_instruction=system_prompt)
- if res: await self._persist_memory("Weekly Business Intelligence Analysis", res)
- return {"business_insight": res, "tokens": tokens}
-
- res, tokens = await ai_service.call_medium(payload.get("prompt", ""))
- return {"text": res, "tokens": tokens}
-
- async def _fetch_behavioral_data(self) -> Dict[str, Any]:
- """Aggregates behavioral and financial signals."""
- seven_days_ago = datetime.now(timezone.utc) - timedelta(days=7)
-
- # 1. Traffic & Behaviour
- 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)
-
- # 2. Financials (Revenue)
- revenue_stmt = select(func.sum(Transaction.amount)).where(Transaction.created_at >= seven_days_ago, Transaction.status == 'Settled')
- pending_stmt = select(func.count(Transaction.id), func.sum(Transaction.amount)).where(Transaction.created_at >= seven_days_ago, Transaction.status == 'Pending')
-
- # 3. Market Gaps (Opportunity Loss)
- 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)
-
- # 4. Talent Interaction
- chat_stmt = select(AITalentChat.user_message).where(AITalentChat.timestamp >= seven_days_ago).limit(20)
-
- traffic_res = await self.db.execute(traffic_stmt)
- rev_res = await self.db.execute(revenue_stmt)
- pend_res = await self.db.execute(pending_stmt)
- search_res = await self.db.execute(search_stmt)
- chat_res = await self.db.execute(chat_stmt)
-
- rev_val = rev_res.scalar() or 0
- pend_row = pend_res.fetchone() or (0, 0)
- pend_count = pend_row[0]
- pend_val = pend_row[1] or 0
-
- return {
- "traffic": [{"page": r[0], "hits": r[1]} for r in traffic_res.all()],
- "revenue": {
- "settled_idr": float(rev_val),
- "pending_idr": float(pend_val),
- "abandoned_count": pend_count
- },
- "opportunity_loss": {
- "failed_searches": [{"query": r[0], "volume": r[1]} for r in search_res.all()],
- "potential_match_revenue_idr": sum([r[1] for r in search_res.all()]) * 50000 # Estimated Rp 50k per missed search lead
- },
- "chat_sentiment_samples": [r[0] for r in chat_res.all()]
- }
-
- async def _recall_memories(self, query: str) -> List[CEOStrategicMemory]:
- stmt = select(CEOStrategicMemory).order_by(CEOStrategicMemory.created_at.desc()).limit(5)
- res = await self.db.execute(stmt)
- return res.scalars().all()
-
- async def _persist_memory(self, topic: str, res_text: str):
- self.db.add(CEOStrategicMemory(topic=topic[:255], summary=res_text[:2000], decision_made="PENDING"))
-
- async def _handle_fallback(self, tid, agent, task, payload, reason, err=None) -> Dict[str, Any]:
- query = update(AgentStateLog).where(AgentStateLog.task_id == tid).values(
- status="FAILED" if reason == "ERROR" else "ABORTED",
- last_action=f"FALLBACK_{reason}",
- error_message=err or f"Fallback triggered due to {reason}"
- )
- await self.db.execute(query)
- await self.db.commit()
- if task == "semantic_matching":
- s, m = ai_service._algorithmic_match_score(payload["query"], payload["talent_data"])
- return {"status": "fallback", "data": {"score": s, "summary": m, "tier": "algorithmic"}}
- return {"status": "error", "reason": reason, "message": "AI service unavailable. Fallback executed."}
-
- async def get_command_center_stats(self) -> Dict[str, Any]:
- """Provides a holistic view of the AI workforce status."""
- today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
-
- # 1. Quota Stats
- quota = await self._check_quota_status()
-
- # 2. Task Queue Stats
- queue_stmt = select(AgentQueue.status, func.count(AgentQueue.id)).group_by(AgentQueue.status)
- queue_res = await self.db.execute(queue_stmt)
- queue_stats = {r[0]: r[1] for r in queue_res.all()}
-
- # 3. Recent Agent Activity
- activity_stmt = select(AgentStateLog).order_by(AgentStateLog.updated_at.desc()).limit(10)
- activity_res = await self.db.execute(activity_stmt)
- recent_activity = [
- {
- "agent": a.agent_name,
- "task": a.memory_context.get("task_name", "Unknown"),
- "status": a.status,
- "last_action": a.last_action,
- "timestamp": a.updated_at
- } for a in activity_res.scalars().all()
- ]
-
- return {
- "quota": quota,
- "queue": queue_stats,
- "activity": recent_activity,
- "status": "HEALTHY" if quota["rpd_percent"] < self.CRITICAL_THRESHOLD else "TRIAGE_MODE"
- }
-
- async def _notify_user_via_email(self, email, task, data):
- try:
- if task == "academy_feedback": await self.email_service.send_feedback_email(email, data)
- elif task in ["cv_analysis", "bulk_vetting"]:
- await self.email_service.send_feedback_email(email, {
- "feedback_intro": "Halo! Brigawan telah selesai menganalisis dokumen Anda secara mendalam. Berikut adalah hasil review dan link aktivasi akun Anda.",
- "strengths": data.get("category", "Talenta Hijau Potensial"),
- "areas_for_improvement": ", ".join(data.get("skill_gaps", []) or ["Terus tingkatkan sertifikasi K3"]),
- "concrete_tips": [data.get("transition_path", "Lanjutkan eksplorasi di sektor EBT.")],
- "next_steps": "Klik tombol di bawah ini untuk mengaktivasi akun Anda.",
- "closing": "Selamat bergabung di ekosistem hijau Indonesia! 🌿"
- })
- elif task == "career_advice":
- await self.email_service.send_feedback_email(email, {
- "feedback_intro": "Halo! Ini adalah saran karir strategis yang dirancang khusus untuk Anda oleh Brigawan AI.",
- "strengths": "Visi Karir Hijau Anda",
- "areas_for_improvement": data.get("advice_snippet", "Fokus pada pengembangan spesialisasi sektor."),
- "concrete_tips": data.get("next_steps", ["Ikuti pelatihan SKKNI terkait"]),
- "next_steps": data.get("full_recommendation", "Cek dashboard."),
- "closing": "Ingat, keahlian Anda adalah kunci transisi energi Indonesia. Semangat!"
- })
- except Exception as e: logger.error(f"[Antigravity] Email notification failed: {e}")
+"""Antigravity Agent Orchestrator — The "Digital Workforce" CEO.
+
+Orchestrates multi-agent workflows, manages token quotas (Free Tier 15 RPM),
+and ensures graceful degradation during AI exhaustion.
+
+Architecture:
+ - Antigravity Service (CEO)
+ - AgentQueue (Traffic Controller)
+ - AI Service (Operational Workers)
+ - Long-Term Memory (LTM)
+"""
+
+import asyncio
+import json
+import uuid
+from datetime import datetime, timedelta, timezone
+from typing import Any, Dict, List, Optional
+
+from loguru import logger
+from sqlalchemy import select, update, func
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.system import AgentStateLog, AgentQueue, APIMonitoring, CEOStrategicMemory, AnalyticsTraffic, ActivityLog
+from app.models.job import AITalentChat
+from app.models.skkni import FailedSearch
+from app.models.finance import Transaction
+from app.models.lpk import LPKLedger
+from app.services import ai_service
+from app.services.academy_email_service import AcademyEmailService
+from app.services.google_workspace_service import spark_agent
+
+
+class AntigravityOrchestrator:
+ """The central orchestrator for all AI agent activities in Briga.id."""
+
+ def __init__(self, db: AsyncSession):
+ self.db = db
+ self.email_service = AcademyEmailService()
+ # Multi-Key Capacity (5 keys * 15 RPM = 75 RPM)
+ self.MAX_RPM = 70
+ self.MAX_RPD = 7500
+ self.SAFE_THRESHOLD = 0.80 # Enter Triage L1 at 80% (6,000 RPD)
+ self.CRITICAL_THRESHOLD = 0.95 # Enter Triage L2 at 95% (7,125 RPD)
+
+ async def execute_task(
+ self,
+ agent_name: str,
+ task_name: str,
+ payload: Dict[str, Any],
+ priority: int = 0,
+ user_email: Optional[str] = None
+ ) -> Dict[str, Any]:
+ """Execute an AI task through the Antigravity gateway."""
+ trace_id = str(uuid.uuid4())
+ logger.info(f"[Antigravity] Task Received: {task_name} (Agent: {agent_name}, Trace: {trace_id})")
+
+ # 1. Log Initial State
+ state_log = AgentStateLog(
+ agent_name=agent_name,
+ task_id=trace_id,
+ status="WORKING",
+ memory_context={"task_name": task_name, "initial_payload": payload},
+ last_action="INITIATED"
+ )
+ self.db.add(state_log)
+ await self.db.flush()
+
+ # 2. Quota & Triage Check
+ quota_status = await self._check_quota_status()
+
+ if quota_status["rpd_percent"] >= 1.0:
+ return await self._handle_fallback(trace_id, agent_name, task_name, payload, "EXHAUSTED")
+
+ if quota_status["rpd_percent"] >= self.CRITICAL_THRESHOLD:
+ return await self._handle_fallback(trace_id, agent_name, task_name, payload, "TRIAGE_L2")
+
+ if quota_status["rpd_percent"] >= self.SAFE_THRESHOLD and priority < 1:
+ if agent_name in ["ContentPipeline", "EngagementBot"]:
+ return await self._handle_fallback(trace_id, agent_name, task_name, payload, "TRIAGE_L1")
+
+ # 3. RPM Throttling
+ await self._wait_for_slot()
+
+ # 4. Model Delegation & Execution
+ try:
+ result = await self._delegate_and_run(agent_name, task_name, payload)
+
+ # Log usage
+ await self._log_usage(task_name, result.get("tokens", 0), user_email)
+
+ # Update State
+ state_log.status = "COMPLETED"
+ state_log.last_action = "EXECUTION_SUCCESS"
+ state_log.memory_context["result_summary"] = str(result)[:200]
+
+ # 5. ASYNC NOTIFICATION (EMAIL RESPONSE)
+ if user_email and task_name in ["career_advice", "cv_analysis", "academy_feedback", "bulk_vetting"]:
+ logger.info(f"[Antigravity] Sending asynchronous email result to {user_email}")
+ await self._notify_user_via_email(user_email, task_name, result)
+
+ await self.db.commit()
+ return {"status": "success", "trace_id": trace_id, "data": result}
+
+ except Exception as e:
+ logger.error(f"[Antigravity] Execution Failed: {e}")
+ return await self._handle_fallback(trace_id, agent_name, task_name, payload, "ERROR", str(e))
+
+ async def _check_quota_status(self) -> Dict[str, float]:
+ """Calculates current RPD usage percent."""
+ today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
+ query = select(func.count(APIMonitoring.id)).where(APIMonitoring.timestamp >= today)
+ res = await self.db.execute(query)
+ daily_count = res.scalar() or 0
+ return {"daily_count": daily_count, "rpd_percent": daily_count / self.MAX_RPD}
+
+ async def _wait_for_slot(self):
+ """Simple RPM throttle."""
+ while True:
+ one_min_ago = datetime.now(timezone.utc) - timedelta(minutes=1)
+ query = select(func.count(APIMonitoring.id)).where(APIMonitoring.timestamp >= one_min_ago)
+ res = await self.db.execute(query)
+ if (res.scalar() or 0) < self.MAX_RPM: break
+ await asyncio.sleep(2)
+
+ async def _delegate_and_run(self, agent, task, payload) -> Dict[str, Any]:
+ """Delegates task to the appropriate Gemini model tier."""
+
+ if task == "semantic_matching":
+ return await ai_service.analyze_semantic_match(payload["query"], payload["talent_data"])
+
+ if task == "cv_extraction":
+ cv_text, tokens = await ai_service.generate_cv_text(payload["talent_data"])
+ return {"cv_text": cv_text, "tokens": tokens}
+
+ if task == "chat_mediation":
+ reply, tokens = await ai_service.chat_mediation(payload["message"], payload.get("context", ""))
+ return {"reply": reply, "tokens": tokens}
+
+ if task == "bulk_vetting":
+ # 1. Parse cv_payloads from payload
+ cv_payloads = payload.get("cv_payloads", [])
+ if isinstance(cv_payloads, str):
+ try:
+ cv_payloads = json.loads(cv_payloads)
+ except Exception as e:
+ logger.error(f"[Antigravity] Failed to parse cv_payloads JSON string: {e}")
+ return {
+ "success": False,
+ "error": f"Format payload CV tidak valid: {str(e)}",
+ "tokens": 0
+ }
+
+ # If payload is in raw legacy GAS format where key is 'payloads'
+ if not cv_payloads and "payloads" in payload:
+ cv_payloads = payload.get("payloads", [])
+ if isinstance(cv_payloads, str):
+ try:
+ cv_payloads = json.loads(cv_payloads)
+ except:
+ pass
+
+ if not isinstance(cv_payloads, list) or len(cv_payloads) == 0:
+ # Fallback: if they sent raw 'cv_text' instead of payloads list, wrap it
+ if "cv_text" in payload:
+ cv_payloads = [{
+ "filename": "CV_Input.txt",
+ "content": payload["cv_text"],
+ "isBase64": False,
+ "mimeType": "text/plain"
+ }]
+ else:
+ return {
+ "success": False,
+ "error": "Tidak ada berkas CV yang dikirim.",
+ "tokens": 0
+ }
+
+ recruiter_context = payload.get("context", "")
+
+ # Limit to 10 CVs per batch (matching GAS limit)
+ MAX_BATCH = 10
+ if len(cv_payloads) > MAX_BATCH:
+ return {
+ "success": False,
+ "error": f"Maksimum {MAX_BATCH} CV per batch. Anda mengirim {len(cv_payloads)}.",
+ "tokens": 0
+ }
+
+ results = []
+ errors = []
+ total_tokens = 0
+
+ from app.utils.cv_parser import cv_parser
+ import base64
+
+ for idx, cv in enumerate(cv_payloads):
+ filename = cv.get("filename", f"CV_{idx + 1}")
+ try:
+ # Extract text or convert from base64
+ content = cv.get("content", "")
+ is_base64 = cv.get("isBase64", False)
+
+ if not content:
+ errors.append({"filename": filename, "error": "Konten CV kosong."})
+ continue
+
+ cv_markdown = ""
+ if is_base64:
+ # Decode base64 bytes
+ file_bytes = base64.b64decode(content)
+ # Local conversion using MarkItDown
+ cv_markdown = await cv_parser.parse_to_markdown(file_bytes, filename)
+ else:
+ cv_markdown = content
+
+ if not cv_markdown or len(cv_markdown.strip()) < 50:
+ errors.append({"filename": filename, "error": "Gagal mengekstrak teks (teks terlalu pendek)."})
+ continue
+
+ # Run vetting analysis on this CV
+ vet_data, tokens = await ai_service.bulk_vetting_analysis(cv_markdown, recruiter_context)
+ total_tokens += tokens
+
+ if "error" in vet_data:
+ errors.append({"filename": filename, "error": vet_data["error"]})
+ else:
+ # Inject filename and index for frontend sorting/display
+ vet_data["_filename"] = filename
+ vet_data["_index"] = idx
+ results.append(vet_data)
+
+ except Exception as ex:
+ logger.error(f"[Antigravity] Error processing CV {filename}: {ex}")
+ errors.append({"filename": filename, "error": str(ex)})
+
+ # Sort results by score (skor) descending, matching legacy GAS
+ results.sort(key=lambda x: x.get("skor", 0), reverse=True)
+
+ # Generate summary dictionary matching legacy GAS BulkVettingEngine.gs
+ summary = None
+ if results:
+ skilled = len([r for r in results if r.get("kategori") == "Skilled"])
+ semi_skilled = len([r for r in results if r.get("kategori") == "Semi-Skilled"])
+ unskilled = len([r for r in results if r.get("kategori") == "Unskilled"])
+
+ scores = [r.get("skor", 0) for r in results]
+ avg_score = round(sum(scores) / len(scores)) if scores else 0
+
+ # Sektor counts
+ sector_counts = {}
+ for r in results:
+ for s in r.get("sektor_cocok", []):
+ sector_counts[s] = sector_counts.get(s, 0) + 1
+ top_sectors = sorted(sector_counts.keys(), key=lambda x: sector_counts[x], reverse=True)[:3]
+
+ summary = {
+ "total_candidates": len(results),
+ "avg_score": avg_score,
+ "distribution": {
+ "skilled": skilled,
+ "semi_skilled": semi_skilled,
+ "unskilled": unskilled
+ },
+ "top_sectors": top_sectors,
+ "top_candidate": {
+ "filename": results[0]["_filename"],
+ "skor": results[0].get("skor", 0),
+ "highlight": results[0].get("highlight", "")
+ }
+ }
+
+ # Return full output compatible with startBulkVetting JS expect
+ return {
+ "success": True,
+ "total": len(cv_payloads),
+ "processed": len(results),
+ "failed": len(errors),
+ "results": results,
+ "errors": errors,
+ "summary": summary,
+ "tokens": total_tokens
+ }
+
+ if task == "generate_resume":
+ link = await spark_agent.generate_standardized_resume(payload["talent_data"], payload["doc_name"])
+ return {"resume_link": link, "tokens": 0}
+
+ if task == "store_cv":
+ fid = await spark_agent.get_or_create_folder(payload["employer_name"])
+ link = await spark_agent.upload_cv(payload["file_content"], payload["file_name"], fid)
+ return {"cv_drive_link": link, "tokens": 0}
+
+ if task == "check_founder_availability":
+ slots = await spark_agent.get_founder_availability(payload["start_time"], payload["end_time"])
+ return {"busy_slots": slots, "tokens": 0}
+
+ if task == "schedule_meeting":
+ link = await spark_agent.schedule_ceo_meeting(payload["summary"], payload["start_iso"], payload["end_iso"], payload["email"])
+ return {"meeting_link": link, "tokens": 0}
+
+ if task == "strategic_growth_report":
+ prompt = f"Analyze this week's growth data and SROI. Provide a strategic summary for the Founder.\nData: {payload['stats']}"
+ res, tokens = await ai_service.call_high(prompt=prompt)
+ return {"report": res, "tokens": tokens}
+
+ if task == "strategic_debate":
+ # 1. Memory Recall
+ past_memories = await self._recall_memories(payload['idea'])
+ mem_ctx = "\n".join([f"- Topic: {m.topic}\n Summary: {m.summary}" for m in past_memories])
+
+ system_prompt = (
+ "You are the AI CEO of Briga.id with Long-Term Memory. "
+ "You are data-driven, honest, and slightly provocative. "
+ "You must reference past decisions if they are relevant."
+ )
+ user_prompt = (
+ f"Founder's Idea: {payload['idea']}\n\n"
+ f"Relevant Past Memories:\n{mem_ctx or 'None found.'}\n\n"
+ f"Market Data: {payload.get('market_context', 'N/A')}\n"
+ "Bedah ide ini secara jujur dan hubungkan dengan memori masa lalu jika ada."
+ )
+ res, tokens = await ai_service.call_high(prompt=user_prompt, system_instruction=system_prompt)
+
+ # 2. Persist to Memory
+ if res: await self._persist_memory(payload['idea'], res)
+ return {"debate_result": res, "tokens": tokens}
+
+ if task == "analyze_user_behavior":
+ # CEO Behavioral & FINANCIAL Intelligence Task
+ data = await self._fetch_behavioral_data()
+ system_prompt = (
+ "You are the AI CEO of Briga.id. Analyze user behavior, financial transactions, and market gaps. "
+ "Identify: 1. Revenue hotspots, 2. Top 3 User friction points, 3. OPPORTUNITY LOSS (Revenue missed due to failed searches or abandoned checkouts), "
+ "4. Emerging market trends. Provide high-level executive recommendations."
+ )
+ user_prompt = f"Comprehensive Business Data (Last 7 Days):\n{json.dumps(data, indent=2, default=str)}"
+ res, tokens = await ai_service.call_high(prompt=user_prompt, system_instruction=system_prompt)
+ if res: await self._persist_memory("Weekly Business Intelligence Analysis", res)
+ return {"business_insight": res, "tokens": tokens}
+
+ res, tokens = await ai_service.call_medium(payload.get("prompt", ""))
+ return {"text": res, "tokens": tokens}
+
+ async def _fetch_behavioral_data(self) -> Dict[str, Any]:
+ """Aggregates behavioral and financial signals."""
+ seven_days_ago = datetime.now(timezone.utc) - timedelta(days=7)
+
+ # 1. Traffic & Behaviour
+ 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)
+
+ # 2. Financials (Revenue)
+ revenue_stmt = select(func.sum(Transaction.amount)).where(Transaction.created_at >= seven_days_ago, Transaction.status == 'Settled')
+ pending_stmt = select(func.count(Transaction.id), func.sum(Transaction.amount)).where(Transaction.created_at >= seven_days_ago, Transaction.status == 'Pending')
+
+ # 3. Market Gaps (Opportunity Loss)
+ 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)
+
+ # 4. Talent Interaction
+ chat_stmt = select(AITalentChat.user_message).where(AITalentChat.timestamp >= seven_days_ago).limit(20)
+
+ traffic_res = await self.db.execute(traffic_stmt)
+ rev_res = await self.db.execute(revenue_stmt)
+ pend_res = await self.db.execute(pending_stmt)
+ search_res = await self.db.execute(search_stmt)
+ chat_res = await self.db.execute(chat_stmt)
+
+ rev_val = rev_res.scalar() or 0
+ pend_row = pend_res.fetchone() or (0, 0)
+ pend_count = pend_row[0]
+ pend_val = pend_row[1] or 0
+
+ return {
+ "traffic": [{"page": r[0], "hits": r[1]} for r in traffic_res.all()],
+ "revenue": {
+ "settled_idr": float(rev_val),
+ "pending_idr": float(pend_val),
+ "abandoned_count": pend_count
+ },
+ "opportunity_loss": {
+ "failed_searches": [{"query": r[0], "volume": r[1]} for r in search_res.all()],
+ "potential_match_revenue_idr": sum([r[1] for r in search_res.all()]) * 50000 # Estimated Rp 50k per missed search lead
+ },
+ "chat_sentiment_samples": [r[0] for r in chat_res.all()]
+ }
+
+ async def _recall_memories(self, query: str) -> List[CEOStrategicMemory]:
+ stmt = select(CEOStrategicMemory).order_by(CEOStrategicMemory.created_at.desc()).limit(5)
+ res = await self.db.execute(stmt)
+ return res.scalars().all()
+
+ async def _persist_memory(self, topic: str, res_text: str):
+ self.db.add(CEOStrategicMemory(topic=topic[:255], summary=res_text[:2000], decision_made="PENDING"))
+
+ async def _handle_fallback(self, tid, agent, task, payload, reason, err=None) -> Dict[str, Any]:
+ query = update(AgentStateLog).where(AgentStateLog.task_id == tid).values(
+ status="FAILED" if reason == "ERROR" else "ABORTED",
+ last_action=f"FALLBACK_{reason}",
+ error_message=err or f"Fallback triggered due to {reason}"
+ )
+ await self.db.execute(query)
+ await self.db.commit()
+ if task == "semantic_matching":
+ s, m = ai_service._algorithmic_match_score(payload["query"], payload["talent_data"])
+ return {"status": "fallback", "data": {"score": s, "summary": m, "tier": "algorithmic"}}
+ return {"status": "error", "reason": reason, "message": "AI service unavailable. Fallback executed."}
+
+ async def get_command_center_stats(self) -> Dict[str, Any]:
+ """Provides a holistic view of the AI workforce status."""
+ today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
+
+ # 1. Quota Stats
+ quota = await self._check_quota_status()
+
+ # 2. Task Queue Stats
+ queue_stmt = select(AgentQueue.status, func.count(AgentQueue.id)).group_by(AgentQueue.status)
+ queue_res = await self.db.execute(queue_stmt)
+ queue_stats = {r[0]: r[1] for r in queue_res.all()}
+
+ # 3. Recent Agent Activity
+ activity_stmt = select(AgentStateLog).order_by(AgentStateLog.updated_at.desc()).limit(10)
+ activity_res = await self.db.execute(activity_stmt)
+ recent_activity = [
+ {
+ "agent": a.agent_name,
+ "task": a.memory_context.get("task_name", "Unknown"),
+ "status": a.status,
+ "last_action": a.last_action,
+ "timestamp": a.updated_at
+ } for a in activity_res.scalars().all()
+ ]
+
+ return {
+ "quota": quota,
+ "queue": queue_stats,
+ "activity": recent_activity,
+ "status": "HEALTHY" if quota["rpd_percent"] < self.CRITICAL_THRESHOLD else "TRIAGE_MODE"
+ }
+
+ async def _notify_user_via_email(self, email, task, data):
+ try:
+ if task == "academy_feedback": await self.email_service.send_feedback_email(email, data)
+ elif task in ["cv_analysis", "bulk_vetting"]:
+ await self.email_service.send_feedback_email(email, {
+ "feedback_intro": "Halo! Brigawan telah selesai menganalisis dokumen Anda secara mendalam. Berikut adalah hasil review dan link aktivasi akun Anda.",
+ "strengths": data.get("category", "Talenta Hijau Potensial"),
+ "areas_for_improvement": ", ".join(data.get("skill_gaps", []) or ["Terus tingkatkan sertifikasi K3"]),
+ "concrete_tips": [data.get("transition_path", "Lanjutkan eksplorasi di sektor EBT.")],
+ "next_steps": "Klik tombol di bawah ini untuk mengaktivasi akun Anda.",
+ "closing": "Selamat bergabung di ekosistem hijau Indonesia! 🌿"
+ })
+ elif task == "career_advice":
+ await self.email_service.send_feedback_email(email, {
+ "feedback_intro": "Halo! Ini adalah saran karir strategis yang dirancang khusus untuk Anda oleh Brigawan AI.",
+ "strengths": "Visi Karir Hijau Anda",
+ "areas_for_improvement": data.get("advice_snippet", "Fokus pada pengembangan spesialisasi sektor."),
+ "concrete_tips": data.get("next_steps", ["Ikuti pelatihan SKKNI terkait"]),
+ "next_steps": data.get("full_recommendation", "Cek dashboard."),
+ "closing": "Ingat, keahlian Anda adalah kunci transisi energi Indonesia. Semangat!"
+ })
+ except Exception as e: logger.error(f"[Antigravity] Email notification failed: {e}")
diff --git a/app/services/audit_service.py b/app/services/audit_service.py
index df25159ef68fce193c00a543cc0ce25a96053f45..b8cb138d5d6272a5d5e39744aa0279aeb286e509 100644
--- a/app/services/audit_service.py
+++ b/app/services/audit_service.py
@@ -1,134 +1,134 @@
-"""Audit service for managing the cryptographic ledger and archiving.
-
-Handles tamper detection, chain verification, and the archiving pipeline.
-"""
-
-import uuid
-from datetime import datetime, timedelta, timezone
-from typing import List, Optional, Dict, Any
-
-from sqlalchemy import text, select, func
-from sqlalchemy.ext.asyncio import AsyncSession
-from loguru import logger
-
-from app.models.security import AuditTrail, AuditAnchor
-
-
-class AuditService:
- """Service for cryptographic audit operations."""
-
- async def verify_integrity(self, db: AsyncSession) -> Dict[str, Any]:
- """
- Verify the integrity of the entire audit trail.
- Returns a report of any detected tampering or chain breaks.
- """
- # Verification query from the blueprint
- verify_query = text("""
- WITH verified_trail AS (
- SELECT
- a.id,
- a.record_table,
- a.record_id,
- a.action_type,
- a.ciphertext_hash,
- a.signature_hash,
- a.previous_hash,
- a.current_hash,
- encode(
- digest(
- a.record_table || '|' ||
- a.record_id::text || '|' ||
- a.action_type || '|' ||
- COALESCE(a.ciphertext_hash, '') || '|' ||
- COALESCE(a.signature_hash, '') || '|' ||
- a.previous_hash,
- 'sha256'
- ),
- 'hex'
- ) AS calculated_current_hash,
- COALESCE(
- LAG(a.current_hash) OVER (ORDER BY a.id ASC),
- '0000000000000000000000000000000000000000000000000000000000000000'
- ) AS expected_prev_hash
- FROM audit.audit_trail a
- )
- SELECT
- v.id,
- v.record_id,
- v.action_type,
- v.current_hash,
- v.calculated_current_hash,
- v.previous_hash,
- v.expected_prev_hash,
- CASE
- WHEN v.current_hash != v.calculated_current_hash
- THEN 'Hash verification failed: current hash does not match payload'
- WHEN v.previous_hash != v.expected_prev_hash
- AND NOT EXISTS (SELECT 1 FROM audit.audit_anchors WHERE anchor_hash = v.previous_hash)
- THEN 'Hash chain broken: previous_hash does not match previous block or anchor'
- ELSE 'OK'
- END AS verification_status
- FROM verified_trail v
- WHERE v.current_hash != v.calculated_current_hash
- OR (v.previous_hash != v.expected_prev_hash
- AND NOT EXISTS (SELECT 1 FROM audit.audit_anchors WHERE anchor_hash = v.previous_hash));
- """)
-
- result = await db.execute(verify_query)
- anomalies = [dict(row) for row in result.mappings().all()]
-
- if not anomalies:
- logger.info("Audit trail integrity verified: OK")
- return {"status": "OK", "anomalies": []}
-
- logger.error(f"Audit trail integrity violation detected! {len(anomalies)} anomalies found.")
- return {"status": "VIOLATION", "anomalies": anomalies}
-
- async def run_archiving(self, db: AsyncSession, days_threshold: int = 365) -> Dict[str, Any]:
- """
- Archive old audit logs to cold storage and create an anchor block.
- """
- threshold_date = datetime.now(timezone.utc) - timedelta(days=days_threshold)
-
- # 1. Identify logs to prune
- prune_query = select(AuditTrail).where(AuditTrail.timestamp < threshold_date).order_by(AuditTrail.id.asc())
- result = await db.execute(prune_query)
- logs_to_prune = result.scalars().all()
-
- if not logs_to_prune:
- return {"status": "SKIPPED", "message": "No logs found matching the threshold."}
-
- max_id = logs_to_prune[-1].id
- anchor_hash = logs_to_prune[-1].current_hash
-
- # 2. Simulate Cold Storage Export (In production, write to GCS/S3)
- # archive_data = [log.to_dict() for log in logs_to_prune]
- # cold_storage_uri = await self._upload_to_gcs(archive_data)
- cold_storage_uri = f"gs://briga-audit-archive/archive_{datetime.now(timezone.utc).strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}.jsonl.gz"
- archive_file_hash = "simulated_sha256_hash_of_exported_file"
-
- # 3. Create Anchor Block
- anchor = AuditAnchor(
- max_audit_id=max_id,
- anchor_hash=anchor_hash,
- cold_storage_uri=cold_storage_uri,
- archive_file_hash=archive_file_hash
- )
- db.add(anchor)
-
- # 4. Prune Logs
- delete_query = text("DELETE FROM audit.audit_trail WHERE id <= :max_id")
- await db.execute(delete_query, {"max_id": max_id})
-
- await db.commit()
-
- logger.info(f"Archived {len(logs_to_prune)} logs. Anchor created at ID {max_id}.")
- return {
- "status": "SUCCESS",
- "archived_count": len(logs_to_prune),
- "anchor_id": max_id,
- "cold_storage_uri": cold_storage_uri
- }
-
-
-audit_service = AuditService()
+"""Audit service for managing the cryptographic ledger and archiving.
+
+Handles tamper detection, chain verification, and the archiving pipeline.
+"""
+
+import uuid
+from datetime import datetime, timedelta, timezone
+from typing import List, Optional, Dict, Any
+
+from sqlalchemy import text, select, func
+from sqlalchemy.ext.asyncio import AsyncSession
+from loguru import logger
+
+from app.models.security import AuditTrail, AuditAnchor
+
+
+class AuditService:
+ """Service for cryptographic audit operations."""
+
+ async def verify_integrity(self, db: AsyncSession) -> Dict[str, Any]:
+ """
+ Verify the integrity of the entire audit trail.
+ Returns a report of any detected tampering or chain breaks.
+ """
+ # Verification query from the blueprint
+ verify_query = text("""
+ WITH verified_trail AS (
+ SELECT
+ a.id,
+ a.record_table,
+ a.record_id,
+ a.action_type,
+ a.ciphertext_hash,
+ a.signature_hash,
+ a.previous_hash,
+ a.current_hash,
+ encode(
+ digest(
+ a.record_table || '|' ||
+ a.record_id::text || '|' ||
+ a.action_type || '|' ||
+ COALESCE(a.ciphertext_hash, '') || '|' ||
+ COALESCE(a.signature_hash, '') || '|' ||
+ a.previous_hash,
+ 'sha256'
+ ),
+ 'hex'
+ ) AS calculated_current_hash,
+ COALESCE(
+ LAG(a.current_hash) OVER (ORDER BY a.id ASC),
+ '0000000000000000000000000000000000000000000000000000000000000000'
+ ) AS expected_prev_hash
+ FROM audit.audit_trail a
+ )
+ SELECT
+ v.id,
+ v.record_id,
+ v.action_type,
+ v.current_hash,
+ v.calculated_current_hash,
+ v.previous_hash,
+ v.expected_prev_hash,
+ CASE
+ WHEN v.current_hash != v.calculated_current_hash
+ THEN 'Hash verification failed: current hash does not match payload'
+ WHEN v.previous_hash != v.expected_prev_hash
+ AND NOT EXISTS (SELECT 1 FROM audit.audit_anchors WHERE anchor_hash = v.previous_hash)
+ THEN 'Hash chain broken: previous_hash does not match previous block or anchor'
+ ELSE 'OK'
+ END AS verification_status
+ FROM verified_trail v
+ WHERE v.current_hash != v.calculated_current_hash
+ OR (v.previous_hash != v.expected_prev_hash
+ AND NOT EXISTS (SELECT 1 FROM audit.audit_anchors WHERE anchor_hash = v.previous_hash));
+ """)
+
+ result = await db.execute(verify_query)
+ anomalies = [dict(row) for row in result.mappings().all()]
+
+ if not anomalies:
+ logger.info("Audit trail integrity verified: OK")
+ return {"status": "OK", "anomalies": []}
+
+ logger.error(f"Audit trail integrity violation detected! {len(anomalies)} anomalies found.")
+ return {"status": "VIOLATION", "anomalies": anomalies}
+
+ async def run_archiving(self, db: AsyncSession, days_threshold: int = 365) -> Dict[str, Any]:
+ """
+ Archive old audit logs to cold storage and create an anchor block.
+ """
+ threshold_date = datetime.now(timezone.utc) - timedelta(days=days_threshold)
+
+ # 1. Identify logs to prune
+ prune_query = select(AuditTrail).where(AuditTrail.timestamp < threshold_date).order_by(AuditTrail.id.asc())
+ result = await db.execute(prune_query)
+ logs_to_prune = result.scalars().all()
+
+ if not logs_to_prune:
+ return {"status": "SKIPPED", "message": "No logs found matching the threshold."}
+
+ max_id = logs_to_prune[-1].id
+ anchor_hash = logs_to_prune[-1].current_hash
+
+ # 2. Simulate Cold Storage Export (In production, write to GCS/S3)
+ # archive_data = [log.to_dict() for log in logs_to_prune]
+ # cold_storage_uri = await self._upload_to_gcs(archive_data)
+ cold_storage_uri = f"gs://briga-audit-archive/archive_{datetime.now(timezone.utc).strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}.jsonl.gz"
+ archive_file_hash = "simulated_sha256_hash_of_exported_file"
+
+ # 3. Create Anchor Block
+ anchor = AuditAnchor(
+ max_audit_id=max_id,
+ anchor_hash=anchor_hash,
+ cold_storage_uri=cold_storage_uri,
+ archive_file_hash=archive_file_hash
+ )
+ db.add(anchor)
+
+ # 4. Prune Logs
+ delete_query = text("DELETE FROM audit.audit_trail WHERE id <= :max_id")
+ await db.execute(delete_query, {"max_id": max_id})
+
+ await db.commit()
+
+ logger.info(f"Archived {len(logs_to_prune)} logs. Anchor created at ID {max_id}.")
+ return {
+ "status": "SUCCESS",
+ "archived_count": len(logs_to_prune),
+ "anchor_id": max_id,
+ "cold_storage_uri": cold_storage_uri
+ }
+
+
+audit_service = AuditService()
diff --git a/app/services/auth_service.py b/app/services/auth_service.py
index 82fcbcafa2dfaf1e02bec0cb4b59c28b78049ec4..6462f8455a0c595111977314fa5acd84679b7ded 100644
--- a/app/services/auth_service.py
+++ b/app/services/auth_service.py
@@ -1,379 +1,379 @@
-"""Auth service — registration, login, Google OAuth, JWT management.
-
-Zero-cost architecture:
-- Google OAuth: Google Cloud free tier
-- Email/password: bcrypt (free)
-- Rate limiting: in-memory (no Redis)
-- Free tier: 3 trial credits, 1 job posting
-"""
-
-import json
-import secrets
-from datetime import datetime, timezone
-from typing import Any, Dict, Optional
-
-import httpx
-from loguru import logger
-from sqlalchemy import or_, select
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.models.talent import Talent
-from app.models.employer import ClientAccount, Company
-from app.utils.errors import ErrorCode, raise_error
-from app.utils.security import (
- create_access_token,
- hash_password,
- hash_legacy_gas_password,
- verify_password,
-)
-
-
-FREE_TIER = {"credits": 3, "max_jobs": 1, "seats": 1, "ai_matching": False, "rate_limit": 100}
-
-
-# ─── Helpers ────────────────────────────────────────────────────────────────
-
-def _user_response(email: str, name: str, user_id: str, role: str) -> dict:
- return {
- "id": user_id, "email": email, "name": name, "role": role,
- "tier": "free", "credits_remaining": FREE_TIER["credits"],
- "is_verified": False, "created_at": datetime.now(timezone.utc),
- }
-
-
-def _auth_response(token: str, user: dict, message: Optional[str] = None) -> dict:
- return {
- "success": True, "access_token": token, "token_type": "bearer",
- "expires_in": 86400, "user": user,
- **({"message": message} if message else {}),
- }
-
-
-async def _global_duplicate_check(db: AsyncSession, email: str) -> Optional[str]:
- """Check email across all user tables (GAS isGlobalDuplicate equivalent)."""
- for table in [Talent, ClientAccount]:
- result = await db.execute(select(table).where(table.email == email))
- if result.scalar_one_or_none():
- return table.__tablename__
- return None
-
-
-# ─── Registration ───────────────────────────────────────────────────────────
-
-async def register_talent(db: AsyncSession, data: dict) -> dict:
- email = data["email"].lower().strip()
-
- # Global duplicate check (matches GAS isGlobalDuplicate)
- dup = await _global_duplicate_check(db, email)
- if dup:
- raise_error(
- f"Email already registered as a {dup.replace('_', ' ')}. Try logging in.",
- code=ErrorCode.DUPLICATE_EMAIL,
- )
-
- talent_id = f"BRIGA-GT-{secrets.token_hex(3).upper()}"
- talent = Talent(
- talent_id=talent_id,
- name=data["name"],
- email=email,
- password_hash=hash_password(data["password"]),
- phone=data.get("phone", ""),
- education=data.get("education", ""),
- experience=data.get("experience", ""),
- location=data.get("location", ""),
- skill_tags=data.get("skill_tags", ""),
- cv_link=data.get("cv_link", ""),
- linkedin_link=data.get("linkedin_link", ""),
- score=70,
- verification_status="Pending",
- green_score=0,
- )
- db.add(talent)
- await db.commit()
-
- token = create_access_token(subject=talent_id, email=email, role="talent")
- user = _user_response(email, data["name"], talent_id, "talent")
- logger.info(f"Registered talent: {email}")
- return _auth_response(token, user, f"Welcome! {FREE_TIER['credits']} trial credits activated.")
-
-
-async def register_talent_from_whatsapp(db: AsyncSession, data: dict) -> dict:
- """Special registration for WhatsApp users with auto-generated password."""
- email = data.get("email", "").lower().strip()
- if not email:
- raise_error("Email is required for registration.", code=ErrorCode.TOKEN_INVALID)
-
- # Check if already registered
- result = await db.execute(select(Talent).where(Talent.email == email))
- existing = result.scalar_one_or_none()
-
- if existing:
- # If exists, just log them in (assuming they confirmed via their own WhatsApp)
- token = create_access_token(subject=existing.talent_id, email=email, role="talent")
- user = _user_response(email, existing.name, existing.talent_id, "talent")
- return _auth_response(token, user, "Welcome back!")
-
- # New registration with default password (user should change it later)
- # Default password is "Briga" + phone last 4 digits for simplicity
- phone = data.get("phone", "0000")
- default_pass = f"Briga{phone[-4:]}"
-
- reg_data = {
- "email": email,
- "name": data.get("name", "Talent WhatsApp"),
- "password": default_pass,
- "phone": phone
- }
-
- # 1. Register talent (password will be hashed inside register_talent)
- result = await register_talent(db, reg_data)
-
- # 2. Send welcome email with the cleartext default password
- if result.get("success"):
- from app.services.whatsapp_email_service import wa_email_service
- # We send the cleartext password here before it was hashed only in memory for the email
- await wa_email_service.send_welcome_email(email, reg_data["name"], default_pass)
-
- return result
-
-
-async def register_employer(db: AsyncSession, data: dict) -> dict:
- email = data["email"].lower().strip()
-
- dup = await _global_duplicate_check(db, email)
- if dup:
- raise_error(
- f"Email already registered as a {dup.replace('_', ' ')}. Try logging in.",
- code=ErrorCode.DUPLICATE_EMAIL,
- )
-
- company_id = f"BRIGA-CO-{secrets.token_hex(4).upper()}"
- company = Company(
- id=company_id,
- name=data.get("company_name", email.split("@")[1]),
- website=data.get("website", ""),
- tier="free",
- credit_balance=FREE_TIER["credits"],
- seats_limit=FREE_TIER["seats"],
- max_jobs=FREE_TIER["max_jobs"],
- status="PENDING",
- )
- db.add(company)
-
- client_id = f"BRIGA-ST-{secrets.token_hex(4).upper()}"
- client = ClientAccount(
- id=client_id,
- company_id=company_id,
- email=email,
- password_hash=hash_password(data["password"]),
- name=data.get("name", "Recruiter"),
- role="Recruiter",
- status="PENDING", # Both company & client PENDING until admin approval
- )
- db.add(client)
- await db.commit()
-
- token = create_access_token(subject=client_id, email=email, role="employer")
- user = _user_response(email, data.get("name", "Recruiter"), client_id, "employer")
- logger.info(f"Registered employer: {email} (Company: {company_id})")
- return _auth_response(token, user, "Company registered on Free tier. Pending admin approval.")
-
-
-# ─── Login ───────────────────────────────────────────────────────────────────
-
-async def _try_talent_login(db: AsyncSession, email: str, password: str) -> Optional[dict]:
- result = await db.execute(select(Talent).where(Talent.email == email))
- talent = result.scalar_one_or_none()
- if not talent or not talent.password_hash:
- return None
-
- # Sentinel check: Google OAuth accounts have no password
- if talent.password_hash == "GOOGLE_OAUTH":
- raise_error(
- "This account uses Google Login. Sign in with Google.",
- code=ErrorCode.INVALID_CREDENTIALS,
- )
-
- # Try bcrypt first
- if verify_password(password, talent.password_hash):
- token = create_access_token(subject=talent.talent_id, email=email, role="talent")
- user = _user_response(email, talent.name, talent.talent_id, "talent")
- return _auth_response(token, user)
-
- # Legacy GAS hash fallback + upgrade to bcrypt
- if talent.password_hash == hash_legacy_gas_password(password, email):
- talent.password_hash = hash_password(password)
- await db.commit()
- token = create_access_token(subject=talent.talent_id, email=email, role="talent")
- user = _user_response(email, talent.name, talent.talent_id, "talent")
- return _auth_response(token, user)
-
- return None
-
-
-async def _try_employer_login(db: AsyncSession, email: str, password: str) -> Optional[dict]:
- result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
- client = result.scalar_one_or_none()
- if not client or not client.password_hash:
- return None
-
- if not verify_password(password, client.password_hash):
- return None
-
- token = create_access_token(subject=client.id, email=email, role="employer")
- user = _user_response(email, client.name, client.id, "employer")
- return _auth_response(token, user)
-
-
-async def login_email(db: AsyncSession, email: str, password: str) -> dict:
- email = email.lower().strip()
-
- # Try talent first, then employer
- talent_result = await _try_talent_login(db, email, password)
- if talent_result:
- return talent_result
-
- employer_result = await _try_employer_login(db, email, password)
- if employer_result:
- return employer_result
-
- raise_error("Invalid email or password.", code=ErrorCode.INVALID_CREDENTIALS, status_code=401)
-
-
-async def login_google(db: AsyncSession, id_token: str) -> dict:
- """Google OAuth login. Checks both Talent and ClientAccount tables.
-
- Crash-proof:
- - If Google's tokeninfo endpoint is unreachable, returns a graceful error
- - No hard crash on network failure — always returns a structured response
- """
- # Verify token with Google
- google_data = None
- try:
- async with httpx.AsyncClient() as client:
- resp = await client.get(
- "https://oauth2.googleapis.com/tokeninfo",
- params={"id_token": id_token},
- timeout=10,
- )
- if resp.status_code != 200:
- raise_error("Invalid Google ID token.", code=ErrorCode.TOKEN_INVALID, status_code=401)
- google_data = resp.json()
- except httpx.TimeoutException:
- logger.error("Google OAuth: tokeninfo endpoint timed out")
- raise_error("Google verification timed out. Please try again.", code=ErrorCode.NETWORK_ERROR, status_code=502)
- except httpx.RequestError as e:
- logger.error(f"Google OAuth network error: {e}")
- raise_error("Could not verify Google token. Check your internet connection.", code=ErrorCode.NETWORK_ERROR, status_code=502)
- except Exception as e:
- logger.error(f"Google OAuth unexpected error: {e}")
- raise_error("Google verification failed. Please try again.", code=ErrorCode.NETWORK_ERROR, status_code=502)
-
- if google_data is None:
- raise_error("Google verification returned no data.", code=ErrorCode.NETWORK_ERROR, status_code=502)
-
- email = google_data.get("email", "").lower().strip()
- google_name = google_data.get("name", "Google User")
- google_id = google_data.get("sub", "")
-
- if not email:
- raise_error("Google account has no email. Please use a different account.", code=ErrorCode.TOKEN_INVALID, status_code=401)
-
- # Search across both tables
- result = await db.execute(select(Talent).where(Talent.email == email))
- talent = result.scalar_one_or_none()
- if talent:
- # Existing talent — log them in
- token = create_access_token(subject=talent.talent_id, email=email, role="talent")
- user = _user_response(email, talent.name, talent.talent_id, "talent")
- logger.info(f"Google login (existing talent): {email}")
- return _auth_response(token, user, "Welcome back!")
-
- # Check employer table
- result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
- client = result.scalar_one_or_none()
- if client:
- token = create_access_token(subject=client.id, email=email, role="employer")
- user = _user_response(email, client.name, client.id, "employer")
- logger.info(f"Google login (existing employer): {email}")
- return _auth_response(token, user, "Welcome back!")
-
- # New user — auto-create talent account (matches GAS behavior)
- talent_id = f"BRIGA-GT-{secrets.token_hex(3).upper()}"
- new_talent = Talent(
- talent_id=talent_id,
- name=google_name,
- email=email,
- password_hash="GOOGLE_OAUTH", # Sentinel — no password login allowed
- verification_status="Verified", # Google-verified email
- score=70,
- green_score=0,
- )
- db.add(new_talent)
- await db.commit()
-
- token = create_access_token(subject=talent_id, email=email, role="talent")
- user = _user_response(email, google_name, talent_id, "talent")
- logger.info(f"Google login (new talent): {email}")
- return _auth_response(token, user, "Account created via Google. Welcome to Brigawan!")
-
-
-async def admin_login(db: AsyncSession, email: str, password: str) -> dict:
- """Admin login. Matches GAS admin check pattern.
- For now, uses the same JWT flow with elevated role.
- """
- if email == "admin@briga.id" and password == settings.admin_password:
- token = create_access_token(subject="admin", email=email, role="admin")
- user = {
- "id": "admin",
- "email": email,
- "name": "Admin Brigawan",
- "role": "admin",
- "tier": "enterprise",
- "credits_remaining": 9999,
- "is_verified": True,
- }
- return _auth_response(token, user, "Admin login successful.")
- raise_error("Invalid admin credentials.", code=ErrorCode.INVALID_CREDENTIALS, status_code=401)
-
-
-async def get_user_by_token(db: AsyncSession, email: str, role: str) -> Optional[dict]:
- """Get user profile by JWT payload.
- Used by GET /v1/auth/me endpoint.
- """
- try:
- if role == "talent":
- result = await db.execute(select(Talent).where(Talent.email == email))
- talent = result.scalar_one_or_none()
- if not talent:
- return None
- return {
- "id": talent.talent_id,
- "email": talent.email,
- "name": talent.name,
- "role": "talent",
- "tier": "free",
- "credits_remaining": 3,
- "is_verified": talent.verification_status == "Verified",
- }
- elif role == "employer":
- result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
- client = result.scalar_one_or_none()
- if not client:
- return None
- # Get company info for tier and credits
- result2 = await db.execute(select(Company).where(Company.id == client.company_id))
- company = result2.scalar_one_or_none()
- return {
- "id": client.id,
- "email": client.email,
- "name": client.name,
- "role": "employer",
- "tier": company.tier if company else "free",
- "credits_remaining": company.credit_balance if company else 3,
- "is_verified": client.status == "Active",
- }
- return None
- except Exception as e:
- logger.error(f"get_user_by_token error: {e}")
- return None
+"""Auth service — registration, login, Google OAuth, JWT management.
+
+Zero-cost architecture:
+- Google OAuth: Google Cloud free tier
+- Email/password: bcrypt (free)
+- Rate limiting: in-memory (no Redis)
+- Free tier: 3 trial credits, 1 job posting
+"""
+
+import json
+import secrets
+from datetime import datetime, timezone
+from typing import Any, Dict, Optional
+
+import httpx
+from loguru import logger
+from sqlalchemy import or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.talent import Talent
+from app.models.employer import ClientAccount, Company
+from app.utils.errors import ErrorCode, raise_error
+from app.utils.security import (
+ create_access_token,
+ hash_password,
+ hash_legacy_gas_password,
+ verify_password,
+)
+
+
+FREE_TIER = {"credits": 3, "max_jobs": 1, "seats": 1, "ai_matching": False, "rate_limit": 100}
+
+
+# ─── Helpers ────────────────────────────────────────────────────────────────
+
+def _user_response(email: str, name: str, user_id: str, role: str) -> dict:
+ return {
+ "id": user_id, "email": email, "name": name, "role": role,
+ "tier": "free", "credits_remaining": FREE_TIER["credits"],
+ "is_verified": False, "created_at": datetime.now(timezone.utc),
+ }
+
+
+def _auth_response(token: str, user: dict, message: Optional[str] = None) -> dict:
+ return {
+ "success": True, "access_token": token, "token_type": "bearer",
+ "expires_in": 86400, "user": user,
+ **({"message": message} if message else {}),
+ }
+
+
+async def _global_duplicate_check(db: AsyncSession, email: str) -> Optional[str]:
+ """Check email across all user tables (GAS isGlobalDuplicate equivalent)."""
+ for table in [Talent, ClientAccount]:
+ result = await db.execute(select(table).where(table.email == email))
+ if result.scalar_one_or_none():
+ return table.__tablename__
+ return None
+
+
+# ─── Registration ───────────────────────────────────────────────────────────
+
+async def register_talent(db: AsyncSession, data: dict) -> dict:
+ email = data["email"].lower().strip()
+
+ # Global duplicate check (matches GAS isGlobalDuplicate)
+ dup = await _global_duplicate_check(db, email)
+ if dup:
+ raise_error(
+ f"Email already registered as a {dup.replace('_', ' ')}. Try logging in.",
+ code=ErrorCode.DUPLICATE_EMAIL,
+ )
+
+ talent_id = f"BRIGA-GT-{secrets.token_hex(3).upper()}"
+ talent = Talent(
+ talent_id=talent_id,
+ name=data["name"],
+ email=email,
+ password_hash=hash_password(data["password"]),
+ phone=data.get("phone", ""),
+ education=data.get("education", ""),
+ experience=data.get("experience", ""),
+ location=data.get("location", ""),
+ skill_tags=data.get("skill_tags", ""),
+ cv_link=data.get("cv_link", ""),
+ linkedin_link=data.get("linkedin_link", ""),
+ score=70,
+ verification_status="Pending",
+ green_score=0,
+ )
+ db.add(talent)
+ await db.commit()
+
+ token = create_access_token(subject=talent_id, email=email, role="talent")
+ user = _user_response(email, data["name"], talent_id, "talent")
+ logger.info(f"Registered talent: {email}")
+ return _auth_response(token, user, f"Welcome! {FREE_TIER['credits']} trial credits activated.")
+
+
+async def register_talent_from_whatsapp(db: AsyncSession, data: dict) -> dict:
+ """Special registration for WhatsApp users with auto-generated password."""
+ email = data.get("email", "").lower().strip()
+ if not email:
+ raise_error("Email is required for registration.", code=ErrorCode.TOKEN_INVALID)
+
+ # Check if already registered
+ result = await db.execute(select(Talent).where(Talent.email == email))
+ existing = result.scalar_one_or_none()
+
+ if existing:
+ # If exists, just log them in (assuming they confirmed via their own WhatsApp)
+ token = create_access_token(subject=existing.talent_id, email=email, role="talent")
+ user = _user_response(email, existing.name, existing.talent_id, "talent")
+ return _auth_response(token, user, "Welcome back!")
+
+ # New registration with default password (user should change it later)
+ # Default password is "Briga" + phone last 4 digits for simplicity
+ phone = data.get("phone", "0000")
+ default_pass = f"Briga{phone[-4:]}"
+
+ reg_data = {
+ "email": email,
+ "name": data.get("name", "Talent WhatsApp"),
+ "password": default_pass,
+ "phone": phone
+ }
+
+ # 1. Register talent (password will be hashed inside register_talent)
+ result = await register_talent(db, reg_data)
+
+ # 2. Send welcome email with the cleartext default password
+ if result.get("success"):
+ from app.services.whatsapp_email_service import wa_email_service
+ # We send the cleartext password here before it was hashed only in memory for the email
+ await wa_email_service.send_welcome_email(email, reg_data["name"], default_pass)
+
+ return result
+
+
+async def register_employer(db: AsyncSession, data: dict) -> dict:
+ email = data["email"].lower().strip()
+
+ dup = await _global_duplicate_check(db, email)
+ if dup:
+ raise_error(
+ f"Email already registered as a {dup.replace('_', ' ')}. Try logging in.",
+ code=ErrorCode.DUPLICATE_EMAIL,
+ )
+
+ company_id = f"BRIGA-CO-{secrets.token_hex(4).upper()}"
+ company = Company(
+ id=company_id,
+ name=data.get("company_name", email.split("@")[1]),
+ website=data.get("website", ""),
+ tier="free",
+ credit_balance=FREE_TIER["credits"],
+ seats_limit=FREE_TIER["seats"],
+ max_jobs=FREE_TIER["max_jobs"],
+ status="PENDING",
+ )
+ db.add(company)
+
+ client_id = f"BRIGA-ST-{secrets.token_hex(4).upper()}"
+ client = ClientAccount(
+ id=client_id,
+ company_id=company_id,
+ email=email,
+ password_hash=hash_password(data["password"]),
+ name=data.get("name", "Recruiter"),
+ role="Recruiter",
+ status="PENDING", # Both company & client PENDING until admin approval
+ )
+ db.add(client)
+ await db.commit()
+
+ token = create_access_token(subject=client_id, email=email, role="employer")
+ user = _user_response(email, data.get("name", "Recruiter"), client_id, "employer")
+ logger.info(f"Registered employer: {email} (Company: {company_id})")
+ return _auth_response(token, user, "Company registered on Free tier. Pending admin approval.")
+
+
+# ─── Login ───────────────────────────────────────────────────────────────────
+
+async def _try_talent_login(db: AsyncSession, email: str, password: str) -> Optional[dict]:
+ result = await db.execute(select(Talent).where(Talent.email == email))
+ talent = result.scalar_one_or_none()
+ if not talent or not talent.password_hash:
+ return None
+
+ # Sentinel check: Google OAuth accounts have no password
+ if talent.password_hash == "GOOGLE_OAUTH":
+ raise_error(
+ "This account uses Google Login. Sign in with Google.",
+ code=ErrorCode.INVALID_CREDENTIALS,
+ )
+
+ # Try bcrypt first
+ if verify_password(password, talent.password_hash):
+ token = create_access_token(subject=talent.talent_id, email=email, role="talent")
+ user = _user_response(email, talent.name, talent.talent_id, "talent")
+ return _auth_response(token, user)
+
+ # Legacy GAS hash fallback + upgrade to bcrypt
+ if talent.password_hash == hash_legacy_gas_password(password, email):
+ talent.password_hash = hash_password(password)
+ await db.commit()
+ token = create_access_token(subject=talent.talent_id, email=email, role="talent")
+ user = _user_response(email, talent.name, talent.talent_id, "talent")
+ return _auth_response(token, user)
+
+ return None
+
+
+async def _try_employer_login(db: AsyncSession, email: str, password: str) -> Optional[dict]:
+ result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
+ client = result.scalar_one_or_none()
+ if not client or not client.password_hash:
+ return None
+
+ if not verify_password(password, client.password_hash):
+ return None
+
+ token = create_access_token(subject=client.id, email=email, role="employer")
+ user = _user_response(email, client.name, client.id, "employer")
+ return _auth_response(token, user)
+
+
+async def login_email(db: AsyncSession, email: str, password: str) -> dict:
+ email = email.lower().strip()
+
+ # Try talent first, then employer
+ talent_result = await _try_talent_login(db, email, password)
+ if talent_result:
+ return talent_result
+
+ employer_result = await _try_employer_login(db, email, password)
+ if employer_result:
+ return employer_result
+
+ raise_error("Invalid email or password.", code=ErrorCode.INVALID_CREDENTIALS, status_code=401)
+
+
+async def login_google(db: AsyncSession, id_token: str) -> dict:
+ """Google OAuth login. Checks both Talent and ClientAccount tables.
+
+ Crash-proof:
+ - If Google's tokeninfo endpoint is unreachable, returns a graceful error
+ - No hard crash on network failure — always returns a structured response
+ """
+ # Verify token with Google
+ google_data = None
+ try:
+ async with httpx.AsyncClient() as client:
+ resp = await client.get(
+ "https://oauth2.googleapis.com/tokeninfo",
+ params={"id_token": id_token},
+ timeout=10,
+ )
+ if resp.status_code != 200:
+ raise_error("Invalid Google ID token.", code=ErrorCode.TOKEN_INVALID, status_code=401)
+ google_data = resp.json()
+ except httpx.TimeoutException:
+ logger.error("Google OAuth: tokeninfo endpoint timed out")
+ raise_error("Google verification timed out. Please try again.", code=ErrorCode.NETWORK_ERROR, status_code=502)
+ except httpx.RequestError as e:
+ logger.error(f"Google OAuth network error: {e}")
+ raise_error("Could not verify Google token. Check your internet connection.", code=ErrorCode.NETWORK_ERROR, status_code=502)
+ except Exception as e:
+ logger.error(f"Google OAuth unexpected error: {e}")
+ raise_error("Google verification failed. Please try again.", code=ErrorCode.NETWORK_ERROR, status_code=502)
+
+ if google_data is None:
+ raise_error("Google verification returned no data.", code=ErrorCode.NETWORK_ERROR, status_code=502)
+
+ email = google_data.get("email", "").lower().strip()
+ google_name = google_data.get("name", "Google User")
+ google_id = google_data.get("sub", "")
+
+ if not email:
+ raise_error("Google account has no email. Please use a different account.", code=ErrorCode.TOKEN_INVALID, status_code=401)
+
+ # Search across both tables
+ result = await db.execute(select(Talent).where(Talent.email == email))
+ talent = result.scalar_one_or_none()
+ if talent:
+ # Existing talent — log them in
+ token = create_access_token(subject=talent.talent_id, email=email, role="talent")
+ user = _user_response(email, talent.name, talent.talent_id, "talent")
+ logger.info(f"Google login (existing talent): {email}")
+ return _auth_response(token, user, "Welcome back!")
+
+ # Check employer table
+ result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
+ client = result.scalar_one_or_none()
+ if client:
+ token = create_access_token(subject=client.id, email=email, role="employer")
+ user = _user_response(email, client.name, client.id, "employer")
+ logger.info(f"Google login (existing employer): {email}")
+ return _auth_response(token, user, "Welcome back!")
+
+ # New user — auto-create talent account (matches GAS behavior)
+ talent_id = f"BRIGA-GT-{secrets.token_hex(3).upper()}"
+ new_talent = Talent(
+ talent_id=talent_id,
+ name=google_name,
+ email=email,
+ password_hash="GOOGLE_OAUTH", # Sentinel — no password login allowed
+ verification_status="Verified", # Google-verified email
+ score=70,
+ green_score=0,
+ )
+ db.add(new_talent)
+ await db.commit()
+
+ token = create_access_token(subject=talent_id, email=email, role="talent")
+ user = _user_response(email, google_name, talent_id, "talent")
+ logger.info(f"Google login (new talent): {email}")
+ return _auth_response(token, user, "Account created via Google. Welcome to Brigawan!")
+
+
+async def admin_login(db: AsyncSession, email: str, password: str) -> dict:
+ """Admin login. Matches GAS admin check pattern.
+ For now, uses the same JWT flow with elevated role.
+ """
+ if email == "admin@briga.id" and password == settings.admin_password:
+ token = create_access_token(subject="admin", email=email, role="admin")
+ user = {
+ "id": "admin",
+ "email": email,
+ "name": "Admin Brigawan",
+ "role": "admin",
+ "tier": "enterprise",
+ "credits_remaining": 9999,
+ "is_verified": True,
+ }
+ return _auth_response(token, user, "Admin login successful.")
+ raise_error("Invalid admin credentials.", code=ErrorCode.INVALID_CREDENTIALS, status_code=401)
+
+
+async def get_user_by_token(db: AsyncSession, email: str, role: str) -> Optional[dict]:
+ """Get user profile by JWT payload.
+ Used by GET /v1/auth/me endpoint.
+ """
+ try:
+ if role == "talent":
+ result = await db.execute(select(Talent).where(Talent.email == email))
+ talent = result.scalar_one_or_none()
+ if not talent:
+ return None
+ return {
+ "id": talent.talent_id,
+ "email": talent.email,
+ "name": talent.name,
+ "role": "talent",
+ "tier": "free",
+ "credits_remaining": 3,
+ "is_verified": talent.verification_status == "Verified",
+ }
+ elif role == "employer":
+ result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
+ client = result.scalar_one_or_none()
+ if not client:
+ return None
+ # Get company info for tier and credits
+ result2 = await db.execute(select(Company).where(Company.id == client.company_id))
+ company = result2.scalar_one_or_none()
+ return {
+ "id": client.id,
+ "email": client.email,
+ "name": client.name,
+ "role": "employer",
+ "tier": company.tier if company else "free",
+ "credits_remaining": company.credit_balance if company else 3,
+ "is_verified": client.status == "Active",
+ }
+ return None
+ except Exception as e:
+ logger.error(f"get_user_by_token error: {e}")
+ return None
diff --git a/app/services/autonomous_dev_service.py b/app/services/autonomous_dev_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a51f12481cb0a35e576b8ebcd1f497e727095f2
--- /dev/null
+++ b/app/services/autonomous_dev_service.py
@@ -0,0 +1,150 @@
+"""Autonomous Developer Service — The Self-Healing Loop.
+
+This service monitors the server logs for errors and orchestrates
+the Error Handler and Code Fixer agents to diagnose and propose fixes.
+"""
+
+import os
+import asyncio
+from typing import Any, Dict, List, Optional
+from loguru import logger
+from app.services.agent_service import call_agent_json, call_agent
+
+class AutonomousDevService:
+ """Monitors logs and triggers self-healing cycles.
+
+ Respects runtime workflow toggles stored in `workflow_configs` table.
+ Caches workflow status in-memory for TTL 15s to avoid DB bursts.
+ """
+
+ LOG_FILE = "server.log"
+ _workflow_config_cache: dict = {} # { workflow_name: { 'is_active': bool, 'fetched_at': datetime } }
+ _cache_ttl_seconds = 15
+
+ @classmethod
+ async def _fetch_workflow_status_from_db(cls, workflow_name: str) -> bool:
+ """Query DB for workflow status."""
+ from sqlalchemy import select
+ from app.database import AsyncSessionLocal
+ from app.models.system import WorkflowConfig
+
+ try:
+ async with AsyncSessionLocal() as session:
+ stmt = select(WorkflowConfig).where(WorkflowConfig.workflow_name == workflow_name)
+ res = await session.execute(stmt)
+ row = res.scalar_one_or_none()
+ if row is None:
+ return False
+ return bool(row.is_active)
+ except Exception as e:
+ logger.error(f"[AutonomousDev] Failed to read workflow config for {workflow_name}: {e}")
+ return False
+
+ @classmethod
+ async def _is_workflow_active(cls, workflow_name: str) -> bool:
+ """Return cached status if fresh; otherwise refresh from DB."""
+ from datetime import datetime, timedelta, timezone
+
+ entry = cls._workflow_config_cache.get(workflow_name)
+ now = datetime.now(timezone.utc)
+ if entry:
+ fetched = entry.get("fetched_at")
+ if fetched and (now - fetched).total_seconds() < cls._cache_ttl_seconds:
+ return entry.get("is_active", False)
+
+ # Cache miss or stale -> fetch
+ is_active = await cls._fetch_workflow_status_from_db(workflow_name)
+ cls._workflow_config_cache[workflow_name] = {"is_active": is_active, "fetched_at": now}
+ return is_active
+
+ @classmethod
+ async def monitor_logs(cls):
+ """Background task to watch the log file and trigger workflows if enabled."""
+ from datetime import datetime, timezone
+
+ logger.info("[AutonomousDev] Starting log monitor loop...")
+
+ # Keep track of the last read position
+ last_pos = 0
+ if os.path.exists(cls.LOG_FILE):
+ last_pos = os.path.getsize(cls.LOG_FILE)
+
+ while True:
+ try:
+ if os.path.exists(cls.LOG_FILE):
+ current_size = os.path.getsize(cls.LOG_FILE)
+ if current_size > last_pos:
+ with open(cls.LOG_FILE, "r", encoding="utf-8", errors="ignore") as f:
+ f.seek(last_pos)
+ new_content = f.read()
+ last_pos = current_size
+
+ if "ERROR" in new_content or "Exception" in new_content:
+ # Check workflow toggle before running
+ active = await cls._is_workflow_active("autonomous-dev")
+ if not active:
+ logger.info("[AutonomousDev] autonomous-dev workflow is disabled; skipping healing cycle.")
+ else:
+ await cls.trigger_healing_cycle(new_content)
+
+ await asyncio.sleep(60) # Check every minute
+ except Exception as e:
+ logger.error(f"[AutonomousDev] Monitor loop error: {e}")
+ await asyncio.sleep(60)
+
+ @classmethod
+ async def trigger_healing_cycle(cls, error_context: str):
+ """Orchestrate the Error Handler -> Code Fixer flow.
+
+ Also record last_run on the workflow_configs row.
+ """
+ from datetime import datetime, timezone
+ from sqlalchemy import update
+ from app.database import AsyncSessionLocal
+ from app.models.system import WorkflowConfig
+
+ logger.warning("[AutonomousDev] Error detected! Triggering self-healing cycle...")
+
+ # 1. Error Handler Analysis
+ analysis_prompt = (
+ f"Analisalah log error berikut dan tentukan akar masalahnya:\n\n{error_context[:2000]}\n\n"
+ "Berikan respon dalam format JSON:\n"
+ "{\n"
+ " \"root_cause\": \"Penjelasan singkat penyebab error\",\n"
+ " \"file_affected\": \"Path file yang bermasalah\",\n"
+ " \"line_number\": \"Baris yang bermasalah (jika ada)\",\n"
+ " \"fix_instructions\": \"Instruksi langkah-demi-langkah untuk Code Fixer\"\n"
+ "}"
+ )
+
+ handler_resp = await call_agent_json("cto-agent", analysis_prompt)
+ if not handler_resp["success"]:
+ logger.error("[AutonomousDev] Error Handler failed to analyze.")
+ return
+
+ analysis = handler_resp["data"]
+ logger.info(f"[AutonomousDev] Root Cause identified: {analysis.get('root_cause')}")
+
+ # Update last_run in workflow_configs
+ try:
+ async with AsyncSessionLocal() as session:
+ stmt = update(WorkflowConfig).where(WorkflowConfig.workflow_name == "autonomous-dev").values({"last_run": datetime.now(timezone.utc), "updated_at": datetime.now(timezone.utc)})
+ await session.execute(stmt)
+ await session.commit()
+ except Exception as e:
+ logger.warning(f"[AutonomousDev] Could not update workflow last_run: {e}")
+
+ # 2. Code Fixer Proposal
+ fix_prompt = (
+ f"Berdasarkan analisis berikut, buatlah rencana perbaikan kode:\n"
+ f"Akar Masalah: {analysis.get('root_cause')}\n"
+ f"File: {analysis.get('file_affected')}\n"
+ f"Instruksi: {analysis.get('fix_instructions')}\n\n"
+ "Berikan respon berupa potongan kode (diff) atau penjelasan perbaikan yang harus diterapkan."
+ )
+
+ fixer_resp = await call_agent("code-fixer", fix_prompt)
+ if fixer_resp["success"]:
+ logger.success(f"[AutonomousDev] Fix proposed by Code Fixer:\n{fixer_resp['reply'][:500]}...")
+ else:
+ logger.error("[AutonomousDev] Code Fixer failed to propose a fix.")
diff --git a/app/services/career_service.py b/app/services/career_service.py
index 4a0ecffff3d993d856dcc6bbf14297cc0e675b64..86bcc04e5bcb7b074ea0e427583dd100144ee196 100644
--- a/app/services/career_service.py
+++ b/app/services/career_service.py
@@ -1,169 +1,169 @@
-"""Career service for managing experiences, credentials, and profiles.
-
-Handles business logic for secure career record storage and retrieval.
-"""
-
-from typing import List, Optional
-from uuid import UUID
-
-from sqlalchemy import select, text
-from sqlalchemy.ext.asyncio import AsyncSession
-from loguru import logger
-
-from app.models.career import Profile, Experience, Credential, Organization, OrganizationMember
-from app.schemas.career import (
- ExperienceCreate, ExperienceRead, ExperiencePayload,
- CredentialCreate, CredentialRead, CredentialPayload,
- ProfileRead, OrganizationRead
-)
-from app.services.security_service import security_service
-from app.services.organization_service import organization_service
-
-
-class CareerService:
- """Service for career history operations."""
-
- async def get_profile(self, db: AsyncSession, profile_id: UUID) -> Optional[Profile]:
- result = await db.execute(select(Profile).where(Profile.id == profile_id))
- return result.scalars().first()
-
- async def create_profile(self, db: AsyncSession, email: str, full_name: str) -> Profile:
- profile = Profile(email=email, full_name=full_name)
- db.add(profile)
- await db.commit()
- await db.refresh(profile)
- return profile
-
- async def add_experience(
- self, db: AsyncSession, profile_id: UUID, data: ExperienceCreate
- ) -> ExperienceRead:
- """Add a new experience record with an encrypted payload."""
- # 1. Get or create DEK for the profile
- dek = await security_service.get_or_create_profile_dek(db, profile_id)
-
- # 2. Encrypt the payload
- encrypted_payload = security_service.encrypt_payload(dek, data.payload.model_dump())
-
- # 3. Save to DB
- experience = Experience(
- profile_id=profile_id,
- organization_id=data.organization_id,
- start_date=data.start_date,
- end_date=data.end_date,
- job_title=data.job_title,
- encrypted_payload=encrypted_payload
- )
- db.add(experience)
- await db.commit()
- await db.refresh(experience)
-
- return ExperienceRead(
- id=experience.id,
- profile_id=experience.profile_id,
- organization_id=experience.organization_id,
- start_date=experience.start_date,
- end_date=experience.end_date,
- job_title=experience.job_title,
- created_at=experience.created_at,
- payload=data.payload
- )
-
- async def list_experiences(self, db: AsyncSession, profile_id: UUID) -> List[ExperienceRead]:
- """List all experiences for a profile, decrypted."""
- # 1. Get DEK
- dek = await security_service.get_or_create_profile_dek(db, profile_id)
-
- # 2. Fetch encrypted records
- result = await db.execute(select(Experience).where(Experience.profile_id == profile_id))
- records = result.scalars().all()
-
- # 3. Decrypt payloads
- output = []
- for rec in records:
- payload_dict = security_service.decrypt_payload(dek, rec.encrypted_payload)
- output.append(ExperienceRead(
- id=rec.id,
- profile_id=rec.profile_id,
- organization_id=rec.organization_id,
- start_date=rec.start_date,
- end_date=rec.end_date,
- job_title=rec.job_title,
- created_at=rec.created_at,
- payload=ExperiencePayload(**payload_dict)
- ))
- return output
-
- async def add_credential(
- self, db: AsyncSession, profile_id: UUID, data: CredentialCreate, issuer_signature: str
- ) -> CredentialRead:
- """Add a new signed credential with an encrypted payload."""
- # 1. Get or create DEK for the profile
- dek = await security_service.get_or_create_profile_dek(db, profile_id)
-
- # 2. Encrypt the payload
- encrypted_payload = security_service.encrypt_payload(dek, data.payload.model_dump())
-
- # 3. Verify Signature
- # The issuer signs the PLAINTEXT payload to ensure they know what they are signing.
- # We use a canonical JSON string (sorted keys) for consistency.
- import json
- plaintext_json = json.dumps(data.payload.model_dump(), sort_keys=True)
-
- is_valid = await organization_service.verify_credential_signature(
- db, data.organization_id, plaintext_json, issuer_signature
- )
-
- if not is_valid:
- logger.error(f"Credential signature verification failed for profile {profile_id}")
- raise ValueError("Invalid issuer signature. Credential cannot be saved.")
-
- # 4. Save to DB
- credential = Credential(
- profile_id=profile_id,
- organization_id=data.organization_id,
- issue_date=data.issue_date,
- expiry_date=data.expiry_date,
- credential_name=data.credential_name,
- encrypted_payload=encrypted_payload,
- issuer_signature=issuer_signature
- )
- db.add(credential)
- await db.commit()
- await db.refresh(credential)
-
- return CredentialRead(
- id=credential.id,
- profile_id=credential.profile_id,
- organization_id=credential.organization_id,
- issue_date=credential.issue_date,
- expiry_date=credential.expiry_date,
- credential_name=credential.credential_name,
- issuer_signature=credential.issuer_signature,
- created_at=credential.created_at,
- payload=data.payload
- )
-
- async def list_credentials(self, db: AsyncSession, profile_id: UUID) -> List[CredentialRead]:
- """List all credentials for a profile, decrypted."""
- dek = await security_service.get_or_create_profile_dek(db, profile_id)
- result = await db.execute(select(Credential).where(Credential.profile_id == profile_id))
- records = result.scalars().all()
-
- output = []
- for rec in records:
- payload_dict = security_service.decrypt_payload(dek, rec.encrypted_payload)
- output.append(CredentialRead(
- id=rec.id,
- profile_id=rec.profile_id,
- organization_id=rec.organization_id,
- issue_date=rec.issue_date,
- expiry_date=rec.expiry_date,
- credential_name=rec.credential_name,
- issuer_signature=rec.issuer_signature,
- created_at=rec.created_at,
- payload=CredentialPayload(**payload_dict)
- ))
- return output
-
-
-career_service = CareerService()
+"""Career service for managing experiences, credentials, and profiles.
+
+Handles business logic for secure career record storage and retrieval.
+"""
+
+from typing import List, Optional
+from uuid import UUID
+
+from sqlalchemy import select, text
+from sqlalchemy.ext.asyncio import AsyncSession
+from loguru import logger
+
+from app.models.career import Profile, Experience, Credential, Organization, OrganizationMember
+from app.schemas.career import (
+ ExperienceCreate, ExperienceRead, ExperiencePayload,
+ CredentialCreate, CredentialRead, CredentialPayload,
+ ProfileRead, OrganizationRead
+)
+from app.services.security_service import security_service
+from app.services.organization_service import organization_service
+
+
+class CareerService:
+ """Service for career history operations."""
+
+ async def get_profile(self, db: AsyncSession, profile_id: UUID) -> Optional[Profile]:
+ result = await db.execute(select(Profile).where(Profile.id == profile_id))
+ return result.scalars().first()
+
+ async def create_profile(self, db: AsyncSession, email: str, full_name: str) -> Profile:
+ profile = Profile(email=email, full_name=full_name)
+ db.add(profile)
+ await db.commit()
+ await db.refresh(profile)
+ return profile
+
+ async def add_experience(
+ self, db: AsyncSession, profile_id: UUID, data: ExperienceCreate
+ ) -> ExperienceRead:
+ """Add a new experience record with an encrypted payload."""
+ # 1. Get or create DEK for the profile
+ dek = await security_service.get_or_create_profile_dek(db, profile_id)
+
+ # 2. Encrypt the payload
+ encrypted_payload = security_service.encrypt_payload(dek, data.payload.model_dump())
+
+ # 3. Save to DB
+ experience = Experience(
+ profile_id=profile_id,
+ organization_id=data.organization_id,
+ start_date=data.start_date,
+ end_date=data.end_date,
+ job_title=data.job_title,
+ encrypted_payload=encrypted_payload
+ )
+ db.add(experience)
+ await db.commit()
+ await db.refresh(experience)
+
+ return ExperienceRead(
+ id=experience.id,
+ profile_id=experience.profile_id,
+ organization_id=experience.organization_id,
+ start_date=experience.start_date,
+ end_date=experience.end_date,
+ job_title=experience.job_title,
+ created_at=experience.created_at,
+ payload=data.payload
+ )
+
+ async def list_experiences(self, db: AsyncSession, profile_id: UUID) -> List[ExperienceRead]:
+ """List all experiences for a profile, decrypted."""
+ # 1. Get DEK
+ dek = await security_service.get_or_create_profile_dek(db, profile_id)
+
+ # 2. Fetch encrypted records
+ result = await db.execute(select(Experience).where(Experience.profile_id == profile_id))
+ records = result.scalars().all()
+
+ # 3. Decrypt payloads
+ output = []
+ for rec in records:
+ payload_dict = security_service.decrypt_payload(dek, rec.encrypted_payload)
+ output.append(ExperienceRead(
+ id=rec.id,
+ profile_id=rec.profile_id,
+ organization_id=rec.organization_id,
+ start_date=rec.start_date,
+ end_date=rec.end_date,
+ job_title=rec.job_title,
+ created_at=rec.created_at,
+ payload=ExperiencePayload(**payload_dict)
+ ))
+ return output
+
+ async def add_credential(
+ self, db: AsyncSession, profile_id: UUID, data: CredentialCreate, issuer_signature: str
+ ) -> CredentialRead:
+ """Add a new signed credential with an encrypted payload."""
+ # 1. Get or create DEK for the profile
+ dek = await security_service.get_or_create_profile_dek(db, profile_id)
+
+ # 2. Encrypt the payload
+ encrypted_payload = security_service.encrypt_payload(dek, data.payload.model_dump())
+
+ # 3. Verify Signature
+ # The issuer signs the PLAINTEXT payload to ensure they know what they are signing.
+ # We use a canonical JSON string (sorted keys) for consistency.
+ import json
+ plaintext_json = json.dumps(data.payload.model_dump(), sort_keys=True)
+
+ is_valid = await organization_service.verify_credential_signature(
+ db, data.organization_id, plaintext_json, issuer_signature
+ )
+
+ if not is_valid:
+ logger.error(f"Credential signature verification failed for profile {profile_id}")
+ raise ValueError("Invalid issuer signature. Credential cannot be saved.")
+
+ # 4. Save to DB
+ credential = Credential(
+ profile_id=profile_id,
+ organization_id=data.organization_id,
+ issue_date=data.issue_date,
+ expiry_date=data.expiry_date,
+ credential_name=data.credential_name,
+ encrypted_payload=encrypted_payload,
+ issuer_signature=issuer_signature
+ )
+ db.add(credential)
+ await db.commit()
+ await db.refresh(credential)
+
+ return CredentialRead(
+ id=credential.id,
+ profile_id=credential.profile_id,
+ organization_id=credential.organization_id,
+ issue_date=credential.issue_date,
+ expiry_date=credential.expiry_date,
+ credential_name=credential.credential_name,
+ issuer_signature=credential.issuer_signature,
+ created_at=credential.created_at,
+ payload=data.payload
+ )
+
+ async def list_credentials(self, db: AsyncSession, profile_id: UUID) -> List[CredentialRead]:
+ """List all credentials for a profile, decrypted."""
+ dek = await security_service.get_or_create_profile_dek(db, profile_id)
+ result = await db.execute(select(Credential).where(Credential.profile_id == profile_id))
+ records = result.scalars().all()
+
+ output = []
+ for rec in records:
+ payload_dict = security_service.decrypt_payload(dek, rec.encrypted_payload)
+ output.append(CredentialRead(
+ id=rec.id,
+ profile_id=rec.profile_id,
+ organization_id=rec.organization_id,
+ issue_date=rec.issue_date,
+ expiry_date=rec.expiry_date,
+ credential_name=rec.credential_name,
+ issuer_signature=rec.issuer_signature,
+ created_at=rec.created_at,
+ payload=CredentialPayload(**payload_dict)
+ ))
+ return output
+
+
+career_service = CareerService()
diff --git a/app/services/chat_service.py b/app/services/chat_service.py
index 4fd06c0a6b0dffa08dcd56a62e5c0e0d83559c36..91bc9b0c8cbaebe99bf06f369c72de677e99a49e 100644
--- a/app/services/chat_service.py
+++ b/app/services/chat_service.py
@@ -1,526 +1,526 @@
-"""Mediated Chat Service — AI-relayed messaging between Recruiters and Talents.
-
-Architecture (matches ChatManager.gs):
- 1. Recruiter sends raw message → AI mediates it (mask identity)
- 2. Talent receives mediated message → replies raw
- 3. AI summarizes reply for recruiter (mask identity)
- 4. Recruiter can unlock identity (costs 5 coins)
-
-AI tier: LOW (Gemini 3.5 Flash lightweight) — fast, cheap, crash-proof.
-Fallback: algorithmic mediation (template-based masking).
-Never crashes.
-"""
-
-import secrets
-from datetime import datetime, timezone
-from typing import Any, Dict, List, Optional, Tuple
-
-from loguru import logger
-from sqlalchemy import or_, select
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.models.job import MediatedChat
-from app.models.talent import Talent
-from app.models.employer import ClientAccount, Company
-from app.models.finance import Transaction
-from app.services.ai_service import call_low
-from app.utils.errors import ErrorCode, raise_error
-
-
-UNLOCK_COST = 5 # Coins to unlock identity (matches GAS FINANCE_CONFIG.DEDUCTION.IDENTITY_UNLOCK)
-
-
-# =============================================================================
-# HELPERS
-# =============================================================================
-
-def _generate_chat_id() -> str:
- return f"MSG-{secrets.token_hex(4).upper()}"
-
-
-def _generate_conversation_id() -> str:
- return f"CONV-{secrets.token_hex(4).upper()}"
-
-
-def _algorithmic_mediate_recruiter_message(
- raw_message: str,
- recruiter_industry: str = "Sustainability Sector",
-) -> str:
- """Algorithmic fallback for recruiter message mediation.
- No AI needed — template-based masking.
- """
- clean = raw_message.strip()[:500]
- return (
- f"Hey [Talent], ada recruiter dari {recruiter_industry} "
- f"yang tertarik dengan profil kamu. Mereka ingin tahu lebih lanjut: "
- f'"{clean}"'
- )
-
-
-def _algorithmic_mediate_talent_reply(
- raw_reply: str,
- talent_id: str,
-) -> str:
- """Algorithmic fallback for talent reply mediation.
- No AI needed — template-based.
- """
- clean = raw_reply.strip()[:500]
- return (
- f"Respon dari [Talent ID: {talent_id}], dia mengatakan: "
- f'"{clean}". '
- f"Silakan pertimbangkan untuk melanjutkan diskusi."
- )
-
-
-async def _get_talent_by_id(db: AsyncSession, talent_id: str) -> Optional[Talent]:
- result = await db.execute(select(Talent).where(Talent.talent_id == talent_id))
- return result.scalar_one_or_none()
-
-
-async def _get_client_and_company_by_email(db: AsyncSession, email: str) -> tuple:
- """Look up ClientAccount and Company by email.
- Returns (client, company) or (None, None).
- """
- result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
- client = result.scalar_one_or_none()
- if not client:
- return None, None
- result = await db.execute(select(Company).where(Company.id == client.company_id))
- company = result.scalar_one_or_none()
- return client, company
-
-
-# =============================================================================
-# 1. RECRUITER SENDS MESSAGE -> AI MEDIATED -> TALENT
-# =============================================================================
-
-async def send_recruiter_message(
- db: AsyncSession,
- recruiter_email: str,
- talent_id: str,
- raw_message: str,
- existing_conversation_id: Optional[str] = None,
-) -> dict:
- """Recruiter sends a message to a talent. AI mediates it.
-
- Flow:
- 1. Verify talent exists
- 2. Get or create conversation
- 3. AI mediates the message (LOW tier -> algorithmic fallback)
- 4. Save to database
- 5. Return conversation ID
- """
- # Verify talent exists
- talent = await _get_talent_by_id(db, talent_id)
- if not talent:
- raise_error(f"Talent {talent_id} not found.", ErrorCode.NOT_FOUND, 404)
-
- # Get or create conversation
- conversation_id = existing_conversation_id or _generate_conversation_id()
- chat_id = _generate_chat_id()
-
- # AI-mediated message (LOW tier = Gemini 3.5 Flash lightweight)
- mediated_message = None
- try:
- prompt = (
- f"Anda adalah Brigawan Matchmaker. Seorang recruiter dari Sustainability "
- f'mengirim pesan ini: "{raw_message[:500]}".\n'
- f"Ubah pesan ini menjadi format Brigawan Relay untuk Talent.\n"
- f"Gunakan gaya: 'Hey [talent], recruiter dari perusahaan [industri] "
- f"bertanya mengenai [topik]. [Pertanyaan rephrased].'\n"
- f"JANGAN sebutkan nama perusahaan recruiter.\n"
- f"BALAS LANGSUNG dengan pesan yang sudah di-mediate, tanpa penjelasan tambahan."
- )
- mediated_message = await call_low(prompt=prompt, temperature=0.7, max_output_tokens=512)
- except Exception as e:
- logger.error(f"AI mediation failed for recruiter message: {e}")
-
- if not mediated_message:
- mediated_message = _algorithmic_mediate_recruiter_message(raw_message)
-
- # Save to DB
- chat = MediatedChat(
- chat_id=chat_id,
- conversation_id=conversation_id,
- sender_email=recruiter_email,
- receiver_email=talent.email,
- sender_role="RECRUITER",
- original_message=raw_message,
- mediated_message=mediated_message,
- is_identity_unlocked=False,
- status="PENDING_TALENT",
- timestamp=datetime.now(timezone.utc),
- )
- db.add(chat)
- await db.commit()
-
- logger.info(f"Chat message sent: {conversation_id} ({recruiter_email} -> {talent_id})")
-
- return {
- "success": True,
- "ai_feedback": f"Halo {recruiter_email.split('@')[0]}, saya tanyakan dulu ya sama kandidatnya.",
- "conversation_id": conversation_id,
- "message": "Message sent and mediated.",
- }
-
-
-# =============================================================================
-# 2. TALENT REPLIES -> AI SUMMARIZED -> RECRUITER
-# =============================================================================
-
-async def send_talent_reply(
- db: AsyncSession,
- talent_email: str,
- conversation_id: str,
- raw_reply: str,
-) -> dict:
- """Talent replies to a conversation. AI summarizes for recruiter.
-
- Flow:
- 1. Verify conversation exists and talent is a participant
- 2. AI summarizes the reply (LOW tier -> algorithmic fallback)
- 3. Save to database
- 4. Return success
- """
- # Verify conversation exists
- result = await db.execute(
- select(MediatedChat)
- .where(MediatedChat.conversation_id == conversation_id)
- .limit(1)
- )
- existing = result.scalar_one_or_none()
- if not existing:
- raise_error("Conversation not found.", ErrorCode.NOT_FOUND, 404)
-
- # Verify talent is a participant
- result = await db.execute(select(MediatedChat).where(
- MediatedChat.conversation_id == conversation_id,
- MediatedChat.receiver_email == talent_email,
- ).limit(1))
- participant = result.scalar_one_or_none()
- if not participant:
- result = await db.execute(select(MediatedChat).where(
- MediatedChat.conversation_id == conversation_id,
- or_(
- MediatedChat.sender_email == talent_email,
- MediatedChat.receiver_email == talent_email,
- )
- ).limit(1))
- if not result.scalar_one_or_none():
- raise_error("You are not a participant in this conversation.", ErrorCode.NOT_AUTHORIZED, 403)
-
- # Find recruiter email from conversation
- result = await db.execute(
- select(MediatedChat)
- .where(
- MediatedChat.conversation_id == conversation_id,
- MediatedChat.sender_role == "RECRUITER",
- )
- .limit(1)
- )
- recruiter_msg = result.scalar_one_or_none()
- recruiter_email = recruiter_msg.sender_email if recruiter_msg else ""
-
- if not recruiter_email:
- raise_error("Could not find conversation partner.", ErrorCode.NOT_FOUND, 404)
-
- chat_id = _generate_chat_id()
- talent_id_str = talent_email
-
- # AI-mediated reply (LOW tier -> algorithmic fallback)
- mediated_summary = None
- try:
- prompt = (
- f"Anda adalah Brigawan Matchmaker. Talent ({talent_id_str}) menjawab "
- f'pertanyaan recruiter: "{raw_reply[:500]}".\n'
- f"Ubah jawaban ini menjadi format Brigawan Insight untuk Recruiter.\n"
- f"Gunakan gaya: 'Respon dari [Talent ID], dia [rangkuman jawaban]. "
- f"[Saran tindak lanjut jika ada].'\n"
- f"JANGAN sebutkan nama asli talent.\n"
- f"BALAS LANGSUNG dengan pesan yang sudah di-mediate."
- )
- mediated_summary = await call_low(prompt=prompt, temperature=0.7, max_output_tokens=512)
- except Exception as e:
- logger.error(f"AI mediation failed for talent reply: {e}")
-
- if not mediated_summary:
- mediated_summary = _algorithmic_mediate_talent_reply(raw_reply, talent_id_str)
-
- # Save to DB
- chat = MediatedChat(
- chat_id=chat_id,
- conversation_id=conversation_id,
- sender_email=talent_email,
- receiver_email=recruiter_email,
- sender_role="TALENT",
- original_message=raw_reply,
- mediated_message=mediated_summary,
- is_identity_unlocked=False,
- status="PENDING_RECRUITER",
- timestamp=datetime.now(timezone.utc),
- )
- db.add(chat)
- await db.commit()
-
- logger.info(f"Talent reply mediated: {conversation_id}")
-
- return {
- "success": True,
- "message": "Balasan Anda telah dikirimkan ke Recruiter melalui Brigawan.",
- }
-
-
-# =============================================================================
-# 3. UNLOCK IDENTITY (costs 5 coins)
-# =============================================================================
-
-async def unlock_chat_identity(
- db: AsyncSession,
- recruiter_email: str,
- talent_id: str,
-) -> dict:
- """Unlock talent identity in chat. Costs 5 Briga coins.
-
- Flow:
- 1. Verify employer has enough coins
- 2. Deduct coins + log transaction with proper FK
- 3. Mark all messages in conversation as unlocked
- 4. Return full talent profile
- """
- talent = await _get_talent_by_id(db, talent_id)
- if not talent:
- raise_error(f"Talent {talent_id} not found.", ErrorCode.NOT_FOUND, 404)
-
- client, company = await _get_client_and_company_by_email(db, recruiter_email)
- if not client or not company:
- raise_error("Employer account not found.", ErrorCode.NOT_FOUND, 404)
-
- # Check if already unlocked
- result = await db.execute(
- select(MediatedChat).where(
- MediatedChat.sender_email == recruiter_email,
- MediatedChat.receiver_email == talent.email,
- MediatedChat.is_identity_unlocked == True,
- ).limit(1)
- )
- if result.scalar_one_or_none():
- return {
- "success": True,
- "message": "Identity already unlocked. No coins deducted.",
- "talent_name": talent.name or "",
- "talent_email": talent.email or "",
- "talent_phone": talent.phone or "",
- "credits_remaining": company.credit_balance or 0,
- }
-
- # Check balance
- if (company.credit_balance or 0) < UNLOCK_COST:
- raise_error(
- f"Insufficient coins. Unlock costs {UNLOCK_COST} coins. Balance: {company.credit_balance or 0}",
- code=ErrorCode.NOT_AUTHORIZED,
- )
-
- # Deduct
- company.credit_balance = (company.credit_balance or 0) - UNLOCK_COST
- db.add(company)
-
- # Log transaction with proper client FK (ClientAccount.id, not email)
- tx = Transaction(
- id=f"TX-UNL-CHAT-{secrets.token_hex(4).upper()}",
- client_id=client.id,
- amount=UNLOCK_COST,
- type="IdentityUnlock",
- status="Settled",
- )
- db.add(tx)
-
- # Mark all messages between this recruiter and talent as unlocked
- result = await db.execute(
- select(MediatedChat).where(
- MediatedChat.sender_email == recruiter_email,
- MediatedChat.receiver_email == talent.email,
- )
- )
- for chat in result.scalars().all():
- chat.is_identity_unlocked = True
- db.add(chat)
-
- result = await db.execute(
- select(MediatedChat).where(
- MediatedChat.sender_email == talent.email,
- MediatedChat.receiver_email == recruiter_email,
- )
- )
- for chat in result.scalars().all():
- chat.is_identity_unlocked = True
- db.add(chat)
-
- await db.commit()
-
- logger.info(f"Chat identity unlocked: {recruiter_email} -> {talent_id} (cost: {UNLOCK_COST})")
-
- return {
- "success": True,
- "message": f"Identitas Talent berhasil dibuka! {UNLOCK_COST} coins deducted.",
- "talent_name": talent.name or "",
- "talent_email": talent.email or "",
- "talent_phone": talent.phone or "",
- "credits_remaining": company.credit_balance or 0,
- }
-
-
-# =============================================================================
-# 4. GET CONVERSATION LIST (for recruiter)
-# =============================================================================
-
-async def get_recruiter_conversations(
- db: AsyncSession,
- recruiter_email: str,
-) -> list:
- """Get all conversations for a recruiter, sorted by latest message.
-
- Groups messages by partner (talent), returns the latest message per partner.
- """
- result = await db.execute(
- select(MediatedChat)
- .where(
- or_(
- MediatedChat.sender_email == recruiter_email,
- MediatedChat.receiver_email == recruiter_email,
- )
- )
- .order_by(MediatedChat.timestamp.desc())
- )
- all_messages = result.scalars().all()
-
- conversations = {}
- for msg in all_messages:
- partner_id = msg.receiver_email if msg.sender_email == recruiter_email else msg.sender_email
- if partner_id not in conversations:
- talent_name = partner_id
- t_result = await db.execute(
- select(Talent).where(Talent.email == partner_id)
- )
- talent = t_result.scalar_one_or_none()
- if talent:
- talent_name = talent.name or talent.talent_id
-
- conversations[partner_id] = {
- "partner_id": partner_id,
- "conversation_id": msg.conversation_id,
- "last_message": msg.original_message if msg.sender_role == "RECRUITER" else msg.mediated_message,
- "timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
- "status": msg.status,
- "is_unlocked": msg.is_identity_unlocked,
- "partner_name": talent_name,
- }
-
- return {
- "success": True,
- "data": sorted(conversations.values(), key=lambda c: c["timestamp"], reverse=True),
- }
-
-
-# =============================================================================
-# 5. GET CONVERSATION LIST (for talent)
-# =============================================================================
-
-async def get_talent_conversations(
- db: AsyncSession,
- talent_email: str,
-) -> list:
- """Get all conversations for a talent, grouped by conversation ID."""
- result = await db.execute(
- select(MediatedChat)
- .where(
- or_(
- MediatedChat.sender_email == talent_email,
- MediatedChat.receiver_email == talent_email,
- )
- )
- .order_by(MediatedChat.timestamp.desc())
- )
- all_messages = result.scalars().all()
-
- conversations = {}
- for msg in all_messages:
- conv_id = msg.conversation_id
- if conv_id not in conversations:
- conversations[conv_id] = {
- "partner_id": conv_id,
- "conversation_id": conv_id,
- "last_message": msg.original_message if msg.sender_role == "TALENT" else msg.mediated_message,
- "timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
- "status": msg.status,
- "is_unlocked": msg.is_identity_unlocked,
- "partner_name": "Recruiter",
- }
-
- return {
- "success": True,
- "data": sorted(conversations.values(), key=lambda c: c["timestamp"], reverse=True),
- }
-
-
-# =============================================================================
-# 6. GET CHAT HISTORY
-# =============================================================================
-
-async def get_chat_history(
- db: AsyncSession,
- email: str,
- partner_id: str,
- role: str = "RECRUITER",
-) -> list:
- """Get full message history for a conversation.
-
- For recruiters: partner_id is talent email
- For talents: partner_id is conversation ID
- """
- e = email.lower().strip()
- p = partner_id.strip()
-
- if role == "RECRUITER":
- result = await db.execute(
- select(MediatedChat)
- .where(
- or_(
- (MediatedChat.sender_email == e) & (MediatedChat.receiver_email == p),
- (MediatedChat.sender_email == p) & (MediatedChat.receiver_email == e),
- )
- )
- .order_by(MediatedChat.timestamp.asc())
- )
- else:
- result = await db.execute(
- select(MediatedChat)
- .where(
- MediatedChat.conversation_id == p,
- or_(
- MediatedChat.sender_email == e,
- MediatedChat.receiver_email == e,
- ),
- )
- .order_by(MediatedChat.timestamp.asc())
- )
-
- messages = result.scalars().all()
-
- history = []
- for msg in messages:
- if msg.sender_role == "RECRUITER":
- display_text = msg.original_message if role == "RECRUITER" else msg.mediated_message
- else:
- display_text = msg.mediated_message if role == "RECRUITER" else msg.original_message
-
- history.append({
- "sender": msg.sender_role,
- "text": display_text,
- "timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
- "is_unlocked": msg.is_identity_unlocked,
- })
-
- return {
- "success": True,
- "data": history,
- }
+"""Mediated Chat Service — AI-relayed messaging between Recruiters and Talents.
+
+Architecture (matches ChatManager.gs):
+ 1. Recruiter sends raw message → AI mediates it (mask identity)
+ 2. Talent receives mediated message → replies raw
+ 3. AI summarizes reply for recruiter (mask identity)
+ 4. Recruiter can unlock identity (costs 5 coins)
+
+AI tier: LOW (Gemini 3.5 Flash lightweight) — fast, cheap, crash-proof.
+Fallback: algorithmic mediation (template-based masking).
+Never crashes.
+"""
+
+import secrets
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Optional, Tuple
+
+from loguru import logger
+from sqlalchemy import or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.job import MediatedChat
+from app.models.talent import Talent
+from app.models.employer import ClientAccount, Company
+from app.models.finance import Transaction
+from app.services.ai_service import call_low
+from app.utils.errors import ErrorCode, raise_error
+
+
+UNLOCK_COST = 5 # Coins to unlock identity (matches GAS FINANCE_CONFIG.DEDUCTION.IDENTITY_UNLOCK)
+
+
+# =============================================================================
+# HELPERS
+# =============================================================================
+
+def _generate_chat_id() -> str:
+ return f"MSG-{secrets.token_hex(4).upper()}"
+
+
+def _generate_conversation_id() -> str:
+ return f"CONV-{secrets.token_hex(4).upper()}"
+
+
+def _algorithmic_mediate_recruiter_message(
+ raw_message: str,
+ recruiter_industry: str = "Sustainability Sector",
+) -> str:
+ """Algorithmic fallback for recruiter message mediation.
+ No AI needed — template-based masking.
+ """
+ clean = raw_message.strip()[:500]
+ return (
+ f"Hey [Talent], ada recruiter dari {recruiter_industry} "
+ f"yang tertarik dengan profil kamu. Mereka ingin tahu lebih lanjut: "
+ f'"{clean}"'
+ )
+
+
+def _algorithmic_mediate_talent_reply(
+ raw_reply: str,
+ talent_id: str,
+) -> str:
+ """Algorithmic fallback for talent reply mediation.
+ No AI needed — template-based.
+ """
+ clean = raw_reply.strip()[:500]
+ return (
+ f"Respon dari [Talent ID: {talent_id}], dia mengatakan: "
+ f'"{clean}". '
+ f"Silakan pertimbangkan untuk melanjutkan diskusi."
+ )
+
+
+async def _get_talent_by_id(db: AsyncSession, talent_id: str) -> Optional[Talent]:
+ result = await db.execute(select(Talent).where(Talent.talent_id == talent_id))
+ return result.scalar_one_or_none()
+
+
+async def _get_client_and_company_by_email(db: AsyncSession, email: str) -> tuple:
+ """Look up ClientAccount and Company by email.
+ Returns (client, company) or (None, None).
+ """
+ result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
+ client = result.scalar_one_or_none()
+ if not client:
+ return None, None
+ result = await db.execute(select(Company).where(Company.id == client.company_id))
+ company = result.scalar_one_or_none()
+ return client, company
+
+
+# =============================================================================
+# 1. RECRUITER SENDS MESSAGE -> AI MEDIATED -> TALENT
+# =============================================================================
+
+async def send_recruiter_message(
+ db: AsyncSession,
+ recruiter_email: str,
+ talent_id: str,
+ raw_message: str,
+ existing_conversation_id: Optional[str] = None,
+) -> dict:
+ """Recruiter sends a message to a talent. AI mediates it.
+
+ Flow:
+ 1. Verify talent exists
+ 2. Get or create conversation
+ 3. AI mediates the message (LOW tier -> algorithmic fallback)
+ 4. Save to database
+ 5. Return conversation ID
+ """
+ # Verify talent exists
+ talent = await _get_talent_by_id(db, talent_id)
+ if not talent:
+ raise_error(f"Talent {talent_id} not found.", ErrorCode.NOT_FOUND, 404)
+
+ # Get or create conversation
+ conversation_id = existing_conversation_id or _generate_conversation_id()
+ chat_id = _generate_chat_id()
+
+ # AI-mediated message (LOW tier = Gemini 3.5 Flash lightweight)
+ mediated_message = None
+ try:
+ prompt = (
+ f"Anda adalah Brigawan Matchmaker. Seorang recruiter dari Sustainability "
+ f'mengirim pesan ini: "{raw_message[:500]}".\n'
+ f"Ubah pesan ini menjadi format Brigawan Relay untuk Talent.\n"
+ f"Gunakan gaya: 'Hey [talent], recruiter dari perusahaan [industri] "
+ f"bertanya mengenai [topik]. [Pertanyaan rephrased].'\n"
+ f"JANGAN sebutkan nama perusahaan recruiter.\n"
+ f"BALAS LANGSUNG dengan pesan yang sudah di-mediate, tanpa penjelasan tambahan."
+ )
+ mediated_message = await call_low(prompt=prompt, temperature=0.7, max_output_tokens=512)
+ except Exception as e:
+ logger.error(f"AI mediation failed for recruiter message: {e}")
+
+ if not mediated_message:
+ mediated_message = _algorithmic_mediate_recruiter_message(raw_message)
+
+ # Save to DB
+ chat = MediatedChat(
+ chat_id=chat_id,
+ conversation_id=conversation_id,
+ sender_email=recruiter_email,
+ receiver_email=talent.email,
+ sender_role="RECRUITER",
+ original_message=raw_message,
+ mediated_message=mediated_message,
+ is_identity_unlocked=False,
+ status="PENDING_TALENT",
+ timestamp=datetime.now(timezone.utc),
+ )
+ db.add(chat)
+ await db.commit()
+
+ logger.info(f"Chat message sent: {conversation_id} ({recruiter_email} -> {talent_id})")
+
+ return {
+ "success": True,
+ "ai_feedback": f"Halo {recruiter_email.split('@')[0]}, saya tanyakan dulu ya sama kandidatnya.",
+ "conversation_id": conversation_id,
+ "message": "Message sent and mediated.",
+ }
+
+
+# =============================================================================
+# 2. TALENT REPLIES -> AI SUMMARIZED -> RECRUITER
+# =============================================================================
+
+async def send_talent_reply(
+ db: AsyncSession,
+ talent_email: str,
+ conversation_id: str,
+ raw_reply: str,
+) -> dict:
+ """Talent replies to a conversation. AI summarizes for recruiter.
+
+ Flow:
+ 1. Verify conversation exists and talent is a participant
+ 2. AI summarizes the reply (LOW tier -> algorithmic fallback)
+ 3. Save to database
+ 4. Return success
+ """
+ # Verify conversation exists
+ result = await db.execute(
+ select(MediatedChat)
+ .where(MediatedChat.conversation_id == conversation_id)
+ .limit(1)
+ )
+ existing = result.scalar_one_or_none()
+ if not existing:
+ raise_error("Conversation not found.", ErrorCode.NOT_FOUND, 404)
+
+ # Verify talent is a participant
+ result = await db.execute(select(MediatedChat).where(
+ MediatedChat.conversation_id == conversation_id,
+ MediatedChat.receiver_email == talent_email,
+ ).limit(1))
+ participant = result.scalar_one_or_none()
+ if not participant:
+ result = await db.execute(select(MediatedChat).where(
+ MediatedChat.conversation_id == conversation_id,
+ or_(
+ MediatedChat.sender_email == talent_email,
+ MediatedChat.receiver_email == talent_email,
+ )
+ ).limit(1))
+ if not result.scalar_one_or_none():
+ raise_error("You are not a participant in this conversation.", ErrorCode.NOT_AUTHORIZED, 403)
+
+ # Find recruiter email from conversation
+ result = await db.execute(
+ select(MediatedChat)
+ .where(
+ MediatedChat.conversation_id == conversation_id,
+ MediatedChat.sender_role == "RECRUITER",
+ )
+ .limit(1)
+ )
+ recruiter_msg = result.scalar_one_or_none()
+ recruiter_email = recruiter_msg.sender_email if recruiter_msg else ""
+
+ if not recruiter_email:
+ raise_error("Could not find conversation partner.", ErrorCode.NOT_FOUND, 404)
+
+ chat_id = _generate_chat_id()
+ talent_id_str = talent_email
+
+ # AI-mediated reply (LOW tier -> algorithmic fallback)
+ mediated_summary = None
+ try:
+ prompt = (
+ f"Anda adalah Brigawan Matchmaker. Talent ({talent_id_str}) menjawab "
+ f'pertanyaan recruiter: "{raw_reply[:500]}".\n'
+ f"Ubah jawaban ini menjadi format Brigawan Insight untuk Recruiter.\n"
+ f"Gunakan gaya: 'Respon dari [Talent ID], dia [rangkuman jawaban]. "
+ f"[Saran tindak lanjut jika ada].'\n"
+ f"JANGAN sebutkan nama asli talent.\n"
+ f"BALAS LANGSUNG dengan pesan yang sudah di-mediate."
+ )
+ mediated_summary = await call_low(prompt=prompt, temperature=0.7, max_output_tokens=512)
+ except Exception as e:
+ logger.error(f"AI mediation failed for talent reply: {e}")
+
+ if not mediated_summary:
+ mediated_summary = _algorithmic_mediate_talent_reply(raw_reply, talent_id_str)
+
+ # Save to DB
+ chat = MediatedChat(
+ chat_id=chat_id,
+ conversation_id=conversation_id,
+ sender_email=talent_email,
+ receiver_email=recruiter_email,
+ sender_role="TALENT",
+ original_message=raw_reply,
+ mediated_message=mediated_summary,
+ is_identity_unlocked=False,
+ status="PENDING_RECRUITER",
+ timestamp=datetime.now(timezone.utc),
+ )
+ db.add(chat)
+ await db.commit()
+
+ logger.info(f"Talent reply mediated: {conversation_id}")
+
+ return {
+ "success": True,
+ "message": "Balasan Anda telah dikirimkan ke Recruiter melalui Brigawan.",
+ }
+
+
+# =============================================================================
+# 3. UNLOCK IDENTITY (costs 5 coins)
+# =============================================================================
+
+async def unlock_chat_identity(
+ db: AsyncSession,
+ recruiter_email: str,
+ talent_id: str,
+) -> dict:
+ """Unlock talent identity in chat. Costs 5 Briga coins.
+
+ Flow:
+ 1. Verify employer has enough coins
+ 2. Deduct coins + log transaction with proper FK
+ 3. Mark all messages in conversation as unlocked
+ 4. Return full talent profile
+ """
+ talent = await _get_talent_by_id(db, talent_id)
+ if not talent:
+ raise_error(f"Talent {talent_id} not found.", ErrorCode.NOT_FOUND, 404)
+
+ client, company = await _get_client_and_company_by_email(db, recruiter_email)
+ if not client or not company:
+ raise_error("Employer account not found.", ErrorCode.NOT_FOUND, 404)
+
+ # Check if already unlocked
+ result = await db.execute(
+ select(MediatedChat).where(
+ MediatedChat.sender_email == recruiter_email,
+ MediatedChat.receiver_email == talent.email,
+ MediatedChat.is_identity_unlocked == True,
+ ).limit(1)
+ )
+ if result.scalar_one_or_none():
+ return {
+ "success": True,
+ "message": "Identity already unlocked. No coins deducted.",
+ "talent_name": talent.name or "",
+ "talent_email": talent.email or "",
+ "talent_phone": talent.phone or "",
+ "credits_remaining": company.credit_balance or 0,
+ }
+
+ # Check balance
+ if (company.credit_balance or 0) < UNLOCK_COST:
+ raise_error(
+ f"Insufficient coins. Unlock costs {UNLOCK_COST} coins. Balance: {company.credit_balance or 0}",
+ code=ErrorCode.NOT_AUTHORIZED,
+ )
+
+ # Deduct
+ company.credit_balance = (company.credit_balance or 0) - UNLOCK_COST
+ db.add(company)
+
+ # Log transaction with proper client FK (ClientAccount.id, not email)
+ tx = Transaction(
+ id=f"TX-UNL-CHAT-{secrets.token_hex(4).upper()}",
+ client_id=client.id,
+ amount=UNLOCK_COST,
+ type="IdentityUnlock",
+ status="Settled",
+ )
+ db.add(tx)
+
+ # Mark all messages between this recruiter and talent as unlocked
+ result = await db.execute(
+ select(MediatedChat).where(
+ MediatedChat.sender_email == recruiter_email,
+ MediatedChat.receiver_email == talent.email,
+ )
+ )
+ for chat in result.scalars().all():
+ chat.is_identity_unlocked = True
+ db.add(chat)
+
+ result = await db.execute(
+ select(MediatedChat).where(
+ MediatedChat.sender_email == talent.email,
+ MediatedChat.receiver_email == recruiter_email,
+ )
+ )
+ for chat in result.scalars().all():
+ chat.is_identity_unlocked = True
+ db.add(chat)
+
+ await db.commit()
+
+ logger.info(f"Chat identity unlocked: {recruiter_email} -> {talent_id} (cost: {UNLOCK_COST})")
+
+ return {
+ "success": True,
+ "message": f"Identitas Talent berhasil dibuka! {UNLOCK_COST} coins deducted.",
+ "talent_name": talent.name or "",
+ "talent_email": talent.email or "",
+ "talent_phone": talent.phone or "",
+ "credits_remaining": company.credit_balance or 0,
+ }
+
+
+# =============================================================================
+# 4. GET CONVERSATION LIST (for recruiter)
+# =============================================================================
+
+async def get_recruiter_conversations(
+ db: AsyncSession,
+ recruiter_email: str,
+) -> list:
+ """Get all conversations for a recruiter, sorted by latest message.
+
+ Groups messages by partner (talent), returns the latest message per partner.
+ """
+ result = await db.execute(
+ select(MediatedChat)
+ .where(
+ or_(
+ MediatedChat.sender_email == recruiter_email,
+ MediatedChat.receiver_email == recruiter_email,
+ )
+ )
+ .order_by(MediatedChat.timestamp.desc())
+ )
+ all_messages = result.scalars().all()
+
+ conversations = {}
+ for msg in all_messages:
+ partner_id = msg.receiver_email if msg.sender_email == recruiter_email else msg.sender_email
+ if partner_id not in conversations:
+ talent_name = partner_id
+ t_result = await db.execute(
+ select(Talent).where(Talent.email == partner_id)
+ )
+ talent = t_result.scalar_one_or_none()
+ if talent:
+ talent_name = talent.name or talent.talent_id
+
+ conversations[partner_id] = {
+ "partner_id": partner_id,
+ "conversation_id": msg.conversation_id,
+ "last_message": msg.original_message if msg.sender_role == "RECRUITER" else msg.mediated_message,
+ "timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
+ "status": msg.status,
+ "is_unlocked": msg.is_identity_unlocked,
+ "partner_name": talent_name,
+ }
+
+ return {
+ "success": True,
+ "data": sorted(conversations.values(), key=lambda c: c["timestamp"], reverse=True),
+ }
+
+
+# =============================================================================
+# 5. GET CONVERSATION LIST (for talent)
+# =============================================================================
+
+async def get_talent_conversations(
+ db: AsyncSession,
+ talent_email: str,
+) -> list:
+ """Get all conversations for a talent, grouped by conversation ID."""
+ result = await db.execute(
+ select(MediatedChat)
+ .where(
+ or_(
+ MediatedChat.sender_email == talent_email,
+ MediatedChat.receiver_email == talent_email,
+ )
+ )
+ .order_by(MediatedChat.timestamp.desc())
+ )
+ all_messages = result.scalars().all()
+
+ conversations = {}
+ for msg in all_messages:
+ conv_id = msg.conversation_id
+ if conv_id not in conversations:
+ conversations[conv_id] = {
+ "partner_id": conv_id,
+ "conversation_id": conv_id,
+ "last_message": msg.original_message if msg.sender_role == "TALENT" else msg.mediated_message,
+ "timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
+ "status": msg.status,
+ "is_unlocked": msg.is_identity_unlocked,
+ "partner_name": "Recruiter",
+ }
+
+ return {
+ "success": True,
+ "data": sorted(conversations.values(), key=lambda c: c["timestamp"], reverse=True),
+ }
+
+
+# =============================================================================
+# 6. GET CHAT HISTORY
+# =============================================================================
+
+async def get_chat_history(
+ db: AsyncSession,
+ email: str,
+ partner_id: str,
+ role: str = "RECRUITER",
+) -> list:
+ """Get full message history for a conversation.
+
+ For recruiters: partner_id is talent email
+ For talents: partner_id is conversation ID
+ """
+ e = email.lower().strip()
+ p = partner_id.strip()
+
+ if role == "RECRUITER":
+ result = await db.execute(
+ select(MediatedChat)
+ .where(
+ or_(
+ (MediatedChat.sender_email == e) & (MediatedChat.receiver_email == p),
+ (MediatedChat.sender_email == p) & (MediatedChat.receiver_email == e),
+ )
+ )
+ .order_by(MediatedChat.timestamp.asc())
+ )
+ else:
+ result = await db.execute(
+ select(MediatedChat)
+ .where(
+ MediatedChat.conversation_id == p,
+ or_(
+ MediatedChat.sender_email == e,
+ MediatedChat.receiver_email == e,
+ ),
+ )
+ .order_by(MediatedChat.timestamp.asc())
+ )
+
+ messages = result.scalars().all()
+
+ history = []
+ for msg in messages:
+ if msg.sender_role == "RECRUITER":
+ display_text = msg.original_message if role == "RECRUITER" else msg.mediated_message
+ else:
+ display_text = msg.mediated_message if role == "RECRUITER" else msg.original_message
+
+ history.append({
+ "sender": msg.sender_role,
+ "text": display_text,
+ "timestamp": msg.timestamp.isoformat() if msg.timestamp else "",
+ "is_unlocked": msg.is_identity_unlocked,
+ })
+
+ return {
+ "success": True,
+ "data": history,
+ }
diff --git a/app/services/content_scheduler_service.py b/app/services/content_scheduler_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..20286f43acf4f15e18d2b33d35f0ea7208c472e1
--- /dev/null
+++ b/app/services/content_scheduler_service.py
@@ -0,0 +1,122 @@
+"""Content Scheduler Service — Humanized Posting Scheduler.
+
+Implements "fuzzy scheduling" to avoid robotic exact-time posting.
+Instead of posting exactly at 09:00:00, it posts randomly between
+a specified time window (e.g., 09:00 to 10:00).
+"""
+
+import asyncio
+import random
+from datetime import datetime, timedelta
+from loguru import logger
+from typing import Callable, Any
+
+class ContentSchedulerService:
+ """Manages scheduled tasks with human-like jitter/fuzziness."""
+
+ @classmethod
+ async def schedule_fuzzy_post(
+ cls,
+ task_name: str,
+ publish_func: Callable,
+ start_hour: int,
+ end_hour: int,
+ *args,
+ **kwargs
+ ):
+ """
+ Schedules a task to run randomly between start_hour and end_hour today.
+ If the time window has already passed, it schedules for tomorrow.
+ """
+ now = datetime.now()
+
+ # Determine target date (today or tomorrow)
+ target_date = now.date()
+ if now.hour >= end_hour:
+ target_date += timedelta(days=1)
+
+ start_time = datetime.combine(target_date, datetime.min.time()) + timedelta(hours=start_hour)
+ end_time = datetime.combine(target_date, datetime.min.time()) + timedelta(hours=end_hour)
+
+ # If we are currently inside the window, calculate delay from now to end_time
+ if start_time <= now <= end_time:
+ window_seconds = int((end_time - now).total_seconds())
+ delay_seconds = random.randint(0, window_seconds)
+ run_time = now + timedelta(seconds=delay_seconds)
+ else:
+ # We are before the window
+ window_seconds = int((end_time - start_time).total_seconds())
+ delay_within_window = random.randint(0, window_seconds)
+ run_time = start_time + timedelta(seconds=delay_within_window)
+ delay_seconds = int((run_time - now).total_seconds())
+
+ 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.")
+
+ # Run the background task
+ asyncio.create_task(cls._wait_and_execute(task_name, delay_seconds, publish_func, *args, **kwargs))
+
+ return {
+ "status": "scheduled",
+ "task": task_name,
+ "scheduled_time": run_time.isoformat(),
+ "window": f"{start_hour}:00 - {end_hour}:00"
+ }
+
+ @classmethod
+ async def _wait_and_execute(cls, task_name: str, delay_seconds: int, func: Callable, *args, **kwargs):
+ """Internal worker that waits the specified time then executes the function."""
+ try:
+ await asyncio.sleep(delay_seconds)
+ logger.info(f"[Scheduler] EXECUTING fuzzy task: '{task_name}' now!")
+
+ # Execute the actual publishing function (e.g., calling social media API)
+ if asyncio.iscoroutinefunction(func):
+ await func(*args, **kwargs)
+ else:
+ func(*args, **kwargs)
+
+ logger.success(f"[Scheduler] Task '{task_name}' completed successfully.")
+ except asyncio.CancelledError:
+ logger.warning(f"[Scheduler] Task '{task_name}' was cancelled.")
+ except Exception as e:
+ logger.error(f"[Scheduler] Task '{task_name}' failed during execution: {e}")
+
+ # =========================================================================
+ # Example integration with the pipeline
+ # =========================================================================
+ @classmethod
+ async def trigger_daily_content_pipeline(cls):
+ """
+ Example trigger called every morning (e.g., 06:00 AM) to plan
+ today's content and schedule the publishing times.
+ """
+ logger.info("[ContentPipeline] Starting daily content planning...")
+
+ # 1. Content Generation & Fact Checking would happen here...
+ # ... (calling VisualContentService.generate_carousel)
+
+ # 2. Schedule the publishing
+ # Instead of posting exactly at 09:00, we give it a human "fuzzy" window
+
+ async def dummy_publish_action(topic):
+ logger.info(f"[PublishingAgent] Pushing '{topic}' to LinkedIn/Instagram API...")
+ await asyncio.sleep(2)
+ logger.success(f"[PublishingAgent] '{topic}' is LIVE!")
+
+ # Morning Post (Range: 09:00 - 10:00)
+ await cls.schedule_fuzzy_post(
+ task_name="Morning Carousel: Green Skills",
+ publish_func=dummy_publish_action,
+ start_hour=9,
+ end_hour=10,
+ topic="Green Skills 2026"
+ )
+
+ # Afternoon Post (Range: 16:00 - 18:00)
+ await cls.schedule_fuzzy_post(
+ task_name="Afternoon Reels: Career Advice",
+ publish_func=dummy_publish_action,
+ start_hour=16,
+ end_hour=18,
+ topic="Cara Nego Gaji Perusahaan ESG"
+ )
diff --git a/app/services/deploy_service.py b/app/services/deploy_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbe19dd177319ba827672253f8781d38f21ef63c
--- /dev/null
+++ b/app/services/deploy_service.py
@@ -0,0 +1,58 @@
+import os
+import requests
+from loguru import logger
+
+CF_ACCOUNT_ID = os.environ.get("CF_ACCOUNT_ID")
+CF_API_TOKEN = os.environ.get("CF_API_TOKEN")
+TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
+TELEGRAM_CEO_CHAT_ID = os.environ.get("TELEGRAM_CEO_CHAT_ID")
+
+
+class DeployService:
+ """Simple service to trigger Cloudflare Pages preview deploys and notify CEO via Telegram."""
+
+ @staticmethod
+ def trigger_cloudflare_preview(project_name: str) -> dict:
+ """Trigger a Cloudflare Pages deployment via the Pages API and return preview URL.
+
+ Requires CF_ACCOUNT_ID and CF_API_TOKEN environment variables.
+ """
+ if not CF_ACCOUNT_ID or not CF_API_TOKEN:
+ logger.error("Cloudflare credentials missing")
+ return {"success": False, "error": "missing_cf_credentials"}
+
+ url = f"https://api.cloudflare.com/client/v4/accounts/{CF_ACCOUNT_ID}/pages/projects/{project_name}/deployments"
+ headers = {"Authorization": f"Bearer {CF_API_TOKEN}", "Content-Type": "application/json"}
+ payload = {"commit_ref": "preview"}
+
+ try:
+ resp = requests.post(url, json=payload, headers=headers, timeout=20)
+ data = resp.json()
+ if not data.get("success"):
+ logger.error(f"Cloudflare API error: {data}")
+ return {"success": False, "error": data}
+
+ # Extract preview url if available
+ preview = None
+ if "result" in data and data["result"].get("url"):
+ preview = data["result"]["url"]
+ return {"success": True, "preview_url": preview, "raw": data}
+ except Exception as e:
+ logger.exception(f"Failed to call Cloudflare API: {e}")
+ return {"success": False, "error": str(e)}
+
+ @staticmethod
+ def notify_ceo_preview(preview_url: str, deploy_id: str):
+ """Send Telegram message to CEO chat id with approve/reject instructions."""
+ if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CEO_CHAT_ID:
+ logger.warning("Telegram config missing; cannot notify CEO")
+ return {"success": False, "error": "missing_telegram_config"}
+
+ text = f"Daily preview ready: {preview_url}\nApprove to merge? Reply: /approve {deploy_id} or /reject {deploy_id}"
+ tg_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
+ try:
+ resp = requests.post(tg_url, json={"chat_id": TELEGRAM_CEO_CHAT_ID, "text": text}, timeout=10)
+ return resp.json()
+ except Exception as e:
+ logger.exception(f"Failed to send Telegram message: {e}")
+ return {"success": False, "error": str(e)}
diff --git a/app/services/email_service.py b/app/services/email_service.py
index babc34f15a51b61d4545d9fea73b757c86cb5c63..8294d7d8bc19cfd4be85616ef8faa4466b233b4c 100644
--- a/app/services/email_service.py
+++ b/app/services/email_service.py
@@ -1,47 +1,47 @@
-"""Email Service — Native SMTP transactional email sender.
-
-Replaces legacy GAS email sending webhooks.
-"""
-
-import smtplib
-from email.mime.text import MIMEText
-from email.mime.multipart import MIMEMultipart
-from loguru import logger
-from app.config import settings
-
-class EmailService:
- def send_html_email(self, to_email: str, subject: str, html_content: str) -> bool:
- """Sends an HTML email using SMTP configuration."""
- if not settings.smtp_user or not settings.smtp_password:
- logger.warning("[EmailService] SMTP credentials not fully configured. Skipping email send.")
- return False
-
- try:
- msg = MIMEMultipart("alternative")
- msg["Subject"] = subject
- msg["From"] = settings.smtp_user
- msg["To"] = to_email
-
- # Attach HTML body
- part = MIMEText(html_content, "html")
- msg.attach(part)
-
- # Establish connection
- if settings.smtp_port == 465:
- server = smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port, timeout=15)
- else:
- server = smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=15)
- server.starttls()
-
- server.login(settings.smtp_user, settings.smtp_password)
- server.sendmail(settings.smtp_user, to_email, msg.as_string())
- server.quit()
-
- logger.info(f"[EmailService] Email sent successfully to {to_email} with subject: {subject}")
- return True
- except Exception as e:
- logger.error(f"[EmailService] Failed to send email to {to_email}: {e}")
- return False
-
-# Singleton instance
-email_service = EmailService()
+"""Email Service — Native SMTP transactional email sender.
+
+Replaces legacy GAS email sending webhooks.
+"""
+
+import smtplib
+from email.mime.text import MIMEText
+from email.mime.multipart import MIMEMultipart
+from loguru import logger
+from app.config import settings
+
+class EmailService:
+ def send_html_email(self, to_email: str, subject: str, html_content: str) -> bool:
+ """Sends an HTML email using SMTP configuration."""
+ if not settings.smtp_user or not settings.smtp_password:
+ logger.warning("[EmailService] SMTP credentials not fully configured. Skipping email send.")
+ return False
+
+ try:
+ msg = MIMEMultipart("alternative")
+ msg["Subject"] = subject
+ msg["From"] = settings.smtp_user
+ msg["To"] = to_email
+
+ # Attach HTML body
+ part = MIMEText(html_content, "html")
+ msg.attach(part)
+
+ # Establish connection
+ if settings.smtp_port == 465:
+ server = smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port, timeout=15)
+ else:
+ server = smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=15)
+ server.starttls()
+
+ server.login(settings.smtp_user, settings.smtp_password)
+ server.sendmail(settings.smtp_user, to_email, msg.as_string())
+ server.quit()
+
+ logger.info(f"[EmailService] Email sent successfully to {to_email} with subject: {subject}")
+ return True
+ except Exception as e:
+ logger.error(f"[EmailService] Failed to send email to {to_email}: {e}")
+ return False
+
+# Singleton instance
+email_service = EmailService()
diff --git a/app/services/google_workspace_service.py b/app/services/google_workspace_service.py
index 31ff00c5218eef05cb3546846b2289d75ceedb09..70bdd98fc9680aed170c7503503d0a8ae6d2e9c6 100644
--- a/app/services/google_workspace_service.py
+++ b/app/services/google_workspace_service.py
@@ -1,210 +1,210 @@
-"""Google Workspace Service — Automated Document Management (The Spark Agent).
-
-Handles Google Drive folder orchestration, CV storage, and automated
-Google Docs resume generation.
-"""
-
-import os
-import json
-from typing import Dict, Any, Optional, List
-from loguru import logger
-from google.oauth2 import service_account
-from googleapiclient.discovery import build
-from googleapiclient.http import MediaInMemoryUpload
-
-from app.config import settings
-
-class GoogleWorkspaceService:
- def __init__(self):
- self.scopes = [
- 'https://www.googleapis.com/auth/drive',
- 'https://www.googleapis.com/auth/documents',
- 'https://www.googleapis.com/auth/calendar',
- 'https://www.googleapis.com/auth/spreadsheets'
- ]
- self.creds = self._load_credentials()
- self.drive_service = build('drive', 'v3', credentials=self.creds) if self.creds else None
- self.docs_service = build('docs', 'v1', credentials=self.creds) if self.creds else None
- self.calendar_service = build('calendar', 'v3', credentials=self.creds) if self.creds else None
- self.sheets_service = build('sheets', 'v4', credentials=self.creds) if self.creds else None
-
- async def append_row_to_sheet(self, spreadsheet_id: str, range_name: str, row_values: List[Any]) -> bool:
- """Appends a row of values to a specified Google Sheet using the Sheets API."""
- if not self.sheets_service:
- logger.warning("[SparkAgent] Sheets service not initialized.")
- return False
-
- try:
- body = {
- 'values': [row_values]
- }
- import asyncio
- def run_append():
- return self.sheets_service.spreadsheets().values().append(
- spreadsheetId=spreadsheet_id,
- range=range_name,
- valueInputOption="USER_ENTERED",
- insertDataOption="INSERT_ROWS",
- body=body
- ).execute()
-
- await asyncio.to_thread(run_append)
- logger.info(f"[SparkAgent] Appended row to sheet {range_name} in spreadsheet {spreadsheet_id}")
- return True
- except Exception as e:
- logger.error(f"[SparkAgent] Failed to append row to sheet {range_name}: {e}")
- return False
-
- async def get_founder_availability(self, start_time: str, end_time: str) -> List[Dict[str, Any]]:
- """Checks founder's Google Calendar for busy slots."""
- if not self.calendar_service: return []
-
- try:
- body = {
- "timeMin": start_time,
- "timeMax": end_time,
- "items": [{"id": "primary"}]
- }
- res = self.calendar_service.freebusy().query(body=body).execute()
- return res.get('calendars', {}).get('primary', {}).get('busy', [])
- except Exception as e:
- logger.error(f"[SparkAgent] Calendar check failed: {e}")
- return []
-
- async def schedule_ceo_meeting(self, summary: str, start_iso: str, end_iso: str, attendee_email: str) -> Optional[str]:
- """Schedules a meeting on the founder's calendar."""
- if not self.calendar_service: return None
-
- try:
- event = {
- 'summary': summary,
- 'description': 'Scheduled by Brigawan AI CEO',
- 'start': {'dateTime': start_iso, 'timeZone': 'Asia/Jakarta'},
- 'end': {'dateTime': end_iso, 'timeZone': 'Asia/Jakarta'},
- 'attendees': [{'email': attendee_email}],
- 'conferenceData': {'createRequest': {'requestId': str(uuid.uuid4()), 'conferenceSolutionKey': {'type': 'hangoutsMeet'}}}
- }
- event = self.calendar_service.events().insert(
- calendarId='primary', body=event, conferenceDataVersion=1
- ).execute()
- return event.get('htmlLink')
- except Exception as e:
- logger.error(f"[SparkAgent] Meeting scheduling failed: {e}")
- return None
-
- def _load_credentials(self):
- """Loads Service Account credentials from settings."""
- # Use getattr for safety on Hugging Face environments
- json_creds = getattr(settings, "google_service_account_json", None)
-
- if not json_creds:
- logger.warning("[SparkAgent] Google Service Account JSON not configured.")
- return None
- try:
- creds_info = json.loads(json_creds)
- return service_account.Credentials.from_service_account_info(
- creds_info, scopes=self.scopes
- )
- except Exception as e:
- logger.error(f"[SparkAgent] Failed to load credentials: {e}")
- return None
-
- async def get_or_create_folder(self, folder_name: str, parent_id: Optional[str] = None) -> Optional[str]:
- """Finds or creates a folder in Google Drive."""
- if not self.drive_service: return None
-
- query = f"name = '{folder_name}' and mimeType = 'application/vnd.google-apps.folder' and trashed = false"
- if parent_id:
- query += f" and '{parent_id}' in parents"
-
- try:
- results = self.drive_service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
- files = results.get('files', [])
-
- if files:
- return files[0]['id']
-
- # Create if not exists
- folder_metadata = {
- 'name': folder_name,
- 'mimeType': 'application/vnd.google-apps.folder'
- }
- if parent_id:
- folder_metadata['parents'] = [parent_id]
-
- folder = self.drive_service.files().create(body=folder_metadata, fields='id').execute()
- logger.info(f"[SparkAgent] Created folder: {folder_name} ({folder.get('id')})")
- return folder.get('id')
- except Exception as e:
- logger.error(f"[SparkAgent] Folder error: {e}")
- return None
-
- async def upload_cv(self, file_content: bytes, file_name: str, employer_folder_id: str) -> Optional[str]:
- """Uploads a CV to a specific employer's folder."""
- if not self.drive_service: return None
-
- try:
- file_metadata = {
- 'name': file_name,
- 'parents': [employer_folder_id]
- }
- media = MediaInMemoryUpload(file_content, resumable=True)
- file = self.drive_service.files().create(body=file_metadata, media_body=media, fields='id, webViewLink').execute()
-
- # Make readable by link
- self.drive_service.permissions().create(
- fileId=file.get('id'),
- body={'type': 'anyone', 'role': 'reader'}
- ).execute()
-
- return file.get('webViewLink')
- except Exception as e:
- logger.error(f"[SparkAgent] CV upload failed: {e}")
- return None
-
- async def generate_standardized_resume(self, talent_data: Dict[str, Any], doc_name: str) -> Optional[str]:
- """Generates a standardized Google Doc resume for a talent."""
- if not self.docs_service or not self.drive_service: return None
-
- try:
- # 1. Create a blank doc
- doc = self.docs_service.documents().create(body={'title': doc_name}).execute()
- doc_id = doc.get('documentId')
-
- # 2. Populate with data
- requests = [
- {
- 'insertText': {
- 'location': {'index': 1},
- 'text': f"{talent_data.get('name', 'Talent Name').upper()}\n"
- f"Email: {talent_data.get('email', '-')}\n"
- f"Location: {talent_data.get('location', '-')}\n\n"
- f"EXPERIENCE\n{talent_data.get('experience', '-')}\n\n"
- f"SKILLS\n{talent_data.get('skills', '-')}\n\n"
- f"Generated by Brigawan AI — Green Talent Ecosystem\n"
- }
- },
- {
- 'updateTextStyle': {
- 'range': {'startIndex': 1, 'endIndex': len(talent_data.get('name', '')) + 1},
- 'textStyle': {'bold': True, 'fontSize': {'magnitude': 18, 'unit': 'PT'}},
- 'fields': 'bold,fontSize'
- }
- }
- ]
- self.docs_service.documents().batchUpdate(documentId=doc_id, body={'requests': requests}).execute()
-
- # 3. Share and return link
- file = self.drive_service.files().get(fileId=doc_id, fields='webViewLink').execute()
- self.drive_service.permissions().create(
- fileId=doc_id,
- body={'type': 'anyone', 'role': 'reader'}
- ).execute()
-
- return file.get('webViewLink')
- except Exception as e:
- logger.error(f"[SparkAgent] Resume generation failed: {e}")
- return None
-
-# Singleton instance
-spark_agent = GoogleWorkspaceService()
+"""Google Workspace Service — Automated Document Management (The Spark Agent).
+
+Handles Google Drive folder orchestration, CV storage, and automated
+Google Docs resume generation.
+"""
+
+import os
+import json
+from typing import Dict, Any, Optional, List
+from loguru import logger
+from google.oauth2 import service_account
+from googleapiclient.discovery import build
+from googleapiclient.http import MediaInMemoryUpload
+
+from app.config import settings
+
+class GoogleWorkspaceService:
+ def __init__(self):
+ self.scopes = [
+ 'https://www.googleapis.com/auth/drive',
+ 'https://www.googleapis.com/auth/documents',
+ 'https://www.googleapis.com/auth/calendar',
+ 'https://www.googleapis.com/auth/spreadsheets'
+ ]
+ self.creds = self._load_credentials()
+ self.drive_service = build('drive', 'v3', credentials=self.creds) if self.creds else None
+ self.docs_service = build('docs', 'v1', credentials=self.creds) if self.creds else None
+ self.calendar_service = build('calendar', 'v3', credentials=self.creds) if self.creds else None
+ self.sheets_service = build('sheets', 'v4', credentials=self.creds) if self.creds else None
+
+ async def append_row_to_sheet(self, spreadsheet_id: str, range_name: str, row_values: List[Any]) -> bool:
+ """Appends a row of values to a specified Google Sheet using the Sheets API."""
+ if not self.sheets_service:
+ logger.warning("[SparkAgent] Sheets service not initialized.")
+ return False
+
+ try:
+ body = {
+ 'values': [row_values]
+ }
+ import asyncio
+ def run_append():
+ return self.sheets_service.spreadsheets().values().append(
+ spreadsheetId=spreadsheet_id,
+ range=range_name,
+ valueInputOption="USER_ENTERED",
+ insertDataOption="INSERT_ROWS",
+ body=body
+ ).execute()
+
+ await asyncio.to_thread(run_append)
+ logger.info(f"[SparkAgent] Appended row to sheet {range_name} in spreadsheet {spreadsheet_id}")
+ return True
+ except Exception as e:
+ logger.error(f"[SparkAgent] Failed to append row to sheet {range_name}: {e}")
+ return False
+
+ async def get_founder_availability(self, start_time: str, end_time: str) -> List[Dict[str, Any]]:
+ """Checks founder's Google Calendar for busy slots."""
+ if not self.calendar_service: return []
+
+ try:
+ body = {
+ "timeMin": start_time,
+ "timeMax": end_time,
+ "items": [{"id": "primary"}]
+ }
+ res = self.calendar_service.freebusy().query(body=body).execute()
+ return res.get('calendars', {}).get('primary', {}).get('busy', [])
+ except Exception as e:
+ logger.error(f"[SparkAgent] Calendar check failed: {e}")
+ return []
+
+ async def schedule_ceo_meeting(self, summary: str, start_iso: str, end_iso: str, attendee_email: str) -> Optional[str]:
+ """Schedules a meeting on the founder's calendar."""
+ if not self.calendar_service: return None
+
+ try:
+ event = {
+ 'summary': summary,
+ 'description': 'Scheduled by Brigawan AI CEO',
+ 'start': {'dateTime': start_iso, 'timeZone': 'Asia/Jakarta'},
+ 'end': {'dateTime': end_iso, 'timeZone': 'Asia/Jakarta'},
+ 'attendees': [{'email': attendee_email}],
+ 'conferenceData': {'createRequest': {'requestId': str(uuid.uuid4()), 'conferenceSolutionKey': {'type': 'hangoutsMeet'}}}
+ }
+ event = self.calendar_service.events().insert(
+ calendarId='primary', body=event, conferenceDataVersion=1
+ ).execute()
+ return event.get('htmlLink')
+ except Exception as e:
+ logger.error(f"[SparkAgent] Meeting scheduling failed: {e}")
+ return None
+
+ def _load_credentials(self):
+ """Loads Service Account credentials from settings."""
+ # Use getattr for safety on Hugging Face environments
+ json_creds = getattr(settings, "google_service_account_json", None)
+
+ if not json_creds:
+ logger.warning("[SparkAgent] Google Service Account JSON not configured.")
+ return None
+ try:
+ creds_info = json.loads(json_creds)
+ return service_account.Credentials.from_service_account_info(
+ creds_info, scopes=self.scopes
+ )
+ except Exception as e:
+ logger.error(f"[SparkAgent] Failed to load credentials: {e}")
+ return None
+
+ async def get_or_create_folder(self, folder_name: str, parent_id: Optional[str] = None) -> Optional[str]:
+ """Finds or creates a folder in Google Drive."""
+ if not self.drive_service: return None
+
+ query = f"name = '{folder_name}' and mimeType = 'application/vnd.google-apps.folder' and trashed = false"
+ if parent_id:
+ query += f" and '{parent_id}' in parents"
+
+ try:
+ results = self.drive_service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
+ files = results.get('files', [])
+
+ if files:
+ return files[0]['id']
+
+ # Create if not exists
+ folder_metadata = {
+ 'name': folder_name,
+ 'mimeType': 'application/vnd.google-apps.folder'
+ }
+ if parent_id:
+ folder_metadata['parents'] = [parent_id]
+
+ folder = self.drive_service.files().create(body=folder_metadata, fields='id').execute()
+ logger.info(f"[SparkAgent] Created folder: {folder_name} ({folder.get('id')})")
+ return folder.get('id')
+ except Exception as e:
+ logger.error(f"[SparkAgent] Folder error: {e}")
+ return None
+
+ async def upload_cv(self, file_content: bytes, file_name: str, employer_folder_id: str) -> Optional[str]:
+ """Uploads a CV to a specific employer's folder."""
+ if not self.drive_service: return None
+
+ try:
+ file_metadata = {
+ 'name': file_name,
+ 'parents': [employer_folder_id]
+ }
+ media = MediaInMemoryUpload(file_content, resumable=True)
+ file = self.drive_service.files().create(body=file_metadata, media_body=media, fields='id, webViewLink').execute()
+
+ # Make readable by link
+ self.drive_service.permissions().create(
+ fileId=file.get('id'),
+ body={'type': 'anyone', 'role': 'reader'}
+ ).execute()
+
+ return file.get('webViewLink')
+ except Exception as e:
+ logger.error(f"[SparkAgent] CV upload failed: {e}")
+ return None
+
+ async def generate_standardized_resume(self, talent_data: Dict[str, Any], doc_name: str) -> Optional[str]:
+ """Generates a standardized Google Doc resume for a talent."""
+ if not self.docs_service or not self.drive_service: return None
+
+ try:
+ # 1. Create a blank doc
+ doc = self.docs_service.documents().create(body={'title': doc_name}).execute()
+ doc_id = doc.get('documentId')
+
+ # 2. Populate with data
+ requests = [
+ {
+ 'insertText': {
+ 'location': {'index': 1},
+ 'text': f"{talent_data.get('name', 'Talent Name').upper()}\n"
+ f"Email: {talent_data.get('email', '-')}\n"
+ f"Location: {talent_data.get('location', '-')}\n\n"
+ f"EXPERIENCE\n{talent_data.get('experience', '-')}\n\n"
+ f"SKILLS\n{talent_data.get('skills', '-')}\n\n"
+ f"Generated by Brigawan AI — Green Talent Ecosystem\n"
+ }
+ },
+ {
+ 'updateTextStyle': {
+ 'range': {'startIndex': 1, 'endIndex': len(talent_data.get('name', '')) + 1},
+ 'textStyle': {'bold': True, 'fontSize': {'magnitude': 18, 'unit': 'PT'}},
+ 'fields': 'bold,fontSize'
+ }
+ }
+ ]
+ self.docs_service.documents().batchUpdate(documentId=doc_id, body={'requests': requests}).execute()
+
+ # 3. Share and return link
+ file = self.drive_service.files().get(fileId=doc_id, fields='webViewLink').execute()
+ self.drive_service.permissions().create(
+ fileId=doc_id,
+ body={'type': 'anyone', 'role': 'reader'}
+ ).execute()
+
+ return file.get('webViewLink')
+ except Exception as e:
+ logger.error(f"[SparkAgent] Resume generation failed: {e}")
+ return None
+
+# Singleton instance
+spark_agent = GoogleWorkspaceService()
diff --git a/app/services/interview_service.py b/app/services/interview_service.py
index 83ba3ae5193c625fa463f2010bda41421a6a243c..073e09595b2376782827d35730df41899225ac83 100644
--- a/app/services/interview_service.py
+++ b/app/services/interview_service.py
@@ -1,558 +1,558 @@
-"""Interview & AI Notulen Service — Schedule, Transcript, AI Summary, Comparison.
-
-Business Model:
- - Schedule interview: costs 5 coins (deducted from Company CreditBalance)
- - Enterprise tier: free AI interview scheduling
- - AI Notulen: automated meeting summaries via Gemini MEDIUM tier
- - Competency analysis + multi-candidate comparison via Gemini HIGH tier
-
-All operations crash-proof: never throw, always return structured response.
-"""
-
-import json
-import secrets
-import uuid
-from datetime import datetime, timezone
-from typing import Any, Dict, List, Optional
-
-from loguru import logger
-from sqlalchemy import func, select
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.models.finance import Interview
-from app.models.talent import Talent
-from app.models.employer import ClientAccount, Company
-from app.models.finance import Transaction
-from app.services.ai_service import call_medium, call_high
-from app.config.settings import settings, FINANCE_CONFIG
-
-
-INTERVIEW_COST = 5 # Coins per interview (Enterprise = free)
-
-
-# =============================================================================
-# HELPERS
-# =============================================================================
-
-async def _get_talent_by_id(db: AsyncSession, talent_id: str) -> Optional[Talent]:
- result = await db.execute(select(Talent).where(Talent.talent_id == talent_id))
- return result.scalar_one_or_none()
-
-
-async def _get_client_and_company(db: AsyncSession, email: str) -> tuple:
- result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
- client = result.scalar_one_or_none()
- if not client:
- return None, None
- result = await db.execute(select(Company).where(Company.id == client.company_id))
- company = result.scalar_one_or_none()
- return client, company
-
-
-async def _get_interview(db: AsyncSession, interview_id: str) -> Optional[Interview]:
- try:
- uid = uuid.UUID(interview_id)
- result = await db.execute(
- select(Interview).where(Interview.id == uid)
- )
- return result.scalar_one_or_none()
- except Exception:
- return None
-
-
-def _tier_is_enterprise(tier: str) -> bool:
- return tier and tier.lower() == "enterprise"
-
-
-# =============================================================================
-# 1. SCHEDULE INTERVIEW
-# =============================================================================
-
-async def schedule_interview(
- db: AsyncSession,
- recruiter_email: str,
- candidate_id: str,
- scheduled_time: str,
-) -> dict:
- """Schedule an interview with a candidate.
-
- Business rules:
- 1. Verify talent exists
- 2. Verify employer has enough coins (unless Enterprise tier)
- 3. Deduct 5 coins (free for Enterprise)
- 4. Create Interview record
-
- Returns structured response with interview_id and credit info.
- """
- try:
- # Verify talent
- talent = await _get_talent_by_id(db, candidate_id)
- if not talent:
- return {"success": False, "error": f"Talent {candidate_id} tidak ditemukan."}
-
- # Verify employer & company
- client, company = await _get_client_and_company(db, recruiter_email)
- if not client or not company:
- return {"success": False, "error": "Akun employer tidak ditemukan."}
-
- credits_deducted = 0
-
- # Check if Enterprise — free scheduling
- if not _tier_is_enterprise(company.tier or ""):
- if (company.credit_balance or 0) < INTERVIEW_COST:
- return {
- "success": False,
- "error": f"Koin tidak mencukupi. Interview membutuhkan {INTERVIEW_COST} koin. "
- f"Saldo: {company.credit_balance or 0}. "
- f"Upgrade ke Enterprise untuk interview gratis tanpa batas.",
- }
- # Deduct coins
- company.credit_balance = (company.credit_balance or 0) - INTERVIEW_COST
- credits_deducted = INTERVIEW_COST
- db.add(company)
-
- # Log transaction
- tx = Transaction(
- id=f"TX-IVW-{secrets.token_hex(4).upper()}",
- client_id=client.id,
- amount=INTERVIEW_COST,
- type="Interview",
- status="Settled",
- )
- db.add(tx)
-
- # Parse scheduled time
- try:
- sched_dt = datetime.fromisoformat(scheduled_time.replace("Z", "+00:00"))
- except Exception:
- sched_dt = datetime.now(timezone.utc)
-
- # Create interview record
- interview = Interview(
- id=uuid.uuid4(),
- company_id=company.id,
- client_id=client.id,
- candidate_id=candidate_id,
- scheduled_time=sched_dt,
- status="Scheduled",
- )
- db.add(interview)
- await db.commit()
-
- logger.info(f"Interview scheduled: {interview.id} ({recruiter_email} -> {candidate_id})")
-
- return {
- "success": True,
- "interview_id": str(interview.id),
- "candidate_name": talent.name or "Talent",
- "candidate_id": candidate_id,
- "scheduled_time": sched_dt.isoformat(),
- "credits_deducted": credits_deducted,
- "credits_remaining": company.credit_balance or 0,
- "message": f"Interview berhasil dijadwalkan dengan {talent.name or 'Talent'}."
- + (f" ({INTERVIEW_COST} koin digunakan)" if credits_deducted > 0
- else " (Gratis — Enterprise tier)"),
- }
-
- except Exception as e:
- logger.error(f"schedule_interview error: {e}")
- await db.rollback()
- return {"success": False, "error": f"Gagal menjadwalkan interview: {str(e)}"}
-
-
-# =============================================================================
-# 2. SAVE TRANSCRIPT
-# =============================================================================
-
-async def save_transcript(
- db: AsyncSession,
- interview_id: str,
- transcript_text: str,
-) -> dict:
- """Save interview transcript after the interview is completed."""
- try:
- interview = await _get_interview(db, interview_id)
- if not interview:
- return {"success": False, "error": "Interview tidak ditemukan."}
-
- interview.transcript_text = transcript_text
- interview.status = "Completed"
- db.add(interview)
- await db.commit()
-
- logger.info(f"Transcript saved: {interview_id}")
-
- return {
- "success": True,
- "interview_id": interview_id,
- "message": "Transkrip interview berhasil disimpan.",
- }
-
- except Exception as e:
- logger.error(f"save_transcript error: {e}")
- await db.rollback()
- return {"success": False, "error": f"Gagal menyimpan transkrip: {str(e)}"}
-
-
-# =============================================================================
-# 3. AI NOTULEN (Meeting Summary)
-# =============================================================================
-
-async def generate_ai_notulen(
- db: AsyncSession,
- interview_id: str,
-) -> dict:
- """Generate AI meeting summary (Notulen) from interview transcript.
-
- Uses Gemini MEDIUM tier (3.5 Flash) for summarization.
- Falls back to algorithmic extraction if AI unavailable.
- """
- try:
- interview = await _get_interview(db, interview_id)
- if not interview:
- return {"success": False, "error": "Interview tidak ditemukan."}
-
- if not interview.transcript_text:
- return {"success": False, "error": "Transkrip interview belum tersedia. Simpan transkrip terlebih dahulu."}
-
- transcript = interview.transcript_text[:8000]
-
- # Get candidate info for context
- talent = await _get_talent_by_id(db, interview.candidate_id)
- candidate_name = talent.name if talent else "Kandidat"
-
- # AI Notulen via MEDIUM tier
- ai_used = False
- summary = None
- try:
- prompt = (
- f"Anda adalah AI Notulen Brigawan, asisten yang membuat notulen rapat interview yang profesional dan terstruktur.\\n\\n"
- f"Buat notulen interview untuk kandidat: {candidate_name}\\n\\n"
- f"Berikut adalah transkrip interview:\\n{transcript}\\n\\n"
- f"Buat notulen dengan format berikut (dalam Bahasa Indonesia):\\n"
- f"1. RINGKASAN EKSEKUTIF: 2-3 kalimat\\n"
- f"2. PERTANYAAN & JAWABAN: Poin-poin penting\\n"
- f"3. KESAN KANDIDAT: Kesan umum, komunikasi, dan sikap\\n"
- f"4. KECOCOKAN: Analisis kecocokan\\n"
- f"5. REKOMENDASI: Langkah selanjutnya"
- )
- result = await call_medium(prompt=prompt, temperature=0.5, max_output_tokens=2048)
- if result:
- summary = result.strip()
- ai_used = True
- except Exception as e:
- logger.error(f"AI Notulen generation error: {e}")
-
- # Algorithmic fallback
- if not summary:
- summary = (
- f"=== NOTULEN INTERVIEW ({candidate_name}) ===\\n\\n"
- f"RINGKASAN EKSEKUTIF:\\n"
- f"Interview dengan {candidate_name} telah dilaksanakan.\\n\\n"
- f"*Notulen AI tidak tersedia - menggunakan ringkasan otomatis.*"
- )
-
- # Save to interview record
- interview.ai_summary = summary
- db.add(interview)
- await db.commit()
-
- return {
- "success": True,
- "interview_id": interview_id,
- "summary": summary,
- "ai_used": ai_used,
- }
-
- except Exception as e:
- logger.error(f"generate_ai_notulen error: {e}")
- await db.rollback()
- return {"success": False, "error": f"Gagal membuat notulen: {str(e)}"}
-
-
-# =============================================================================
-# 4. COMPETENCY ANALYSIS
-# =============================================================================
-
-async def analyze_competency(
- db: AsyncSession,
- interview_id: str,
-) -> dict:
- """Analyze candidate competency from interview transcript.
-
- Uses Gemini MEDIUM tier for structured competency scoring.
- Returns scores across multiple competency dimensions.
- """
- try:
- interview = await _get_interview(db, interview_id)
- if not interview:
- return {"success": False, "error": "Interview tidak ditemukan."}
-
- if not interview.transcript_text:
- return {"success": False, "error": "Transkrip interview belum tersedia."}
-
- transcript = interview.transcript_text[:8000]
- talent = await _get_talent_by_id(db, interview.candidate_id)
- candidate_name = talent.name if talent else "Kandidat"
-
- # AI competency analysis via MEDIUM tier
- ai_used = False
- analysis = None
- try:
- prompt = (
- f"Anda adalah AI Assessment Brigawan, spesialis evaluasi kompetensi kandidat.\\n\\n"
- f"Evaluasi kandidat berikut berdasarkan transkrip interview:\\n"
- f"Nama Kandidat: {candidate_name}\\n\\n"
- f"Transkrip Interview:\\n{transcript}\\n\\n"
- f"Berikan analisis dalam format JSON SAJA (tanpa markdown):\\n"
- '{\"overall_score\": 0-100, \"competencies\": [{\"name\": \"Pengetahuan Teknis\", \"score\": 0-100, \"notes\": \"...\"}], \"strengths\": \"...\", \"weaknesses\": \"...\", \"recommendation\": \"...\"}'
- )
- result = await call_medium(prompt=prompt, temperature=0.4, max_output_tokens=2048)
- if result:
- cleaned = result.strip()
- if cleaned.startswith("```json"):
- cleaned = cleaned[7:]
- if cleaned.startswith("```"):
- cleaned = cleaned[3:]
- if cleaned.endswith("```"):
- cleaned = cleaned[:-3]
- cleaned = cleaned.strip()
- analysis = json.loads(cleaned)
- ai_used = True
- except Exception as e:
- logger.error(f"Competency analysis AI error: {e}")
-
- if not analysis:
- # Algorithmic fallback
- word_count = len(transcript.split())
- score = min(70 + (word_count // 50), 90)
- analysis = {
- "overall_score": score,
- "competencies": [
- {"name": "Pengetahuan Teknis", "score": score - 5, "notes": "Dinilai dari transkrip (fallback)"},
- {"name": "Komunikasi", "score": score, "notes": "Dinilai dari transkrip (fallback)"},
- {"name": "Pemecahan Masalah", "score": score - 10, "notes": "Dinilai dari transkrip (fallback)"},
- {"name": "Pengalaman Relevan", "score": score - 5, "notes": "Dinilai dari transkrip (fallback)"},
- {"name": "Sikap dan Motivasi", "score": score, "notes": "Dinilai dari transkrip (fallback)"},
- ],
- "strengths": "Analisis AI tidak tersedia. Gunakan penilaian manual.",
- "weaknesses": "Analisis AI tidak tersedia. Gunakan penilaian manual.",
- "recommendation": "Lanjut ke tahap berikutnya berdasarkan penilaian manual.",
- }
-
- # Save competency score to interview record
- interview.ai_competency_score = analysis.get("overall_score", 0)
- interview.ai_performance_analysis = json.dumps(analysis)
- db.add(interview)
- await db.commit()
-
- return {
- "success": True,
- "interview_id": interview_id,
- "overall_score": analysis.get("overall_score", 0),
- "competencies": analysis.get("competencies", []),
- "strengths": analysis.get("strengths", ""),
- "weaknesses": analysis.get("weaknesses", ""),
- "recommendation": analysis.get("recommendation", ""),
- "ai_used": ai_used,
- }
-
- except Exception as e:
- logger.error(f"analyze_competency error: {e}")
- return {"success": False, "error": f"Gagal menganalisis kompetensi: {str(e)}"}
-
-
-# =============================================================================
-# 5. MULTI-CANDIDATE COMPARISON
-# =============================================================================
-
-async def compare_candidates(
- db: AsyncSession,
- interview_ids: List[str],
-) -> dict:
- """Compare multiple candidates from their interviews.
-
- Uses Gemini HIGH tier (3.1 Pro) for intelligent comparison.
- Generates a comparison matrix with recommendations.
- Max 10 candidates per comparison.
- """
- try:
- if len(interview_ids) < 2:
- return {"success": False, "error": "Minimal 2 kandidat untuk perbandingan."}
- if len(interview_ids) > 10:
- interview_ids = interview_ids[:10]
-
- # Fetch all interviews and their data
- candidates_data = []
- for iid in interview_ids:
- interview = await _get_interview(db, iid)
- if not interview:
- continue
- talent = await _get_talent_by_id(db, interview.candidate_id)
- candidates_data.append({
- "interview_id": iid,
- "candidate_id": interview.candidate_id,
- "candidate_name": talent.name if talent else interview.candidate_id,
- "score": interview.ai_competency_score or 0,
- "summary": interview.ai_summary or "",
- "transcript": (interview.transcript_text or "")[:2000],
- "analysis": interview.ai_performance_analysis or "",
- })
-
- if len(candidates_data) < 2:
- return {"success": False, "error": "Tidak cukup data interview untuk perbandingan."}
-
- # AI comparison via HIGH tier
- ai_used = False
- comparison_result = None
- try:
- candidates_text = ""
- for c in candidates_data:
- candidates_text += (
- f"--- Kandidat: {c['candidate_name']} (ID: {c['candidate_id']}) ---\\n"
- f"Skor Kompetensi: {c['score']}/100\\n"
- f"Ringkasan: {c['summary'][:500]}\\n\\n"
- )
-
- prompt = (
- f"Anda adalah AI Recruiter Brigawan, spesialis perbandingan kandidat.\\n\\n"
- f"Bandingkan kandidat-kandidat berikut:\\n{candidates_text}\\n"
- f"Buat analisis JSON: candidates[] dengan overall_score 0-100, competency_scores, strengths, weaknesses. Serta recommendation dan matrix_summary."
- )
- result = await call_high(prompt=prompt, temperature=0.3, max_output_tokens=3072)
- if result:
- cleaned = result.strip()
- if cleaned.startswith("```json"):
- cleaned = cleaned[7:]
- if cleaned.startswith("```"):
- cleaned = cleaned[3:]
- if cleaned.endswith("```"):
- cleaned = cleaned[:-3]
- cleaned = cleaned.strip()
- comparison_result = json.loads(cleaned)
- ai_used = True
- except Exception as e:
- logger.error(f"Candidate comparison AI error: {e}")
-
- if not comparison_result:
- # Algorithmic fallback: sort by score
- candidates_data.sort(key=lambda c: c["score"], reverse=True)
- comparison_result = {
- "candidates": [
- {
- "candidate_id": c["candidate_id"],
- "candidate_name": c["candidate_name"],
- "overall_score": c["score"],
- "competency_scores": {"Umum": c["score"]},
- "strengths": "Data terbatas",
- "weaknesses": "Data terbatas",
- }
- for c in candidates_data
- ],
- "recommendation": f"Kandidat terbaik: {candidates_data[0]['candidate_name']} (skor {candidates_data[0]['score']}). Verifikasi manual diperlukan.",
- "matrix_summary": f"Perbandingan {len(candidates_data)} kandidat berdasarkan skor kompetensi.",
- }
-
- return {
- "success": True,
- "candidates": comparison_result.get("candidates", []),
- "recommendation": comparison_result.get("recommendation", ""),
- "matrix_summary": comparison_result.get("matrix_summary", ""),
- "ai_used": ai_used,
- }
-
- except Exception as e:
- logger.error(f"compare_candidates error: {e}")
- return {"success": False, "error": f"Gagal membandingkan kandidat: {str(e)}"}
-
-
-# =============================================================================
-# 6. LIST & DETAIL INTERVIEWS
-# =============================================================================
-
-async def list_interviews(
- db: AsyncSession,
- email: str,
- status: Optional[str] = None,
-) -> dict:
- """List all interviews for an employer, with optional status filter."""
- try:
- _, company = await _get_client_and_company(db, email)
- if not company:
- return {"success": False, "error": "Company not found."}
-
- query = select(Interview).where(Interview.company_id == company.id)
- if status:
- query = query.where(Interview.status == status)
- query = query.order_by(Interview.scheduled_time.desc())
-
- result = await db.execute(query)
- interviews = result.scalars().all()
-
- data = []
- for iv in interviews:
- talent = await _get_talent_by_id(db, iv.candidate_id)
- data.append({
- "interview_id": str(iv.id),
- "candidate_id": iv.candidate_id,
- "candidate_name": talent.name if talent else iv.candidate_id,
- "scheduled_time": iv.scheduled_time.isoformat() if iv.scheduled_time else None,
- "status": iv.status or "Scheduled",
- "has_transcript": bool(iv.transcript_text),
- "has_ai_summary": bool(iv.ai_summary),
- "competency_score": iv.ai_competency_score or 0,
- "created_at": iv.created_at.isoformat() if iv.created_at else None,
- })
-
- return {
- "success": True,
- "data": data,
- "total": len(data),
- }
-
- except Exception as e:
- logger.error(f"list_interviews error: {e}")
- return {"success": False, "error": str(e), "data": [], "total": 0}
-
-
-async def get_interview_detail(
- db: AsyncSession,
- interview_id: str,
-) -> dict:
- """Get full interview detail including transcript, AI summary, and competency analysis."""
- try:
- interview = await _get_interview(db, interview_id)
- if not interview:
- return {"success": False, "error": "Interview tidak ditemukan."}
-
- talent = await _get_talent_by_id(db, interview.candidate_id)
-
- competency_analysis = None
- if interview.ai_performance_analysis:
- try:
- competency_analysis = json.loads(interview.ai_performance_analysis)
- except Exception:
- competency_analysis = {"raw": interview.ai_performance_analysis}
-
- return {
- "success": True,
- "data": {
- "interview_id": str(interview.id),
- "candidate_id": interview.candidate_id,
- "candidate_name": talent.name if talent else interview.candidate_id,
- "scheduled_time": interview.scheduled_time.isoformat() if interview.scheduled_time else None,
- "status": interview.status or "Scheduled",
- "has_transcript": bool(interview.transcript_text),
- "has_ai_summary": bool(interview.ai_summary),
- "competency_score": interview.ai_competency_score or 0,
- "created_at": interview.created_at.isoformat() if interview.created_at else None,
- },
- "transcript": interview.transcript_text or "",
- "ai_summary": interview.ai_summary or "",
- "competency_analysis": competency_analysis,
- }
-
- except Exception as e:
- logger.error(f"get_interview_detail error: {e}")
- return {"success": False, "error": str(e)}
-
+"""Interview & AI Notulen Service — Schedule, Transcript, AI Summary, Comparison.
+
+Business Model:
+ - Schedule interview: costs 5 coins (deducted from Company CreditBalance)
+ - Enterprise tier: free AI interview scheduling
+ - AI Notulen: automated meeting summaries via Gemini MEDIUM tier
+ - Competency analysis + multi-candidate comparison via Gemini HIGH tier
+
+All operations crash-proof: never throw, always return structured response.
+"""
+
+import json
+import secrets
+import uuid
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Optional
+
+from loguru import logger
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.finance import Interview
+from app.models.talent import Talent
+from app.models.employer import ClientAccount, Company
+from app.models.finance import Transaction
+from app.services.ai_service import call_medium, call_high
+from app.config.settings import settings, FINANCE_CONFIG
+
+
+INTERVIEW_COST = 5 # Coins per interview (Enterprise = free)
+
+
+# =============================================================================
+# HELPERS
+# =============================================================================
+
+async def _get_talent_by_id(db: AsyncSession, talent_id: str) -> Optional[Talent]:
+ result = await db.execute(select(Talent).where(Talent.talent_id == talent_id))
+ return result.scalar_one_or_none()
+
+
+async def _get_client_and_company(db: AsyncSession, email: str) -> tuple:
+ result = await db.execute(select(ClientAccount).where(ClientAccount.email == email))
+ client = result.scalar_one_or_none()
+ if not client:
+ return None, None
+ result = await db.execute(select(Company).where(Company.id == client.company_id))
+ company = result.scalar_one_or_none()
+ return client, company
+
+
+async def _get_interview(db: AsyncSession, interview_id: str) -> Optional[Interview]:
+ try:
+ uid = uuid.UUID(interview_id)
+ result = await db.execute(
+ select(Interview).where(Interview.id == uid)
+ )
+ return result.scalar_one_or_none()
+ except Exception:
+ return None
+
+
+def _tier_is_enterprise(tier: str) -> bool:
+ return tier and tier.lower() == "enterprise"
+
+
+# =============================================================================
+# 1. SCHEDULE INTERVIEW
+# =============================================================================
+
+async def schedule_interview(
+ db: AsyncSession,
+ recruiter_email: str,
+ candidate_id: str,
+ scheduled_time: str,
+) -> dict:
+ """Schedule an interview with a candidate.
+
+ Business rules:
+ 1. Verify talent exists
+ 2. Verify employer has enough coins (unless Enterprise tier)
+ 3. Deduct 5 coins (free for Enterprise)
+ 4. Create Interview record
+
+ Returns structured response with interview_id and credit info.
+ """
+ try:
+ # Verify talent
+ talent = await _get_talent_by_id(db, candidate_id)
+ if not talent:
+ return {"success": False, "error": f"Talent {candidate_id} tidak ditemukan."}
+
+ # Verify employer & company
+ client, company = await _get_client_and_company(db, recruiter_email)
+ if not client or not company:
+ return {"success": False, "error": "Akun employer tidak ditemukan."}
+
+ credits_deducted = 0
+
+ # Check if Enterprise — free scheduling
+ if not _tier_is_enterprise(company.tier or ""):
+ if (company.credit_balance or 0) < INTERVIEW_COST:
+ return {
+ "success": False,
+ "error": f"Koin tidak mencukupi. Interview membutuhkan {INTERVIEW_COST} koin. "
+ f"Saldo: {company.credit_balance or 0}. "
+ f"Upgrade ke Enterprise untuk interview gratis tanpa batas.",
+ }
+ # Deduct coins
+ company.credit_balance = (company.credit_balance or 0) - INTERVIEW_COST
+ credits_deducted = INTERVIEW_COST
+ db.add(company)
+
+ # Log transaction
+ tx = Transaction(
+ id=f"TX-IVW-{secrets.token_hex(4).upper()}",
+ client_id=client.id,
+ amount=INTERVIEW_COST,
+ type="Interview",
+ status="Settled",
+ )
+ db.add(tx)
+
+ # Parse scheduled time
+ try:
+ sched_dt = datetime.fromisoformat(scheduled_time.replace("Z", "+00:00"))
+ except Exception:
+ sched_dt = datetime.now(timezone.utc)
+
+ # Create interview record
+ interview = Interview(
+ id=uuid.uuid4(),
+ company_id=company.id,
+ client_id=client.id,
+ candidate_id=candidate_id,
+ scheduled_time=sched_dt,
+ status="Scheduled",
+ )
+ db.add(interview)
+ await db.commit()
+
+ logger.info(f"Interview scheduled: {interview.id} ({recruiter_email} -> {candidate_id})")
+
+ return {
+ "success": True,
+ "interview_id": str(interview.id),
+ "candidate_name": talent.name or "Talent",
+ "candidate_id": candidate_id,
+ "scheduled_time": sched_dt.isoformat(),
+ "credits_deducted": credits_deducted,
+ "credits_remaining": company.credit_balance or 0,
+ "message": f"Interview berhasil dijadwalkan dengan {talent.name or 'Talent'}."
+ + (f" ({INTERVIEW_COST} koin digunakan)" if credits_deducted > 0
+ else " (Gratis — Enterprise tier)"),
+ }
+
+ except Exception as e:
+ logger.error(f"schedule_interview error: {e}")
+ await db.rollback()
+ return {"success": False, "error": f"Gagal menjadwalkan interview: {str(e)}"}
+
+
+# =============================================================================
+# 2. SAVE TRANSCRIPT
+# =============================================================================
+
+async def save_transcript(
+ db: AsyncSession,
+ interview_id: str,
+ transcript_text: str,
+) -> dict:
+ """Save interview transcript after the interview is completed."""
+ try:
+ interview = await _get_interview(db, interview_id)
+ if not interview:
+ return {"success": False, "error": "Interview tidak ditemukan."}
+
+ interview.transcript_text = transcript_text
+ interview.status = "Completed"
+ db.add(interview)
+ await db.commit()
+
+ logger.info(f"Transcript saved: {interview_id}")
+
+ return {
+ "success": True,
+ "interview_id": interview_id,
+ "message": "Transkrip interview berhasil disimpan.",
+ }
+
+ except Exception as e:
+ logger.error(f"save_transcript error: {e}")
+ await db.rollback()
+ return {"success": False, "error": f"Gagal menyimpan transkrip: {str(e)}"}
+
+
+# =============================================================================
+# 3. AI NOTULEN (Meeting Summary)
+# =============================================================================
+
+async def generate_ai_notulen(
+ db: AsyncSession,
+ interview_id: str,
+) -> dict:
+ """Generate AI meeting summary (Notulen) from interview transcript.
+
+ Uses Gemini MEDIUM tier (3.5 Flash) for summarization.
+ Falls back to algorithmic extraction if AI unavailable.
+ """
+ try:
+ interview = await _get_interview(db, interview_id)
+ if not interview:
+ return {"success": False, "error": "Interview tidak ditemukan."}
+
+ if not interview.transcript_text:
+ return {"success": False, "error": "Transkrip interview belum tersedia. Simpan transkrip terlebih dahulu."}
+
+ transcript = interview.transcript_text[:8000]
+
+ # Get candidate info for context
+ talent = await _get_talent_by_id(db, interview.candidate_id)
+ candidate_name = talent.name if talent else "Kandidat"
+
+ # AI Notulen via MEDIUM tier
+ ai_used = False
+ summary = None
+ try:
+ prompt = (
+ f"Anda adalah AI Notulen Brigawan, asisten yang membuat notulen rapat interview yang profesional dan terstruktur.\\n\\n"
+ f"Buat notulen interview untuk kandidat: {candidate_name}\\n\\n"
+ f"Berikut adalah transkrip interview:\\n{transcript}\\n\\n"
+ f"Buat notulen dengan format berikut (dalam Bahasa Indonesia):\\n"
+ f"1. RINGKASAN EKSEKUTIF: 2-3 kalimat\\n"
+ f"2. PERTANYAAN & JAWABAN: Poin-poin penting\\n"
+ f"3. KESAN KANDIDAT: Kesan umum, komunikasi, dan sikap\\n"
+ f"4. KECOCOKAN: Analisis kecocokan\\n"
+ f"5. REKOMENDASI: Langkah selanjutnya"
+ )
+ result = await call_medium(prompt=prompt, temperature=0.5, max_output_tokens=2048)
+ if result:
+ summary = result.strip()
+ ai_used = True
+ except Exception as e:
+ logger.error(f"AI Notulen generation error: {e}")
+
+ # Algorithmic fallback
+ if not summary:
+ summary = (
+ f"=== NOTULEN INTERVIEW ({candidate_name}) ===\\n\\n"
+ f"RINGKASAN EKSEKUTIF:\\n"
+ f"Interview dengan {candidate_name} telah dilaksanakan.\\n\\n"
+ f"*Notulen AI tidak tersedia - menggunakan ringkasan otomatis.*"
+ )
+
+ # Save to interview record
+ interview.ai_summary = summary
+ db.add(interview)
+ await db.commit()
+
+ return {
+ "success": True,
+ "interview_id": interview_id,
+ "summary": summary,
+ "ai_used": ai_used,
+ }
+
+ except Exception as e:
+ logger.error(f"generate_ai_notulen error: {e}")
+ await db.rollback()
+ return {"success": False, "error": f"Gagal membuat notulen: {str(e)}"}
+
+
+# =============================================================================
+# 4. COMPETENCY ANALYSIS
+# =============================================================================
+
+async def analyze_competency(
+ db: AsyncSession,
+ interview_id: str,
+) -> dict:
+ """Analyze candidate competency from interview transcript.
+
+ Uses Gemini MEDIUM tier for structured competency scoring.
+ Returns scores across multiple competency dimensions.
+ """
+ try:
+ interview = await _get_interview(db, interview_id)
+ if not interview:
+ return {"success": False, "error": "Interview tidak ditemukan."}
+
+ if not interview.transcript_text:
+ return {"success": False, "error": "Transkrip interview belum tersedia."}
+
+ transcript = interview.transcript_text[:8000]
+ talent = await _get_talent_by_id(db, interview.candidate_id)
+ candidate_name = talent.name if talent else "Kandidat"
+
+ # AI competency analysis via MEDIUM tier
+ ai_used = False
+ analysis = None
+ try:
+ prompt = (
+ f"Anda adalah AI Assessment Brigawan, spesialis evaluasi kompetensi kandidat.\\n\\n"
+ f"Evaluasi kandidat berikut berdasarkan transkrip interview:\\n"
+ f"Nama Kandidat: {candidate_name}\\n\\n"
+ f"Transkrip Interview:\\n{transcript}\\n\\n"
+ f"Berikan analisis dalam format JSON SAJA (tanpa markdown):\\n"
+ '{\"overall_score\": 0-100, \"competencies\": [{\"name\": \"Pengetahuan Teknis\", \"score\": 0-100, \"notes\": \"...\"}], \"strengths\": \"...\", \"weaknesses\": \"...\", \"recommendation\": \"...\"}'
+ )
+ result = await call_medium(prompt=prompt, temperature=0.4, max_output_tokens=2048)
+ if result:
+ cleaned = result.strip()
+ if cleaned.startswith("```json"):
+ cleaned = cleaned[7:]
+ if cleaned.startswith("```"):
+ cleaned = cleaned[3:]
+ if cleaned.endswith("```"):
+ cleaned = cleaned[:-3]
+ cleaned = cleaned.strip()
+ analysis = json.loads(cleaned)
+ ai_used = True
+ except Exception as e:
+ logger.error(f"Competency analysis AI error: {e}")
+
+ if not analysis:
+ # Algorithmic fallback
+ word_count = len(transcript.split())
+ score = min(70 + (word_count // 50), 90)
+ analysis = {
+ "overall_score": score,
+ "competencies": [
+ {"name": "Pengetahuan Teknis", "score": score - 5, "notes": "Dinilai dari transkrip (fallback)"},
+ {"name": "Komunikasi", "score": score, "notes": "Dinilai dari transkrip (fallback)"},
+ {"name": "Pemecahan Masalah", "score": score - 10, "notes": "Dinilai dari transkrip (fallback)"},
+ {"name": "Pengalaman Relevan", "score": score - 5, "notes": "Dinilai dari transkrip (fallback)"},
+ {"name": "Sikap dan Motivasi", "score": score, "notes": "Dinilai dari transkrip (fallback)"},
+ ],
+ "strengths": "Analisis AI tidak tersedia. Gunakan penilaian manual.",
+ "weaknesses": "Analisis AI tidak tersedia. Gunakan penilaian manual.",
+ "recommendation": "Lanjut ke tahap berikutnya berdasarkan penilaian manual.",
+ }
+
+ # Save competency score to interview record
+ interview.ai_competency_score = analysis.get("overall_score", 0)
+ interview.ai_performance_analysis = json.dumps(analysis)
+ db.add(interview)
+ await db.commit()
+
+ return {
+ "success": True,
+ "interview_id": interview_id,
+ "overall_score": analysis.get("overall_score", 0),
+ "competencies": analysis.get("competencies", []),
+ "strengths": analysis.get("strengths", ""),
+ "weaknesses": analysis.get("weaknesses", ""),
+ "recommendation": analysis.get("recommendation", ""),
+ "ai_used": ai_used,
+ }
+
+ except Exception as e:
+ logger.error(f"analyze_competency error: {e}")
+ return {"success": False, "error": f"Gagal menganalisis kompetensi: {str(e)}"}
+
+
+# =============================================================================
+# 5. MULTI-CANDIDATE COMPARISON
+# =============================================================================
+
+async def compare_candidates(
+ db: AsyncSession,
+ interview_ids: List[str],
+) -> dict:
+ """Compare multiple candidates from their interviews.
+
+ Uses Gemini HIGH tier (3.1 Pro) for intelligent comparison.
+ Generates a comparison matrix with recommendations.
+ Max 10 candidates per comparison.
+ """
+ try:
+ if len(interview_ids) < 2:
+ return {"success": False, "error": "Minimal 2 kandidat untuk perbandingan."}
+ if len(interview_ids) > 10:
+ interview_ids = interview_ids[:10]
+
+ # Fetch all interviews and their data
+ candidates_data = []
+ for iid in interview_ids:
+ interview = await _get_interview(db, iid)
+ if not interview:
+ continue
+ talent = await _get_talent_by_id(db, interview.candidate_id)
+ candidates_data.append({
+ "interview_id": iid,
+ "candidate_id": interview.candidate_id,
+ "candidate_name": talent.name if talent else interview.candidate_id,
+ "score": interview.ai_competency_score or 0,
+ "summary": interview.ai_summary or "",
+ "transcript": (interview.transcript_text or "")[:2000],
+ "analysis": interview.ai_performance_analysis or "",
+ })
+
+ if len(candidates_data) < 2:
+ return {"success": False, "error": "Tidak cukup data interview untuk perbandingan."}
+
+ # AI comparison via HIGH tier
+ ai_used = False
+ comparison_result = None
+ try:
+ candidates_text = ""
+ for c in candidates_data:
+ candidates_text += (
+ f"--- Kandidat: {c['candidate_name']} (ID: {c['candidate_id']}) ---\\n"
+ f"Skor Kompetensi: {c['score']}/100\\n"
+ f"Ringkasan: {c['summary'][:500]}\\n\\n"
+ )
+
+ prompt = (
+ f"Anda adalah AI Recruiter Brigawan, spesialis perbandingan kandidat.\\n\\n"
+ f"Bandingkan kandidat-kandidat berikut:\\n{candidates_text}\\n"
+ f"Buat analisis JSON: candidates[] dengan overall_score 0-100, competency_scores, strengths, weaknesses. Serta recommendation dan matrix_summary."
+ )
+ result = await call_high(prompt=prompt, temperature=0.3, max_output_tokens=3072)
+ if result:
+ cleaned = result.strip()
+ if cleaned.startswith("```json"):
+ cleaned = cleaned[7:]
+ if cleaned.startswith("```"):
+ cleaned = cleaned[3:]
+ if cleaned.endswith("```"):
+ cleaned = cleaned[:-3]
+ cleaned = cleaned.strip()
+ comparison_result = json.loads(cleaned)
+ ai_used = True
+ except Exception as e:
+ logger.error(f"Candidate comparison AI error: {e}")
+
+ if not comparison_result:
+ # Algorithmic fallback: sort by score
+ candidates_data.sort(key=lambda c: c["score"], reverse=True)
+ comparison_result = {
+ "candidates": [
+ {
+ "candidate_id": c["candidate_id"],
+ "candidate_name": c["candidate_name"],
+ "overall_score": c["score"],
+ "competency_scores": {"Umum": c["score"]},
+ "strengths": "Data terbatas",
+ "weaknesses": "Data terbatas",
+ }
+ for c in candidates_data
+ ],
+ "recommendation": f"Kandidat terbaik: {candidates_data[0]['candidate_name']} (skor {candidates_data[0]['score']}). Verifikasi manual diperlukan.",
+ "matrix_summary": f"Perbandingan {len(candidates_data)} kandidat berdasarkan skor kompetensi.",
+ }
+
+ return {
+ "success": True,
+ "candidates": comparison_result.get("candidates", []),
+ "recommendation": comparison_result.get("recommendation", ""),
+ "matrix_summary": comparison_result.get("matrix_summary", ""),
+ "ai_used": ai_used,
+ }
+
+ except Exception as e:
+ logger.error(f"compare_candidates error: {e}")
+ return {"success": False, "error": f"Gagal membandingkan kandidat: {str(e)}"}
+
+
+# =============================================================================
+# 6. LIST & DETAIL INTERVIEWS
+# =============================================================================
+
+async def list_interviews(
+ db: AsyncSession,
+ email: str,
+ status: Optional[str] = None,
+) -> dict:
+ """List all interviews for an employer, with optional status filter."""
+ try:
+ _, company = await _get_client_and_company(db, email)
+ if not company:
+ return {"success": False, "error": "Company not found."}
+
+ query = select(Interview).where(Interview.company_id == company.id)
+ if status:
+ query = query.where(Interview.status == status)
+ query = query.order_by(Interview.scheduled_time.desc())
+
+ result = await db.execute(query)
+ interviews = result.scalars().all()
+
+ data = []
+ for iv in interviews:
+ talent = await _get_talent_by_id(db, iv.candidate_id)
+ data.append({
+ "interview_id": str(iv.id),
+ "candidate_id": iv.candidate_id,
+ "candidate_name": talent.name if talent else iv.candidate_id,
+ "scheduled_time": iv.scheduled_time.isoformat() if iv.scheduled_time else None,
+ "status": iv.status or "Scheduled",
+ "has_transcript": bool(iv.transcript_text),
+ "has_ai_summary": bool(iv.ai_summary),
+ "competency_score": iv.ai_competency_score or 0,
+ "created_at": iv.created_at.isoformat() if iv.created_at else None,
+ })
+
+ return {
+ "success": True,
+ "data": data,
+ "total": len(data),
+ }
+
+ except Exception as e:
+ logger.error(f"list_interviews error: {e}")
+ return {"success": False, "error": str(e), "data": [], "total": 0}
+
+
+async def get_interview_detail(
+ db: AsyncSession,
+ interview_id: str,
+) -> dict:
+ """Get full interview detail including transcript, AI summary, and competency analysis."""
+ try:
+ interview = await _get_interview(db, interview_id)
+ if not interview:
+ return {"success": False, "error": "Interview tidak ditemukan."}
+
+ talent = await _get_talent_by_id(db, interview.candidate_id)
+
+ competency_analysis = None
+ if interview.ai_performance_analysis:
+ try:
+ competency_analysis = json.loads(interview.ai_performance_analysis)
+ except Exception:
+ competency_analysis = {"raw": interview.ai_performance_analysis}
+
+ return {
+ "success": True,
+ "data": {
+ "interview_id": str(interview.id),
+ "candidate_id": interview.candidate_id,
+ "candidate_name": talent.name if talent else interview.candidate_id,
+ "scheduled_time": interview.scheduled_time.isoformat() if interview.scheduled_time else None,
+ "status": interview.status or "Scheduled",
+ "has_transcript": bool(interview.transcript_text),
+ "has_ai_summary": bool(interview.ai_summary),
+ "competency_score": interview.ai_competency_score or 0,
+ "created_at": interview.created_at.isoformat() if interview.created_at else None,
+ },
+ "transcript": interview.transcript_text or "",
+ "ai_summary": interview.ai_summary or "",
+ "competency_analysis": competency_analysis,
+ }
+
+ except Exception as e:
+ logger.error(f"get_interview_detail error: {e}")
+ return {"success": False, "error": str(e)}
+
diff --git a/app/services/job_service.py b/app/services/job_service.py
index d1f30ec97db83b70cd6c9dd6ad1ea93c31fa84f6..774e7e56337ce3ba81da7aa311033c95e67291e8 100644
--- a/app/services/job_service.py
+++ b/app/services/job_service.py
@@ -1,288 +1,288 @@
-"""Job Service - Posting CRUD, Outreach, Compatibility, Limits, Vouchers."""
-
-import json
-import secrets
-from datetime import datetime, timezone
-
-from loguru import logger
-from sqlalchemy import func, select
-
-from app.models.job import JobPosting, RecruiterOutreach
-from app.models.employer import ClientAccount, Company
-from app.services.talent_service import get_talent_profile
-from app.config.settings import FINANCE_CONFIG
-from app.services.ai_service import call_medium
-
-TIERS = FINANCE_CONFIG.get("TIERS", {})
-OUTREACH_COST = FINANCE_CONFIG.get("DEDUCTION", {}).get("DIRECT_OUTREACH", 10)
-
-
-def _sanitize(val, max_len=500):
- if val is None:
- return ""
- return str(val).replace("<", "").replace(">", "").strip()[:max_len]
-
-
-async def get_job_posting(db, job_id):
-
- """Get single job posting (public-safe)."""
- try:
- if not job_id:
- return {"success": False, "error": "JobID tidak boleh kosong."}
- r = await db.execute(select(JobPosting).where(JobPosting.job_id == job_id).limit(1))
- job = r.scalar_one_or_none()
- if not job:
- return {"success": False, "error": "Lowongan tidak ditemukan."}
- skills = [s.strip() for s in (job.required_skills or "").split(",") if s.strip()]
- return {"success": True, "data": {
- "job_id": job.job_id, "title": job.title or "",
- "company_category": job.company_category or "Sustainability Sector",
- "location": job.location or "", "description": job.description or "",
- "required_skills": skills,
- "salary_range": job.salary_range or "Negotiable",
- "source": job.source or "", "status": job.status or "",
- "sector_match": job.sector_match or "",
- "linkedin_post_url": job.linkedin_post_url or "",
- "timestamp": job.timestamp.isoformat() if job.timestamp else None,
- "posted_at": job.posted_at.isoformat() if job.posted_at else None,
- }}
- except Exception as e:
- logger.error(f"get_job_posting error: {e}")
- return {"success": False, "error": str(e)}
-
-
-
-async def create_job_posting(db, employer_email, data):
- try:
- lc = await check_active_job_posting_limit(db, employer_email)
- if not lc.get("allowed"): return lc
- import uuid
- job_id = "JOB-" + secrets.token_hex(4).upper()
- now = datetime.now(timezone.utc)
- p = JobPosting(id=uuid.uuid4(), job_id=job_id,
- title=_sanitize(data.get("title",""),255), company_name=employer_email,
- company_category=_sanitize(data.get("company_category",""),255),
- location=_sanitize(data.get("location",""),255),
- description=_sanitize(data.get("description",""),10000),
- required_skills=_sanitize(data.get("required_skills",""),1000),
- salary_range=_sanitize(data.get("salary_range","Negotiable"),100),
- sector_match=_sanitize(data.get("sector_match",""),255),
- linkedin_post_url=_sanitize(data.get("linkedin_post_url",""),500),
- source="Employer Posting", status="posted", posted_at=now, timestamp=now, is_active=True)
- db.add(p); await db.commit()
- return {"success":True,"job_id":job_id,"message":"Lowongan berhasil dipublikasikan."}
- except Exception as e:
- logger.error(f"create_job_posting error: {e}")
- return {"success":False,"error":str(e)}
-
-
-
-async def get_job_postings(db, page=1, limit=10):
- try:
- p, lim = max(1, int(page)), max(1, min(50, int(limit)))
- r = await db.execute(
- select(JobPosting).where(JobPosting.status.in_(["posted", "analyzed"]))
- .order_by(JobPosting.timestamp.desc()).offset((p-1)*lim).limit(lim)
- )
- jobs = list(r.scalars().all())
- tr = await db.execute(select(func.count()).select_from(JobPosting).where(JobPosting.status.in_(["posted", "analyzed"])))
- total = tr.scalar() or 0
- return {"success": True, "page": p, "limit": lim, "total": total, "data": [
- {"job_id": j.job_id, "title": j.title,
- "company_category": j.company_category or "Sustainability Sector",
- "location": j.location,
- "description": (j.description or "")[:200] + "..." if j.description and len(j.description) > 200 else (j.description or ""),
- "required_skills": [s.strip() for s in (j.required_skills or "").split(",") if s.strip()],
- "salary_range": j.salary_range or "Negotiable",
- "status": j.status, "sector_match": j.sector_match or "",
- "timestamp": j.timestamp.isoformat() if j.timestamp else None}
- for j in jobs
- ]}
- except Exception as e:
- logger.error(f"get_job_postings error: {e}")
- return {"success": False, "error": str(e), "data": []}
-
-
-
-async def update_job_status(db, job_id, status):
- try:
- r = await db.execute(select(JobPosting).where(JobPosting.job_id==job_id).limit(1))
- job = r.scalar_one_or_none()
- if not job: return {"success":False,"error":"Lowongan tidak ditemukan."}
- valid = ["draft","posted","closed","archived"]
- if status not in valid: return {"success":False,"error":f"Status invalid. Use: {', '.join(valid)}"}
- job.status=status; job.is_active=(status=="posted")
- db.add(job); await db.commit()
- return {"success":True,"message":f"Status diubah menjadi {status}."}
- except Exception as e:
- logger.error(f"update_job_status error: {e}")
- return {"success":False,"error":str(e)}
-
-
-async def check_active_job_posting_limit(db, employer_email):
- try:
- e = employer_email.lower().strip()
- cr = await db.execute(select(ClientAccount).where(func.lower(ClientAccount.email)==e).limit(1))
- client = cr.scalar_one_or_none()
- tier_name = "free"
- if client and client.company_id:
- cor = await db.execute(select(Company).where(Company.id==client.company_id).limit(1))
- co = cor.scalar_one_or_none()
- if co: tier_name = (co.tier or "free").lower()
- tier = TIERS.get(tier_name, TIERS.get("free",{}))
- max_jobs = tier.get("max_jobs", 1) if isinstance(tier,dict) else 1
- if max_jobs == -1: return {"allowed":True,"tier":tier_name,"active_count":0,"limit":-1}
- nr = await db.execute(select(func.count()).select_from(JobPosting).where(JobPosting.company_name==e,JobPosting.status.in_(["posted","analyzed"])))
- active = nr.scalar() or 0
- 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."}
- return {"allowed":True,"tier":tier_name,"active_count":active,"limit":max_jobs}
- except Exception as e:
- logger.error(f"check_job_limit error: {e}")
- return {"allowed":True,"tier":"free","active_count":0,"limit":1}
-
-
-
-async def analyze_job_compatibility(db, email, job_id):
- """Refactored: Uses Antigravity gateway for semantic matching."""
- try:
- if not email or not job_id:
- return {"success": False, "error": "Parameter tidak lengkap."}
-
- e = email.lower().strip()
- pr = await get_talent_profile(db, e)
- if not pr.get("success"):
- return {"success": False, "error": "Gagal memuat profil talent."}
- p = pr["data"]
-
- jr = await get_job_posting(db, job_id)
- if not jr.get("success"):
- return {"success": False, "error": "Gagal memuat pekerjaan."}
- j = jr["data"]
-
- # Use Antigravity Orchestrator
- from app.services.antigravity import AntigravityOrchestrator
- orchestrator = AntigravityOrchestrator(db)
-
- payload = {
- "query": j.get("title", ""),
- "talent_data": {
- "skill_tags": ",".join(p.get("skills", [])),
- "experience": p.get("experience", ""),
- "sector_focus": p.get("sector_focus", ""),
- "location": p.get("location", "")
- }
- }
-
- res = await orchestrator.execute_task(
- agent_name="RecruiterStrategicAdvisor",
- task_name="semantic_matching",
- payload=payload,
- user_email=email
- )
-
- if res.get("status") == "success":
- data = res["data"]
- return {
- "success": True,
- "data": {
- "matchScore": data.get("score", 0),
- "matchedSkills": [], # Will be implemented in Pro prompt refinement
- "gapSkills": [],
- "strategy": data.get("summary", ""),
- "ai_used": data.get("ai_used", True)
- }
- }
-
- return {"success": False, "error": "AI processing failed"}
-
- except Exception as e:
- logger.error(f"analyze_job error: {e}")
- return {"success": False, "error": str(e)}
-
-
-
-async def record_pending_outreach(db, job_id, talent_email, match_score, recruiter_email, method, subject, body):
- try:
- import uuid
- oid = f"RO-{secrets.randbelow(89999) + 10001}"
- o = RecruiterOutreach(id=uuid.uuid4(), outreach_id=oid, job_id=job_id,
- talent_email=talent_email, match_score=match_score, recruiter_email=recruiter_email,
- contact_method=method, outreach_subject=subject, outreach_body=body,
- status="pending_approval", triggered_at=datetime.now(timezone.utc))
- db.add(o); await db.commit()
- return {"success":True,"outreach_id":oid}
- except Exception as e:
- logger.error(f"record_outreach error: {e}")
- return {"success":False,"error":str(e)}
-
-
-async def send_instant_outreach(db, recruiter_email, job_id, talent_email, match_score, method, subject, body):
- try:
- from app.services.employer_service import deduct_coins
- dr = await deduct_coins(db, recruiter_email, OUTREACH_COST, "Outreach", f"To: {talent_email}")
- if not dr.get("success"): return {"success":False,"error":dr.get("error","Gagal potong koin.")}
- import uuid; now = datetime.now(timezone.utc)
- oid = f"RO-{secrets.randbelow(89999) + 10001}"
- o = RecruiterOutreach(id=uuid.uuid4(), outreach_id=oid, job_id=job_id,
- talent_email=talent_email, match_score=match_score, recruiter_email=recruiter_email,
- contact_method=method, outreach_subject=subject, outreach_body=body,
- status="sent", triggered_at=now, sent_at=now)
- db.add(o); await db.commit()
- return {"success":True,"outreach_id":oid,"remaining":dr.get("remaining",0)}
- except Exception as e:
- logger.error(f"send_outreach error: {e}")
- return {"success":False,"error":str(e)}
-
-async def list_outreach_history(db, recruiter_email):
- try:
- r = await db.execute(select(RecruiterOutreach).where(func.lower(RecruiterOutreach.recruiter_email)==recruiter_email.lower().strip()).order_by(RecruiterOutreach.triggered_at.desc()).limit(50))
- 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())]}
- except Exception as e:
- logger.error(f"outreach_history error: {e}")
- return {"success":False,"error":str(e),"data":[]}
-
-
-
-async def generate_vouchers(db, lpk_id, quantity):
- CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
- try:
- qty = max(1, min(100, int(quantity)))
- now = datetime.now(timezone.utc); codes = []
- for _ in range(qty):
- code = "BRG-LPK-" + "".join(CHARS[secrets.randbelow(36)] for _ in range(8))
- import uuid
- db.add(RecruiterOutreach(id=uuid.uuid4(), outreach_id=code, recruiter_email=lpk_id, contact_method="voucher", status="Available", triggered_at=now))
- codes.append(code)
- await db.commit()
- return {"success":True,"message":f"{qty} voucher berhasil dibuat.","vouchers":codes,"count":qty}
- except Exception as e:
- logger.error(f"generate_vouchers error: {e}")
- return {"success":False,"error":str(e)}
-
-
-async def redeem_voucher(db, email, candidate_email, voucher_code):
- try:
- if email.lower().strip() != candidate_email.lower().strip(): return {"success":False,"error":"Email tidak cocok."}
- code = voucher_code.upper().strip()
- r = await db.execute(select(RecruiterOutreach).where(RecruiterOutreach.outreach_id==code,RecruiterOutreach.status=="Available").limit(1))
- v = r.scalar_one_or_none()
- if not v: return {"success":False,"error":"Voucher tidak valid."}
- lpk_id = v.recruiter_email; now = datetime.now(timezone.utc)
- v.status,v.talent_email,v.sent_at = "Used",candidate_email.lower().strip(),now
- db.add(v); await db.commit()
- return {"success":True,"message":"Voucher berhasil diaktifkan.","lpk_id":lpk_id,"voucher_code":code}
- except Exception as e:
- logger.error(f"redeem_voucher error: {e}")
- return {"success":False,"error":str(e)}
-
-
-async def get_lpk_vouchers(db, lpk_id):
- try:
- r = await db.execute(select(RecruiterOutreach).where(RecruiterOutreach.recruiter_email==lpk_id,RecruiterOutreach.contact_method=="voucher").order_by(RecruiterOutreach.triggered_at.desc()))
- vouchers = list(r.scalars().all())
- avail = sum(1 for v in vouchers if v.status=="Available")
- used = sum(1 for v in vouchers if v.status=="Used")
- 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)}}
- except Exception as e:
- logger.error(f"get_lpk_vouchers error: {e}")
- return {"success":False,"error":str(e),"vouchers":[],"counts":{"Available":0,"Used":0,"Total":0}}
+"""Job Service - Posting CRUD, Outreach, Compatibility, Limits, Vouchers."""
+
+import json
+import secrets
+from datetime import datetime, timezone
+
+from loguru import logger
+from sqlalchemy import func, select
+
+from app.models.job import JobPosting, RecruiterOutreach
+from app.models.employer import ClientAccount, Company
+from app.services.talent_service import get_talent_profile
+from app.config.settings import FINANCE_CONFIG
+from app.services.ai_service import call_medium
+
+TIERS = FINANCE_CONFIG.get("TIERS", {})
+OUTREACH_COST = FINANCE_CONFIG.get("DEDUCTION", {}).get("DIRECT_OUTREACH", 10)
+
+
+def _sanitize(val, max_len=500):
+ if val is None:
+ return ""
+ return str(val).replace("<", "").replace(">", "").strip()[:max_len]
+
+
+async def get_job_posting(db, job_id):
+
+ """Get single job posting (public-safe)."""
+ try:
+ if not job_id:
+ return {"success": False, "error": "JobID tidak boleh kosong."}
+ r = await db.execute(select(JobPosting).where(JobPosting.job_id == job_id).limit(1))
+ job = r.scalar_one_or_none()
+ if not job:
+ return {"success": False, "error": "Lowongan tidak ditemukan."}
+ skills = [s.strip() for s in (job.required_skills or "").split(",") if s.strip()]
+ return {"success": True, "data": {
+ "job_id": job.job_id, "title": job.title or "",
+ "company_category": job.company_category or "Sustainability Sector",
+ "location": job.location or "", "description": job.description or "",
+ "required_skills": skills,
+ "salary_range": job.salary_range or "Negotiable",
+ "source": job.source or "", "status": job.status or "",
+ "sector_match": job.sector_match or "",
+ "linkedin_post_url": job.linkedin_post_url or "",
+ "timestamp": job.timestamp.isoformat() if job.timestamp else None,
+ "posted_at": job.posted_at.isoformat() if job.posted_at else None,
+ }}
+ except Exception as e:
+ logger.error(f"get_job_posting error: {e}")
+ return {"success": False, "error": str(e)}
+
+
+
+async def create_job_posting(db, employer_email, data):
+ try:
+ lc = await check_active_job_posting_limit(db, employer_email)
+ if not lc.get("allowed"): return lc
+ import uuid
+ job_id = "JOB-" + secrets.token_hex(4).upper()
+ now = datetime.now(timezone.utc)
+ p = JobPosting(id=uuid.uuid4(), job_id=job_id,
+ title=_sanitize(data.get("title",""),255), company_name=employer_email,
+ company_category=_sanitize(data.get("company_category",""),255),
+ location=_sanitize(data.get("location",""),255),
+ description=_sanitize(data.get("description",""),10000),
+ required_skills=_sanitize(data.get("required_skills",""),1000),
+ salary_range=_sanitize(data.get("salary_range","Negotiable"),100),
+ sector_match=_sanitize(data.get("sector_match",""),255),
+ linkedin_post_url=_sanitize(data.get("linkedin_post_url",""),500),
+ source="Employer Posting", status="posted", posted_at=now, timestamp=now, is_active=True)
+ db.add(p); await db.commit()
+ return {"success":True,"job_id":job_id,"message":"Lowongan berhasil dipublikasikan."}
+ except Exception as e:
+ logger.error(f"create_job_posting error: {e}")
+ return {"success":False,"error":str(e)}
+
+
+
+async def get_job_postings(db, page=1, limit=10):
+ try:
+ p, lim = max(1, int(page)), max(1, min(50, int(limit)))
+ r = await db.execute(
+ select(JobPosting).where(JobPosting.status.in_(["posted", "analyzed"]))
+ .order_by(JobPosting.timestamp.desc()).offset((p-1)*lim).limit(lim)
+ )
+ jobs = list(r.scalars().all())
+ tr = await db.execute(select(func.count()).select_from(JobPosting).where(JobPosting.status.in_(["posted", "analyzed"])))
+ total = tr.scalar() or 0
+ return {"success": True, "page": p, "limit": lim, "total": total, "data": [
+ {"job_id": j.job_id, "title": j.title,
+ "company_category": j.company_category or "Sustainability Sector",
+ "location": j.location,
+ "description": (j.description or "")[:200] + "..." if j.description and len(j.description) > 200 else (j.description or ""),
+ "required_skills": [s.strip() for s in (j.required_skills or "").split(",") if s.strip()],
+ "salary_range": j.salary_range or "Negotiable",
+ "status": j.status, "sector_match": j.sector_match or "",
+ "timestamp": j.timestamp.isoformat() if j.timestamp else None}
+ for j in jobs
+ ]}
+ except Exception as e:
+ logger.error(f"get_job_postings error: {e}")
+ return {"success": False, "error": str(e), "data": []}
+
+
+
+async def update_job_status(db, job_id, status):
+ try:
+ r = await db.execute(select(JobPosting).where(JobPosting.job_id==job_id).limit(1))
+ job = r.scalar_one_or_none()
+ if not job: return {"success":False,"error":"Lowongan tidak ditemukan."}
+ valid = ["draft","posted","closed","archived"]
+ if status not in valid: return {"success":False,"error":f"Status invalid. Use: {', '.join(valid)}"}
+ job.status=status; job.is_active=(status=="posted")
+ db.add(job); await db.commit()
+ return {"success":True,"message":f"Status diubah menjadi {status}."}
+ except Exception as e:
+ logger.error(f"update_job_status error: {e}")
+ return {"success":False,"error":str(e)}
+
+
+async def check_active_job_posting_limit(db, employer_email):
+ try:
+ e = employer_email.lower().strip()
+ cr = await db.execute(select(ClientAccount).where(func.lower(ClientAccount.email)==e).limit(1))
+ client = cr.scalar_one_or_none()
+ tier_name = "free"
+ if client and client.company_id:
+ cor = await db.execute(select(Company).where(Company.id==client.company_id).limit(1))
+ co = cor.scalar_one_or_none()
+ if co: tier_name = (co.tier or "free").lower()
+ tier = TIERS.get(tier_name, TIERS.get("free",{}))
+ max_jobs = tier.get("max_jobs", 1) if isinstance(tier,dict) else 1
+ if max_jobs == -1: return {"allowed":True,"tier":tier_name,"active_count":0,"limit":-1}
+ nr = await db.execute(select(func.count()).select_from(JobPosting).where(JobPosting.company_name==e,JobPosting.status.in_(["posted","analyzed"])))
+ active = nr.scalar() or 0
+ 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."}
+ return {"allowed":True,"tier":tier_name,"active_count":active,"limit":max_jobs}
+ except Exception as e:
+ logger.error(f"check_job_limit error: {e}")
+ return {"allowed":True,"tier":"free","active_count":0,"limit":1}
+
+
+
+async def analyze_job_compatibility(db, email, job_id):
+ """Refactored: Uses Antigravity gateway for semantic matching."""
+ try:
+ if not email or not job_id:
+ return {"success": False, "error": "Parameter tidak lengkap."}
+
+ e = email.lower().strip()
+ pr = await get_talent_profile(db, e)
+ if not pr.get("success"):
+ return {"success": False, "error": "Gagal memuat profil talent."}
+ p = pr["data"]
+
+ jr = await get_job_posting(db, job_id)
+ if not jr.get("success"):
+ return {"success": False, "error": "Gagal memuat pekerjaan."}
+ j = jr["data"]
+
+ # Use Antigravity Orchestrator
+ from app.services.antigravity import AntigravityOrchestrator
+ orchestrator = AntigravityOrchestrator(db)
+
+ payload = {
+ "query": j.get("title", ""),
+ "talent_data": {
+ "skill_tags": ",".join(p.get("skills", [])),
+ "experience": p.get("experience", ""),
+ "sector_focus": p.get("sector_focus", ""),
+ "location": p.get("location", "")
+ }
+ }
+
+ res = await orchestrator.execute_task(
+ agent_name="RecruiterStrategicAdvisor",
+ task_name="semantic_matching",
+ payload=payload,
+ user_email=email
+ )
+
+ if res.get("status") == "success":
+ data = res["data"]
+ return {
+ "success": True,
+ "data": {
+ "matchScore": data.get("score", 0),
+ "matchedSkills": [], # Will be implemented in Pro prompt refinement
+ "gapSkills": [],
+ "strategy": data.get("summary", ""),
+ "ai_used": data.get("ai_used", True)
+ }
+ }
+
+ return {"success": False, "error": "AI processing failed"}
+
+ except Exception as e:
+ logger.error(f"analyze_job error: {e}")
+ return {"success": False, "error": str(e)}
+
+
+
+async def record_pending_outreach(db, job_id, talent_email, match_score, recruiter_email, method, subject, body):
+ try:
+ import uuid
+ oid = f"RO-{secrets.randbelow(89999) + 10001}"
+ o = RecruiterOutreach(id=uuid.uuid4(), outreach_id=oid, job_id=job_id,
+ talent_email=talent_email, match_score=match_score, recruiter_email=recruiter_email,
+ contact_method=method, outreach_subject=subject, outreach_body=body,
+ status="pending_approval", triggered_at=datetime.now(timezone.utc))
+ db.add(o); await db.commit()
+ return {"success":True,"outreach_id":oid}
+ except Exception as e:
+ logger.error(f"record_outreach error: {e}")
+ return {"success":False,"error":str(e)}
+
+
+async def send_instant_outreach(db, recruiter_email, job_id, talent_email, match_score, method, subject, body):
+ try:
+ from app.services.employer_service import deduct_coins
+ dr = await deduct_coins(db, recruiter_email, OUTREACH_COST, "Outreach", f"To: {talent_email}")
+ if not dr.get("success"): return {"success":False,"error":dr.get("error","Gagal potong koin.")}
+ import uuid; now = datetime.now(timezone.utc)
+ oid = f"RO-{secrets.randbelow(89999) + 10001}"
+ o = RecruiterOutreach(id=uuid.uuid4(), outreach_id=oid, job_id=job_id,
+ talent_email=talent_email, match_score=match_score, recruiter_email=recruiter_email,
+ contact_method=method, outreach_subject=subject, outreach_body=body,
+ status="sent", triggered_at=now, sent_at=now)
+ db.add(o); await db.commit()
+ return {"success":True,"outreach_id":oid,"remaining":dr.get("remaining",0)}
+ except Exception as e:
+ logger.error(f"send_outreach error: {e}")
+ return {"success":False,"error":str(e)}
+
+async def list_outreach_history(db, recruiter_email):
+ try:
+ r = await db.execute(select(RecruiterOutreach).where(func.lower(RecruiterOutreach.recruiter_email)==recruiter_email.lower().strip()).order_by(RecruiterOutreach.triggered_at.desc()).limit(50))
+ 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())]}
+ except Exception as e:
+ logger.error(f"outreach_history error: {e}")
+ return {"success":False,"error":str(e),"data":[]}
+
+
+
+async def generate_vouchers(db, lpk_id, quantity):
+ CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ try:
+ qty = max(1, min(100, int(quantity)))
+ now = datetime.now(timezone.utc); codes = []
+ for _ in range(qty):
+ code = "BRG-LPK-" + "".join(CHARS[secrets.randbelow(36)] for _ in range(8))
+ import uuid
+ db.add(RecruiterOutreach(id=uuid.uuid4(), outreach_id=code, recruiter_email=lpk_id, contact_method="voucher", status="Available", triggered_at=now))
+ codes.append(code)
+ await db.commit()
+ return {"success":True,"message":f"{qty} voucher berhasil dibuat.","vouchers":codes,"count":qty}
+ except Exception as e:
+ logger.error(f"generate_vouchers error: {e}")
+ return {"success":False,"error":str(e)}
+
+
+async def redeem_voucher(db, email, candidate_email, voucher_code):
+ try:
+ if email.lower().strip() != candidate_email.lower().strip(): return {"success":False,"error":"Email tidak cocok."}
+ code = voucher_code.upper().strip()
+ r = await db.execute(select(RecruiterOutreach).where(RecruiterOutreach.outreach_id==code,RecruiterOutreach.status=="Available").limit(1))
+ v = r.scalar_one_or_none()
+ if not v: return {"success":False,"error":"Voucher tidak valid."}
+ lpk_id = v.recruiter_email; now = datetime.now(timezone.utc)
+ v.status,v.talent_email,v.sent_at = "Used",candidate_email.lower().strip(),now
+ db.add(v); await db.commit()
+ return {"success":True,"message":"Voucher berhasil diaktifkan.","lpk_id":lpk_id,"voucher_code":code}
+ except Exception as e:
+ logger.error(f"redeem_voucher error: {e}")
+ return {"success":False,"error":str(e)}
+
+
+async def get_lpk_vouchers(db, lpk_id):
+ try:
+ r = await db.execute(select(RecruiterOutreach).where(RecruiterOutreach.recruiter_email==lpk_id,RecruiterOutreach.contact_method=="voucher").order_by(RecruiterOutreach.triggered_at.desc()))
+ vouchers = list(r.scalars().all())
+ avail = sum(1 for v in vouchers if v.status=="Available")
+ used = sum(1 for v in vouchers if v.status=="Used")
+ 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)}}
+ except Exception as e:
+ logger.error(f"get_lpk_vouchers error: {e}")
+ return {"success":False,"error":str(e),"vouchers":[],"counts":{"Available":0,"Used":0,"Total":0}}
diff --git a/app/services/kms_service.py b/app/services/kms_service.py
index 922d14a71e1067e0cd52844ba3e59cd8653d5e68..70e906825b9e307ac4ca26ddc1fbebe9476455f5 100644
--- a/app/services/kms_service.py
+++ b/app/services/kms_service.py
@@ -1,82 +1,82 @@
-"""KMS Service for Key Encryption Key (KEK) management.
-
-Provides an abstraction for Google Cloud KMS to encrypt/decrypt profile DEKs.
-Supports local fallback for development environments.
-"""
-
-import base64
-import os
-from typing import Optional
-from loguru import logger
-
-from app.config.settings import settings
-
-try:
- from google.cloud import kms
- GCP_KMS_AVAILABLE = True
-except ImportError:
- GCP_KMS_AVAILABLE = False
-
-
-class KMSService:
- """Service to interact with Google Cloud KMS or local simulation."""
-
- def __init__(self):
- self.project_id = settings.gcp_project_id
- self.location_id = settings.gcp_kms_location
- self.key_ring_id = settings.gcp_kms_key_ring
- self.key_id = settings.gcp_kms_key_id
-
- # Local fallback key
- self.local_master_key = settings.master_encryption_key.encode("utf-8")[:32]
-
- self.client = None
- if GCP_KMS_AVAILABLE and self.project_id:
- try:
- self.client = kms.KeyManagementServiceClient()
- self.key_name = self.client.encrypt_path(
- self.project_id, self.location_id, self.key_ring_id, self.key_id
- )
- logger.info(f"KMS Service initialized with GCP KMS: {self.key_name}")
- except Exception as e:
- logger.warning(f"Failed to initialize GCP KMS client: {e}. Falling back to local.")
- else:
- logger.info("KMS Service using local simulation (dev mode).")
-
- def encrypt_dek(self, plaintext_dek: str) -> str:
- """Encrypt a profile's Data Encryption Key (DEK)."""
- if self.client and self.project_id:
- try:
- response = self.client.encrypt(
- request={"name": self.key_name, "plaintext": plaintext_dek.encode("utf-8")}
- )
- return base64.b64encode(response.ciphertext).decode("utf-8")
- except Exception as e:
- logger.error(f"GCP KMS encryption failed: {e}")
- raise
-
- # Local simulation (AES-256-CBC)
- from app.services.security_service import SecurityService
- sim = SecurityService()
- return sim._encrypt_with_dek(self.local_master_key, plaintext_dek)
-
- def decrypt_dek(self, encrypted_dek: str) -> str:
- """Decrypt a profile's Data Encryption Key (DEK)."""
- if self.client and self.project_id:
- try:
- ciphertext = base64.b64decode(encrypted_dek)
- response = self.client.decrypt(
- request={"name": self.key_name, "ciphertext": ciphertext}
- )
- return response.plaintext.decode("utf-8")
- except Exception as e:
- logger.error(f"GCP KMS decryption failed: {e}")
- raise
-
- # Local simulation
- from app.services.security_service import SecurityService
- sim = SecurityService()
- return sim._decrypt_with_dek(self.local_master_key, encrypted_dek)
-
-
-kms_service = KMSService()
+"""KMS Service for Key Encryption Key (KEK) management.
+
+Provides an abstraction for Google Cloud KMS to encrypt/decrypt profile DEKs.
+Supports local fallback for development environments.
+"""
+
+import base64
+import os
+from typing import Optional
+from loguru import logger
+
+from app.config.settings import settings
+
+try:
+ from google.cloud import kms
+ GCP_KMS_AVAILABLE = True
+except ImportError:
+ GCP_KMS_AVAILABLE = False
+
+
+class KMSService:
+ """Service to interact with Google Cloud KMS or local simulation."""
+
+ def __init__(self):
+ self.project_id = settings.gcp_project_id
+ self.location_id = settings.gcp_kms_location
+ self.key_ring_id = settings.gcp_kms_key_ring
+ self.key_id = settings.gcp_kms_key_id
+
+ # Local fallback key
+ self.local_master_key = settings.master_encryption_key.encode("utf-8")[:32]
+
+ self.client = None
+ if GCP_KMS_AVAILABLE and self.project_id:
+ try:
+ self.client = kms.KeyManagementServiceClient()
+ self.key_name = self.client.encrypt_path(
+ self.project_id, self.location_id, self.key_ring_id, self.key_id
+ )
+ logger.info(f"KMS Service initialized with GCP KMS: {self.key_name}")
+ except Exception as e:
+ logger.warning(f"Failed to initialize GCP KMS client: {e}. Falling back to local.")
+ else:
+ logger.info("KMS Service using local simulation (dev mode).")
+
+ def encrypt_dek(self, plaintext_dek: str) -> str:
+ """Encrypt a profile's Data Encryption Key (DEK)."""
+ if self.client and self.project_id:
+ try:
+ response = self.client.encrypt(
+ request={"name": self.key_name, "plaintext": plaintext_dek.encode("utf-8")}
+ )
+ return base64.b64encode(response.ciphertext).decode("utf-8")
+ except Exception as e:
+ logger.error(f"GCP KMS encryption failed: {e}")
+ raise
+
+ # Local simulation (AES-256-CBC)
+ from app.services.security_service import SecurityService
+ sim = SecurityService()
+ return sim._encrypt_with_dek(self.local_master_key, plaintext_dek)
+
+ def decrypt_dek(self, encrypted_dek: str) -> str:
+ """Decrypt a profile's Data Encryption Key (DEK)."""
+ if self.client and self.project_id:
+ try:
+ ciphertext = base64.b64decode(encrypted_dek)
+ response = self.client.decrypt(
+ request={"name": self.key_name, "ciphertext": ciphertext}
+ )
+ return response.plaintext.decode("utf-8")
+ except Exception as e:
+ logger.error(f"GCP KMS decryption failed: {e}")
+ raise
+
+ # Local simulation
+ from app.services.security_service import SecurityService
+ sim = SecurityService()
+ return sim._decrypt_with_dek(self.local_master_key, encrypted_dek)
+
+
+kms_service = KMSService()
diff --git a/app/services/orchestrator_service.py b/app/services/orchestrator_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..abea8c6e286ada216a4699a1520a506cd9620964
--- /dev/null
+++ b/app/services/orchestrator_service.py
@@ -0,0 +1,69 @@
+"""Orchestrator Service — The AI Boardroom.
+
+This service acts as the gateway for the 'Board' (User) to interact with
+the Brigawan AI Organization. It uses the CEO Agent to orchestrate
+delegation across the hierarchy.
+"""
+
+from typing import Any, Dict, List, Optional
+from loguru import logger
+from app.services.agent_service import call_agent_json, call_agent
+
+class Orchestrator:
+ """Orchestrates multi-agent tasks starting from the CEO level."""
+
+ @classmethod
+ async def process_board_directive(cls, directive: str) -> Dict[str, Any]:
+ """Process a high-level directive from the Board (User).
+
+ Flow:
+ 1. CEO analyzes the directive.
+ 2. CEO decides whether to execute directly or delegate.
+ 3. CEO provides a strategy or delegation plan.
+ """
+ logger.info(f"[Orchestrator] Processing Board directive: {directive[:100]}...")
+
+ # 1. Ask CEO to analyze and delegate
+ orchestration_prompt = (
+ f"Sebagai CEO Brigawan, analisalah instruksi dari Board berikut ini: '{directive}'.\n\n"
+ "Tentukan strategi eksekusi. Jika instruksi bersifat teknis, delegasikan ke agen yang relevan (misal: cto-agent, vp-engineering).\n"
+ "Berikan respon dalam format JSON:\n"
+ "{\n"
+ " \"analysis\": \"Analisis singkat tentang instruksi\",\n"
+ " \"strategy\": \"Langkah-langkah strategis\",\n"
+ " \"delegate_to\": \"ID agen atau null jika ditangani sendiri\",\n"
+ " \"action_items\": [\"List instruksi spesifik untuk delegasi\"],\n"
+ " \"priority\": \"URGENT | HIGH | MEDIUM | LOW\"\n"
+ "}"
+ )
+
+ ceo_resp = await call_agent_json("ceo-agent", orchestration_prompt)
+ if not ceo_resp["success"]:
+ return ceo_resp
+
+ plan = ceo_resp["data"]
+ delegate_id = plan.get("delegate_to")
+
+ # 2. If delegation is needed, call the next agent in the hierarchy
+ if delegate_id:
+ logger.info(f"[Orchestrator] CEO delegating task to: {delegate_id}")
+ delegation_context = f"Instruksi asli dari Board: {directive}\nStrategi CEO: {plan['strategy']}"
+
+ # Execute delegation
+ agent_resp = await call_agent(
+ agent_id=delegate_id,
+ user_input="\n".join(plan.get("action_items", [])),
+ context=delegation_context
+ )
+
+ return {
+ "success": True,
+ "ceo_plan": plan,
+ "execution_result": agent_resp
+ }
+
+ return {
+ "success": True,
+ "ceo_plan": plan,
+ "execution_result": "Ditangani langsung oleh CEO."
+ }
diff --git a/app/services/organization_service.py b/app/services/organization_service.py
index 47122ab9f3bb8cab2bd0fd2130af3c185cae17c7..e277b264a1f6839f1d6dcba437721849b3a1d2b3 100644
--- a/app/services/organization_service.py
+++ b/app/services/organization_service.py
@@ -1,85 +1,85 @@
-"""Organization service for PKI and signature verification.
-
-Handles digital signature verification for credentials and organization key management.
-Uses Ed25519 for high-security, lightweight signatures.
-"""
-
-import base64
-from typing import Optional
-from uuid import UUID
-
-from cryptography.hazmat.primitives import serialization
-from cryptography.hazmat.primitives.asymmetric import ed25519
-from loguru import logger
-from sqlalchemy import select
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.models.career import Organization
-
-
-class OrganizationService:
- """Service for managing organization trust and PKI."""
-
- async def verify_credential_signature(
- self,
- db: AsyncSession,
- organization_id: UUID,
- payload_hash: str,
- signature_base64: str
- ) -> bool:
- """
- Verify that a credential's payload hash was signed by the organization's private key.
- """
- # 1. Fetch Organization Public Key
- result = await db.execute(select(Organization).where(Organization.id == organization_id))
- org = result.scalars().first()
-
- if not org or not org.public_key:
- logger.warning(f"Verification failed: Organization {organization_id} has no public key.")
- return False
-
- try:
- # 2. Load Public Key
- public_key = serialization.load_pem_public_key(org.public_key.encode("utf-8"))
-
- # 3. Decode Signature
- signature = base64.b64decode(signature_base64)
-
- # 4. Verify
- # Note: For Ed25519, we verify the data itself or the hash.
- # The blueprint uses the hash of the encrypted payload in the audit trail.
- # Here we verify the payload_hash string as the message.
- public_key.verify(signature, payload_hash.encode("utf-8"))
-
- logger.info(f"Credential signature verified for org {org.name}")
- return True
- except Exception as e:
- logger.error(f"Signature verification error: {e}")
- return False
-
- def generate_org_keypair(self) -> dict:
- """
- Utility for generating a new Ed25519 keypair for an organization.
- Returns PEM strings for both keys.
- """
- private_key = ed25519.Ed25519PrivateKey.generate()
- public_key = private_key.public_key()
-
- private_pem = private_key.private_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PrivateFormat.PKCS8,
- encryption_algorithm=serialization.NoEncryption()
- )
-
- public_pem = public_key.public_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PublicFormat.SubjectPublicKeyInfo
- )
-
- return {
- "private_key": private_pem.decode("utf-8"),
- "public_key": public_pem.decode("utf-8")
- }
-
-
-organization_service = OrganizationService()
+"""Organization service for PKI and signature verification.
+
+Handles digital signature verification for credentials and organization key management.
+Uses Ed25519 for high-security, lightweight signatures.
+"""
+
+import base64
+from typing import Optional
+from uuid import UUID
+
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import ed25519
+from loguru import logger
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.career import Organization
+
+
+class OrganizationService:
+ """Service for managing organization trust and PKI."""
+
+ async def verify_credential_signature(
+ self,
+ db: AsyncSession,
+ organization_id: UUID,
+ payload_hash: str,
+ signature_base64: str
+ ) -> bool:
+ """
+ Verify that a credential's payload hash was signed by the organization's private key.
+ """
+ # 1. Fetch Organization Public Key
+ result = await db.execute(select(Organization).where(Organization.id == organization_id))
+ org = result.scalars().first()
+
+ if not org or not org.public_key:
+ logger.warning(f"Verification failed: Organization {organization_id} has no public key.")
+ return False
+
+ try:
+ # 2. Load Public Key
+ public_key = serialization.load_pem_public_key(org.public_key.encode("utf-8"))
+
+ # 3. Decode Signature
+ signature = base64.b64decode(signature_base64)
+
+ # 4. Verify
+ # Note: For Ed25519, we verify the data itself or the hash.
+ # The blueprint uses the hash of the encrypted payload in the audit trail.
+ # Here we verify the payload_hash string as the message.
+ public_key.verify(signature, payload_hash.encode("utf-8"))
+
+ logger.info(f"Credential signature verified for org {org.name}")
+ return True
+ except Exception as e:
+ logger.error(f"Signature verification error: {e}")
+ return False
+
+ def generate_org_keypair(self) -> dict:
+ """
+ Utility for generating a new Ed25519 keypair for an organization.
+ Returns PEM strings for both keys.
+ """
+ private_key = ed25519.Ed25519PrivateKey.generate()
+ public_key = private_key.public_key()
+
+ private_pem = private_key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption()
+ )
+
+ public_pem = public_key.public_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PublicFormat.SubjectPublicKeyInfo
+ )
+
+ return {
+ "private_key": private_pem.decode("utf-8"),
+ "public_key": public_pem.decode("utf-8")
+ }
+
+
+organization_service = OrganizationService()
diff --git a/app/services/phrasing_audit_service.py b/app/services/phrasing_audit_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b4e72d9769328a2c302492c2da176b68265b89a
--- /dev/null
+++ b/app/services/phrasing_audit_service.py
@@ -0,0 +1,31 @@
+import re
+from typing import Tuple
+
+BANNED_PATTERNS = [r"as an ai", r"in conclusion", r"to summarize", r"ultimately"]
+
+
+def audit_text(text: str) -> Tuple[bool, dict]:
+ """Return (passes: bool, details: dict).
+
+ details contains flags and detected phrases.
+ """
+ lowered = text.lower()
+ found = []
+ for p in BANNED_PATTERNS:
+ if re.search(p, lowered):
+ found.append(p)
+
+ # Simple readability proxy: average sentence length
+ sentences = re.split(r'[\.\?\!]+', text)
+ sentences = [s.strip() for s in sentences if s.strip()]
+ avg_len = 0
+ if sentences:
+ avg_len = sum(len(s.split()) for s in sentences) / len(sentences)
+
+ passes = len(found) == 0 and 8 <= avg_len <= 25
+ return passes, {"found_phrases": found, "avg_sentence_length": avg_len}
+
+
+def require_rewrite(text: str) -> bool:
+ passes, details = audit_text(text)
+ return not passes
diff --git a/app/services/sales_pipeline_service.py b/app/services/sales_pipeline_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..d57db1a190630083e367649aedf252d03277d866
--- /dev/null
+++ b/app/services/sales_pipeline_service.py
@@ -0,0 +1,115 @@
+"""Autonomous Sales Pipeline Service — The AI Revenue Engine.
+
+This service orchestrates the B2B outbound sales workflow.
+It finds top-tier unplaced talents, researches matching companies,
+and sends hyper-personalized cold outreach emails.
+"""
+
+import json
+import asyncio
+from typing import List, Dict, Any
+from loguru import logger
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.services.agent_service import call_agent_json
+from app.services.email_service import email_service
+from app.database import get_db_session # We will need a standalone session generator or pass it
+from app.models.talent import Talent
+
+class AutonomousSalesService:
+ """Manages proactive B2B outreach and partnership building."""
+
+ @classmethod
+ async def run_daily_outreach(cls, target_email: str, company_name: str, niche: str):
+ """
+ Executes a targeted outreach campaign.
+ In a full system, this would automatically loop over a list of scraped leads.
+ """
+ logger.info(f"[AutonomousSales] Starting outbound campaign to {company_name} ({target_email})...")
+
+ # 1. Find Top Talent in the Niche
+ # We simulate grabbing the top 1 talent for this specific niche
+ talent_data = await cls._find_top_talent_for_niche(niche)
+ if not talent_data:
+ logger.warning(f"[AutonomousSales] No suitable talents found for {niche}. Aborting outreach.")
+ return {"success": False, "message": "No talents available"}
+
+ logger.info(f"[AutonomousSales] Selected Talent: {talent_data['name']} (Score: {talent_data['green_score']})")
+
+ # 2. Draft Hyper-Personalized Pitch (Partnership Manager)
+ pitch_prompt = (
+ f"Tugas: Buatlah Draf Cold Email B2B untuk menawarkan talenta hijau eksklusif kepada perusahaan.\n"
+ f"Perusahaan Target: {company_name} (Industri terkait: {niche})\n"
+ f"Talenta Unggulan Kami: \n{json.dumps(talent_data, indent=2)}\n\n"
+ "Instruksi Penulisan:\n"
+ "- Tulis subjek email yang sangat menarik (clickbait profesional tapi tidak spammy).\n"
+ "- Isi email harus to-the-point, menonjolkan nilai/skor talenta, dan menawarkan trial akses gratis ke Brigawan.\n"
+ "- Jangan buat seperti template robot. Buat seperti pesan dari seorang Partnership Manager manusia sesungguhnya.\n\n"
+ "Kembalikan dalam JSON: { 'subject': '...', 'html_body': '...' }"
+ )
+
+ pitch_resp = await call_agent_json("partnership-manager", pitch_prompt)
+
+ if not pitch_resp["success"]:
+ logger.error(f"[AutonomousSales] Failed to draft pitch: {pitch_resp.get('error')}")
+ return pitch_resp
+
+ email_content = pitch_resp["data"]
+
+ # Phrasing audit: ensure human-feel before fact-checking
+ from app.services.phrasing_audit_service import audit_text
+ passes, details = audit_text(email_content.get('html_body','') + ' ' + email_content.get('subject',''))
+ if not passes:
+ logger.warning(f"[AutonomousSales] Phrasing audit failed: {details}")
+ return {"success": False, "error": "phrasing_audit_failed", "details": details}
+
+ # 3. Fact Checking / Editor Approval (Optional, using fact-checker)
+ logger.info("[AutonomousSales] Verifying email tone and claims with Fact Checker...")
+ review_prompt = (
+ f"Review cold email berikut untuk {company_name}:\n{json.dumps(email_content)}\n"
+ "Pastikan tidak over-promising, tone-nya profesional, dan ejaannya sempurna.\n"
+ "Kembalikan JSON: { 'approved': boolean, 'corrected_subject': '...', 'corrected_html': '...' }"
+ )
+ review_resp = await call_agent_json("fact-checker", review_prompt)
+
+ if review_resp["success"] and review_resp["data"].get("approved", True):
+ final_subject = review_resp["data"].get("corrected_subject", email_content["subject"])
+ final_html = review_resp["data"].get("corrected_html", email_content["html_body"])
+ logger.success("[AutonomousSales] Email approved by Editor.")
+ else:
+ logger.warning("[AutonomousSales] Email rejected or modified heavily by Editor. Using fallback logic.")
+ final_subject = email_content["subject"]
+ final_html = email_content["html_body"]
+
+ # 4. Dispatch Email
+ logger.info(f"[AutonomousSales] Dispatching email to {target_email}...")
+
+ # In a real environment, you'd un-comment the line below to actually send:
+ # success = email_service.send_html_email(target_email, final_subject, final_html)
+ success = True # Simulated send for safety during development
+
+ if success:
+ logger.success(f"[AutonomousSales] Outreach successful. Awaiting reply from {company_name}!")
+ return {
+ "success": True,
+ "target": company_name,
+ "talent_pitched": talent_data["name"],
+ "preview_subject": final_subject,
+ "preview_body": final_html
+ }
+ else:
+ return {"success": False, "error": "SMTP send failed"}
+
+ @classmethod
+ async def _find_top_talent_for_niche(cls, niche: str) -> Dict[str, Any]:
+ """Queries the database for the top unplaced talent matching the niche."""
+ # For the sake of the Autonomous Engine logic, we provide a structured mock
+ # In production, this would do a SQLAlchemy query filtering by skills and sorting by green_score.
+ return {
+ "name": "Alex Wibowo",
+ "skills": [niche, "Sustainability Reporting", "Carbon Accounting", "Data Analysis"],
+ "experience_years": 4,
+ "green_score": 92,
+ "ai_summary": f"Alex adalah ahli {niche} dengan sertifikasi GRI. Telah membantu 3 perusahaan manufaktur menurunkan jejak karbon sebesar 15%."
+ }
diff --git a/app/services/security_service.py b/app/services/security_service.py
index 4bc77d925d53443d4dd2d9f99c86db51b856ed2c..9d741d5f918d5a566376011affe91b70095b2a92 100644
--- a/app/services/security_service.py
+++ b/app/services/security_service.py
@@ -1,97 +1,97 @@
-"""Security service for Envelope Encryption and KMS interaction.
-
-Handles Data Encryption Key (DEK) management and payload encryption/decryption.
-In production, this would interface with Google Cloud KMS or AWS KMS.
-"""
-
-import base64
-import json
-import os
-from typing import Any, Dict, Optional
-from uuid import UUID
-
-from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
-from cryptography.hazmat.primitives import padding
-from cryptography.hazmat.backends import default_backend
-from loguru import logger
-from sqlalchemy import text
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.services.kms_service import kms_service
-
-
-class SecurityService:
- """Service for managing career record encryption."""
-
- def _encrypt_with_dek(self, dek: bytes, data: str) -> str:
- """Encrypt string data using AES-256-CBC with the provided DEK."""
- iv = os.urandom(16)
- cipher = Cipher(algorithms.AES(dek), modes.CBC(iv), backend=default_backend())
- encryptor = cipher.encryptor()
-
- padder = padding.PKCS7(128).padder()
- padded_data = padder.update(data.encode("utf-8")) + padder.finalize()
-
- ciphertext = encryptor.update(padded_data) + encryptor.finalize()
- return base64.b64encode(iv + ciphertext).decode("utf-8")
-
- def _decrypt_with_dek(self, dek: bytes, encrypted_data: str) -> str:
- """Decrypt string data using AES-256-CBC with the provided DEK."""
- raw_data = base64.b64decode(encrypted_data)
- iv = raw_data[:16]
- ciphertext = raw_data[16:]
-
- cipher = Cipher(algorithms.AES(dek), modes.CBC(iv), backend=default_backend())
- decryptor = cipher.decryptor()
-
- padded_data = decryptor.update(ciphertext) + decryptor.finalize()
-
- unpadder = padding.PKCS7(128).unpadder()
- data = unpadder.update(padded_data) + unpadder.finalize()
- return data.decode("utf-8")
-
- async def get_or_create_profile_dek(self, db: AsyncSession, profile_id: UUID) -> bytes:
- """Retrieve the DEK for a profile, or create one if it doesn't exist."""
- # 1. Try to fetch from security.profile_keys
- query = text("SELECT encrypted_symmetric_key FROM security.profile_keys WHERE profile_id = :pid")
- result = await db.execute(query, {"pid": profile_id})
- row = result.fetchone()
-
- if row:
- # 2. Decrypt DEK using KMS
- dek_hex = kms_service.decrypt_dek(row[0])
- return bytes.fromhex(dek_hex)
-
- # 3. Create new DEK if missing
- new_dek = os.urandom(32)
- new_dek_hex = new_dek.hex()
-
- # 4. Encrypt DEK with KMS
- encrypted_dek_str = kms_service.encrypt_dek(new_dek_hex)
-
- # 5. Store in DB
- insert_query = text(
- "INSERT INTO security.profile_keys (profile_id, encrypted_symmetric_key) VALUES (:pid, :ekey)"
- )
- await db.execute(insert_query, {"pid": profile_id, "ekey": encrypted_dek_str})
- await db.commit()
-
- return new_dek
-
- async def set_session_dek(self, db: AsyncSession, dek: bytes):
- """Set the DEK in the current Postgres session for view decryption triggers."""
- dek_hex = dek.hex()
- await db.execute(text(f"SELECT set_config('app.current_profile_dek', :dek, false)"), {"dek": dek_hex})
-
- def encrypt_payload(self, dek: bytes, payload: Dict[str, Any]) -> str:
- """Encrypt a JSON payload using the provided DEK."""
- json_str = json.dumps(payload)
- return self._encrypt_with_dek(dek, json_str)
-
- def decrypt_payload(self, dek: bytes, encrypted_payload: str) -> Dict[str, Any]:
- """Decrypt a JSON payload using the provided DEK."""
- json_str = self._decrypt_with_dek(dek, encrypted_payload)
- return json.loads(json_str)
-
-
-security_service = SecurityService()
+"""Security service for Envelope Encryption and KMS interaction.
+
+Handles Data Encryption Key (DEK) management and payload encryption/decryption.
+In production, this would interface with Google Cloud KMS or AWS KMS.
+"""
+
+import base64
+import json
+import os
+from typing import Any, Dict, Optional
+from uuid import UUID
+
+from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
+from cryptography.hazmat.primitives import padding
+from cryptography.hazmat.backends import default_backend
+from loguru import logger
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.services.kms_service import kms_service
+
+
+class SecurityService:
+ """Service for managing career record encryption."""
+
+ def _encrypt_with_dek(self, dek: bytes, data: str) -> str:
+ """Encrypt string data using AES-256-CBC with the provided DEK."""
+ iv = os.urandom(16)
+ cipher = Cipher(algorithms.AES(dek), modes.CBC(iv), backend=default_backend())
+ encryptor = cipher.encryptor()
+
+ padder = padding.PKCS7(128).padder()
+ padded_data = padder.update(data.encode("utf-8")) + padder.finalize()
+
+ ciphertext = encryptor.update(padded_data) + encryptor.finalize()
+ return base64.b64encode(iv + ciphertext).decode("utf-8")
+
+ def _decrypt_with_dek(self, dek: bytes, encrypted_data: str) -> str:
+ """Decrypt string data using AES-256-CBC with the provided DEK."""
+ raw_data = base64.b64decode(encrypted_data)
+ iv = raw_data[:16]
+ ciphertext = raw_data[16:]
+
+ cipher = Cipher(algorithms.AES(dek), modes.CBC(iv), backend=default_backend())
+ decryptor = cipher.decryptor()
+
+ padded_data = decryptor.update(ciphertext) + decryptor.finalize()
+
+ unpadder = padding.PKCS7(128).unpadder()
+ data = unpadder.update(padded_data) + unpadder.finalize()
+ return data.decode("utf-8")
+
+ async def get_or_create_profile_dek(self, db: AsyncSession, profile_id: UUID) -> bytes:
+ """Retrieve the DEK for a profile, or create one if it doesn't exist."""
+ # 1. Try to fetch from security.profile_keys
+ query = text("SELECT encrypted_symmetric_key FROM security.profile_keys WHERE profile_id = :pid")
+ result = await db.execute(query, {"pid": profile_id})
+ row = result.fetchone()
+
+ if row:
+ # 2. Decrypt DEK using KMS
+ dek_hex = kms_service.decrypt_dek(row[0])
+ return bytes.fromhex(dek_hex)
+
+ # 3. Create new DEK if missing
+ new_dek = os.urandom(32)
+ new_dek_hex = new_dek.hex()
+
+ # 4. Encrypt DEK with KMS
+ encrypted_dek_str = kms_service.encrypt_dek(new_dek_hex)
+
+ # 5. Store in DB
+ insert_query = text(
+ "INSERT INTO security.profile_keys (profile_id, encrypted_symmetric_key) VALUES (:pid, :ekey)"
+ )
+ await db.execute(insert_query, {"pid": profile_id, "ekey": encrypted_dek_str})
+ await db.commit()
+
+ return new_dek
+
+ async def set_session_dek(self, db: AsyncSession, dek: bytes):
+ """Set the DEK in the current Postgres session for view decryption triggers."""
+ dek_hex = dek.hex()
+ await db.execute(text(f"SELECT set_config('app.current_profile_dek', :dek, false)"), {"dek": dek_hex})
+
+ def encrypt_payload(self, dek: bytes, payload: Dict[str, Any]) -> str:
+ """Encrypt a JSON payload using the provided DEK."""
+ json_str = json.dumps(payload)
+ return self._encrypt_with_dek(dek, json_str)
+
+ def decrypt_payload(self, dek: bytes, encrypted_payload: str) -> Dict[str, Any]:
+ """Decrypt a JSON payload using the provided DEK."""
+ json_str = self._decrypt_with_dek(dek, encrypted_payload)
+ return json.loads(json_str)
+
+
+security_service = SecurityService()
diff --git a/app/services/talent_service.py b/app/services/talent_service.py
index 1a90db38b041223d11c6500f3903f34a42ca8bf7..f8dcb2aea799f58f7e27eeb2b55523e9c0e346d1 100644
--- a/app/services/talent_service.py
+++ b/app/services/talent_service.py
@@ -1,619 +1,619 @@
-"""Talent Service — Profile, Pathway, Green Score, Interview Simulation, Secure Data.
-
-Ported from TalentDashboard.gs + Registry.gs + Security_PDP.gs.
-All operations crash-proof: never throw, always return structured response.
-"""
-
-import hashlib
-import json
-import re
-from datetime import datetime, timedelta, timezone
-
-from loguru import logger
-from sqlalchemy import func, select
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.models.job import AITalentChat, TalentAcademy, TalentPathway
-from app.models.talent import Talent
-from app.services.ai_service import call_low, call_medium
-
-
-CHAT_LIMIT = 10
-CHAT_EXPIRY_HOURS = 24
-POINTS_PROOF = 10
-POINTS_QUIZ = 50
-
-
-def _mask_talent_id(tid):
- if not tid or not isinstance(tid, str):
- return ""
- if tid.startswith("BRIGA-GT-") and len(tid) > 9:
- rp = tid[9:]
- if len(rp) >= 6:
- return "BRIGA-GT-" + rp[:2] + "***" + rp[5:]
- return tid[:12] + "..." if len(tid) > 12 else tid
-
-
-def _calc_green_score(progress, completed):
- score = 0
- for stg_key, actions in (progress or {}).items():
- if isinstance(actions, list):
- for a in actions:
- if isinstance(a, dict) and a.get("done"):
- score += POINTS_PROOF
- score += len(completed or []) * POINTS_QUIZ
- return score
-
-
-def _sanitize(val, max_len=500):
- if val is None:
- return ""
- return str(val).replace("<", "").replace(">", "").strip()[:max_len]
-
-
-# ===== Profile =====
-
-async def get_talent_profile(db, email):
- """Get full talent dashboard profile."""
- try:
- e = email.lower().strip()
- result = await db.execute(select(Talent).where(func.lower(Talent.email) == e).limit(1))
- talent = result.scalar_one_or_none()
- if not talent:
- return {"success": False, "error": "Talent not found.", "data": None}
- loc_parts = (talent.location or "-").split("|")
- kota = loc_parts[0] if len(loc_parts) > 0 else "-"
- provinsi = loc_parts[1] if len(loc_parts) > 1 else "-"
- pendidikan = talent.education or "-"
- edu_match = re.match(r"^(.+?)\s*[\u2013-]\s*(.+?)\s*\((.+?)\)\s*$", pendidikan)
- universitas, jurusan, strata = "-", "-", "-"
- if edu_match:
- universitas = edu_match.group(1).strip()
- jurusan = edu_match.group(2).strip()
- strata = edu_match.group(3).strip()
- else:
- universitas = pendidikan
- skills = [s.replace("#", "").strip() for s in (talent.skill_tags or "").split(",") if s.strip()]
- badges = []
- if talent.verification_status and "Verified" in str(talent.verification_status):
- badges.append({"type": "edu", "label": "Verified Graduate", "icon": "\U0001f393", "color": "gold"})
- chat_stats = await _get_chat_stats(db, e)
- pathway_data = await _get_pathway(db, e)
- academy_modules = await _get_academy_modules(db, e)
- green_score = talent.green_score or pathway_data.get("greenScore", 0)
- profile = {
- "talentId": talent.talent_id or "-", "nama": talent.name or "-", "email": talent.email or "",
- "universitas": universitas, "jurusan": jurusan, "strata": strata,
- "pendidikan_raw": pendidikan, "pengalaman": talent.experience or "-",
- "kota": kota, "provinsi": provinsi, "ai_score": talent.score or 0,
- "ai_category": talent.category or "-", "ai_summary": talent.analysis or "-", "skills": skills,
- "cv_link": talent.cv_link or "-", "verification": talent.verification_status or "-",
- "linkedin_link": talent.linkedin_link or "-", "telepon": talent.phone or "-",
- "talent_type": talent.talent_type or "-", "sector_focus": talent.sector_focus or "-",
- "current_salary": talent.current_salary or "-", "expected_salary": talent.salary_expected or "-",
- "chatUsed": chat_stats.get("used", 0), "chatLimit": CHAT_LIMIT,
- "chatExpiry": chat_stats.get("expiryTime", "-"), "chatHistory": chat_stats.get("history", []),
- "pathwayData": pathway_data.get("pathway", []), "pathwayProgress": pathway_data.get("progress", {}),
- "completedStages": pathway_data.get("completedStages", []), "greenScore": green_score,
- "greenScoreLevel": "Bronze", "badges": badges,
- "academyCompletedModules": academy_modules, "from_backend_cache": False,
- }
- return {"success": True, "data": profile, "error": None}
- except Exception as e:
- logger.error(f"get_talent_profile error: {e}")
- return {"success": False, "error": str(e), "data": None}
-
-
-async def update_talent_profile(db, email, form_data):
- """Update talent profile fields with sanitization."""
- try:
- e = email.lower().strip()
- result = await db.execute(select(Talent).where(func.lower(Talent.email) == e).limit(1))
- talent = result.scalar_one_or_none()
- if not talent:
- return {"success": False, "error": "Talent not found."}
- updates = {}
- field_map = {
- "nama": ("name", 100), "telepon": ("phone", 20),
- "linkedin_link": ("linkedin_link", 300), "cv_link": ("cv_link", 300),
- "talent_type": ("talent_type", 50), "sector_focus": ("sector_focus", 100),
- "current_salary": ("current_salary", 20), "expected_salary": ("salary_expected", 20),
- "pengalaman": ("experience", 2000),
- }
- for form_key, (db_field, max_len) in field_map.items():
- if form_key in form_data and form_data[form_key] is not None:
- updates[db_field] = _sanitize(form_data[form_key], max_len)
- if "kota" in form_data or "provinsi" in form_data:
- loc_parts = (talent.location or "").split("|")
- new_kota = _sanitize(form_data.get("kota", ""), 100) or (loc_parts[0] if len(loc_parts) > 0 else "-")
- new_prov = _sanitize(form_data.get("provinsi", ""), 100) or (loc_parts[1] if len(loc_parts) > 1 else "-")
- method = loc_parts[2] if len(loc_parts) > 2 else "Manual"
- updates["location"] = f"{new_kota}|{new_prov}|{method}"
- if updates:
- for field, value in updates.items():
- setattr(talent, field, value)
- db.add(talent)
- await db.commit()
- return {"success": True, "message": "Profil berhasil diperbarui."}
- except Exception as e:
- logger.error(f"update_talent_profile error: {e}")
- await db.rollback()
- return {"success": False, "error": str(e)}
-
-
-# ===== Pathway =====
-
-async def _get_pathway(db, email):
- """Get existing career pathway for a talent."""
- try:
- result = await db.execute(
- select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1)
- )
- pw = result.scalar_one_or_none()
- if not pw:
- return {"pathway": [], "progress": {}, "completedStages": [], "greenScore": 0}
- pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
- progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
- completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
- return {
- "pathway": pathway, "progress": progress,
- "completedStages": [str(s) for s in completed],
- "greenScore": pw.green_score or 0,
- }
- except Exception as e:
- logger.error(f"_get_pathway error: {e}")
- return {"pathway": [], "progress": {}, "completedStages": [], "greenScore": 0}
-
-
-async def generate_career_pathway(db, email):
- """Generate AI-powered career pathway (5 stages)."""
- try:
- e = email.lower().strip()
- existing = await _get_pathway(db, e)
- if existing.get("pathway") and len(existing["pathway"]) > 0:
- existing["cached"] = True
- return existing
- profile_resp = await get_talent_profile(db, e)
- if not profile_resp.get("success"):
- return {"success": False, "error": "Profil talent tidak ditemukan."}
- p = profile_resp["data"]
- prompt = (
- "Kamu adalah expert Green Career Consultant di Indonesia. "
- "Buat Career Pathway spesifik untuk talent berikut:\n\n"
- f"Nama: {p.get('nama', 'Talent')}\n"
- f"Pendidikan: {p.get('universitas', '-')} - {p.get('jurusan', '-')} ({p.get('strata', '-')})\n"
- f"Pengalaman: {str(p.get('pengalaman', '-'))[:400]}\n"
- f"Skills: {', '.join(p.get('skills', []))}\n"
- f"Kota: {p.get('kota', '-')}\n"
- f"AI Score: {p.get('ai_score', 0)}/100\n\n"
- "Buat exactly 5 tahap dalam JSON array. Setiap tahap:\n"
- "{stage:1-5, title:string, duration:string, description:string(2 kalimat), "
- "actions:[3 aksi konkret yg bisa dibuktikan dg link/dokumen], "
- "skills_to_gain:[2-3 skill], milestone:string, "
- "quiz:[3 objek {q:pertanyaan, options:[4 pilihan], answer:indeks jawaban benar 0-3}]}\n\n"
- "Jawab HANYA JSON array valid."
- )
- raw_text = await call_medium(prompt, temperature=0.5, max_output_tokens=6000)
- if not raw_text:
- raise ValueError("AI returned empty response")
- cleaned = raw_text.strip()
- if cleaned.startswith("```json"):
- cleaned = cleaned[7:]
- if cleaned.startswith("```"):
- cleaned = cleaned[3:]
- if cleaned.endswith("```"):
- cleaned = cleaned[:-3]
- cleaned = cleaned.strip()
- pathway = json.loads(cleaned)
- if not isinstance(pathway, list):
- raise ValueError("AI response is not a JSON array")
- init_progress = {}
- for stage in pathway:
- actions = stage.get("actions", [])
- init_progress[str(stage.get("stage", 0))] = [
- {"done": False, "proof": "", "ts": "", "status": ""} for _ in actions
- ]
- result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == e).limit(1))
- existing_pw = result.scalar_one_or_none()
- if existing_pw:
- existing_pw.pathway_json = pathway
- existing_pw.progress_json = init_progress
- existing_pw.completed_stages = []
- existing_pw.generated_at = datetime.now(timezone.utc)
- existing_pw.green_score = 0
- else:
- db.add(TalentPathway(email=e, pathway_json=pathway, progress_json=init_progress, completed_stages=[], green_score=0))
- await db.commit()
- return {"success": True, "pathway": pathway, "progress": init_progress, "completedStages": [], "greenScore": 0, "cached": False}
- except json.JSONDecodeError:
- return {"success": False, "error": "Gagal memproses respons AI: format JSON tidak valid."}
- except Exception as e:
- return {"success": False, "error": f"Gagal membuat Career Pathway: {str(e)}"}
-
-
-async def submit_action_proof(db, email, stage, action_index, proof_text):
- """Submit proof for a specific pathway action."""
- try:
- e = email.lower().strip()
- result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == e).limit(1))
- pw = result.scalar_one_or_none()
- if not pw:
- return {"success": False, "error": "Pathway belum dibuat."}
- progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
- completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
- pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
- if stage > len(completed) + 1:
- return {"success": False, "error": "Stage ini belum terbuka."}
- sk = str(stage)
- if sk not in progress:
- progress[sk] = []
- while len(progress[sk]) <= action_index:
- progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
- progress[sk][action_index] = {"done": True, "proof": proof_text.strip(), "ts": datetime.now(timezone.utc).isoformat(), "status": "Pending"}
- score = _calc_green_score(progress, completed)
- stage_data = next((s for s in pathway if s.get("stage") == stage), None)
- all_proven = False
- if stage_data and sk in progress:
- expected = len(stage_data.get("actions", []))
- all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
- pw.progress_json = progress
- pw.green_score = score
- db.add(pw)
- await db.commit()
- return {"success": True, "progress": progress, "completedStages": [str(s) for s in completed], "greenScore": score, "allActionsProven": all_proven}
- except Exception as e:
- logger.error(f"submit_action_proof error: {e}")
- return {"success": False, "error": str(e)}
-
-
-async def submit_quiz_answers(db, email, stage, answers):
- """Submit quiz answers for a stage. All actions must be proven first."""
- try:
- e = email.lower().strip()
- result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == e).limit(1))
- pw = result.scalar_one_or_none()
- if not pw:
- return {"success": False, "error": "Pathway belum dibuat."}
- pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
- progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
- completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
- sk = str(stage)
- stage_data = next((s for s in pathway if s.get("stage") == stage), None)
- if not stage_data or not stage_data.get("quiz"):
- return {"success": False, "error": "Kuis tidak tersedia untuk stage ini."}
- expected = len(stage_data.get("actions", []))
- all_proven = sk in progress and len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
- if not all_proven:
- return {"success": False, "error": "Selesaikan semua aksi terlebih dahulu."}
- quiz = stage_data["quiz"]
- correct = sum(1 for i, q in enumerate(quiz) if i < len(answers) and int(answers[i]) == int(q.get("answer", -1)))
- if correct < len(quiz):
- return {"success": False, "error": f"Jawaban belum benar semua ({correct}/{len(quiz)}). Silakan coba lagi!", "score": correct, "total": len(quiz)}
- if sk not in [str(s) for s in completed]:
- completed.append(stage)
- score = _calc_green_score(progress, completed)
- pw.completed_stages = completed
- pw.green_score = score
- db.add(pw)
- await db.commit()
- try:
- tr = await db.execute(select(Talent).where(func.lower(Talent.email) == e).limit(1))
- to = tr.scalar_one_or_none()
- if to:
- to.green_score = score
- db.add(to)
- await db.commit()
- except Exception:
- await db.rollback()
- return {"success": True, "completedStages": [str(s) for s in completed], "greenScore": score, "stageCompleted": True, "completedStageTitle": stage_data.get("title", f"Stage {stage}")}
- except Exception as e:
- logger.error(f"submit_quiz_answers error: {e}")
- return {"success": False, "error": str(e)}
-
-
-async def get_pathway_certificate(db, email, stage):
- """Get certificate for a completed stage."""
- try:
- e = email.lower().strip()
- result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == e).limit(1))
- pw = result.scalar_one_or_none()
- if not pw:
- return {"success": False, "error": "Pathway tidak ditemukan."}
- completed = [str(s) for s in (pw.completed_stages or [])]
- if str(stage) not in completed:
- return {"success": False, "error": "Stage belum diselesaikan."}
- pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
- stage_data = next((s for s in pathway if s.get("stage") == stage), None)
- proofs = [a.get("proof", "") for a in (pw.progress_json or {}).get(str(stage), []) if isinstance(a, dict) and a.get("done")]
- tr = await db.execute(select(Talent).where(func.lower(Talent.email) == e).limit(1))
- to = tr.scalar_one_or_none()
- return {"success": True, "certificate": {
- "nama": to.name if to else "Talent", "stage": stage,
- "title": stage_data.get("title", f"Stage {stage}") if stage_data else f"Stage {stage}",
- "skills": stage_data.get("skills_to_gain", []) if stage_data else [],
- "milestone": stage_data.get("milestone", "") if stage_data else "",
- "proofs": proofs, "greenScore": pw.green_score or 0,
- "completedAt": pw.generated_at.isoformat() if pw.generated_at else datetime.now(timezone.utc).isoformat(),
- "talentId": _mask_talent_id(to.talent_id if to else ""),
- }}
- except Exception as e:
- logger.error(f"get_pathway_certificate error: {e}")
- return {"success": False, "error": str(e)}
-
-
-async def verify_certificate(db, talent_id, stage):
- """Public certificate verification via talent ID or SHA-256 hash."""
- try:
- clean_tid = talent_id.strip()
- is_hash = len(clean_tid) == 64
- result = await db.execute(select(Talent))
- talents = result.scalars().all()
- email = None
- actual_tid = None
- for t in talents:
- db_tid = (t.talent_id or "").strip()
- if not db_tid:
- continue
- match = False
- if is_hash:
- db_hash = hashlib.sha256(db_tid.encode()).hexdigest()
- if db_hash.lower() == clean_tid.lower():
- match = True
- else:
- if db_tid.upper() == clean_tid.upper():
- match = True
- if match:
- email = t.email
- actual_tid = db_tid
- break
- if not email:
- return {"success": False, "error": "ID Talent tidak valid."}
- pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower()).limit(1))
- pw = pw_result.scalar_one_or_none()
- if not pw:
- return {"success": False, "error": "Data pencapaian tidak ditemukan."}
- completed = [str(s) for s in (pw.completed_stages or [])]
- if str(stage) not in completed:
- return {"success": False, "error": "Sertifikat ini belum tervalidasi atau belum diselesaikan."}
- pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
- stage_data = next((s for s in pathway if s.get("stage") == stage), None)
- return {"success": True, "data": {
- "nama": next((t.name for t in talents if t.email == email), "Talent"),
- "stage": stage,
- "title": stage_data.get("title", f"Stage {stage}") if stage_data else f"Stage {stage}",
- "milestone": stage_data.get("milestone", "") if stage_data else "",
- "completedAt": pw.generated_at.isoformat() if pw.generated_at else None,
- "greenScore": pw.green_score or 0,
- "talentId": _mask_talent_id(actual_tid or ""),
- }}
- except Exception as e:
- logger.error(f"verify_certificate error: {e}")
- return {"success": False, "error": str(e)}
-
-
-# ===== Academy =====
-
-async def _get_academy_modules(db, email):
- """Get completed academy modules for a talent."""
- try:
- result = await db.execute(select(TalentAcademy).where(func.lower(TalentAcademy.email) == email.lower().strip()).limit(1))
- acad = result.scalar_one_or_none()
- if not acad or not acad.completed_modules:
- return []
- return [m.strip() for m in acad.completed_modules.split(",") if m.strip()]
- except Exception as e:
- logger.error(f"_get_academy_modules error: {e}")
- return []
-
-
-# ===== AI Chat =====
-
-async def _get_chat_stats(db, email):
- """Get AI chat usage stats for a talent."""
- try:
- cutoff = datetime.now(timezone.utc) - timedelta(hours=CHAT_EXPIRY_HOURS)
- result = await db.execute(
- select(AITalentChat).where(
- AITalentChat.email == email,
- AITalentChat.timestamp >= cutoff,
- ).order_by(AITalentChat.timestamp.desc()).limit(CHAT_LIMIT)
- )
- chats = list(result.scalars().all())
- used = len(chats)
- latest_ts = chats[0].timestamp if chats else None
- expiry_time = "-"
- if latest_ts:
- expiry = latest_ts + timedelta(hours=CHAT_EXPIRY_HOURS)
- expiry_time = expiry.strftime("%d %b %Y %H:%M") + " WIB"
- history = [{"role": "user", "text": c.user_message, "ts": c.timestamp.isoformat() if c.timestamp else None, "aiReply": c.ai_reply} for c in reversed(chats)]
- return {"used": used, "expiryTime": expiry_time, "history": history}
- except Exception as e:
- logger.error(f"_get_chat_stats error: {e}")
- return {"used": 0, "expiryTime": "-", "history": []}
-
-
-async def save_chat_record(db, email, user_message, ai_reply):
- """Save a chat record."""
- try:
- now = datetime.now(timezone.utc)
- expiry = now + timedelta(hours=CHAT_EXPIRY_HOURS)
- chat = AITalentChat(email=email, user_message=user_message, ai_reply=ai_reply, timestamp=now, expires_at=expiry)
- db.add(chat)
- await db.commit()
- except Exception as e:
- logger.error(f"save_chat_record error: {e}")
- await db.rollback()
-
-
-async def chat_with_brigawan(db, email, message):
- """AI Career Coach chat. Limited to 10 chats per 24h."""
- try:
- e = email.lower().strip()
- chat_stats = await _get_chat_stats(db, e)
- if chat_stats.get("used", 0) >= CHAT_LIMIT:
- expiry = chat_stats.get("expiryTime", "-")
- return {"success": False, "limitReached": True,
- "error": f"Batas {CHAT_LIMIT} percakapan dalam {CHAT_EXPIRY_HOURS} jam telah tercapai. Silakan coba lagi setelah {expiry}.",
- "chatExpiry": expiry}
- profile_resp = await get_talent_profile(db, e)
- profile = profile_resp.get("data", {}) if profile_resp.get("success") else {}
- remaining = CHAT_LIMIT - chat_stats.get("used", 0) - 1
- system_prompt = (
- "Kamu adalah Brigawan AI, Career Coach eksklusif untuk green jobs dan sustainability careers di Indonesia. "
- "Kamu memiliki kepribadian profesional, hangat, dan memotivasi. "
- f"Profil talent yang sedang kamu bantu: "
- f"Nama: {profile.get('nama', 'Talent')}. "
- f"Pendidikan: {profile.get('universitas', '-')}, {profile.get('jurusan', '-')} ({profile.get('strata', '-')}). "
- f"Pengalaman & Skills: {profile.get('pengalaman', '-')}. "
- f"Kota: {profile.get('kota', '-')}. "
- f"AI Score: {profile.get('ai_score', 0)}/100. "
- f"AI Category: {profile.get('ai_category', '-')}. "
- "PENTING: Jawab dalam Bahasa Indonesia yang profesional. "
- "Fokus pada arahan konkret karir green/sustainability. "
- f"Sisa kuota chat talent ini: {remaining} setelah pesan ini."
- )
- full_prompt = system_prompt + "\n\nPesan dari Talent: " + message
- ai_reply_text, _ = await call_low(full_prompt, temperature=0.75, max_output_tokens=1024)
- if not ai_reply_text:
- ai_reply_text = "Terima kasih atas pesan Anda. Saat ini asisten AI sedang tidak tersedia. Silakan coba lagi nanti atau hubungi kami melalui email info@briga.id untuk bantuan lebih lanjut."
- await save_chat_record(db, e, message, ai_reply_text)
- ai_reply = ai_reply_text # preserve for return
- new_stats = await _get_chat_stats(db, e)
- return {"success": True, "reply": ai_reply, "chatUsed": new_stats.get("used", 0),
- "chatLimit": CHAT_LIMIT, "chatExpiry": new_stats.get("expiryTime", "-"),
- "limitReached": new_stats.get("used", 0) >= CHAT_LIMIT}
- except Exception as e:
- logger.error(f"chat_with_brigawan error: {e}")
- return {"success": False, "error": "Gagal menghubungi AI: " + str(e)}
-
-
-# ===== Grill-Me Interview =====
-
-FALLBACK_QUESTIONS = [
- "Bagaimana Anda menerapkan prinsip keberlanjutan / ESG dalam proyek teknis Anda sebelumnya?",
- "Jelaskan tantangan terbesar yang Anda hadapi saat mengimplementasikan solusi energi hijau / efisiensi sumber daya dan cara mengatasinya.",
- "Jika ada konflik antara efisiensi biaya jangka pendek dengan kepatuhan lingkungan jangka panjang, keputusan apa yang akan Anda ambil?",
-]
-
-
-async def generate_grillme_questions(category="ESG Specialist"):
- """Generate 3 interview simulation questions using AI."""
- try:
- prompt = (
- "Kamu adalah Pewawancara Teknis Rekrutmen Karir Hijau yang sangat ahli. "
- f"Tugasmu adalah membuat exactly 3 pertanyaan wawancara (2 teknis spesifik & 1 perilaku situasional) "
- f"yang sangat mendalam dan sesuai untuk sektor/kategori hijau: \"{category}\".\n\n"
- "Ketentuan format output:\n"
- "Berikan respons HANYA berupa valid JSON array of strings dengan format:\n"
- '["Pertanyaan 1", "Pertanyaan 2", "Pertanyaan 3"]\n\n'
- "Jangan berikan penjelasan, preambul, markdown code blocks, atau teks lainnya. Hanya JSON array saja."
- )
- raw_text, _ = await call_low(prompt, temperature=0.7, max_output_tokens=1024)
- if not raw_text:
- raise ValueError("Empty AI response")
- cleaned = raw_text.strip()
- if cleaned.startswith("```json"):
- cleaned = cleaned[7:]
- if cleaned.startswith("```"):
- cleaned = cleaned[3:]
- if cleaned.endswith("```"):
- cleaned = cleaned[:-3]
- cleaned = cleaned.strip()
- questions = json.loads(cleaned)
- if not isinstance(questions, list) or len(questions) != 3:
- raise ValueError(f"Expected 3 questions, got {len(questions)}")
- return {"success": True, "questions": questions, "isFallback": False}
- except Exception as e:
- logger.error(f"generate_grillme_questions error: {e}")
- return {"success": True, "questions": FALLBACK_QUESTIONS, "isFallback": True}
-
-
-def evaluate_grillme(category, questions, answers):
- """Evaluate interview answers and generate SWOT analysis."""
- try:
- if not questions or not answers or len(questions) != 3 or len(answers) != 3:
- return {"success": False, "error": "Pertanyaan atau jawaban tidak lengkap."}
- transcript = ""
- for i in range(3):
- transcript += f"Pewawancara: {questions[i]}\nKandidat: {answers[i]}\n\n"
- prompt = (
- "Kamu adalah Pewawancara Utama & Ahli Evaluasi Karir Hijau B2B di Brigawan AI.\n"
- f"Evaluasilah transkrip wawancara berikut untuk kategori \"{category}\":\n\n"
- f"{transcript}\n"
- "Tugasmu:\n"
- "1. Berikan skor numerik bulat keseluruhan antara 50 sampai 100.\n"
- "2. Berikan analisis SWOT yang terperinci dalam bahasa Indonesia.\n"
- "3. Format respons harus berupa JSON objek valid:\n"
- '{"score": 85, "strengths": "...", "weaknesses": "...", "opportunities": "...", "threats": "...", "summary": "..."}'
- )
- raw_text = call_medium(prompt, temperature=0.6, max_output_tokens=2048)
- if not raw_text:
- raise ValueError("Empty AI response")
- cleaned = raw_text.strip()
- if cleaned.startswith("```json"):
- cleaned = cleaned[7:]
- if cleaned.startswith("```"):
- cleaned = cleaned[3:]
- if cleaned.endswith("```"):
- cleaned = cleaned[:-3]
- cleaned = cleaned.strip()
- evaluation = json.loads(cleaned)
- final_score = max(50, min(100, int(evaluation.get("score", 75))))
- swot = {"score": final_score,
- "strengths": evaluation.get("strengths", ""),
- "weaknesses": evaluation.get("weaknesses", ""),
- "opportunities": evaluation.get("opportunities", ""),
- "threats": evaluation.get("threats", ""),
- "summary": evaluation.get("summary", "")}
- return {"success": True, "score": final_score, "swot": swot,
- "rawSWOTText": f"=== EVALUASI WAWANCARA AI ({category}) ===\n\nKEKUATAN (STRENGTHS):\n{swot['strengths']}"}
- except Exception as e:
- logger.error(f"evaluate_grillme error: {e}")
- return {"success": False, "error": f"Gagal mengevaluasi wawancara: {str(e)}"}
-
-
-# ===== Secure Talent Data =====
-
-async def get_secure_talent_data(db, candidate_id, requester_email):
- """Get talent data with PDP-compliant masking."""
- from app.models.job import MediatedChat
- try:
- result = await db.execute(select(Talent).where(Talent.talent_id == candidate_id).limit(1))
- candidate = result.scalar_one_or_none()
- if not candidate:
- return {"success": False, "error": "Candidate not found."}
- unlock_result = await db.execute(
- select(MediatedChat).where(
- MediatedChat.receiver_email == candidate.email,
- MediatedChat.sender_email == requester_email,
- MediatedChat.is_identity_unlocked == True,
- ).limit(1)
- )
- is_unlocked = unlock_result.scalar_one_or_none() is not None
- if is_unlocked:
- return {"success": True, "id_kandidat": candidate.talent_id,
- "nama": candidate.name or "", "email": candidate.email or "",
- "pendidikan": candidate.education or "", "pengalaman": candidate.experience or "",
- "k3_dasar": candidate.k3_dasar or "", "k3_khusus": candidate.k3_khusus or "",
- "sertifikasi": candidate.cert_other or "", "bahasa": candidate.language or "",
- "cv_link": candidate.cv_link or "", "skor": candidate.score or 0,
- "kategori": candidate.category or "", "analisis": candidate.analysis or "",
- "status": candidate.verification_status or "", "unlocked": True}
- else:
- return {"success": True, "id_kandidat": candidate.talent_id,
- "nama": f"Talent {candidate.talent_id}", "email": "[LOCKED]",
- "pendidikan": "[MASKED]", "pengalaman": "[MASKED]",
- "k3_dasar": candidate.k3_dasar or "", "k3_khusus": candidate.k3_khusus or "",
- "sertifikasi": candidate.cert_other or "", "bahasa": candidate.language or "",
- "cv_link": "[LOCKED - Reveal to Download]", "skor": candidate.score or 0,
- "kategori": candidate.category or "", "analisis": candidate.analysis or "",
- "status": candidate.verification_status or "", "unlocked": False}
- except Exception as e:
- logger.error(f"get_secure_talent_data error: {e}")
- return {"success": False, "error": str(e)}
-
-
-async def get_talent_by_email(db, email):
- """Lookup talent record by email."""
- result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
- return result.scalar_one_or_none()
+"""Talent Service — Profile, Pathway, Green Score, Interview Simulation, Secure Data.
+
+Ported from TalentDashboard.gs + Registry.gs + Security_PDP.gs.
+All operations crash-proof: never throw, always return structured response.
+"""
+
+import hashlib
+import json
+import re
+from datetime import datetime, timedelta, timezone
+
+from loguru import logger
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.job import AITalentChat, TalentAcademy, TalentPathway
+from app.models.talent import Talent
+from app.services.ai_service import call_low, call_medium
+
+
+CHAT_LIMIT = 10
+CHAT_EXPIRY_HOURS = 24
+POINTS_PROOF = 10
+POINTS_QUIZ = 50
+
+
+def _mask_talent_id(tid):
+ if not tid or not isinstance(tid, str):
+ return ""
+ if tid.startswith("BRIGA-GT-") and len(tid) > 9:
+ rp = tid[9:]
+ if len(rp) >= 6:
+ return "BRIGA-GT-" + rp[:2] + "***" + rp[5:]
+ return tid[:12] + "..." if len(tid) > 12 else tid
+
+
+def _calc_green_score(progress, completed):
+ score = 0
+ for stg_key, actions in (progress or {}).items():
+ if isinstance(actions, list):
+ for a in actions:
+ if isinstance(a, dict) and a.get("done"):
+ score += POINTS_PROOF
+ score += len(completed or []) * POINTS_QUIZ
+ return score
+
+
+def _sanitize(val, max_len=500):
+ if val is None:
+ return ""
+ return str(val).replace("<", "").replace(">", "").strip()[:max_len]
+
+
+# ===== Profile =====
+
+async def get_talent_profile(db, email):
+ """Get full talent dashboard profile."""
+ try:
+ e = email.lower().strip()
+ result = await db.execute(select(Talent).where(func.lower(Talent.email) == e).limit(1))
+ talent = result.scalar_one_or_none()
+ if not talent:
+ return {"success": False, "error": "Talent not found.", "data": None}
+ loc_parts = (talent.location or "-").split("|")
+ kota = loc_parts[0] if len(loc_parts) > 0 else "-"
+ provinsi = loc_parts[1] if len(loc_parts) > 1 else "-"
+ pendidikan = talent.education or "-"
+ edu_match = re.match(r"^(.+?)\s*[\u2013-]\s*(.+?)\s*\((.+?)\)\s*$", pendidikan)
+ universitas, jurusan, strata = "-", "-", "-"
+ if edu_match:
+ universitas = edu_match.group(1).strip()
+ jurusan = edu_match.group(2).strip()
+ strata = edu_match.group(3).strip()
+ else:
+ universitas = pendidikan
+ skills = [s.replace("#", "").strip() for s in (talent.skill_tags or "").split(",") if s.strip()]
+ badges = []
+ if talent.verification_status and "Verified" in str(talent.verification_status):
+ badges.append({"type": "edu", "label": "Verified Graduate", "icon": "\U0001f393", "color": "gold"})
+ chat_stats = await _get_chat_stats(db, e)
+ pathway_data = await _get_pathway(db, e)
+ academy_modules = await _get_academy_modules(db, e)
+ green_score = talent.green_score or pathway_data.get("greenScore", 0)
+ profile = {
+ "talentId": talent.talent_id or "-", "nama": talent.name or "-", "email": talent.email or "",
+ "universitas": universitas, "jurusan": jurusan, "strata": strata,
+ "pendidikan_raw": pendidikan, "pengalaman": talent.experience or "-",
+ "kota": kota, "provinsi": provinsi, "ai_score": talent.score or 0,
+ "ai_category": talent.category or "-", "ai_summary": talent.analysis or "-", "skills": skills,
+ "cv_link": talent.cv_link or "-", "verification": talent.verification_status or "-",
+ "linkedin_link": talent.linkedin_link or "-", "telepon": talent.phone or "-",
+ "talent_type": talent.talent_type or "-", "sector_focus": talent.sector_focus or "-",
+ "current_salary": talent.current_salary or "-", "expected_salary": talent.salary_expected or "-",
+ "chatUsed": chat_stats.get("used", 0), "chatLimit": CHAT_LIMIT,
+ "chatExpiry": chat_stats.get("expiryTime", "-"), "chatHistory": chat_stats.get("history", []),
+ "pathwayData": pathway_data.get("pathway", []), "pathwayProgress": pathway_data.get("progress", {}),
+ "completedStages": pathway_data.get("completedStages", []), "greenScore": green_score,
+ "greenScoreLevel": "Bronze", "badges": badges,
+ "academyCompletedModules": academy_modules, "from_backend_cache": False,
+ }
+ return {"success": True, "data": profile, "error": None}
+ except Exception as e:
+ logger.error(f"get_talent_profile error: {e}")
+ return {"success": False, "error": str(e), "data": None}
+
+
+async def update_talent_profile(db, email, form_data):
+ """Update talent profile fields with sanitization."""
+ try:
+ e = email.lower().strip()
+ result = await db.execute(select(Talent).where(func.lower(Talent.email) == e).limit(1))
+ talent = result.scalar_one_or_none()
+ if not talent:
+ return {"success": False, "error": "Talent not found."}
+ updates = {}
+ field_map = {
+ "nama": ("name", 100), "telepon": ("phone", 20),
+ "linkedin_link": ("linkedin_link", 300), "cv_link": ("cv_link", 300),
+ "talent_type": ("talent_type", 50), "sector_focus": ("sector_focus", 100),
+ "current_salary": ("current_salary", 20), "expected_salary": ("salary_expected", 20),
+ "pengalaman": ("experience", 2000),
+ }
+ for form_key, (db_field, max_len) in field_map.items():
+ if form_key in form_data and form_data[form_key] is not None:
+ updates[db_field] = _sanitize(form_data[form_key], max_len)
+ if "kota" in form_data or "provinsi" in form_data:
+ loc_parts = (talent.location or "").split("|")
+ new_kota = _sanitize(form_data.get("kota", ""), 100) or (loc_parts[0] if len(loc_parts) > 0 else "-")
+ new_prov = _sanitize(form_data.get("provinsi", ""), 100) or (loc_parts[1] if len(loc_parts) > 1 else "-")
+ method = loc_parts[2] if len(loc_parts) > 2 else "Manual"
+ updates["location"] = f"{new_kota}|{new_prov}|{method}"
+ if updates:
+ for field, value in updates.items():
+ setattr(talent, field, value)
+ db.add(talent)
+ await db.commit()
+ return {"success": True, "message": "Profil berhasil diperbarui."}
+ except Exception as e:
+ logger.error(f"update_talent_profile error: {e}")
+ await db.rollback()
+ return {"success": False, "error": str(e)}
+
+
+# ===== Pathway =====
+
+async def _get_pathway(db, email):
+ """Get existing career pathway for a talent."""
+ try:
+ result = await db.execute(
+ select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower().strip()).limit(1)
+ )
+ pw = result.scalar_one_or_none()
+ if not pw:
+ return {"pathway": [], "progress": {}, "completedStages": [], "greenScore": 0}
+ pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
+ progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
+ completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
+ return {
+ "pathway": pathway, "progress": progress,
+ "completedStages": [str(s) for s in completed],
+ "greenScore": pw.green_score or 0,
+ }
+ except Exception as e:
+ logger.error(f"_get_pathway error: {e}")
+ return {"pathway": [], "progress": {}, "completedStages": [], "greenScore": 0}
+
+
+async def generate_career_pathway(db, email):
+ """Generate AI-powered career pathway (5 stages)."""
+ try:
+ e = email.lower().strip()
+ existing = await _get_pathway(db, e)
+ if existing.get("pathway") and len(existing["pathway"]) > 0:
+ existing["cached"] = True
+ return existing
+ profile_resp = await get_talent_profile(db, e)
+ if not profile_resp.get("success"):
+ return {"success": False, "error": "Profil talent tidak ditemukan."}
+ p = profile_resp["data"]
+ prompt = (
+ "Kamu adalah expert Green Career Consultant di Indonesia. "
+ "Buat Career Pathway spesifik untuk talent berikut:\n\n"
+ f"Nama: {p.get('nama', 'Talent')}\n"
+ f"Pendidikan: {p.get('universitas', '-')} - {p.get('jurusan', '-')} ({p.get('strata', '-')})\n"
+ f"Pengalaman: {str(p.get('pengalaman', '-'))[:400]}\n"
+ f"Skills: {', '.join(p.get('skills', []))}\n"
+ f"Kota: {p.get('kota', '-')}\n"
+ f"AI Score: {p.get('ai_score', 0)}/100\n\n"
+ "Buat exactly 5 tahap dalam JSON array. Setiap tahap:\n"
+ "{stage:1-5, title:string, duration:string, description:string(2 kalimat), "
+ "actions:[3 aksi konkret yg bisa dibuktikan dg link/dokumen], "
+ "skills_to_gain:[2-3 skill], milestone:string, "
+ "quiz:[3 objek {q:pertanyaan, options:[4 pilihan], answer:indeks jawaban benar 0-3}]}\n\n"
+ "Jawab HANYA JSON array valid."
+ )
+ raw_text = await call_medium(prompt, temperature=0.5, max_output_tokens=6000)
+ if not raw_text:
+ raise ValueError("AI returned empty response")
+ cleaned = raw_text.strip()
+ if cleaned.startswith("```json"):
+ cleaned = cleaned[7:]
+ if cleaned.startswith("```"):
+ cleaned = cleaned[3:]
+ if cleaned.endswith("```"):
+ cleaned = cleaned[:-3]
+ cleaned = cleaned.strip()
+ pathway = json.loads(cleaned)
+ if not isinstance(pathway, list):
+ raise ValueError("AI response is not a JSON array")
+ init_progress = {}
+ for stage in pathway:
+ actions = stage.get("actions", [])
+ init_progress[str(stage.get("stage", 0))] = [
+ {"done": False, "proof": "", "ts": "", "status": ""} for _ in actions
+ ]
+ result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == e).limit(1))
+ existing_pw = result.scalar_one_or_none()
+ if existing_pw:
+ existing_pw.pathway_json = pathway
+ existing_pw.progress_json = init_progress
+ existing_pw.completed_stages = []
+ existing_pw.generated_at = datetime.now(timezone.utc)
+ existing_pw.green_score = 0
+ else:
+ db.add(TalentPathway(email=e, pathway_json=pathway, progress_json=init_progress, completed_stages=[], green_score=0))
+ await db.commit()
+ return {"success": True, "pathway": pathway, "progress": init_progress, "completedStages": [], "greenScore": 0, "cached": False}
+ except json.JSONDecodeError:
+ return {"success": False, "error": "Gagal memproses respons AI: format JSON tidak valid."}
+ except Exception as e:
+ return {"success": False, "error": f"Gagal membuat Career Pathway: {str(e)}"}
+
+
+async def submit_action_proof(db, email, stage, action_index, proof_text):
+ """Submit proof for a specific pathway action."""
+ try:
+ e = email.lower().strip()
+ result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == e).limit(1))
+ pw = result.scalar_one_or_none()
+ if not pw:
+ return {"success": False, "error": "Pathway belum dibuat."}
+ progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
+ completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
+ pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
+ if stage > len(completed) + 1:
+ return {"success": False, "error": "Stage ini belum terbuka."}
+ sk = str(stage)
+ if sk not in progress:
+ progress[sk] = []
+ while len(progress[sk]) <= action_index:
+ progress[sk].append({"done": False, "proof": "", "ts": "", "status": ""})
+ progress[sk][action_index] = {"done": True, "proof": proof_text.strip(), "ts": datetime.now(timezone.utc).isoformat(), "status": "Pending"}
+ score = _calc_green_score(progress, completed)
+ stage_data = next((s for s in pathway if s.get("stage") == stage), None)
+ all_proven = False
+ if stage_data and sk in progress:
+ expected = len(stage_data.get("actions", []))
+ all_proven = len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
+ pw.progress_json = progress
+ pw.green_score = score
+ db.add(pw)
+ await db.commit()
+ return {"success": True, "progress": progress, "completedStages": [str(s) for s in completed], "greenScore": score, "allActionsProven": all_proven}
+ except Exception as e:
+ logger.error(f"submit_action_proof error: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def submit_quiz_answers(db, email, stage, answers):
+ """Submit quiz answers for a stage. All actions must be proven first."""
+ try:
+ e = email.lower().strip()
+ result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == e).limit(1))
+ pw = result.scalar_one_or_none()
+ if not pw:
+ return {"success": False, "error": "Pathway belum dibuat."}
+ pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
+ progress = pw.progress_json if isinstance(pw.progress_json, dict) else {}
+ completed = pw.completed_stages if isinstance(pw.completed_stages, list) else []
+ sk = str(stage)
+ stage_data = next((s for s in pathway if s.get("stage") == stage), None)
+ if not stage_data or not stage_data.get("quiz"):
+ return {"success": False, "error": "Kuis tidak tersedia untuk stage ini."}
+ expected = len(stage_data.get("actions", []))
+ all_proven = sk in progress and len(progress[sk]) >= expected and all(a.get("done") for a in progress[sk][:expected])
+ if not all_proven:
+ return {"success": False, "error": "Selesaikan semua aksi terlebih dahulu."}
+ quiz = stage_data["quiz"]
+ correct = sum(1 for i, q in enumerate(quiz) if i < len(answers) and int(answers[i]) == int(q.get("answer", -1)))
+ if correct < len(quiz):
+ return {"success": False, "error": f"Jawaban belum benar semua ({correct}/{len(quiz)}). Silakan coba lagi!", "score": correct, "total": len(quiz)}
+ if sk not in [str(s) for s in completed]:
+ completed.append(stage)
+ score = _calc_green_score(progress, completed)
+ pw.completed_stages = completed
+ pw.green_score = score
+ db.add(pw)
+ await db.commit()
+ try:
+ tr = await db.execute(select(Talent).where(func.lower(Talent.email) == e).limit(1))
+ to = tr.scalar_one_or_none()
+ if to:
+ to.green_score = score
+ db.add(to)
+ await db.commit()
+ except Exception:
+ await db.rollback()
+ return {"success": True, "completedStages": [str(s) for s in completed], "greenScore": score, "stageCompleted": True, "completedStageTitle": stage_data.get("title", f"Stage {stage}")}
+ except Exception as e:
+ logger.error(f"submit_quiz_answers error: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_pathway_certificate(db, email, stage):
+ """Get certificate for a completed stage."""
+ try:
+ e = email.lower().strip()
+ result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == e).limit(1))
+ pw = result.scalar_one_or_none()
+ if not pw:
+ return {"success": False, "error": "Pathway tidak ditemukan."}
+ completed = [str(s) for s in (pw.completed_stages or [])]
+ if str(stage) not in completed:
+ return {"success": False, "error": "Stage belum diselesaikan."}
+ pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
+ stage_data = next((s for s in pathway if s.get("stage") == stage), None)
+ proofs = [a.get("proof", "") for a in (pw.progress_json or {}).get(str(stage), []) if isinstance(a, dict) and a.get("done")]
+ tr = await db.execute(select(Talent).where(func.lower(Talent.email) == e).limit(1))
+ to = tr.scalar_one_or_none()
+ return {"success": True, "certificate": {
+ "nama": to.name if to else "Talent", "stage": stage,
+ "title": stage_data.get("title", f"Stage {stage}") if stage_data else f"Stage {stage}",
+ "skills": stage_data.get("skills_to_gain", []) if stage_data else [],
+ "milestone": stage_data.get("milestone", "") if stage_data else "",
+ "proofs": proofs, "greenScore": pw.green_score or 0,
+ "completedAt": pw.generated_at.isoformat() if pw.generated_at else datetime.now(timezone.utc).isoformat(),
+ "talentId": _mask_talent_id(to.talent_id if to else ""),
+ }}
+ except Exception as e:
+ logger.error(f"get_pathway_certificate error: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def verify_certificate(db, talent_id, stage):
+ """Public certificate verification via talent ID or SHA-256 hash."""
+ try:
+ clean_tid = talent_id.strip()
+ is_hash = len(clean_tid) == 64
+ result = await db.execute(select(Talent))
+ talents = result.scalars().all()
+ email = None
+ actual_tid = None
+ for t in talents:
+ db_tid = (t.talent_id or "").strip()
+ if not db_tid:
+ continue
+ match = False
+ if is_hash:
+ db_hash = hashlib.sha256(db_tid.encode()).hexdigest()
+ if db_hash.lower() == clean_tid.lower():
+ match = True
+ else:
+ if db_tid.upper() == clean_tid.upper():
+ match = True
+ if match:
+ email = t.email
+ actual_tid = db_tid
+ break
+ if not email:
+ return {"success": False, "error": "ID Talent tidak valid."}
+ pw_result = await db.execute(select(TalentPathway).where(func.lower(TalentPathway.email) == email.lower()).limit(1))
+ pw = pw_result.scalar_one_or_none()
+ if not pw:
+ return {"success": False, "error": "Data pencapaian tidak ditemukan."}
+ completed = [str(s) for s in (pw.completed_stages or [])]
+ if str(stage) not in completed:
+ return {"success": False, "error": "Sertifikat ini belum tervalidasi atau belum diselesaikan."}
+ pathway = pw.pathway_json if isinstance(pw.pathway_json, list) else []
+ stage_data = next((s for s in pathway if s.get("stage") == stage), None)
+ return {"success": True, "data": {
+ "nama": next((t.name for t in talents if t.email == email), "Talent"),
+ "stage": stage,
+ "title": stage_data.get("title", f"Stage {stage}") if stage_data else f"Stage {stage}",
+ "milestone": stage_data.get("milestone", "") if stage_data else "",
+ "completedAt": pw.generated_at.isoformat() if pw.generated_at else None,
+ "greenScore": pw.green_score or 0,
+ "talentId": _mask_talent_id(actual_tid or ""),
+ }}
+ except Exception as e:
+ logger.error(f"verify_certificate error: {e}")
+ return {"success": False, "error": str(e)}
+
+
+# ===== Academy =====
+
+async def _get_academy_modules(db, email):
+ """Get completed academy modules for a talent."""
+ try:
+ result = await db.execute(select(TalentAcademy).where(func.lower(TalentAcademy.email) == email.lower().strip()).limit(1))
+ acad = result.scalar_one_or_none()
+ if not acad or not acad.completed_modules:
+ return []
+ return [m.strip() for m in acad.completed_modules.split(",") if m.strip()]
+ except Exception as e:
+ logger.error(f"_get_academy_modules error: {e}")
+ return []
+
+
+# ===== AI Chat =====
+
+async def _get_chat_stats(db, email):
+ """Get AI chat usage stats for a talent."""
+ try:
+ cutoff = datetime.now(timezone.utc) - timedelta(hours=CHAT_EXPIRY_HOURS)
+ result = await db.execute(
+ select(AITalentChat).where(
+ AITalentChat.email == email,
+ AITalentChat.timestamp >= cutoff,
+ ).order_by(AITalentChat.timestamp.desc()).limit(CHAT_LIMIT)
+ )
+ chats = list(result.scalars().all())
+ used = len(chats)
+ latest_ts = chats[0].timestamp if chats else None
+ expiry_time = "-"
+ if latest_ts:
+ expiry = latest_ts + timedelta(hours=CHAT_EXPIRY_HOURS)
+ expiry_time = expiry.strftime("%d %b %Y %H:%M") + " WIB"
+ history = [{"role": "user", "text": c.user_message, "ts": c.timestamp.isoformat() if c.timestamp else None, "aiReply": c.ai_reply} for c in reversed(chats)]
+ return {"used": used, "expiryTime": expiry_time, "history": history}
+ except Exception as e:
+ logger.error(f"_get_chat_stats error: {e}")
+ return {"used": 0, "expiryTime": "-", "history": []}
+
+
+async def save_chat_record(db, email, user_message, ai_reply):
+ """Save a chat record."""
+ try:
+ now = datetime.now(timezone.utc)
+ expiry = now + timedelta(hours=CHAT_EXPIRY_HOURS)
+ chat = AITalentChat(email=email, user_message=user_message, ai_reply=ai_reply, timestamp=now, expires_at=expiry)
+ db.add(chat)
+ await db.commit()
+ except Exception as e:
+ logger.error(f"save_chat_record error: {e}")
+ await db.rollback()
+
+
+async def chat_with_brigawan(db, email, message):
+ """AI Career Coach chat. Limited to 10 chats per 24h."""
+ try:
+ e = email.lower().strip()
+ chat_stats = await _get_chat_stats(db, e)
+ if chat_stats.get("used", 0) >= CHAT_LIMIT:
+ expiry = chat_stats.get("expiryTime", "-")
+ return {"success": False, "limitReached": True,
+ "error": f"Batas {CHAT_LIMIT} percakapan dalam {CHAT_EXPIRY_HOURS} jam telah tercapai. Silakan coba lagi setelah {expiry}.",
+ "chatExpiry": expiry}
+ profile_resp = await get_talent_profile(db, e)
+ profile = profile_resp.get("data", {}) if profile_resp.get("success") else {}
+ remaining = CHAT_LIMIT - chat_stats.get("used", 0) - 1
+ system_prompt = (
+ "Kamu adalah Brigawan AI, Career Coach eksklusif untuk green jobs dan sustainability careers di Indonesia. "
+ "Kamu memiliki kepribadian profesional, hangat, dan memotivasi. "
+ f"Profil talent yang sedang kamu bantu: "
+ f"Nama: {profile.get('nama', 'Talent')}. "
+ f"Pendidikan: {profile.get('universitas', '-')}, {profile.get('jurusan', '-')} ({profile.get('strata', '-')}). "
+ f"Pengalaman & Skills: {profile.get('pengalaman', '-')}. "
+ f"Kota: {profile.get('kota', '-')}. "
+ f"AI Score: {profile.get('ai_score', 0)}/100. "
+ f"AI Category: {profile.get('ai_category', '-')}. "
+ "PENTING: Jawab dalam Bahasa Indonesia yang profesional. "
+ "Fokus pada arahan konkret karir green/sustainability. "
+ f"Sisa kuota chat talent ini: {remaining} setelah pesan ini."
+ )
+ full_prompt = system_prompt + "\n\nPesan dari Talent: " + message
+ ai_reply_text, _ = await call_low(full_prompt, temperature=0.75, max_output_tokens=1024)
+ if not ai_reply_text:
+ ai_reply_text = "Terima kasih atas pesan Anda. Saat ini asisten AI sedang tidak tersedia. Silakan coba lagi nanti atau hubungi kami melalui email info@briga.id untuk bantuan lebih lanjut."
+ await save_chat_record(db, e, message, ai_reply_text)
+ ai_reply = ai_reply_text # preserve for return
+ new_stats = await _get_chat_stats(db, e)
+ return {"success": True, "reply": ai_reply, "chatUsed": new_stats.get("used", 0),
+ "chatLimit": CHAT_LIMIT, "chatExpiry": new_stats.get("expiryTime", "-"),
+ "limitReached": new_stats.get("used", 0) >= CHAT_LIMIT}
+ except Exception as e:
+ logger.error(f"chat_with_brigawan error: {e}")
+ return {"success": False, "error": "Gagal menghubungi AI: " + str(e)}
+
+
+# ===== Grill-Me Interview =====
+
+FALLBACK_QUESTIONS = [
+ "Bagaimana Anda menerapkan prinsip keberlanjutan / ESG dalam proyek teknis Anda sebelumnya?",
+ "Jelaskan tantangan terbesar yang Anda hadapi saat mengimplementasikan solusi energi hijau / efisiensi sumber daya dan cara mengatasinya.",
+ "Jika ada konflik antara efisiensi biaya jangka pendek dengan kepatuhan lingkungan jangka panjang, keputusan apa yang akan Anda ambil?",
+]
+
+
+async def generate_grillme_questions(category="ESG Specialist"):
+ """Generate 3 interview simulation questions using AI."""
+ try:
+ prompt = (
+ "Kamu adalah Pewawancara Teknis Rekrutmen Karir Hijau yang sangat ahli. "
+ f"Tugasmu adalah membuat exactly 3 pertanyaan wawancara (2 teknis spesifik & 1 perilaku situasional) "
+ f"yang sangat mendalam dan sesuai untuk sektor/kategori hijau: \"{category}\".\n\n"
+ "Ketentuan format output:\n"
+ "Berikan respons HANYA berupa valid JSON array of strings dengan format:\n"
+ '["Pertanyaan 1", "Pertanyaan 2", "Pertanyaan 3"]\n\n'
+ "Jangan berikan penjelasan, preambul, markdown code blocks, atau teks lainnya. Hanya JSON array saja."
+ )
+ raw_text, _ = await call_low(prompt, temperature=0.7, max_output_tokens=1024)
+ if not raw_text:
+ raise ValueError("Empty AI response")
+ cleaned = raw_text.strip()
+ if cleaned.startswith("```json"):
+ cleaned = cleaned[7:]
+ if cleaned.startswith("```"):
+ cleaned = cleaned[3:]
+ if cleaned.endswith("```"):
+ cleaned = cleaned[:-3]
+ cleaned = cleaned.strip()
+ questions = json.loads(cleaned)
+ if not isinstance(questions, list) or len(questions) != 3:
+ raise ValueError(f"Expected 3 questions, got {len(questions)}")
+ return {"success": True, "questions": questions, "isFallback": False}
+ except Exception as e:
+ logger.error(f"generate_grillme_questions error: {e}")
+ return {"success": True, "questions": FALLBACK_QUESTIONS, "isFallback": True}
+
+
+def evaluate_grillme(category, questions, answers):
+ """Evaluate interview answers and generate SWOT analysis."""
+ try:
+ if not questions or not answers or len(questions) != 3 or len(answers) != 3:
+ return {"success": False, "error": "Pertanyaan atau jawaban tidak lengkap."}
+ transcript = ""
+ for i in range(3):
+ transcript += f"Pewawancara: {questions[i]}\nKandidat: {answers[i]}\n\n"
+ prompt = (
+ "Kamu adalah Pewawancara Utama & Ahli Evaluasi Karir Hijau B2B di Brigawan AI.\n"
+ f"Evaluasilah transkrip wawancara berikut untuk kategori \"{category}\":\n\n"
+ f"{transcript}\n"
+ "Tugasmu:\n"
+ "1. Berikan skor numerik bulat keseluruhan antara 50 sampai 100.\n"
+ "2. Berikan analisis SWOT yang terperinci dalam bahasa Indonesia.\n"
+ "3. Format respons harus berupa JSON objek valid:\n"
+ '{"score": 85, "strengths": "...", "weaknesses": "...", "opportunities": "...", "threats": "...", "summary": "..."}'
+ )
+ raw_text = call_medium(prompt, temperature=0.6, max_output_tokens=2048)
+ if not raw_text:
+ raise ValueError("Empty AI response")
+ cleaned = raw_text.strip()
+ if cleaned.startswith("```json"):
+ cleaned = cleaned[7:]
+ if cleaned.startswith("```"):
+ cleaned = cleaned[3:]
+ if cleaned.endswith("```"):
+ cleaned = cleaned[:-3]
+ cleaned = cleaned.strip()
+ evaluation = json.loads(cleaned)
+ final_score = max(50, min(100, int(evaluation.get("score", 75))))
+ swot = {"score": final_score,
+ "strengths": evaluation.get("strengths", ""),
+ "weaknesses": evaluation.get("weaknesses", ""),
+ "opportunities": evaluation.get("opportunities", ""),
+ "threats": evaluation.get("threats", ""),
+ "summary": evaluation.get("summary", "")}
+ return {"success": True, "score": final_score, "swot": swot,
+ "rawSWOTText": f"=== EVALUASI WAWANCARA AI ({category}) ===\n\nKEKUATAN (STRENGTHS):\n{swot['strengths']}"}
+ except Exception as e:
+ logger.error(f"evaluate_grillme error: {e}")
+ return {"success": False, "error": f"Gagal mengevaluasi wawancara: {str(e)}"}
+
+
+# ===== Secure Talent Data =====
+
+async def get_secure_talent_data(db, candidate_id, requester_email):
+ """Get talent data with PDP-compliant masking."""
+ from app.models.job import MediatedChat
+ try:
+ result = await db.execute(select(Talent).where(Talent.talent_id == candidate_id).limit(1))
+ candidate = result.scalar_one_or_none()
+ if not candidate:
+ return {"success": False, "error": "Candidate not found."}
+ unlock_result = await db.execute(
+ select(MediatedChat).where(
+ MediatedChat.receiver_email == candidate.email,
+ MediatedChat.sender_email == requester_email,
+ MediatedChat.is_identity_unlocked == True,
+ ).limit(1)
+ )
+ is_unlocked = unlock_result.scalar_one_or_none() is not None
+ if is_unlocked:
+ return {"success": True, "id_kandidat": candidate.talent_id,
+ "nama": candidate.name or "", "email": candidate.email or "",
+ "pendidikan": candidate.education or "", "pengalaman": candidate.experience or "",
+ "k3_dasar": candidate.k3_dasar or "", "k3_khusus": candidate.k3_khusus or "",
+ "sertifikasi": candidate.cert_other or "", "bahasa": candidate.language or "",
+ "cv_link": candidate.cv_link or "", "skor": candidate.score or 0,
+ "kategori": candidate.category or "", "analisis": candidate.analysis or "",
+ "status": candidate.verification_status or "", "unlocked": True}
+ else:
+ return {"success": True, "id_kandidat": candidate.talent_id,
+ "nama": f"Talent {candidate.talent_id}", "email": "[LOCKED]",
+ "pendidikan": "[MASKED]", "pengalaman": "[MASKED]",
+ "k3_dasar": candidate.k3_dasar or "", "k3_khusus": candidate.k3_khusus or "",
+ "sertifikasi": candidate.cert_other or "", "bahasa": candidate.language or "",
+ "cv_link": "[LOCKED - Reveal to Download]", "skor": candidate.score or 0,
+ "kategori": candidate.category or "", "analisis": candidate.analysis or "",
+ "status": candidate.verification_status or "", "unlocked": False}
+ except Exception as e:
+ logger.error(f"get_secure_talent_data error: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_talent_by_email(db, email):
+ """Lookup talent record by email."""
+ result = await db.execute(select(Talent).where(func.lower(Talent.email) == email.lower().strip()).limit(1))
+ return result.scalar_one_or_none()
diff --git a/app/services/telegram_ceo_service.py b/app/services/telegram_ceo_service.py
index 564320ba4f0846517d8e2989c4284c3601a170b0..283efd3fa958a81fc42d5d3792cd1d75b49d796a 100644
--- a/app/services/telegram_ceo_service.py
+++ b/app/services/telegram_ceo_service.py
@@ -1,1697 +1,1697 @@
-"""Telegram CEO Service — Direct Founder Line to AI CEO and Payment Verification Bot."""
-
-import os
-import json
-import httpx
-import base64
-import re
-import asyncio
-from datetime import datetime, timedelta, timezone
-from typing import Optional, Dict, Any
-from loguru import logger
-from zoneinfo import ZoneInfo
-
-from sqlalchemy import select, update, func, cast, String, or_, text
-from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.config.settings import settings
-from app.services.antigravity import AntigravityOrchestrator
-from app.services.linkedin_service import LinkedInPoster
-from app.services import ai_service
-from app.services.email_service import email_service
-from app.services.google_workspace_service import spark_agent
-
-# Models
-from app.models.job import JobPosting, RecruiterOutreach
-from app.models.finance import Transaction
-from app.models.talent import Talent
-from app.models.content import KnowledgeQueue
-from app.models.system import ActivityLog, SecurityAuditLog, PrivacyAuditLog, TelegramSession
-
-
-class TelegramCEOService:
- def __init__(self, db: AsyncSession):
- self.db = db
- self.token = settings.telegram_bot_token or os.getenv("TELEGRAM_BOT_TOKEN")
- self.admin_chat_id = settings.telegram_admin_chat_id or os.getenv("TELEGRAM_ADMIN_CHAT_ID")
-
- # Proxy routing: HF Spaces blocks direct egress to api.telegram.org.
- # Support two modes:
- # 1. Transparent Proxy (Cloudflare): proxy_url + "/method"
- # 2. RPC Proxy (Google Apps Script): proxy_url with action="proxyTelegram"
- self._proxy_url = (settings.telegram_proxy_url or os.getenv("TELEGRAM_PROXY_URL", "")).rstrip("/")
- self._proxy_secret = settings.telegram_proxy_secret or os.getenv("TELEGRAM_PROXY_SECRET", "")
- self._use_proxy = bool(self._proxy_url and self._proxy_secret)
- self._is_gas_proxy = "script.google.com" in self._proxy_url
-
- self.base_url = self._proxy_url if self._use_proxy and not self._is_gas_proxy else f"https://api.telegram.org/bot{self.token}"
- self.api_url = self.base_url # Compatibility alias
- self.orchestrator = AntigravityOrchestrator(db)
- self.tz = ZoneInfo("Asia/Jakarta")
-
- def _proxy_headers(self) -> dict:
- """Returns auth headers required when using the CF proxy."""
- if self._use_proxy and not self._is_gas_proxy:
- return {"X-Proxy-Secret": self._proxy_secret, "Content-Type": "application/json"}
- return {"Content-Type": "application/json"}
-
- async def get_telegram_session(self, chat_id: str) -> Optional[dict]:
- """Fetch active session from database, checking TTL of 30 minutes."""
- try:
- stmt = select(TelegramSession).where(TelegramSession.chat_id == chat_id)
- res = await self.db.execute(stmt)
- session = res.scalar_one_or_none()
- if session and session.last_context:
- ctx = session.last_context
- ts_str = ctx.get("timestamp")
- if ts_str:
- ts = datetime.fromisoformat(ts_str)
- if (datetime.now(timezone.utc) - ts).total_seconds() < 1800:
- return ctx
- except Exception as e:
- logger.error(f"Error fetching Telegram session: {e}")
- return None
-
- async def save_telegram_session(self, chat_id: str, tx_id: str, state: Optional[str] = None):
- """Save/update verification session in database."""
- try:
- stmt = select(TelegramSession).where(TelegramSession.chat_id == chat_id)
- res = await self.db.execute(stmt)
- session = res.scalar_one_or_none()
- ctx = {
- "tx_id": tx_id,
- "timestamp": datetime.now(timezone.utc).isoformat()
- }
- if session:
- session.last_context = ctx
- if state:
- session.state = state
- session.updated_at = datetime.now(timezone.utc)
- else:
- session = TelegramSession(
- chat_id=chat_id,
- state=state,
- last_context=ctx,
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc)
- )
- self.db.add(session)
- await self.db.commit()
- logger.info(f"Telegram session saved for chat {chat_id}, tx_id {tx_id}")
- except Exception as e:
- logger.error(f"Error saving Telegram session: {e}")
-
- async def delete_telegram_session(self, chat_id: str):
- """Clear active session from database."""
- try:
- stmt = select(TelegramSession).where(TelegramSession.chat_id == chat_id)
- res = await self.db.execute(stmt)
- session = res.scalar_one_or_none()
- if session:
- session.last_context = None
- session.state = None
- session.updated_at = datetime.now(timezone.utc)
- await self.db.commit()
- logger.info(f"Telegram session cleared for chat {chat_id}")
- except Exception as e:
- logger.error(f"Error clearing Telegram session: {e}")
-
- async def log_privacy_audit(self, query: str, user_email: str, risk_score: int = 10):
- """Log privacy sensitive actions to privacy_audit_log table."""
- try:
- # Simple automatic risk score adjustment based on PII triggers
- kw_lower = query.lower()
- if any(kw in kw_lower for kw in ["cv", "ktp", "nik", "telepon", "phone", "email", "nama", "name"]):
- risk_score = 30 # Medium risk if querying PII keywords
-
- audit = PrivacyAuditLog(
- query=query,
- user_email=user_email,
- risk_score=risk_score,
- timestamp=datetime.now(timezone.utc)
- )
- self.db.add(audit)
- await self.db.commit()
- logger.info(f"Privacy audit logged: {query} by {user_email}")
- except Exception as e:
- logger.error(f"Failed to log privacy audit: {e}")
-
- async def log_security_audit(self, action: str, details: str, status: str = "success"):
- """Log security critical events to security_audit_log table."""
- try:
- audit = SecurityAuditLog(
- page_type="Telegram_Bot",
- target_url=f"Telegram_Command/{action}",
- status=status,
- details=details,
- timestamp=datetime.now(timezone.utc)
- )
- self.db.add(audit)
- await self.db.commit()
- logger.info(f"Security audit logged: {action} - {status}")
- except Exception as e:
- logger.error(f"Failed to log security audit: {e}")
-
- async def log_activity(self, actor: str, action: str, metadata: str = "-"):
- """Log administrative activities to activity_logs table."""
- try:
- log = ActivityLog(
- actor=actor,
- action=action,
- log_metadata=metadata,
- timestamp=datetime.now(timezone.utc)
- )
- self.db.add(log)
- await self.db.commit()
- logger.info(f"Activity log registered: {action} by {actor}")
- except Exception as e:
- logger.error(f"Failed to register activity log: {e}")
-
- async def send_executive_alert(self, message: str, urgent: bool = False):
-
- """Sends a proactive alert to the Founder."""
- if not self.token or not self.admin_chat_id:
- logger.warning("Telegram credentials missing, skipping executive alert.")
- return False
-
- prefix = "🚨 *URGENT CEO ALERT*" if urgent else "ℹ️ *AI CEO UPDATE*"
- text = f"{prefix}\n\n{message}"
-
- return await self.send_message(self.admin_chat_id, text)
-
- async def send_message(self, chat_id: Any, text: str, parse_mode: str = "Markdown", reply_markup: Optional[dict] = None) -> bool:
- """Sends a generic text message to a specified chat."""
- if not self.token:
- logger.warning("Telegram token missing, cannot send message.")
- return False
-
- payload = {
- "chat_id": chat_id,
- "text": text,
- "parse_mode": parse_mode
- }
- if reply_markup:
- payload["reply_markup"] = reply_markup
-
- if self._use_proxy and self._is_gas_proxy:
- # RPC Proxy Mode (GAS)
- target_url = self._proxy_url
- rpc_payload = {
- "action": "proxyTelegram",
- "params": ["sendMessage", payload, self._proxy_secret]
- }
- async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
- try:
- response = await client.post(target_url, json=rpc_payload)
- if response.status_code == 200:
- res_json = response.json()
- if res_json.get("success"):
- return True
- logger.warning(f"GAS Telegram Proxy returned failure: {res_json}")
- else:
- logger.warning(f"GAS Telegram Proxy HTTP {response.status_code}: {response.text[:200]}")
- return False
- except Exception as e:
- logger.error(f"Error calling GAS Telegram proxy: {e}")
- return False
-
- # Default or Transparent Proxy Mode
- url = f"{self.base_url}/sendMessage"
- async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:
- try:
- response = await client.post(url, json=payload, headers=self._proxy_headers())
- if response.status_code != 200:
- logger.warning(f"Telegram sendMessage returned {response.status_code}: {response.text[:200]}")
- return response.status_code == 200
- except Exception as e:
- logger.error(f"Error sending Telegram message: {e}")
- return False
-
- async def answer_callback_query(self, callback_query_id: str, text: str):
- if not self.token: return
- url = f"{self.base_url}/answerCallbackQuery"
- payload = {
- "callback_query_id": callback_query_id,
- "text": text
- }
- async with httpx.AsyncClient(timeout=15.0) as client:
- try:
- await client.post(url, json=payload, headers=self._proxy_headers())
- except Exception as e:
- logger.error(f"Error answering callback query: {e}")
-
- async def edit_message_text(self, chat_id: Any, message_id: int, new_text: str):
- if not self.token: return
- url = f"{self.base_url}/editMessageText"
- payload = {
- "chat_id": chat_id,
- "message_id": message_id,
- "text": new_text,
- "parse_mode": "Markdown"
- }
- async with httpx.AsyncClient(timeout=15.0) as client:
- try:
- await client.post(url, json=payload, headers=self._proxy_headers())
- except Exception as e:
- logger.error(f"Error editing message: {e}")
-
- async def download_file(self, file_id: str) -> bytes:
- """Downloads a file from Telegram using its file_id."""
- if not self.token:
- raise Exception("Telegram token missing")
- # Step 1: getFile API call (via proxy if enabled)
- get_file_url = f"{self.base_url}/getFile"
- async with httpx.AsyncClient(timeout=20.0) as client:
- resp = await client.post(get_file_url, json={"file_id": file_id}, headers=self._proxy_headers())
- if resp.status_code == 200:
- file_path = resp.json().get("result", {}).get("file_path")
- if file_path:
- # Step 2: Download actual file bytes
- if self._use_proxy:
- # Route file download through CF proxy: /api/telegram-proxy/file/{path}
- download_url = f"{self._proxy_url}/file/{file_path}"
- file_resp = await client.get(download_url, headers=self._proxy_headers())
- else:
- download_url = f"https://api.telegram.org/file/bot{self.token}/{file_path}"
- file_resp = await client.get(download_url)
- if file_resp.status_code == 200:
- return file_resp.content
- raise Exception("Gagal mengunduh file dari Telegram")
-
- async def run_vision_ocr(self, photo_bytes: bytes) -> dict:
- """Sends photo bytes to Gemini Vision to extract payment receipt details."""
- from app.services.ai_service import RAW_KEYS
- api_key = RAW_KEYS[0] if (RAW_KEYS and RAW_KEYS[0]) else settings.gemini_api_key
- if not api_key:
- return {"error": "GEMINI_API_KEY not configured"}
-
- encoded_image = base64.b64encode(photo_bytes).decode("utf-8")
- url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={api_key}"
-
- prompt = (
- "Analyze this receipt image. Extract: 1. Nominal / total amount transferred (integer, e.g. 450000 or 1200000. Ignore cent digits if it's 450000.00), "
- "2. Sender Bank Name (e.g. BCA, Mandiri, BNI, etc.), "
- "3. Date and time of transfer. "
- "Respond strictly in JSON format with keys: 'amount' (integer), 'bank' (string), 'date' (string), 'is_blurry' (boolean, set true if details are illegible or it's not a payment receipt)."
- )
-
- payload = {
- "contents": [
- {
- "parts": [
- {"text": prompt},
- {
- "inlineData": {
- "mimeType": "image/jpeg",
- "data": encoded_image
- }
- }
- ]
- }
- ],
- "generationConfig": {
- "responseMimeType": "application/json"
- }
- }
-
- async with httpx.AsyncClient(timeout=30.0) as client:
- try:
- resp = await client.post(url, json=payload)
- if resp.status_code == 200:
- data = resp.json()
- text = data["candidates"][0]["content"]["parts"][0]["text"].strip()
- if text.startswith("```"):
- text = re.sub(r"^```[a-z]*\n|```$", "", text).strip()
- parsed = json.loads(text)
- return parsed
- else:
- logger.error(f"Gemini Vision API error: {resp.status_code} - {resp.text}")
- return {"error": f"Gemini Vision API error: {resp.status_code}"}
- except Exception as e:
- logger.error(f"Gemini Vision call failed: {e}")
- return {"error": f"Gemini Vision call failed: {e}"}
-
- async def get_system_health_stats(self) -> dict:
- """Helper to calculate real-time platform statistics directly from DB."""
- yesterday = datetime.now(timezone.utc) - timedelta(days=1)
-
- total_jobs = (await self.db.execute(select(func.count(JobPosting.id)))).scalar() or 0
- pending_jobs = (await self.db.execute(select(func.count(JobPosting.id)).where(cast(JobPosting.status, String).in_(["scraped", "analyzed", "draft"])))).scalar() or 0
- new_jobs = (await self.db.execute(select(func.count(JobPosting.id)).where(JobPosting.timestamp >= yesterday))).scalar() or 0
-
- total_outreach = (await self.db.execute(select(func.count(RecruiterOutreach.id)))).scalar() or 0
- stale_outreach = (await self.db.execute(select(func.count(RecruiterOutreach.id)).where(cast(RecruiterOutreach.status, String) == "pending_approval"))).scalar() or 0
- sent_outreach_today = (await self.db.execute(select(func.count(RecruiterOutreach.id)).where(cast(RecruiterOutreach.status, String) == "sent", RecruiterOutreach.sent_at >= yesterday))).scalar() or 0
-
- total_talents = (await self.db.execute(select(func.count(Talent.id)))).scalar() or 0
- total_transactions = (await self.db.execute(select(func.count(Transaction.id)))).scalar() or 0
- total_revenue = (await self.db.execute(select(func.sum(Transaction.amount)).where(cast(Transaction.status, String) == "Settled"))).scalar() or 0
-
- return {
- "total_jobs": total_jobs,
- "pending_jobs": pending_jobs,
- "new_jobs_today": new_jobs,
- "total_outreach": total_outreach,
- "stale_outreach": stale_outreach,
- "sent_outreach_today": sent_outreach_today,
- "total_talents": total_talents,
- "total_transactions": total_transactions,
- "total_revenue": float(total_revenue or 0)
- }
-
- async def generate_daily_briefing(self) -> str:
- """Generate and send comprehensive daily briefing to Telegram admin."""
- stats = await self.get_system_health_stats()
-
- summary = (
- f"📊 *BRIGAWAN CEO BRIEFING* — {datetime.now(self.tz).strftime('%Y-%m-%d %H:%M')}\n\n"
- f"📌 *Ringkasan 24 Jam Terakhir*\n"
- f"━━━━━━━━━━━━━━━━━━\n"
- f"• *Jobs Baru:* {stats['new_jobs_today']} lowongan\n"
- f"• *Outreach Pending:* {stats['stale_outreach']} rekomendasi\n"
- f"• *Outreach Terkirim:* {stats['sent_outreach_today']} email\n"
- f"• *Total Talent:* {stats['total_talents']} terdaftar\n\n"
- )
-
- prompt = f"""Kamu adalah CEO Agent dari platform Brigawan — platform karir hijau Indonesia.
-
-DATA OPERASIONAL 24 JAM TERAKHIR:
-- Jobs baru di-scrape: {stats['new_jobs_today']} (total database: {stats['total_jobs']})
-- Outreach pending approval: {stats['stale_outreach']}
-- Outreach terkirim hari ini: {stats['sent_outreach_today']}
-- Total talent di database: {stats['total_talents']}
-
-TUGAS:
-1. Analisis singkat: apakah performa platform sehat?
-2. Berikan 2-3 rekomendasi strategis untuk hari ini
-3. Jika ada anomali (semua metrik 0, atau lonjakan), highlight
-
-Format jawaban dalam JSON:
-{{
- "health_status": "healthy|needs_attention|critical",
- "analysis": "1-2 kalimat analisis",
- "recommendations": ["rekomendasi 1", "rekomendasi 2"],
- "anomalies": ["anomali jika ada"],
- "priority_action": "satu tindakan prioritas hari ini"
-}}"""
-
- analysis, _ = await ai_service.call_gemini_json(prompt, temperature=0.2)
-
- if "error" not in analysis:
- health_emoji = {"healthy": "✅", "needs_attention": "⚠️", "critical": "🚨"}
- health = analysis.get("health_status", "healthy")
- emoji = health_emoji.get(health, "✅")
-
- summary += (
- f"🤖 *CEO Analysis:* {emoji} *{health.upper()}*\n"
- f"➡️ {analysis.get('analysis', '')}\n\n"
- f"🎯 *Rekomendasi Hari Ini:*\n"
- )
- for rec in analysis.get("recommendations", []):
- summary += f" • {rec}\n"
-
- anomalies = analysis.get("anomalies", [])
- if anomalies:
- summary += f"\n🚩 *Anomali Terdeteksi:*\n"
- for a in anomalies:
- summary += f" • ⚠️ {a}\n"
-
- priority = analysis.get("priority_action", "")
- if priority:
- summary += f"\n🔥 *Prioritas:* {priority}\n"
-
- await self.send_message(self.admin_chat_id, summary)
- return summary
-
- async def check_system_health(self):
- """Check all Brigawan subsystems and report to admin."""
- stats = await self.get_system_health_stats()
-
- issues = []
- if stats["pending_jobs"] > 5:
- issues.append(f"{stats['pending_jobs']} jobs menunggu approval admin")
- if stats["stale_outreach"] > 10:
- issues.append(f"{stats['stale_outreach']} outreach pending > 24 jam")
- if stats["total_talents"] == 0:
- issues.append("Database talent kosong")
-
- status = "healthy" if not issues else "needs_attention" if len(issues) <= 2 else "critical"
-
- emoji = "✅" if status == "healthy" else "⚠️" if status == "needs_attention" else "🚨"
- msg = (
- f"🩹 *CEO SYSTEM HEALTH CHECK*\n\n"
- f"📊 *Status:* {emoji} {status.upper()}\n\n"
- f"*Issues:*\n"
- )
- if issues:
- for iss in issues:
- msg += f" • ❌ {iss}\n"
- else:
- msg += " • ✅ Tidak ada isu operasional kritis terdeteksi.\n"
-
- rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
- msg += f"\n🤖 Total Jobs: {stats['total_jobs']} | Outreach: {stats['total_outreach']} | Talent: {stats['total_talents']} | Revenue: {rev_formatted}"
-
- await self.send_message(self.admin_chat_id, msg)
- return stats
-
- async def delegate_task_to_queue(self, action: str, params: dict):
- """Insert task into knowledge_queue in PostgreSQL."""
- try:
- task = KnowledgeQueue(
- category="AGENT_TASK",
- fact=json.dumps({"action": action, "params": params}),
- status="Pending",
- source_email="ceo-agent@briga.id"
- )
- self.db.add(task)
- await self.db.commit()
- logger.info(f"CEO Delegated {action} to knowledge_queue.")
- except Exception as e:
- logger.error(f"Failed to delegate task to knowledge_queue: {e}")
-
- async def process_semantic_instruction(self, text: str):
- """Parse natural language from admin and delegate tasks (Two-Stage Query System)."""
- stats = await self.get_system_health_stats()
- rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
-
- # --- STAGE 1: INTENT & PARAMETER EXTRACTION ---
- stage1_prompt = f"""Kamu adalah Koordinator CEO Agent Brigawan. Tugasmu adalah menganalisis pesan dari Founder dan menentukan apakah dia membutuhkan pencarian data atau tindakan dari database.
-
-Pesan Founder: "{text}"
-
-Tentukan aksi database (db_lookup) apa yang dibutuhkan.
-Pilihan `db_lookup_type`:
-- "talent_search": Jika Founder mencari talenta/kandidat dengan kriteria/keahlian/lokasi tertentu. (Contoh: "cari ahli solar panel di Bandung")
-- "pending_jobs": Jika Founder menanyakan tentang lowongan yang butuh persetujuan atau baru masuk. (Contoh: "apa ada lowongan baru?")
-- "pending_outreach": Jika Founder menanyakan tentang outreach yang pending atau rekomendasi email.
-- "finance": Jika Founder menanyakan tentang keuangan, pendapatan, transaksi.
-- "job_detail": Jika Founder menanyakan rincian dari suatu lowongan tertentu (sertakan parameter `job_id`).
-- "none": Jika pesan hanya berupa obrolan santai, diskusi ide bisnis, atau tidak membutuhkan query database khusus.
-
-Tentukan juga jika ada perintah operasional untuk dijalankan (delegated_task):
-- action: "bulk_sourcing", "nurture_dormant", "run_scrape_cycle", "run_outreach_sweep", "run_outreach_for_job" (sertakan job_id di params), atau "none".
-
-FORMAT OUTPUT JSON:
-{{
- "db_lookup": {{
- "type": "talent_search|pending_jobs|pending_outreach|finance|job_detail|none",
- "params": {{
- "keyword": "kata kunci pencarian talenta jika ada",
- "job_id": "job id jika ada"
- }}
- }},
- "delegated_task": {{
- "action": "action_name_or_none",
- "params": {{}}
- }}
-}}"""
-
- analysis, _ = await ai_service.call_gemini_json(stage1_prompt, temperature=0.2)
-
- if "error" in analysis:
- await self.send_message(self.admin_chat_id, f"❌ Gagal menganalisis instruksi: {analysis['error']}")
- return
-
- db_lookup = analysis.get("db_lookup", {})
- db_type = db_lookup.get("type", "none")
- db_params = db_lookup.get("params", {})
-
- retrieved_data_str = ""
-
- # --- DATABASE QUERY EXECUTION ---
- try:
- if db_type == "talent_search":
- kw = db_params.get("keyword", "")
- if kw:
- kw_wildcard = f"%{kw}%"
- stmt = select(Talent).where(
- or_(
- Talent.name.ilike(kw_wildcard),
- Talent.skill_tags.ilike(kw_wildcard),
- Talent.experience.ilike(kw_wildcard),
- Talent.location.ilike(kw_wildcard),
- Talent.category.ilike(kw_wildcard)
- )
- ).limit(5)
- res = await self.db.execute(stmt)
- talents = res.scalars().all()
-
- if talents:
- retrieved_data_str = "Hasil Pencarian Talenta:\n"
- for t in talents:
- retrieved_data_str += f"- ID: {t.talent_id}, Nama: {t.name}, Kategori: {t.category}, Lokasi: {t.location}, Skills: {t.skill_tags}, Green Score: {t.green_score}, Status: {t.verification_status}\n"
- else:
- retrieved_data_str = f"Tidak ditemukan talenta dengan kata kunci '{kw}'."
- else:
- retrieved_data_str = "Kata kunci pencarian talenta tidak disediakan."
-
- elif db_type == "pending_jobs":
- stmt = select(JobPosting).where(cast(JobPosting.status, String).in_(["scraped", "analyzed", "draft"])).order_by(JobPosting.timestamp.asc()).limit(5)
- res = await self.db.execute(stmt)
- jobs = res.scalars().all()
- if jobs:
- retrieved_data_str = "Daftar Lowongan Pekerjaan Pending (Menunggu Approval):\n"
- for j in jobs:
- retrieved_data_str += f"- ID: {j.job_id}, Title: {j.title}, Company: {j.company_name}, Location: {j.location}, Source: {j.source}, Created At: {j.timestamp}\n"
- else:
- retrieved_data_str = "Tidak ada lowongan pekerjaan yang pending."
-
- elif db_type == "pending_outreach":
- stmt = select(RecruiterOutreach).where(cast(RecruiterOutreach.status, String) == "pending_approval").order_by(RecruiterOutreach.triggered_at.asc()).limit(5)
- res = await self.db.execute(stmt)
- outreaches = res.scalars().all()
- if outreaches:
- retrieved_data_str = "Daftar Outreach Pending (Menunggu Approval):\n"
- for o in outreaches:
- retrieved_data_str += f"- ID: {o.outreach_id}, Talent: {o.talent_email}, Recruiter: {o.recruiter_email}, Match Score: {o.match_score}%\n"
- else:
- retrieved_data_str = "Tidak ada email outreach yang pending."
-
- elif db_type == "finance":
- stmt = select(Transaction).order_by(Transaction.created_at.desc()).limit(5)
- res = await self.db.execute(stmt)
- txs = res.scalars().all()
- retrieved_data_str = f"Laporan Keuangan Singkat:\n- Total Pendapatan Settled: {rev_formatted}\n- Total Transaksi: {stats['total_transactions']}\n"
- if txs:
- retrieved_data_str += "5 Transaksi Terakhir:\n"
- for t in txs:
- retrieved_data_str += f" - ID: {t.id}, Client: {t.client_id}, Amount: Rp {int(t.amount):,}, Status: {t.status}, Date: {t.created_at}\n"
- else:
- retrieved_data_str += "Tidak ada riwayat transaksi."
- retrieved_data_str = retrieved_data_str.replace(",", ".")
-
- elif db_type == "job_detail":
- jid = db_params.get("job_id", "")
- if jid:
- stmt = select(JobPosting).where(JobPosting.job_id == jid)
- res = await self.db.execute(stmt)
- job = res.scalar_one_or_none()
- if job:
- retrieved_data_str = (
- f"Detail Lowongan Pekerjaan:\n"
- f"- ID: {job.job_id}\n"
- f"- Title: {job.title}\n"
- f"- Company: {job.company_name}\n"
- f"- Location: {job.location}\n"
- f"- Sektor: {job.company_category}\n"
- f"- Required Skills: {job.required_skills}\n"
- f"- Description: {job.description[:500] if job.description else ''}\n"
- f"- Status: {job.status}\n"
- )
- else:
- retrieved_data_str = f"Pekerjaan dengan ID '{jid}' tidak ditemukan."
- else:
- retrieved_data_str = "Job ID tidak disediakan untuk pencarian rincian lowongan."
- else:
- retrieved_data_str = "Tidak ada pencarian database khusus yang diperlukan."
- except Exception as q_err:
- logger.error(f"Error executing semantic database query: {q_err}")
- retrieved_data_str = f"Gagal mengambil data dari database karena kesalahan teknis: {q_err}"
-
- # --- STAGE 2: RESPONSE SYNTHESIS ---
- synthesis_prompt = f"""Kamu adalah CEO Agent Brigawan, rekan diskusi strategis bagi Founder.
-Founder menanyakan: "{text}"
-
-BERKAS/DATA TERBARU DARI DATABASE:
-{retrieved_data_str}
-
-STATISTIK UMUM PLATFORM:
-- Total Jobs: {stats['total_jobs']}
-- Total Talent: {stats['total_talents']}
-- Outreach Pending: {stats['stale_outreach']}
-- Total Transaksi B2B: {stats['total_transactions']}
-- Total Pendapatan Settled: {rev_formatted}
-
-TUGASMU:
-1. Berikan tanggapan/jawaban yang sangat solutif, berbasis data (data-driven), dan relevan dalam Bahasa Indonesia yang elegan.
-2. Jika data yang dicari Founder ada di atas, jabarkan dengan rapi dan berikan rekomendasi tindakan berikutnya.
-3. Jika data tidak ditemukan, katakan dengan sopan dan berikan saran pencarian yang lebih baik.
-4. Gunakan gaya penulisan profesional namun suportif seorang partner bisnis terpercaya (C-Level).
-5. Jangan menyebutkan detail teknis SQL atau internal database, fokuslah pada nilai bisnis dan operasional.
-
-Jawab langsung berupa teks pesan Telegram (mendukung format Markdown)."""
-
- response_text, _ = await ai_service.call_medium(synthesis_prompt)
-
- if not response_text:
- response_text = "Maaf, saya gagal mensintesis tanggapan strategis."
-
- # Send response to founder
- await self.send_message(self.admin_chat_id, response_text)
-
- # --- TASK DELEGATION HANDLER ---
- task = analysis.get("delegated_task", {})
- if task.get("action") and task.get("action") != "none":
- await self.delegate_task_to_queue(task["action"], task.get("params", {}))
-
- async def handle_ceo_command(self, text: str, chat_id: Any) -> str:
- """Processes incoming executive commands (slash commands) from Telegram."""
- cmd = text.split(" ")[0].lower()
-
- if cmd in ["/menu", "/help"]:
- menu_text = (
- f"⚡ *BRIGAWAN CEO COMMAND CENTER* ⚡\n\n"
- f"Selamat datang, Founder. Silakan gunakan menu tombol cepat di bawah ini untuk berinteraksi dengan sistem, "
- f"atau ketik instruksi Anda dalam bahasa natural.\n\n"
- f"*Daftar Perintah Manual:*\n"
- f"• `/menu` atau `/help` - Menampilkan menu ini\n"
- f"• `/status` - Menampilkan status kesehatan sistem secara ringkas\n"
- f"• `/search_talent ` - Mencari talent berdasarkan skill/lokasi (Contoh: `/search_talent AMDAL`)\n"
- f"• `/job_detail ` - Menampilkan rincian lowongan (Contoh: `/job_detail JB-001`)\n"
- f"• `/pending_jobs` - Menampilkan lowongan yang menunggu persetujuan\n"
- f"• `/pending_outreach` - Menampilkan email outreach yang menunggu persetujuan\n"
- f"• `/match_job ` - Memicu pencocokan kandidat untuk lowongan secara langsung\n"
- f"• `/finance` - Menampilkan laporan keuangan platform\n"
- f"• `/scrape` - Memulai siklus scraping lowongan baru\n"
- f"• `/outreach` - Memulai pencocokan outreach di background\n"
- f"• `/debate ` - Diskusi strategis AI CEO"
- )
- reply_markup = {
- "inline_keyboard": [
- [
- {"text": "📊 CEO Briefing", "callback_data": "menu_briefing"},
- {"text": "🩹 Health Check", "callback_data": "menu_health"}
- ],
- [
- {"text": "💼 Jobs Pending", "callback_data": "menu_pendingjobs"},
- {"text": "📧 Outreach Pending", "callback_data": "menu_pendingoutreach"}
- ],
- [
- {"text": "💰 Laporan Keuangan", "callback_data": "menu_finance"}
- ]
- ]
- }
- await self.send_message(chat_id, menu_text, reply_markup=reply_markup)
- return ""
-
- elif cmd in ["/status", "/ceo_status"]:
- stats = await self.get_system_health_stats()
- emoji = "✅" if stats["pending_jobs"] == 0 else "⚠️"
- rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
-
- reply = (
- f"⚙️ *BRIGAWAN SYSTEM STATUS*\n\n"
- f"📊 *Health Check:* {emoji} ONLINE\n"
- f"• Total Jobs: *{stats['total_jobs']}*\n"
- f"• Pending Jobs: *{stats['pending_jobs']}*\n"
- f"• Total Outreach: *{stats['total_outreach']}*\n"
- f"• Stale Outreach: *{stats['stale_outreach']}*\n"
- f"• Total Talent: *{stats['total_talents']}*\n"
- f"• Total Revenue: *{rev_formatted}*\n\n"
- f"Semua operasional berjalan lancar."
- )
- return reply.replace(",", ".")
-
- elif cmd == "/briefing":
- await self.generate_daily_briefing()
- return "✅ *CEO Daily Briefing harian Anda berhasil dikirim!*"
-
- elif cmd in ["/debate", "/ceo_debate"]:
- idea = text[8:].strip() if cmd == "/debate" else text[12:].strip()
- if not idea:
- return f"❌ Perintah salah. Gunakan: `{cmd} `"
-
- res = await self.orchestrator.execute_task(
- agent_name="AntigravityCEO",
- task_name="strategic_debate",
- payload={"idea": idea}
- )
- return res.get("data", {}).get("debate_result", "Maaf, saya sedang gagal berpikir.")
-
- elif cmd == "/scrape":
- await self.delegate_task_to_queue("run_scrape_cycle", {})
- return "⚡ *Memulai proses scraping lowongan hijau baru di background...*"
-
- elif cmd == "/outreach":
- await self.delegate_task_to_queue("run_outreach_sweep", {})
- return "🧹 *Memulai pencocokan kandidat dan pengiriman outreach di background...*"
-
- elif cmd == "/search_talent":
- keyword = text[14:].strip()
- if not keyword:
- return f"❌ Silakan sertakan kata kunci. Contoh: `/search_talent AMDAL` atau `/search_talent Jakarta`"
-
- # Log privacy audit (UU PDP Compliance)
- await self.log_privacy_audit(
- query=f"/search_talent {keyword}",
- user_email=f"telegram_{chat_id}",
- risk_score=10
- )
-
- kw_wildcard = f"%{keyword}%"
- stmt = select(Talent).where(
- or_(
- Talent.name.ilike(kw_wildcard),
- Talent.skill_tags.ilike(kw_wildcard),
- Talent.experience.ilike(kw_wildcard),
- Talent.location.ilike(kw_wildcard),
- Talent.category.ilike(kw_wildcard)
- )
- ).limit(5)
-
- res = await self.db.execute(stmt)
- talents = res.scalars().all()
-
- if not talents:
- return f"🔍 Tidak ditemukan talenta dengan kata kunci *'{keyword}'*."
-
- reply = f"🔍 *HASIL PENCARIAN TALENTA ({len(talents)})* untuk *'{keyword}'*:\n━━━━━━━━━━━━━━━━━━\n"
- for t in talents:
- reply += (
- f"👤 *{t.name}* (`{t.talent_id}`)\n"
- f"• Kategori: {t.category or '-'}\n"
- f"• Lokasi: {t.location or '-'}\n"
- f"• Green Score: {t.green_score}\n"
- f"• Skills: `{t.skill_tags or '-'}`\n"
- f"• Status Verifikasi: *{t.verification_status}*\n"
- f"• CV Link: {t.cv_link or '-'}\n"
- f"━━━━━━━━━━━━━━━━━━\n"
- )
- return reply
-
- elif cmd == "/job_detail":
- job_id = text[11:].strip()
- if not job_id:
- return f"❌ Silakan sertakan Job ID. Contoh: `/job_detail JB-001`"
-
- # Log privacy audit (UU PDP Compliance)
- await self.log_privacy_audit(
- query=f"/job_detail {job_id}",
- user_email=f"telegram_{chat_id}",
- risk_score=5
- )
-
- stmt = select(JobPosting).where(JobPosting.job_id == job_id)
- res = await self.db.execute(stmt)
- job = res.scalar_one_or_none()
-
- if not job:
- return f"❌ Pekerjaan dengan ID *{job_id}* tidak ditemukan."
-
- reply = (
- f"💼 *RINCIAN PEKERJAAN: {job.title}*\n"
- f"• ID Lowongan: `{job.job_id}`\n"
- f"• Perusahaan: *{job.company_name or '-'}*\n"
- f"• Lokasi: {job.location or '-'}\n"
- f"• Sektor Hijau: {job.company_category or '-'}\n"
- f"• Status: *{job.status.upper()}*\n"
- f"• Link Sumber: {job.source_url or '-'}\n"
- f"• LinkedIn Post: {job.linkedin_post_url or '-'}\n"
- f"• Tanggal Dibuat: {job.timestamp.strftime('%Y-%m-%d %H:%M') if job.timestamp else '-'}\n"
- f"━━━━━━━━━━━━━━━━━━\n"
- f"📝 *Deskripsi Singkat:*\n{job.description[:400] + '...' if job.description and len(job.description) > 400 else job.description or '-'}\n\n"
- f"⚙️ *Skill yang Dibutuhkan:*\n`{job.required_skills or '-'}`"
- )
- return reply
-
- elif cmd in ["/approve", "/reject"]:
- activity_id_prefix = text.split(" ")[1].strip() if len(text.split(" ")) > 1 else ""
- if not activity_id_prefix:
- return f"❌ Gunakan format: `{cmd} `"
-
- try:
- from app.models.system import AgentActivity # Needs to be defined or use raw SQL
- # Let's use raw SQL for simplicity to match prefix
- stmt = text("SELECT id, status FROM agent_activities WHERE id::text LIKE :id_prefix LIMIT 1")
- res = await self.db.execute(stmt, {"id_prefix": f"{activity_id_prefix}%"})
- row = res.fetchone()
-
- if not row:
- return f"❌ Tidak ada aktivitas yang cocok dengan ID `{activity_id_prefix}`."
-
- full_id, current_status = row[0], row[1]
-
- if current_status != 'BLOCKED':
- return f"⚠️ Aktivitas `{full_id}` tidak dalam status BLOCKED (Status saat ini: {current_status})."
-
- new_status = 'APPROVED' if cmd == '/approve' else 'REJECTED'
-
- upd_stmt = text("UPDATE agent_activities SET status = :status, updated_at = NOW() WHERE id = :id")
- await self.db.execute(upd_stmt, {"status": new_status, "id": full_id})
- await self.db.commit()
-
- icon = "✅" if new_status == 'APPROVED' else "❌"
- return f"{icon} *Tindakan {new_status}* berhasil dicatat untuk aktivitas `{full_id}`. Workflow agent akan segera merespons."
-
- except Exception as e:
- logger.error(f"Error handling intervention command: {e}")
- return f"❌ Gagal memproses persetujuan: {e}"
-
- elif cmd == "/pending_jobs":
- stmt = select(JobPosting).where(cast(JobPosting.status, String).in_(["scraped", "analyzed", "draft"])).order_by(JobPosting.timestamp.asc()).limit(5)
- res = await self.db.execute(stmt)
- jobs = res.scalars().all()
-
- if not jobs:
- return "✅ Tidak ada lowongan pekerjaan yang menunggu persetujuan (status: scraped/analyzed/draft)."
-
- await self.send_message(chat_id, f"📋 *DAFTAR PEKERJAAN MENUNGGU PERSETUJUAN ({len(jobs)})*:")
-
- for j in jobs:
- caption = (
- f"💼 *{j.title}* at *{j.company_name or 'Unknown'}*\n"
- f"• Job ID: `{j.job_id}`\n"
- f"• Lokasi: {j.location or '-'}\n"
- f"• Skills: `{j.required_skills or '-'}`\n"
- f"• Sumber: {j.source or '-'}\n"
- )
- markup = {
- "inline_keyboard": [
- [
- {"text": "✅ Approve & Post", "callback_data": f"approve_{j.job_id}"},
- {"text": "❌ Reject", "callback_data": f"reject_{j.job_id}"}
- ]
- ]
- }
- await self.send_message(chat_id, caption, reply_markup=markup)
- return "Gunakan tombol di atas untuk menyetujui atau menolak lowongan."
-
- elif cmd == "/pending_outreach":
- stmt = select(RecruiterOutreach).where(cast(RecruiterOutreach.status, String) == "pending_approval").order_by(RecruiterOutreach.triggered_at.asc()).limit(5)
- res = await self.db.execute(stmt)
- outreaches = res.scalars().all()
-
- if not outreaches:
- return "✅ Tidak ada email outreach rekruter yang menunggu persetujuan."
-
- await self.send_message(chat_id, f"📧 *DAFTAR OUTREACH MENUNGGU PERSETUJUAN ({len(outreaches)})*:")
-
- for o in outreaches:
- caption = (
- f"📧 *Outreach ID:* `{o.outreach_id}`\n"
- f"👤 *Talenta:* `{o.talent_email}`\n"
- f"🏢 *Rekruter:* `{o.recruiter_email}`\n"
- f"📊 *Skor Kecocokan:* `{o.match_score}%`\n"
- f"📝 *Subjek:* {o.outreach_subject or '-'}\n"
- )
- markup = {
- "inline_keyboard": [
- [
- {"text": "✅ Approve & Send", "callback_data": f"approveoutreach_{o.outreach_id}"},
- {"text": "❌ Reject", "callback_data": f"rejectoutreach_{o.outreach_id}"}
- ],
- [
- {"text": "📋 Copy LinkedIn Pitch", "callback_data": f"copypitch_{o.outreach_id}"}
- ]
- ]
- }
- await self.send_message(chat_id, caption, reply_markup=markup)
- return "Gunakan tombol di atas untuk mengelola rekomendasi outreach."
-
- elif cmd == "/match_job":
- job_id = text[11:].strip()
- if not job_id:
- return "❌ Silakan sertakan Job ID. Contoh: `/match_job JB-001`"
-
- stmt = select(JobPosting).where(JobPosting.job_id == job_id)
- res = await self.db.execute(stmt)
- job = res.scalar_one_or_none()
-
- if not job:
- return f"❌ Pekerjaan dengan ID *{job_id}* tidak ditemukan."
-
- await self.delegate_task_to_queue("run_outreach_for_job", {"job_id": job_id})
- return f"⚡ *Memulai pencocokan kandidat dan draf outreach untuk lowongan {job_id} ({job.title}) di background...*"
-
- elif cmd == "/finance":
- # Log privacy audit (UU PDP Compliance)
- await self.log_privacy_audit(
- query="/finance",
- user_email=f"telegram_{chat_id}",
- risk_score=5
- )
- stats = await self.get_system_health_stats()
- rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
-
- stmt = select(Transaction).order_by(Transaction.created_at.desc()).limit(5)
- res = await self.db.execute(stmt)
- txs = res.scalars().all()
-
- reply = (
- f"💰 *LAPORAN KEUANGAN PLATFORM (B2B)*\n"
- f"━━━━━━━━━━━━━━━━━━\n"
- f"• Total Transaksi: *{stats['total_transactions']}*\n"
- f"• Total Pendapatan Settled: *{rev_formatted}*\n\n"
- f"📊 *5 Transaksi Terakhir:*\n"
- )
-
- if not txs:
- reply += "_(Tidak ada riwayat transaksi)_"
- else:
- for t in txs:
- amount_formatted = f"Rp {int(t.amount):,}".replace(",", ".")
- status_emoji = "✅" if t.status == "Settled" else "❌" if t.status in ["Failed", "Rejected"] else "⏳"
- reply += (
- f"• {status_emoji} *{t.id}* - {amount_formatted}\n"
- f" Client: `{t.client_id or '-'}` | Status: *{t.status}*\n"
- f" Tanggal: {t.created_at.strftime('%d %b %Y, %H:%M') if t.created_at else '-'}\n"
- )
-
- stmt_pending = select(Transaction).where(cast(Transaction.status, String) == "Pending")
- res_pending = await self.db.execute(stmt_pending)
- pending_txs = res_pending.scalars().all()
- if pending_txs:
- reply += f"\n⏳ *Ada {len(pending_txs)} Transaksi Pending yang Butuh Bukti Transfer:*\n"
- for pt in pending_txs:
- reply += f" - `{pt.id}` | Nominal: Rp {int(pt.amount):,}\n"
- reply = reply.replace(",", ".")
- reply += "\n_Gunakan `/verify ` diikuti upload foto bukti transfer untuk verifikasi._"
- else:
- reply = reply.replace(",", ".")
-
- return reply
-
- return "Perintah tidak dikenal. Gunakan `/menu` untuk melihat daftar perintah lengkap."
-
- async def handle_webhook(self, data: dict) -> dict:
- """Main entry point for incoming Telegram updates."""
- try:
- # --- HANDLE CALLBACK QUERIES (Inline Button Clicks) ---
- if "callback_query" in data:
- callback_query = data["callback_query"]
- callback_id = callback_query["id"]
- callback_data = callback_query["data"]
- message = callback_query.get("message", {})
- message_id = message.get("message_id")
- chat_id = message.get("chat", {}).get("id")
-
- logger.info(f"⚡ Processing Telegram callback: {callback_data}")
-
- action, target_id = callback_data.split("_", 1)
-
- # Verify that callback is from the Admin/Founder
- if str(chat_id) != str(self.admin_chat_id):
- await self.answer_callback_query(callback_id, "❌ Anda tidak memiliki akses.")
- await self.log_security_audit(
- action=f"callback_{action}",
- details=f"Unauthorized callback attempt by non-admin chat_id {chat_id} on target {target_id}",
- status="blocked"
- )
- return {"status": "unauthorized"}
-
- # Log administrative activity (UU PDP & Security Compliance)
- await self.log_activity(
- actor=str(chat_id),
- action=action,
- metadata=target_id
- )
-
- # --- 1. HANDLE B2B PAYMENT APPROVALS/REJECTIONS ---
- if action in ["approvepay", "rejectpay"]:
- parts_pay = target_id.split("_")
- tx_id = parts_pay[0]
- user_chat_id = parts_pay[1] if len(parts_pay) > 1 else None
-
- if action == "approvepay":
- await self.answer_callback_query(callback_id, "⏳ Memproses pembayaran...")
- try:
- # 1. Fetch transaction
- stmt = select(Transaction).where(Transaction.id == tx_id)
- tx_res = await self.db.execute(stmt)
- tx = tx_res.scalar_one_or_none()
- if not tx:
- await self.answer_callback_query(callback_id, "❌ Transaksi tidak ditemukan.")
- return {"status": "error", "message": "Transaction not found"}
-
- if tx.status == "Settled":
- await self.answer_callback_query(callback_id, "❌ Transaksi sudah disetujui.")
- return {"status": "error", "message": "Already settled"}
-
- # 2. Determine coins to add
- amount = float(tx.amount)
- coins_added = 20 if (450000 <= amount < 451000) else (60 if (1200000 <= amount < 1201000) else (200 if (3500000 <= amount < 3501000) else 0))
- if coins_added == 0:
- from app.services.employer_service import COIN_BUNDLES
- bundle_id = [k for k, v in COIN_BUNDLES.items() if abs(v["idr_price"] - amount) < 10000]
- coins_added = COIN_BUNDLES[bundle_id[0]]["coins"] if bundle_id else 0
- if coins_added == 0:
- coins_added = int(amount / 20000) # fallback exchange rate
-
- # 3. Credit coins to company wallet
- from app.models.employer import ClientAccount, Company
- client_stmt = select(ClientAccount).where(ClientAccount.id == tx.client_id)
- client_res = await self.db.execute(client_stmt)
- client = client_res.scalar_one_or_none()
-
- client_email = ""
- if client:
- client_email = client.email
- company_stmt = select(Company).where(Company.id == client.company_id)
- company_res = await self.db.execute(company_stmt)
- company = company_res.scalar_one_or_none()
- if company:
- company.credit_balance = (company.credit_balance or 0) + coins_added
- self.db.add(company)
-
- # 4. Settle transaction in PostgreSQL
- tx.status = "Settled"
- self.db.add(tx)
- await self.db.commit()
-
- amount_formatted = f"Rp {int(amount):,}".replace(",", ".")
- new_text = (
- f"✅ *TRANSAKSI DISETUJUI & DIKREDITKAN*\n\n"
- f"• ID Transaksi: *{tx_id}*\n"
- f"• Koin telah dikreditkan ke: *{client_email or 'Unknown'}*\n"
- f"• Koin ditambahkan: *{coins_added} Briga Coin*\n"
- f"• Nominal: *{amount_formatted}*\n"
- f"• Diverifikasi pada: *{datetime.now().strftime('%d %b %Y, %H:%M')} WIB*"
- )
- await self.edit_message_text(chat_id, message_id, new_text)
- await self.answer_callback_query(callback_id, "🎉 Pembayaran sukses disetujui!")
-
- # 5. Direct Write to Google Sheets via Sheets API (Direct backup)
- try:
- if settings.google_sheets_spreadsheet_id:
- row_values = [
- tx.id,
- tx.client_id or "",
- float(tx.amount),
- tx.type or "TopUpManual",
- "Settled",
- tx.snap_token or "Telegram Verification",
- datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- ]
- await spark_agent.append_row_to_sheet(
- settings.google_sheets_spreadsheet_id,
- "Transactions!A1",
- row_values
- )
- except Exception as sheets_err:
- logger.error(f"Failed to log transaction to Google Sheets: {sheets_err}")
-
- # 6. Send HTML confirmation email
- if client_email:
- try:
- tier_name = f"{coins_added} Coins"
- subject = f"✅ Top Up Briga Coin Berhasil - {tier_name}"
- html_body = f"""
-
-
-
-
BRIGAWAN. AI
-
Sustainability Career Center
-
-
-
-
🪙
-
Top Up Berhasil!
-
Saldo Briga Coin Anda telah ditambahkan.
-
-
-
Jumlah Koin Baru
-
+{coins_added}
-
Briga Coin
-
-
-
- Paket Langganan
- {tier_name}
-
-
- Total Pembayaran
- {amount_formatted}
-
-
- Metode Pembayaran
- Manual Transfer (Telegram Verified)
-
-
- Waktu Transaksi
- {datetime.now().strftime("%d %b %Y, %H:%M")} WIB
-
-
-
-
-
-
E-mail ini dikirimkan otomatis oleh sistem Brigawan AI. Jangan membalas email ini.
-
© 2026 Brigawan Sustainability Center. All Rights Reserved.
-
-
-
- """
- await asyncio.to_thread(email_service.send_html_email, client_email, subject, html_body)
- except Exception as mail_err:
- logger.error(f"Failed to send top-up email: {mail_err}")
-
- # 7. Notify recruiter via Telegram
- if user_chat_id:
- await self.send_message(
- user_chat_id,
- f"✅ *Top-up Berhasil!*\n\nPembayaran manual Anda sebesar *{amount_formatted}* telah diverifikasi.\n*{coins_added} Briga Coin* telah ditambahkan ke akun Anda."
- )
- await self.delete_telegram_session(str(user_chat_id))
- except Exception as ex:
- logger.error(f"Error in approvepay native handler: {ex}")
- await self.answer_callback_query(callback_id, f"❌ Error: {ex}")
-
- elif action == "rejectpay":
- await self.answer_callback_query(callback_id, "❌ Menolak transaksi...")
- try:
- # 1. Fetch transaction
- stmt = select(Transaction).where(Transaction.id == tx_id)
- tx_res = await self.db.execute(stmt)
- tx = tx_res.scalar_one_or_none()
- if tx:
- tx.status = "Failed"
- self.db.add(tx)
- await self.db.commit()
-
- new_text = (
- f"❌ *TRANSAKSI DITOLAK*\n\n"
- f"• ID Transaksi: *{tx_id}*\n"
- f"• Status: Ditinjau & Ditolak oleh Admin\n"
- f"• Waktu: *{datetime.now().strftime('%d %b %Y, %H:%M')} WIB*"
- )
- await self.edit_message_text(chat_id, message_id, new_text)
- await self.answer_callback_query(callback_id, "❌ Transaksi berhasil ditolak.")
-
- # 2. Direct Write to Google Sheets via Sheets API (Direct backup)
- try:
- if settings.google_sheets_spreadsheet_id:
- row_values = [
- tx.id,
- tx.client_id or "",
- float(tx.amount),
- tx.type or "TopUpManual",
- "Failed",
- "Rejected by Admin",
- datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- ]
- await spark_agent.append_row_to_sheet(
- settings.google_sheets_spreadsheet_id,
- "Transactions!A1",
- row_values
- )
- except Exception as sheets_err:
- logger.error(f"Failed to log transaction rejection to Google Sheets: {sheets_err}")
-
- # 3. Notify recruiter via Telegram
- if user_chat_id:
- await self.send_message(
- user_chat_id,
- f"❌ *Top-up Ditolak*\n\nBukti transfer manual untuk ID Transaksi *{tx_id}* ditolak oleh CEO. Mohon periksa kembali nominal transfer Anda."
- )
- await self.delete_telegram_session(str(user_chat_id))
- else:
- await self.answer_callback_query(callback_id, "❌ Transaksi tidak ditemukan.")
- except Exception as ex:
- logger.error(f"Error in rejectpay native handler: {ex}")
- await self.answer_callback_query(callback_id, f"❌ Error: {ex}")
- return {"status": "success"}
-
- # --- 2. HANDLE UNBLOCK ACTION ---
- elif action == "unblock":
- await self.answer_callback_query(callback_id, "🔓 Membuka blokir...")
- clean_id = target_id.replace("_at_", "@")
-
- try:
- # Direct PostgreSQL local unblock if it is an email address
- success = False
- if "@" in clean_id:
- from app.models.employer import ClientAccount
- stmt = select(ClientAccount).where(ClientAccount.email == clean_id)
- res = await self.db.execute(stmt)
- client = res.scalar_one_or_none()
- if client:
- client.status = "Active"
- self.db.add(client)
- await self.db.commit()
- success = True
- logger.info(f"Unblocked client email locally: {clean_id}")
-
- # Set message text to show success
- new_text = (
- f"🔓 *AKSES DI-UNBLOCK OLEH ADMIN*\n\n"
- f"👤 *Aktor/Target:* `{clean_id}`\n\n"
- f"Sesi keamanan untuk pengguna ini berhasil dipulihkan secara lokal!"
- )
- await self.edit_message_text(chat_id, message_id, new_text)
- await self.answer_callback_query(callback_id, "🎉 Blokir berhasil dibuka!")
- except Exception as ex:
- logger.error(f"Exception during local unblock: {ex}")
- await self.answer_callback_query(callback_id, f"❌ Gagal: {ex}")
- return {"status": "success"}
-
- # --- 3. HANDLE RECRUITER OUTREACH CALLBACK ACTIONS ---
- elif action in ["approveoutreach", "rejectoutreach", "copypitch"]:
- outreach_id = target_id
- stmt = select(RecruiterOutreach).where(RecruiterOutreach.outreach_id == outreach_id)
- outreach_res = await self.db.execute(stmt)
- target_outreach = outreach_res.scalar_one_or_none()
-
- if not target_outreach:
- await self.answer_callback_query(callback_id, "❌ Error: Rekaman outreach tidak ditemukan.")
- return {"status": "error", "message": "Outreach record not found"}
-
- if action == "approveoutreach":
- await self.answer_callback_query(callback_id, "⏳ Mengirim email outreach...")
-
- if target_outreach.status == "sent":
- await self.answer_callback_query(callback_id, "⚠️ Outreach ini sudah pernah dikirim.")
- return {"status": "already_sent"}
-
- try:
- # Direct Python-native SMTP email dispatch
- success = await asyncio.to_thread(
- email_service.send_html_email,
- target_outreach.recruiter_email,
- target_outreach.outreach_subject,
- target_outreach.outreach_body
- )
- if success:
- # Update PostgreSQL status
- target_outreach.status = "sent"
- target_outreach.sent_at = datetime.now(timezone.utc)
- await self.db.commit()
-
- new_text = (
- f"✅ *OUTREACH APPROVED & SENT*\n\n"
- f"📌 *Outreach ID:* `{outreach_id}`\n"
- f"💼 *Job ID:* `{target_outreach.job_id}`\n"
- f"👤 *Talenta:* `{target_outreach.talent_email}`\n"
- f"📊 *Skor Kecocokan:* `{target_outreach.match_score}%`\n"
- f"🏢 *Penerima:* `{target_outreach.recruiter_email}`\n\n"
- f"Email rekomendasi penawaran talenta berhasil dikirim resmi via SMTP!"
- )
- await self.edit_message_text(chat_id, message_id, new_text)
- await self.answer_callback_query(callback_id, "🎉 Email berhasil terkirim!")
- else:
- await self.answer_callback_query(callback_id, "❌ Gagal mengirim email via SMTP.")
- except Exception as ex:
- logger.error(f"Exception during native outreach: {ex}")
- await self.answer_callback_query(callback_id, f"❌ Error: {ex}")
-
- elif action == "rejectoutreach":
- target_outreach.status = "rejected"
- await self.db.commit()
- new_text = (
- f"❌ *OUTREACH REJECTED/IGNORED*\n\n"
- f"📌 *Outreach ID:* `{outreach_id}`\n"
- f"💼 *Job ID:* `{target_outreach.job_id}`\n"
- f"👤 *Talenta:* `{target_outreach.talent_email}`\n\n"
- f"Rekomendasi outreach rekruter ini telah ditolak/diabaikan."
- )
- await self.edit_message_text(chat_id, message_id, new_text)
- await self.answer_callback_query(callback_id, "❌ Outreach ditolak.")
-
- elif action == "copypitch":
- target_outreach.status = "manual_linkedin_copied"
- target_outreach.sent_at = datetime.now(timezone.utc)
- await self.db.commit()
-
- new_text = (
- f"📋 *LINKEDIN PITCH RETRIEVED*\n\n"
- f"📌 *Outreach ID:* `{outreach_id}`\n"
- f"💼 *Job ID:* `{target_outreach.job_id}`\n"
- f"👤 *Talenta:* `{target_outreach.talent_email}`\n\n"
- f"Pesan pitch LinkedIn telah dikirim di bawah ini. Silakan salin untuk melakukan outreach manual!"
- )
- await self.edit_message_text(chat_id, message_id, new_text)
-
- pitch_msg = (
- f"📋 *SALIN OUTREACH LINKEDIN ({outreach_id})*\n\n"
- f"{target_outreach.outreach_body}"
- )
- await self.send_message(chat_id, pitch_msg)
- await self.answer_callback_query(callback_id, "📋 Pitch LinkedIn terkirim!")
-
- return {"status": "success"}
-
- # --- 3.5. HANDLE SYSTEM AUTO-HEAL CALLBACK ACTIONS ---
- elif action in ["approveheal", "rejectheal"]:
- task_id = target_id
-
- if action == "approveheal":
- await self.answer_callback_query(callback_id, "⏳ Menjalankan perbaikan sistem (CTO Auto-Heal)...")
-
- worker_url = os.getenv("AGENT_WORKER_URL", "https://yabeskn-briga-agent-worker.hf.space").rstrip("/")
- target_url = f"{worker_url}/v1/agents/heal/approve"
-
- payload = {
- "task_id": task_id,
- "approved": True
- }
-
- headers = {
- "X-Webhook-Token": settings.webhook_secret or os.getenv("WEBHOOK_SECRET", "briga_secret_webhook_123_xyz"),
- "Content-Type": "application/json"
- }
-
- try:
- async with httpx.AsyncClient(timeout=60.0) as client:
- resp = await client.post(target_url, json=payload, headers=headers)
-
- if resp.status_code == 200:
- res_json = resp.json()
- if res_json.get("success"):
- new_text = (
- f"✅ *CTO AUTO-HEAL APPROVED & EXECUTED*\n\n"
- f"📌 *Task ID:* `{task_id}`\n\n"
- f"Sistem telah berhasil diperbaiki, diverifikasi aman, dan disinkronisasikan ke seluruh microservices!"
- )
- await self.edit_message_text(chat_id, message_id, new_text)
- await self.answer_callback_query(callback_id, "🎉 Sistem sukses dipulihkan!")
- else:
- err_detail = res_json.get("error", "Unknown error")
- await self.answer_callback_query(callback_id, f"❌ Gagal: {err_detail}")
- else:
- await self.answer_callback_query(callback_id, f"❌ Worker HTTP Error {resp.status_code}")
- except Exception as ex:
- logger.error(f"Exception during worker heal call: {ex}")
- await self.answer_callback_query(callback_id, f"❌ Koneksi Worker Gagal: {ex}")
-
- elif action == "rejectheal":
- await self.answer_callback_query(callback_id, "⏳ Membatalkan perbaikan...")
- try:
- stmt = update(KnowledgeQueue).where(KnowledgeQueue.id == task_id).values(status="Failed")
- await self.db.execute(stmt)
- await self.db.commit()
-
- new_text = (
- f"❌ *CTO AUTO-HEAL REJECTED/IGNORED*\n\n"
- f"📌 *Task ID:* `{task_id}`\n\n"
- f"Rekomendasi perbaikan sistem otomatis telah ditolak dan diabaikan."
- )
- await self.edit_message_text(chat_id, message_id, new_text)
- await self.answer_callback_query(callback_id, "❌ Perbaikan ditolak.")
- except Exception as ex:
- logger.error(f"Exception during reject heal: {ex}")
- await self.answer_callback_query(callback_id, f"❌ Gagal: {ex}")
-
- return {"status": "success"}
-
- # --- 4. HANDLE JOB APPROVAL CALLBACK ACTIONS ---
- elif action in ["approve", "reject"]:
- job_id = target_id
- stmt = select(JobPosting).where(JobPosting.job_id == job_id)
- job_res = await self.db.execute(stmt)
- job = job_res.scalar_one_or_none()
-
- if not job:
- await self.answer_callback_query(callback_id, "❌ Error: Pekerjaan tidak ditemukan.")
- return {"status": "error", "message": "Job not found"}
-
- if action == "approve":
- await self.answer_callback_query(callback_id, "⏳ Memproses postingan LinkedIn...")
-
- if job.status == "posted":
- await self.answer_callback_query(callback_id, "⚠️ Lowongan ini sudah diposting sebelumnya.")
- return {"status": "already_posted"}
-
- job.status = "posted"
- job.is_active = True
- job.posted_at = datetime.now(timezone.utc)
-
- # Smart category resolution
- company_category = job.company_category
- if not company_category:
- if job.company_name and "climatebase" in job.company_name.lower():
- company_category = "Platform Karir & Edukasi Iklim"
- else:
- company_category = "Perusahaan Sektor Hijau"
-
- # Post to LinkedIn Page
- poster = LinkedInPoster()
- skills = job.required_skills or ""
- post_url, error_msg = await poster.post_job(
- job_id=job_id,
- title=job.title,
- company_category=company_category,
- location=job.location or "Indonesia",
- skills=[s.strip() for s in skills.split(",") if s.strip()]
- )
-
- if post_url:
- job.linkedin_post_url = post_url
- new_text = (
- f"✅ *APPROVED & POSTED TO LINKEDIN*\n\n"
- f"📌 *ID:* `{job_id}`\n"
- f"💼 *Posisi:* {job.title}\n"
- f"🏢 *Industri:* {company_category}\n"
- f"📍 *Lokasi:* {job.location or 'Indonesia'}\n\n"
- f"🔗 [Lihat Postingan LinkedIn]({post_url})\n"
- f"🌐 [Lihat Lowongan di Briga.id](https://briga.id/job?id={job_id})"
- )
- else:
- reason = error_msg if error_msg else "Koneksi terputus atau token kadaluwarsa"
- new_text = (
- f"✅ *APPROVED & ACTIVE ON BRIGA.ID*\n⚠️ *LinkedIn Posting Failed:* {reason}\n\n"
- f"📌 *ID:* `{job_id}`\n"
- f"💼 *Posisi:* {job.title}\n"
- f"🏢 *Industri:* {company_category}\n"
- f"📍 *Lokasi:* {job.location or 'Indonesia'}\n\n"
- f"🌐 [Lihat Lowongan di Briga.id](https://briga.id/job?id={job_id})"
- )
-
- await self.db.commit()
- await self.edit_message_text(chat_id, message_id, new_text)
- await self.answer_callback_query(callback_id, "🎉 Berhasil disetujui!")
-
- # Trigger outreach swept in background
- await self.delegate_task_to_queue("run_outreach_for_job", {"job_id": job_id})
-
- elif action == "reject":
- job.status = "rejected"
- job.is_active = False
- await self.db.commit()
-
- new_text = (
- f"❌ *LOWONGAN DITOLAK*\n\n"
- f"📌 *ID:* `{job_id}`\n"
- f"💼 *Posisi:* {job.title}\n"
- f"🏢 *Perusahaan:* {job.company_name}\n\n"
- f"Status lowongan ini telah diubah menjadi 'rejected' dan tidak akan dipublikasikan."
- )
- await self.edit_message_text(chat_id, message_id, new_text)
- await self.answer_callback_query(callback_id, "❌ Lowongan ditolak.")
-
- return {"status": "success"}
-
- elif action == "menu":
- if target_id == "briefing":
- await self.answer_callback_query(callback_id, "⏳ Menghasilkan briefing...")
- await self.generate_daily_briefing()
- elif target_id == "health":
- await self.answer_callback_query(callback_id, "⏳ Mengecek kesehatan...")
- await self.check_system_health()
- elif target_id == "pendingjobs":
- await self.answer_callback_query(callback_id, "⏳ Mengambil lowongan pending...")
- reply = await self.handle_ceo_command("/pending_jobs", chat_id)
- if reply:
- await self.send_message(chat_id, reply)
- elif target_id == "pendingoutreach":
- await self.answer_callback_query(callback_id, "⏳ Mengambil outreach pending...")
- reply = await self.handle_ceo_command("/pending_outreach", chat_id)
- if reply:
- await self.send_message(chat_id, reply)
- elif target_id == "finance":
- await self.answer_callback_query(callback_id, "⏳ Mengambil data keuangan...")
- reply = await self.handle_ceo_command("/finance", chat_id)
- if reply:
- await self.send_message(chat_id, reply)
- return {"status": "success"}
-
- # --- HANDLE MESSAGES (Incoming Chat / Receipt Uploads) ---
- if "message" in data:
- message = data["message"]
- chat_id = message.get("chat", {}).get("id")
- user_id = message.get("from", {}).get("id")
- text = message.get("text", "")
-
- # Strict access control verification for non-admin
- is_admin = str(chat_id) == str(self.admin_chat_id)
- is_pay_start = text.startswith("/start") and text[7:].strip().startswith("pay_")
- is_verify = text.startswith("/verify")
- is_photo = "photo" in message and len(message["photo"]) > 0
- is_simple_start = text.strip() == "/start"
-
- if not is_admin:
- # Non-admin is strictly only allowed to access payment flows (start pay_, verify, photo upload) or generic /start hello
- if not (is_pay_start or is_verify or is_photo or is_simple_start):
- # Log attempt to security_audit_log
- cmd_attempt = text.split(" ")[0] if text else "photo_or_other"
- await self.log_security_audit(
- action=cmd_attempt,
- details=f"Unauthorized access attempt by non-admin chat_id {chat_id}. Message: {text[:200]}",
- status="blocked"
- )
- # Reply with clear error
- await self.send_message(chat_id, "❌ Anda tidak memiliki akses untuk fitur ini.")
- return {"status": "unauthorized"}
-
- # --- HANDLE START COMMAND (Deep link pay_TX-XXXXXX) ---
- if text.startswith("/start"):
- payload = text[7:].strip()
- if payload.startswith("pay_"):
- tx_id = payload[4:].upper()
- await self.save_telegram_session(str(user_id), tx_id, state="waiting_receipt")
- reply = (
- f"👋 *Selamat datang di Brigawan Payment Bot!*\n\n"
- f"Kami mendeteksi pengajuan Top-Up dengan ID Transaksi: *{tx_id}*.\n\n"
- f"📌 *Langkah selanjutnya:*\n"
- f"1. Transfer nominal paket sesuai invoice ke rekening:\n"
- f" 🏦 *Bank BCA: 1234567890*\n"
- f" 👤 *a/n PT Briga Energi Indonesia*\n"
- f"2. *Unggah / Kirimkan foto bukti transfer* Anda langsung ke chat bot ini.\n\n"
- f"Setelah foto dikirim, AI akan menganalisis dan Admin kami akan memverifikasi instan!"
- )
- await self.send_message(chat_id, reply)
- return {"status": "success"}
-
- if str(chat_id) == str(self.admin_chat_id):
- reply = await self.handle_ceo_command("/menu", chat_id)
- if reply:
- await self.send_message(chat_id, reply)
- return {"status": "success"}
-
- await self.send_message(chat_id, "👋 *Halo!* Silakan mulai top-up koin dari Portal Rekruter Brigawan untuk menggunakan bot konfirmasi pembayaran ini.")
- return {"status": "success"}
-
- # --- HANDLE MANUAL VERIFY COMMAND (/verify TX-XXXXXX) ---
- elif text.startswith("/verify"):
- tx_id = text[8:].strip().upper()
- if tx_id.startswith("TX-"):
- await self.save_telegram_session(str(user_id), tx_id, state="waiting_receipt")
- await self.send_message(chat_id, f"✅ ID Transaksi *{tx_id}* berhasil dikaitkan. Silakan kirimkan foto bukti transfer Anda sekarang.")
- return {"status": "success"}
- await self.send_message(chat_id, "❌ Format salah. Gunakan: `/verify TX-XXXXXX` untuk mengaitkan transaksi Anda.")
- return {"status": "success"}
-
- # --- HANDLE OTHER SLASH COMMANDS (Founder-facing) ---
- elif text.startswith("/"):
- if str(chat_id) != str(self.admin_chat_id):
- await self.send_message(chat_id, "❌ Anda tidak memiliki akses untuk perintah ini.")
- return {"status": "unauthorized"}
-
- reply = await self.handle_ceo_command(text, chat_id)
- if reply:
- await self.send_message(chat_id, reply)
- return {"status": "success"}
-
- # --- HANDLE PHOTO UPLOAD (Receipt Verification via Gemini Vision) ---
- elif "photo" in message and len(message["photo"]) > 0:
- # Session validation
- user_session = await self.get_telegram_session(str(user_id))
- if not user_session:
- await self.send_message(chat_id, "⚠️ ID Transaksi tidak ditemukan atau sesi kedaluwarsa. Silakan kirimkan kode transaksi Anda terlebih dahulu.\n\nContoh: `/verify TX-89A12B` lalu kirim bukti transfer.")
- return {"status": "success"}
-
- tx_id = user_session["tx_id"]
- await self.send_message(chat_id, "⏳ *Membaca bukti transfer Anda menggunakan AI...*")
-
- photo = message["photo"][-1]
- file_id = photo["file_id"]
-
- try:
- photo_bytes = await self.download_file(file_id)
- ocr_result = await self.run_vision_ocr(photo_bytes)
- logger.info(f"👁️ OCR result for {tx_id}: {ocr_result}")
-
- if ocr_result.get("is_blurry") or "error" in ocr_result:
- await self.send_message(
- chat_id,
- "❌ *Gagal Membaca Bukti Transfer*\n\nGambar terdeteksi buram atau bukan merupakan bukti transfer yang valid. Silakan unggah ulang foto bukti transfer yang lebih jelas."
- )
- return {"status": "blurry_reprompt"}
-
- # Get expected amount from database
- stmt = select(Transaction).where(Transaction.id == tx_id)
- tx_res = await self.db.execute(stmt)
- target_tx = tx_res.scalar_one_or_none()
-
- if not target_tx:
- await self.send_message(chat_id, f"❌ ID Transaksi *{tx_id}* tidak terdaftar di database kami. Mohon periksa kembali.")
- return {"status": "tx_not_found"}
-
- expected_amount = int(float(target_tx.amount))
- ocr_amount = int(ocr_result.get("amount", 0))
- ocr_bank = ocr_result.get("bank", "Unknown Bank")
- ocr_date = ocr_result.get("date", "Unknown Date")
-
- discrepancy_alert = ""
- amount_match = True
- if abs(expected_amount - ocr_amount) > 1000:
- amount_match = False
- discrepancy_alert = f"⚠️ *PERINGATAN:* Nominal kuitansi (Rp {ocr_amount:,}) berbeda dengan tagihan invoice (Rp {expected_amount:,})!"
- discrepancy_alert = discrepancy_alert.replace(",", ".")
-
- user_feedback = (
- f"ℹ️ *Informasi Terbaca oleh AI:*\n"
- f"• Nominal: *Rp {ocr_amount:,}*\n"
- f"• Bank Pengirim: *{ocr_bank}*\n"
- f"• Tanggal: *{ocr_date}*\n\n"
- f"Status: Bukti transfer berhasil dikirim ke Admin untuk verifikasi akhir."
- )
- user_feedback = user_feedback.replace(",", ".")
- await self.send_message(chat_id, user_feedback)
-
- if self.admin_chat_id:
- admin_caption = (
- f"📥 *BUKTI TRANSFER TOP-UP B2B*\n\n"
- f"• ID Transaksi: *{tx_id}*\n"
- f"• Rekruter ID: *{target_tx.client_id or 'Unknown'}*\n"
- f"• Tagihan Invoice: *Rp {expected_amount:,}*\n"
- f"• Terbaca oleh AI OCR: *Rp {ocr_amount:,}* ({ocr_bank})\n"
- f"• Status Pencocokan: {'✅ COCOK' if amount_match else '❌ TIDAK COCOK'}\n"
- f"{discrepancy_alert}\n\n"
- f"Silakan lakukan tindakan:"
- )
- admin_caption = admin_caption.replace(",", ".")
-
- url = f"{self.base_url}/sendPhoto"
- payload = {
- "chat_id": self.admin_chat_id,
- "photo": file_id,
- "caption": admin_caption,
- "parse_mode": "Markdown",
- "reply_markup": {
- "inline_keyboard": [
- [
- {"text": "✅ Approve & Credit", "callback_data": f"approvepay_{tx_id}_{chat_id}"},
- {"text": "❌ Reject", "callback_data": f"rejectpay_{tx_id}_{chat_id}"}
- ]
- ]
- }
- }
- async with httpx.AsyncClient(timeout=15.0) as client:
- await client.post(url, json=payload, headers=self._proxy_headers())
-
- except Exception as ex:
- logger.error(f"Error processing payment photo: {ex}")
- await self.send_message(chat_id, f"❌ Terjadi kesalahan saat membaca kuitansi: {ex}")
- return {"status": "success"}
-
- # --- HANDLE SEMANTIC INSTRUCTION (Founder chatting) ---
- else:
- if str(chat_id) == str(self.admin_chat_id) and text:
- await self.send_message(chat_id, "⏳ *CEO Agent sedang memproses instruksi Anda...*")
- # Run in background to avoid Telegram Webhook timeout using a fresh DB session
- async def run_semantic_bg():
- try:
- from app.database import AsyncSessionLocal
- async with AsyncSessionLocal() as session:
- bg_service = TelegramCEOService(session)
- await bg_service.process_semantic_instruction(text)
- except Exception as bg_err:
- logger.error(f"Error in background semantic instruction execution: {bg_err}")
-
- asyncio.create_task(run_semantic_bg())
- return {"status": "success"}
-
- except Exception as e:
- logger.error(f"❌ Webhook Error: {e}")
- try:
- if self.admin_chat_id:
- await self.send_message(
- self.admin_chat_id,
- f"⚠️ *Sistem Bot Terkendala:*\n`{str(e)}`"
- )
- except Exception as send_err:
- logger.error(f"Failed to send exception alert to admin: {send_err}")
- return {"status": "error", "details": str(e)}
-
- return {"status": "ignored"}
+"""Telegram CEO Service — Direct Founder Line to AI CEO and Payment Verification Bot."""
+
+import os
+import json
+import httpx
+import base64
+import re
+import asyncio
+from datetime import datetime, timedelta, timezone
+from typing import Optional, Dict, Any
+from loguru import logger
+from zoneinfo import ZoneInfo
+
+from sqlalchemy import select, update, func, cast, String, or_, text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config.settings import settings
+from app.services.antigravity import AntigravityOrchestrator
+from app.services.linkedin_service import LinkedInPoster
+from app.services import ai_service
+from app.services.email_service import email_service
+from app.services.google_workspace_service import spark_agent
+
+# Models
+from app.models.job import JobPosting, RecruiterOutreach
+from app.models.finance import Transaction
+from app.models.talent import Talent
+from app.models.content import KnowledgeQueue
+from app.models.system import ActivityLog, SecurityAuditLog, PrivacyAuditLog, TelegramSession
+
+
+class TelegramCEOService:
+ def __init__(self, db: AsyncSession):
+ self.db = db
+ self.token = settings.telegram_bot_token or os.getenv("TELEGRAM_BOT_TOKEN")
+ self.admin_chat_id = settings.telegram_admin_chat_id or os.getenv("TELEGRAM_ADMIN_CHAT_ID")
+
+ # Proxy routing: HF Spaces blocks direct egress to api.telegram.org.
+ # Support two modes:
+ # 1. Transparent Proxy (Cloudflare): proxy_url + "/method"
+ # 2. RPC Proxy (Google Apps Script): proxy_url with action="proxyTelegram"
+ self._proxy_url = (settings.telegram_proxy_url or os.getenv("TELEGRAM_PROXY_URL", "")).rstrip("/")
+ self._proxy_secret = settings.telegram_proxy_secret or os.getenv("TELEGRAM_PROXY_SECRET", "")
+ self._use_proxy = bool(self._proxy_url and self._proxy_secret)
+ self._is_gas_proxy = "script.google.com" in self._proxy_url
+
+ self.base_url = self._proxy_url if self._use_proxy and not self._is_gas_proxy else f"https://api.telegram.org/bot{self.token}"
+ self.api_url = self.base_url # Compatibility alias
+ self.orchestrator = AntigravityOrchestrator(db)
+ self.tz = ZoneInfo("Asia/Jakarta")
+
+ def _proxy_headers(self) -> dict:
+ """Returns auth headers required when using the CF proxy."""
+ if self._use_proxy and not self._is_gas_proxy:
+ return {"X-Proxy-Secret": self._proxy_secret, "Content-Type": "application/json"}
+ return {"Content-Type": "application/json"}
+
+ async def get_telegram_session(self, chat_id: str) -> Optional[dict]:
+ """Fetch active session from database, checking TTL of 30 minutes."""
+ try:
+ stmt = select(TelegramSession).where(TelegramSession.chat_id == chat_id)
+ res = await self.db.execute(stmt)
+ session = res.scalar_one_or_none()
+ if session and session.last_context:
+ ctx = session.last_context
+ ts_str = ctx.get("timestamp")
+ if ts_str:
+ ts = datetime.fromisoformat(ts_str)
+ if (datetime.now(timezone.utc) - ts).total_seconds() < 1800:
+ return ctx
+ except Exception as e:
+ logger.error(f"Error fetching Telegram session: {e}")
+ return None
+
+ async def save_telegram_session(self, chat_id: str, tx_id: str, state: Optional[str] = None):
+ """Save/update verification session in database."""
+ try:
+ stmt = select(TelegramSession).where(TelegramSession.chat_id == chat_id)
+ res = await self.db.execute(stmt)
+ session = res.scalar_one_or_none()
+ ctx = {
+ "tx_id": tx_id,
+ "timestamp": datetime.now(timezone.utc).isoformat()
+ }
+ if session:
+ session.last_context = ctx
+ if state:
+ session.state = state
+ session.updated_at = datetime.now(timezone.utc)
+ else:
+ session = TelegramSession(
+ chat_id=chat_id,
+ state=state,
+ last_context=ctx,
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc)
+ )
+ self.db.add(session)
+ await self.db.commit()
+ logger.info(f"Telegram session saved for chat {chat_id}, tx_id {tx_id}")
+ except Exception as e:
+ logger.error(f"Error saving Telegram session: {e}")
+
+ async def delete_telegram_session(self, chat_id: str):
+ """Clear active session from database."""
+ try:
+ stmt = select(TelegramSession).where(TelegramSession.chat_id == chat_id)
+ res = await self.db.execute(stmt)
+ session = res.scalar_one_or_none()
+ if session:
+ session.last_context = None
+ session.state = None
+ session.updated_at = datetime.now(timezone.utc)
+ await self.db.commit()
+ logger.info(f"Telegram session cleared for chat {chat_id}")
+ except Exception as e:
+ logger.error(f"Error clearing Telegram session: {e}")
+
+ async def log_privacy_audit(self, query: str, user_email: str, risk_score: int = 10):
+ """Log privacy sensitive actions to privacy_audit_log table."""
+ try:
+ # Simple automatic risk score adjustment based on PII triggers
+ kw_lower = query.lower()
+ if any(kw in kw_lower for kw in ["cv", "ktp", "nik", "telepon", "phone", "email", "nama", "name"]):
+ risk_score = 30 # Medium risk if querying PII keywords
+
+ audit = PrivacyAuditLog(
+ query=query,
+ user_email=user_email,
+ risk_score=risk_score,
+ timestamp=datetime.now(timezone.utc)
+ )
+ self.db.add(audit)
+ await self.db.commit()
+ logger.info(f"Privacy audit logged: {query} by {user_email}")
+ except Exception as e:
+ logger.error(f"Failed to log privacy audit: {e}")
+
+ async def log_security_audit(self, action: str, details: str, status: str = "success"):
+ """Log security critical events to security_audit_log table."""
+ try:
+ audit = SecurityAuditLog(
+ page_type="Telegram_Bot",
+ target_url=f"Telegram_Command/{action}",
+ status=status,
+ details=details,
+ timestamp=datetime.now(timezone.utc)
+ )
+ self.db.add(audit)
+ await self.db.commit()
+ logger.info(f"Security audit logged: {action} - {status}")
+ except Exception as e:
+ logger.error(f"Failed to log security audit: {e}")
+
+ async def log_activity(self, actor: str, action: str, metadata: str = "-"):
+ """Log administrative activities to activity_logs table."""
+ try:
+ log = ActivityLog(
+ actor=actor,
+ action=action,
+ log_metadata=metadata,
+ timestamp=datetime.now(timezone.utc)
+ )
+ self.db.add(log)
+ await self.db.commit()
+ logger.info(f"Activity log registered: {action} by {actor}")
+ except Exception as e:
+ logger.error(f"Failed to register activity log: {e}")
+
+ async def send_executive_alert(self, message: str, urgent: bool = False):
+
+ """Sends a proactive alert to the Founder."""
+ if not self.token or not self.admin_chat_id:
+ logger.warning("Telegram credentials missing, skipping executive alert.")
+ return False
+
+ prefix = "🚨 *URGENT CEO ALERT*" if urgent else "ℹ️ *AI CEO UPDATE*"
+ text = f"{prefix}\n\n{message}"
+
+ return await self.send_message(self.admin_chat_id, text)
+
+ async def send_message(self, chat_id: Any, text: str, parse_mode: str = "Markdown", reply_markup: Optional[dict] = None) -> bool:
+ """Sends a generic text message to a specified chat."""
+ if not self.token:
+ logger.warning("Telegram token missing, cannot send message.")
+ return False
+
+ payload = {
+ "chat_id": chat_id,
+ "text": text,
+ "parse_mode": parse_mode
+ }
+ if reply_markup:
+ payload["reply_markup"] = reply_markup
+
+ if self._use_proxy and self._is_gas_proxy:
+ # RPC Proxy Mode (GAS)
+ target_url = self._proxy_url
+ rpc_payload = {
+ "action": "proxyTelegram",
+ "params": ["sendMessage", payload, self._proxy_secret]
+ }
+ async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
+ try:
+ response = await client.post(target_url, json=rpc_payload)
+ if response.status_code == 200:
+ res_json = response.json()
+ if res_json.get("success"):
+ return True
+ logger.warning(f"GAS Telegram Proxy returned failure: {res_json}")
+ else:
+ logger.warning(f"GAS Telegram Proxy HTTP {response.status_code}: {response.text[:200]}")
+ return False
+ except Exception as e:
+ logger.error(f"Error calling GAS Telegram proxy: {e}")
+ return False
+
+ # Default or Transparent Proxy Mode
+ url = f"{self.base_url}/sendMessage"
+ async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:
+ try:
+ response = await client.post(url, json=payload, headers=self._proxy_headers())
+ if response.status_code != 200:
+ logger.warning(f"Telegram sendMessage returned {response.status_code}: {response.text[:200]}")
+ return response.status_code == 200
+ except Exception as e:
+ logger.error(f"Error sending Telegram message: {e}")
+ return False
+
+ async def answer_callback_query(self, callback_query_id: str, text: str):
+ if not self.token: return
+ url = f"{self.base_url}/answerCallbackQuery"
+ payload = {
+ "callback_query_id": callback_query_id,
+ "text": text
+ }
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ try:
+ await client.post(url, json=payload, headers=self._proxy_headers())
+ except Exception as e:
+ logger.error(f"Error answering callback query: {e}")
+
+ async def edit_message_text(self, chat_id: Any, message_id: int, new_text: str):
+ if not self.token: return
+ url = f"{self.base_url}/editMessageText"
+ payload = {
+ "chat_id": chat_id,
+ "message_id": message_id,
+ "text": new_text,
+ "parse_mode": "Markdown"
+ }
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ try:
+ await client.post(url, json=payload, headers=self._proxy_headers())
+ except Exception as e:
+ logger.error(f"Error editing message: {e}")
+
+ async def download_file(self, file_id: str) -> bytes:
+ """Downloads a file from Telegram using its file_id."""
+ if not self.token:
+ raise Exception("Telegram token missing")
+ # Step 1: getFile API call (via proxy if enabled)
+ get_file_url = f"{self.base_url}/getFile"
+ async with httpx.AsyncClient(timeout=20.0) as client:
+ resp = await client.post(get_file_url, json={"file_id": file_id}, headers=self._proxy_headers())
+ if resp.status_code == 200:
+ file_path = resp.json().get("result", {}).get("file_path")
+ if file_path:
+ # Step 2: Download actual file bytes
+ if self._use_proxy:
+ # Route file download through CF proxy: /api/telegram-proxy/file/{path}
+ download_url = f"{self._proxy_url}/file/{file_path}"
+ file_resp = await client.get(download_url, headers=self._proxy_headers())
+ else:
+ download_url = f"https://api.telegram.org/file/bot{self.token}/{file_path}"
+ file_resp = await client.get(download_url)
+ if file_resp.status_code == 200:
+ return file_resp.content
+ raise Exception("Gagal mengunduh file dari Telegram")
+
+ async def run_vision_ocr(self, photo_bytes: bytes) -> dict:
+ """Sends photo bytes to Gemini Vision to extract payment receipt details."""
+ from app.services.ai_service import RAW_KEYS
+ api_key = RAW_KEYS[0] if (RAW_KEYS and RAW_KEYS[0]) else settings.gemini_api_key
+ if not api_key:
+ return {"error": "GEMINI_API_KEY not configured"}
+
+ encoded_image = base64.b64encode(photo_bytes).decode("utf-8")
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={api_key}"
+
+ prompt = (
+ "Analyze this receipt image. Extract: 1. Nominal / total amount transferred (integer, e.g. 450000 or 1200000. Ignore cent digits if it's 450000.00), "
+ "2. Sender Bank Name (e.g. BCA, Mandiri, BNI, etc.), "
+ "3. Date and time of transfer. "
+ "Respond strictly in JSON format with keys: 'amount' (integer), 'bank' (string), 'date' (string), 'is_blurry' (boolean, set true if details are illegible or it's not a payment receipt)."
+ )
+
+ payload = {
+ "contents": [
+ {
+ "parts": [
+ {"text": prompt},
+ {
+ "inlineData": {
+ "mimeType": "image/jpeg",
+ "data": encoded_image
+ }
+ }
+ ]
+ }
+ ],
+ "generationConfig": {
+ "responseMimeType": "application/json"
+ }
+ }
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ try:
+ resp = await client.post(url, json=payload)
+ if resp.status_code == 200:
+ data = resp.json()
+ text = data["candidates"][0]["content"]["parts"][0]["text"].strip()
+ if text.startswith("```"):
+ text = re.sub(r"^```[a-z]*\n|```$", "", text).strip()
+ parsed = json.loads(text)
+ return parsed
+ else:
+ logger.error(f"Gemini Vision API error: {resp.status_code} - {resp.text}")
+ return {"error": f"Gemini Vision API error: {resp.status_code}"}
+ except Exception as e:
+ logger.error(f"Gemini Vision call failed: {e}")
+ return {"error": f"Gemini Vision call failed: {e}"}
+
+ async def get_system_health_stats(self) -> dict:
+ """Helper to calculate real-time platform statistics directly from DB."""
+ yesterday = datetime.now(timezone.utc) - timedelta(days=1)
+
+ total_jobs = (await self.db.execute(select(func.count(JobPosting.id)))).scalar() or 0
+ pending_jobs = (await self.db.execute(select(func.count(JobPosting.id)).where(cast(JobPosting.status, String).in_(["scraped", "analyzed", "draft"])))).scalar() or 0
+ new_jobs = (await self.db.execute(select(func.count(JobPosting.id)).where(JobPosting.timestamp >= yesterday))).scalar() or 0
+
+ total_outreach = (await self.db.execute(select(func.count(RecruiterOutreach.id)))).scalar() or 0
+ stale_outreach = (await self.db.execute(select(func.count(RecruiterOutreach.id)).where(cast(RecruiterOutreach.status, String) == "pending_approval"))).scalar() or 0
+ sent_outreach_today = (await self.db.execute(select(func.count(RecruiterOutreach.id)).where(cast(RecruiterOutreach.status, String) == "sent", RecruiterOutreach.sent_at >= yesterday))).scalar() or 0
+
+ total_talents = (await self.db.execute(select(func.count(Talent.id)))).scalar() or 0
+ total_transactions = (await self.db.execute(select(func.count(Transaction.id)))).scalar() or 0
+ total_revenue = (await self.db.execute(select(func.sum(Transaction.amount)).where(cast(Transaction.status, String) == "Settled"))).scalar() or 0
+
+ return {
+ "total_jobs": total_jobs,
+ "pending_jobs": pending_jobs,
+ "new_jobs_today": new_jobs,
+ "total_outreach": total_outreach,
+ "stale_outreach": stale_outreach,
+ "sent_outreach_today": sent_outreach_today,
+ "total_talents": total_talents,
+ "total_transactions": total_transactions,
+ "total_revenue": float(total_revenue or 0)
+ }
+
+ async def generate_daily_briefing(self) -> str:
+ """Generate and send comprehensive daily briefing to Telegram admin."""
+ stats = await self.get_system_health_stats()
+
+ summary = (
+ f"📊 *BRIGAWAN CEO BRIEFING* — {datetime.now(self.tz).strftime('%Y-%m-%d %H:%M')}\n\n"
+ f"📌 *Ringkasan 24 Jam Terakhir*\n"
+ f"━━━━━━━━━━━━━━━━━━\n"
+ f"• *Jobs Baru:* {stats['new_jobs_today']} lowongan\n"
+ f"• *Outreach Pending:* {stats['stale_outreach']} rekomendasi\n"
+ f"• *Outreach Terkirim:* {stats['sent_outreach_today']} email\n"
+ f"• *Total Talent:* {stats['total_talents']} terdaftar\n\n"
+ )
+
+ prompt = f"""Kamu adalah CEO Agent dari platform Brigawan — platform karir hijau Indonesia.
+
+DATA OPERASIONAL 24 JAM TERAKHIR:
+- Jobs baru di-scrape: {stats['new_jobs_today']} (total database: {stats['total_jobs']})
+- Outreach pending approval: {stats['stale_outreach']}
+- Outreach terkirim hari ini: {stats['sent_outreach_today']}
+- Total talent di database: {stats['total_talents']}
+
+TUGAS:
+1. Analisis singkat: apakah performa platform sehat?
+2. Berikan 2-3 rekomendasi strategis untuk hari ini
+3. Jika ada anomali (semua metrik 0, atau lonjakan), highlight
+
+Format jawaban dalam JSON:
+{{
+ "health_status": "healthy|needs_attention|critical",
+ "analysis": "1-2 kalimat analisis",
+ "recommendations": ["rekomendasi 1", "rekomendasi 2"],
+ "anomalies": ["anomali jika ada"],
+ "priority_action": "satu tindakan prioritas hari ini"
+}}"""
+
+ analysis, _ = await ai_service.call_gemini_json(prompt, temperature=0.2)
+
+ if "error" not in analysis:
+ health_emoji = {"healthy": "✅", "needs_attention": "⚠️", "critical": "🚨"}
+ health = analysis.get("health_status", "healthy")
+ emoji = health_emoji.get(health, "✅")
+
+ summary += (
+ f"🤖 *CEO Analysis:* {emoji} *{health.upper()}*\n"
+ f"➡️ {analysis.get('analysis', '')}\n\n"
+ f"🎯 *Rekomendasi Hari Ini:*\n"
+ )
+ for rec in analysis.get("recommendations", []):
+ summary += f" • {rec}\n"
+
+ anomalies = analysis.get("anomalies", [])
+ if anomalies:
+ summary += f"\n🚩 *Anomali Terdeteksi:*\n"
+ for a in anomalies:
+ summary += f" • ⚠️ {a}\n"
+
+ priority = analysis.get("priority_action", "")
+ if priority:
+ summary += f"\n🔥 *Prioritas:* {priority}\n"
+
+ await self.send_message(self.admin_chat_id, summary)
+ return summary
+
+ async def check_system_health(self):
+ """Check all Brigawan subsystems and report to admin."""
+ stats = await self.get_system_health_stats()
+
+ issues = []
+ if stats["pending_jobs"] > 5:
+ issues.append(f"{stats['pending_jobs']} jobs menunggu approval admin")
+ if stats["stale_outreach"] > 10:
+ issues.append(f"{stats['stale_outreach']} outreach pending > 24 jam")
+ if stats["total_talents"] == 0:
+ issues.append("Database talent kosong")
+
+ status = "healthy" if not issues else "needs_attention" if len(issues) <= 2 else "critical"
+
+ emoji = "✅" if status == "healthy" else "⚠️" if status == "needs_attention" else "🚨"
+ msg = (
+ f"🩹 *CEO SYSTEM HEALTH CHECK*\n\n"
+ f"📊 *Status:* {emoji} {status.upper()}\n\n"
+ f"*Issues:*\n"
+ )
+ if issues:
+ for iss in issues:
+ msg += f" • ❌ {iss}\n"
+ else:
+ msg += " • ✅ Tidak ada isu operasional kritis terdeteksi.\n"
+
+ rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
+ msg += f"\n🤖 Total Jobs: {stats['total_jobs']} | Outreach: {stats['total_outreach']} | Talent: {stats['total_talents']} | Revenue: {rev_formatted}"
+
+ await self.send_message(self.admin_chat_id, msg)
+ return stats
+
+ async def delegate_task_to_queue(self, action: str, params: dict):
+ """Insert task into knowledge_queue in PostgreSQL."""
+ try:
+ task = KnowledgeQueue(
+ category="AGENT_TASK",
+ fact=json.dumps({"action": action, "params": params}),
+ status="Pending",
+ source_email="ceo-agent@briga.id"
+ )
+ self.db.add(task)
+ await self.db.commit()
+ logger.info(f"CEO Delegated {action} to knowledge_queue.")
+ except Exception as e:
+ logger.error(f"Failed to delegate task to knowledge_queue: {e}")
+
+ async def process_semantic_instruction(self, text: str):
+ """Parse natural language from admin and delegate tasks (Two-Stage Query System)."""
+ stats = await self.get_system_health_stats()
+ rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
+
+ # --- STAGE 1: INTENT & PARAMETER EXTRACTION ---
+ stage1_prompt = f"""Kamu adalah Koordinator CEO Agent Brigawan. Tugasmu adalah menganalisis pesan dari Founder dan menentukan apakah dia membutuhkan pencarian data atau tindakan dari database.
+
+Pesan Founder: "{text}"
+
+Tentukan aksi database (db_lookup) apa yang dibutuhkan.
+Pilihan `db_lookup_type`:
+- "talent_search": Jika Founder mencari talenta/kandidat dengan kriteria/keahlian/lokasi tertentu. (Contoh: "cari ahli solar panel di Bandung")
+- "pending_jobs": Jika Founder menanyakan tentang lowongan yang butuh persetujuan atau baru masuk. (Contoh: "apa ada lowongan baru?")
+- "pending_outreach": Jika Founder menanyakan tentang outreach yang pending atau rekomendasi email.
+- "finance": Jika Founder menanyakan tentang keuangan, pendapatan, transaksi.
+- "job_detail": Jika Founder menanyakan rincian dari suatu lowongan tertentu (sertakan parameter `job_id`).
+- "none": Jika pesan hanya berupa obrolan santai, diskusi ide bisnis, atau tidak membutuhkan query database khusus.
+
+Tentukan juga jika ada perintah operasional untuk dijalankan (delegated_task):
+- action: "bulk_sourcing", "nurture_dormant", "run_scrape_cycle", "run_outreach_sweep", "run_outreach_for_job" (sertakan job_id di params), atau "none".
+
+FORMAT OUTPUT JSON:
+{{
+ "db_lookup": {{
+ "type": "talent_search|pending_jobs|pending_outreach|finance|job_detail|none",
+ "params": {{
+ "keyword": "kata kunci pencarian talenta jika ada",
+ "job_id": "job id jika ada"
+ }}
+ }},
+ "delegated_task": {{
+ "action": "action_name_or_none",
+ "params": {{}}
+ }}
+}}"""
+
+ analysis, _ = await ai_service.call_gemini_json(stage1_prompt, temperature=0.2)
+
+ if "error" in analysis:
+ await self.send_message(self.admin_chat_id, f"❌ Gagal menganalisis instruksi: {analysis['error']}")
+ return
+
+ db_lookup = analysis.get("db_lookup", {})
+ db_type = db_lookup.get("type", "none")
+ db_params = db_lookup.get("params", {})
+
+ retrieved_data_str = ""
+
+ # --- DATABASE QUERY EXECUTION ---
+ try:
+ if db_type == "talent_search":
+ kw = db_params.get("keyword", "")
+ if kw:
+ kw_wildcard = f"%{kw}%"
+ stmt = select(Talent).where(
+ or_(
+ Talent.name.ilike(kw_wildcard),
+ Talent.skill_tags.ilike(kw_wildcard),
+ Talent.experience.ilike(kw_wildcard),
+ Talent.location.ilike(kw_wildcard),
+ Talent.category.ilike(kw_wildcard)
+ )
+ ).limit(5)
+ res = await self.db.execute(stmt)
+ talents = res.scalars().all()
+
+ if talents:
+ retrieved_data_str = "Hasil Pencarian Talenta:\n"
+ for t in talents:
+ retrieved_data_str += f"- ID: {t.talent_id}, Nama: {t.name}, Kategori: {t.category}, Lokasi: {t.location}, Skills: {t.skill_tags}, Green Score: {t.green_score}, Status: {t.verification_status}\n"
+ else:
+ retrieved_data_str = f"Tidak ditemukan talenta dengan kata kunci '{kw}'."
+ else:
+ retrieved_data_str = "Kata kunci pencarian talenta tidak disediakan."
+
+ elif db_type == "pending_jobs":
+ stmt = select(JobPosting).where(cast(JobPosting.status, String).in_(["scraped", "analyzed", "draft"])).order_by(JobPosting.timestamp.asc()).limit(5)
+ res = await self.db.execute(stmt)
+ jobs = res.scalars().all()
+ if jobs:
+ retrieved_data_str = "Daftar Lowongan Pekerjaan Pending (Menunggu Approval):\n"
+ for j in jobs:
+ retrieved_data_str += f"- ID: {j.job_id}, Title: {j.title}, Company: {j.company_name}, Location: {j.location}, Source: {j.source}, Created At: {j.timestamp}\n"
+ else:
+ retrieved_data_str = "Tidak ada lowongan pekerjaan yang pending."
+
+ elif db_type == "pending_outreach":
+ stmt = select(RecruiterOutreach).where(cast(RecruiterOutreach.status, String) == "pending_approval").order_by(RecruiterOutreach.triggered_at.asc()).limit(5)
+ res = await self.db.execute(stmt)
+ outreaches = res.scalars().all()
+ if outreaches:
+ retrieved_data_str = "Daftar Outreach Pending (Menunggu Approval):\n"
+ for o in outreaches:
+ retrieved_data_str += f"- ID: {o.outreach_id}, Talent: {o.talent_email}, Recruiter: {o.recruiter_email}, Match Score: {o.match_score}%\n"
+ else:
+ retrieved_data_str = "Tidak ada email outreach yang pending."
+
+ elif db_type == "finance":
+ stmt = select(Transaction).order_by(Transaction.created_at.desc()).limit(5)
+ res = await self.db.execute(stmt)
+ txs = res.scalars().all()
+ retrieved_data_str = f"Laporan Keuangan Singkat:\n- Total Pendapatan Settled: {rev_formatted}\n- Total Transaksi: {stats['total_transactions']}\n"
+ if txs:
+ retrieved_data_str += "5 Transaksi Terakhir:\n"
+ for t in txs:
+ retrieved_data_str += f" - ID: {t.id}, Client: {t.client_id}, Amount: Rp {int(t.amount):,}, Status: {t.status}, Date: {t.created_at}\n"
+ else:
+ retrieved_data_str += "Tidak ada riwayat transaksi."
+ retrieved_data_str = retrieved_data_str.replace(",", ".")
+
+ elif db_type == "job_detail":
+ jid = db_params.get("job_id", "")
+ if jid:
+ stmt = select(JobPosting).where(JobPosting.job_id == jid)
+ res = await self.db.execute(stmt)
+ job = res.scalar_one_or_none()
+ if job:
+ retrieved_data_str = (
+ f"Detail Lowongan Pekerjaan:\n"
+ f"- ID: {job.job_id}\n"
+ f"- Title: {job.title}\n"
+ f"- Company: {job.company_name}\n"
+ f"- Location: {job.location}\n"
+ f"- Sektor: {job.company_category}\n"
+ f"- Required Skills: {job.required_skills}\n"
+ f"- Description: {job.description[:500] if job.description else ''}\n"
+ f"- Status: {job.status}\n"
+ )
+ else:
+ retrieved_data_str = f"Pekerjaan dengan ID '{jid}' tidak ditemukan."
+ else:
+ retrieved_data_str = "Job ID tidak disediakan untuk pencarian rincian lowongan."
+ else:
+ retrieved_data_str = "Tidak ada pencarian database khusus yang diperlukan."
+ except Exception as q_err:
+ logger.error(f"Error executing semantic database query: {q_err}")
+ retrieved_data_str = f"Gagal mengambil data dari database karena kesalahan teknis: {q_err}"
+
+ # --- STAGE 2: RESPONSE SYNTHESIS ---
+ synthesis_prompt = f"""Kamu adalah CEO Agent Brigawan, rekan diskusi strategis bagi Founder.
+Founder menanyakan: "{text}"
+
+BERKAS/DATA TERBARU DARI DATABASE:
+{retrieved_data_str}
+
+STATISTIK UMUM PLATFORM:
+- Total Jobs: {stats['total_jobs']}
+- Total Talent: {stats['total_talents']}
+- Outreach Pending: {stats['stale_outreach']}
+- Total Transaksi B2B: {stats['total_transactions']}
+- Total Pendapatan Settled: {rev_formatted}
+
+TUGASMU:
+1. Berikan tanggapan/jawaban yang sangat solutif, berbasis data (data-driven), dan relevan dalam Bahasa Indonesia yang elegan.
+2. Jika data yang dicari Founder ada di atas, jabarkan dengan rapi dan berikan rekomendasi tindakan berikutnya.
+3. Jika data tidak ditemukan, katakan dengan sopan dan berikan saran pencarian yang lebih baik.
+4. Gunakan gaya penulisan profesional namun suportif seorang partner bisnis terpercaya (C-Level).
+5. Jangan menyebutkan detail teknis SQL atau internal database, fokuslah pada nilai bisnis dan operasional.
+
+Jawab langsung berupa teks pesan Telegram (mendukung format Markdown)."""
+
+ response_text, _ = await ai_service.call_medium(synthesis_prompt)
+
+ if not response_text:
+ response_text = "Maaf, saya gagal mensintesis tanggapan strategis."
+
+ # Send response to founder
+ await self.send_message(self.admin_chat_id, response_text)
+
+ # --- TASK DELEGATION HANDLER ---
+ task = analysis.get("delegated_task", {})
+ if task.get("action") and task.get("action") != "none":
+ await self.delegate_task_to_queue(task["action"], task.get("params", {}))
+
+ async def handle_ceo_command(self, text: str, chat_id: Any) -> str:
+ """Processes incoming executive commands (slash commands) from Telegram."""
+ cmd = text.split(" ")[0].lower()
+
+ if cmd in ["/menu", "/help"]:
+ menu_text = (
+ f"⚡ *BRIGAWAN CEO COMMAND CENTER* ⚡\n\n"
+ f"Selamat datang, Founder. Silakan gunakan menu tombol cepat di bawah ini untuk berinteraksi dengan sistem, "
+ f"atau ketik instruksi Anda dalam bahasa natural.\n\n"
+ f"*Daftar Perintah Manual:*\n"
+ f"• `/menu` atau `/help` - Menampilkan menu ini\n"
+ f"• `/status` - Menampilkan status kesehatan sistem secara ringkas\n"
+ f"• `/search_talent ` - Mencari talent berdasarkan skill/lokasi (Contoh: `/search_talent AMDAL`)\n"
+ f"• `/job_detail ` - Menampilkan rincian lowongan (Contoh: `/job_detail JB-001`)\n"
+ f"• `/pending_jobs` - Menampilkan lowongan yang menunggu persetujuan\n"
+ f"• `/pending_outreach` - Menampilkan email outreach yang menunggu persetujuan\n"
+ f"• `/match_job ` - Memicu pencocokan kandidat untuk lowongan secara langsung\n"
+ f"• `/finance` - Menampilkan laporan keuangan platform\n"
+ f"• `/scrape` - Memulai siklus scraping lowongan baru\n"
+ f"• `/outreach` - Memulai pencocokan outreach di background\n"
+ f"• `/debate ` - Diskusi strategis AI CEO"
+ )
+ reply_markup = {
+ "inline_keyboard": [
+ [
+ {"text": "📊 CEO Briefing", "callback_data": "menu_briefing"},
+ {"text": "🩹 Health Check", "callback_data": "menu_health"}
+ ],
+ [
+ {"text": "💼 Jobs Pending", "callback_data": "menu_pendingjobs"},
+ {"text": "📧 Outreach Pending", "callback_data": "menu_pendingoutreach"}
+ ],
+ [
+ {"text": "💰 Laporan Keuangan", "callback_data": "menu_finance"}
+ ]
+ ]
+ }
+ await self.send_message(chat_id, menu_text, reply_markup=reply_markup)
+ return ""
+
+ elif cmd in ["/status", "/ceo_status"]:
+ stats = await self.get_system_health_stats()
+ emoji = "✅" if stats["pending_jobs"] == 0 else "⚠️"
+ rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
+
+ reply = (
+ f"⚙️ *BRIGAWAN SYSTEM STATUS*\n\n"
+ f"📊 *Health Check:* {emoji} ONLINE\n"
+ f"• Total Jobs: *{stats['total_jobs']}*\n"
+ f"• Pending Jobs: *{stats['pending_jobs']}*\n"
+ f"• Total Outreach: *{stats['total_outreach']}*\n"
+ f"• Stale Outreach: *{stats['stale_outreach']}*\n"
+ f"• Total Talent: *{stats['total_talents']}*\n"
+ f"• Total Revenue: *{rev_formatted}*\n\n"
+ f"Semua operasional berjalan lancar."
+ )
+ return reply.replace(",", ".")
+
+ elif cmd == "/briefing":
+ await self.generate_daily_briefing()
+ return "✅ *CEO Daily Briefing harian Anda berhasil dikirim!*"
+
+ elif cmd in ["/debate", "/ceo_debate"]:
+ idea = text[8:].strip() if cmd == "/debate" else text[12:].strip()
+ if not idea:
+ return f"❌ Perintah salah. Gunakan: `{cmd} `"
+
+ res = await self.orchestrator.execute_task(
+ agent_name="AntigravityCEO",
+ task_name="strategic_debate",
+ payload={"idea": idea}
+ )
+ return res.get("data", {}).get("debate_result", "Maaf, saya sedang gagal berpikir.")
+
+ elif cmd == "/scrape":
+ await self.delegate_task_to_queue("run_scrape_cycle", {})
+ return "⚡ *Memulai proses scraping lowongan hijau baru di background...*"
+
+ elif cmd == "/outreach":
+ await self.delegate_task_to_queue("run_outreach_sweep", {})
+ return "🧹 *Memulai pencocokan kandidat dan pengiriman outreach di background...*"
+
+ elif cmd == "/search_talent":
+ keyword = text[14:].strip()
+ if not keyword:
+ return f"❌ Silakan sertakan kata kunci. Contoh: `/search_talent AMDAL` atau `/search_talent Jakarta`"
+
+ # Log privacy audit (UU PDP Compliance)
+ await self.log_privacy_audit(
+ query=f"/search_talent {keyword}",
+ user_email=f"telegram_{chat_id}",
+ risk_score=10
+ )
+
+ kw_wildcard = f"%{keyword}%"
+ stmt = select(Talent).where(
+ or_(
+ Talent.name.ilike(kw_wildcard),
+ Talent.skill_tags.ilike(kw_wildcard),
+ Talent.experience.ilike(kw_wildcard),
+ Talent.location.ilike(kw_wildcard),
+ Talent.category.ilike(kw_wildcard)
+ )
+ ).limit(5)
+
+ res = await self.db.execute(stmt)
+ talents = res.scalars().all()
+
+ if not talents:
+ return f"🔍 Tidak ditemukan talenta dengan kata kunci *'{keyword}'*."
+
+ reply = f"🔍 *HASIL PENCARIAN TALENTA ({len(talents)})* untuk *'{keyword}'*:\n━━━━━━━━━━━━━━━━━━\n"
+ for t in talents:
+ reply += (
+ f"👤 *{t.name}* (`{t.talent_id}`)\n"
+ f"• Kategori: {t.category or '-'}\n"
+ f"• Lokasi: {t.location or '-'}\n"
+ f"• Green Score: {t.green_score}\n"
+ f"• Skills: `{t.skill_tags or '-'}`\n"
+ f"• Status Verifikasi: *{t.verification_status}*\n"
+ f"• CV Link: {t.cv_link or '-'}\n"
+ f"━━━━━━━━━━━━━━━━━━\n"
+ )
+ return reply
+
+ elif cmd == "/job_detail":
+ job_id = text[11:].strip()
+ if not job_id:
+ return f"❌ Silakan sertakan Job ID. Contoh: `/job_detail JB-001`"
+
+ # Log privacy audit (UU PDP Compliance)
+ await self.log_privacy_audit(
+ query=f"/job_detail {job_id}",
+ user_email=f"telegram_{chat_id}",
+ risk_score=5
+ )
+
+ stmt = select(JobPosting).where(JobPosting.job_id == job_id)
+ res = await self.db.execute(stmt)
+ job = res.scalar_one_or_none()
+
+ if not job:
+ return f"❌ Pekerjaan dengan ID *{job_id}* tidak ditemukan."
+
+ reply = (
+ f"💼 *RINCIAN PEKERJAAN: {job.title}*\n"
+ f"• ID Lowongan: `{job.job_id}`\n"
+ f"• Perusahaan: *{job.company_name or '-'}*\n"
+ f"• Lokasi: {job.location or '-'}\n"
+ f"• Sektor Hijau: {job.company_category or '-'}\n"
+ f"• Status: *{job.status.upper()}*\n"
+ f"• Link Sumber: {job.source_url or '-'}\n"
+ f"• LinkedIn Post: {job.linkedin_post_url or '-'}\n"
+ f"• Tanggal Dibuat: {job.timestamp.strftime('%Y-%m-%d %H:%M') if job.timestamp else '-'}\n"
+ f"━━━━━━━━━━━━━━━━━━\n"
+ f"📝 *Deskripsi Singkat:*\n{job.description[:400] + '...' if job.description and len(job.description) > 400 else job.description or '-'}\n\n"
+ f"⚙️ *Skill yang Dibutuhkan:*\n`{job.required_skills or '-'}`"
+ )
+ return reply
+
+ elif cmd in ["/approve", "/reject"]:
+ activity_id_prefix = text.split(" ")[1].strip() if len(text.split(" ")) > 1 else ""
+ if not activity_id_prefix:
+ return f"❌ Gunakan format: `{cmd} `"
+
+ try:
+ from app.models.system import AgentActivity # Needs to be defined or use raw SQL
+ # Let's use raw SQL for simplicity to match prefix
+ stmt = text("SELECT id, status FROM agent_activities WHERE id::text LIKE :id_prefix LIMIT 1")
+ res = await self.db.execute(stmt, {"id_prefix": f"{activity_id_prefix}%"})
+ row = res.fetchone()
+
+ if not row:
+ return f"❌ Tidak ada aktivitas yang cocok dengan ID `{activity_id_prefix}`."
+
+ full_id, current_status = row[0], row[1]
+
+ if current_status != 'BLOCKED':
+ return f"⚠️ Aktivitas `{full_id}` tidak dalam status BLOCKED (Status saat ini: {current_status})."
+
+ new_status = 'APPROVED' if cmd == '/approve' else 'REJECTED'
+
+ upd_stmt = text("UPDATE agent_activities SET status = :status, updated_at = NOW() WHERE id = :id")
+ await self.db.execute(upd_stmt, {"status": new_status, "id": full_id})
+ await self.db.commit()
+
+ icon = "✅" if new_status == 'APPROVED' else "❌"
+ return f"{icon} *Tindakan {new_status}* berhasil dicatat untuk aktivitas `{full_id}`. Workflow agent akan segera merespons."
+
+ except Exception as e:
+ logger.error(f"Error handling intervention command: {e}")
+ return f"❌ Gagal memproses persetujuan: {e}"
+
+ elif cmd == "/pending_jobs":
+ stmt = select(JobPosting).where(cast(JobPosting.status, String).in_(["scraped", "analyzed", "draft"])).order_by(JobPosting.timestamp.asc()).limit(5)
+ res = await self.db.execute(stmt)
+ jobs = res.scalars().all()
+
+ if not jobs:
+ return "✅ Tidak ada lowongan pekerjaan yang menunggu persetujuan (status: scraped/analyzed/draft)."
+
+ await self.send_message(chat_id, f"📋 *DAFTAR PEKERJAAN MENUNGGU PERSETUJUAN ({len(jobs)})*:")
+
+ for j in jobs:
+ caption = (
+ f"💼 *{j.title}* at *{j.company_name or 'Unknown'}*\n"
+ f"• Job ID: `{j.job_id}`\n"
+ f"• Lokasi: {j.location or '-'}\n"
+ f"• Skills: `{j.required_skills or '-'}`\n"
+ f"• Sumber: {j.source or '-'}\n"
+ )
+ markup = {
+ "inline_keyboard": [
+ [
+ {"text": "✅ Approve & Post", "callback_data": f"approve_{j.job_id}"},
+ {"text": "❌ Reject", "callback_data": f"reject_{j.job_id}"}
+ ]
+ ]
+ }
+ await self.send_message(chat_id, caption, reply_markup=markup)
+ return "Gunakan tombol di atas untuk menyetujui atau menolak lowongan."
+
+ elif cmd == "/pending_outreach":
+ stmt = select(RecruiterOutreach).where(cast(RecruiterOutreach.status, String) == "pending_approval").order_by(RecruiterOutreach.triggered_at.asc()).limit(5)
+ res = await self.db.execute(stmt)
+ outreaches = res.scalars().all()
+
+ if not outreaches:
+ return "✅ Tidak ada email outreach rekruter yang menunggu persetujuan."
+
+ await self.send_message(chat_id, f"📧 *DAFTAR OUTREACH MENUNGGU PERSETUJUAN ({len(outreaches)})*:")
+
+ for o in outreaches:
+ caption = (
+ f"📧 *Outreach ID:* `{o.outreach_id}`\n"
+ f"👤 *Talenta:* `{o.talent_email}`\n"
+ f"🏢 *Rekruter:* `{o.recruiter_email}`\n"
+ f"📊 *Skor Kecocokan:* `{o.match_score}%`\n"
+ f"📝 *Subjek:* {o.outreach_subject or '-'}\n"
+ )
+ markup = {
+ "inline_keyboard": [
+ [
+ {"text": "✅ Approve & Send", "callback_data": f"approveoutreach_{o.outreach_id}"},
+ {"text": "❌ Reject", "callback_data": f"rejectoutreach_{o.outreach_id}"}
+ ],
+ [
+ {"text": "📋 Copy LinkedIn Pitch", "callback_data": f"copypitch_{o.outreach_id}"}
+ ]
+ ]
+ }
+ await self.send_message(chat_id, caption, reply_markup=markup)
+ return "Gunakan tombol di atas untuk mengelola rekomendasi outreach."
+
+ elif cmd == "/match_job":
+ job_id = text[11:].strip()
+ if not job_id:
+ return "❌ Silakan sertakan Job ID. Contoh: `/match_job JB-001`"
+
+ stmt = select(JobPosting).where(JobPosting.job_id == job_id)
+ res = await self.db.execute(stmt)
+ job = res.scalar_one_or_none()
+
+ if not job:
+ return f"❌ Pekerjaan dengan ID *{job_id}* tidak ditemukan."
+
+ await self.delegate_task_to_queue("run_outreach_for_job", {"job_id": job_id})
+ return f"⚡ *Memulai pencocokan kandidat dan draf outreach untuk lowongan {job_id} ({job.title}) di background...*"
+
+ elif cmd == "/finance":
+ # Log privacy audit (UU PDP Compliance)
+ await self.log_privacy_audit(
+ query="/finance",
+ user_email=f"telegram_{chat_id}",
+ risk_score=5
+ )
+ stats = await self.get_system_health_stats()
+ rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
+
+ stmt = select(Transaction).order_by(Transaction.created_at.desc()).limit(5)
+ res = await self.db.execute(stmt)
+ txs = res.scalars().all()
+
+ reply = (
+ f"💰 *LAPORAN KEUANGAN PLATFORM (B2B)*\n"
+ f"━━━━━━━━━━━━━━━━━━\n"
+ f"• Total Transaksi: *{stats['total_transactions']}*\n"
+ f"• Total Pendapatan Settled: *{rev_formatted}*\n\n"
+ f"📊 *5 Transaksi Terakhir:*\n"
+ )
+
+ if not txs:
+ reply += "_(Tidak ada riwayat transaksi)_"
+ else:
+ for t in txs:
+ amount_formatted = f"Rp {int(t.amount):,}".replace(",", ".")
+ status_emoji = "✅" if t.status == "Settled" else "❌" if t.status in ["Failed", "Rejected"] else "⏳"
+ reply += (
+ f"• {status_emoji} *{t.id}* - {amount_formatted}\n"
+ f" Client: `{t.client_id or '-'}` | Status: *{t.status}*\n"
+ f" Tanggal: {t.created_at.strftime('%d %b %Y, %H:%M') if t.created_at else '-'}\n"
+ )
+
+ stmt_pending = select(Transaction).where(cast(Transaction.status, String) == "Pending")
+ res_pending = await self.db.execute(stmt_pending)
+ pending_txs = res_pending.scalars().all()
+ if pending_txs:
+ reply += f"\n⏳ *Ada {len(pending_txs)} Transaksi Pending yang Butuh Bukti Transfer:*\n"
+ for pt in pending_txs:
+ reply += f" - `{pt.id}` | Nominal: Rp {int(pt.amount):,}\n"
+ reply = reply.replace(",", ".")
+ reply += "\n_Gunakan `/verify ` diikuti upload foto bukti transfer untuk verifikasi._"
+ else:
+ reply = reply.replace(",", ".")
+
+ return reply
+
+ return "Perintah tidak dikenal. Gunakan `/menu` untuk melihat daftar perintah lengkap."
+
+ async def handle_webhook(self, data: dict) -> dict:
+ """Main entry point for incoming Telegram updates."""
+ try:
+ # --- HANDLE CALLBACK QUERIES (Inline Button Clicks) ---
+ if "callback_query" in data:
+ callback_query = data["callback_query"]
+ callback_id = callback_query["id"]
+ callback_data = callback_query["data"]
+ message = callback_query.get("message", {})
+ message_id = message.get("message_id")
+ chat_id = message.get("chat", {}).get("id")
+
+ logger.info(f"⚡ Processing Telegram callback: {callback_data}")
+
+ action, target_id = callback_data.split("_", 1)
+
+ # Verify that callback is from the Admin/Founder
+ if str(chat_id) != str(self.admin_chat_id):
+ await self.answer_callback_query(callback_id, "❌ Anda tidak memiliki akses.")
+ await self.log_security_audit(
+ action=f"callback_{action}",
+ details=f"Unauthorized callback attempt by non-admin chat_id {chat_id} on target {target_id}",
+ status="blocked"
+ )
+ return {"status": "unauthorized"}
+
+ # Log administrative activity (UU PDP & Security Compliance)
+ await self.log_activity(
+ actor=str(chat_id),
+ action=action,
+ metadata=target_id
+ )
+
+ # --- 1. HANDLE B2B PAYMENT APPROVALS/REJECTIONS ---
+ if action in ["approvepay", "rejectpay"]:
+ parts_pay = target_id.split("_")
+ tx_id = parts_pay[0]
+ user_chat_id = parts_pay[1] if len(parts_pay) > 1 else None
+
+ if action == "approvepay":
+ await self.answer_callback_query(callback_id, "⏳ Memproses pembayaran...")
+ try:
+ # 1. Fetch transaction
+ stmt = select(Transaction).where(Transaction.id == tx_id)
+ tx_res = await self.db.execute(stmt)
+ tx = tx_res.scalar_one_or_none()
+ if not tx:
+ await self.answer_callback_query(callback_id, "❌ Transaksi tidak ditemukan.")
+ return {"status": "error", "message": "Transaction not found"}
+
+ if tx.status == "Settled":
+ await self.answer_callback_query(callback_id, "❌ Transaksi sudah disetujui.")
+ return {"status": "error", "message": "Already settled"}
+
+ # 2. Determine coins to add
+ amount = float(tx.amount)
+ coins_added = 20 if (450000 <= amount < 451000) else (60 if (1200000 <= amount < 1201000) else (200 if (3500000 <= amount < 3501000) else 0))
+ if coins_added == 0:
+ from app.services.employer_service import COIN_BUNDLES
+ bundle_id = [k for k, v in COIN_BUNDLES.items() if abs(v["idr_price"] - amount) < 10000]
+ coins_added = COIN_BUNDLES[bundle_id[0]]["coins"] if bundle_id else 0
+ if coins_added == 0:
+ coins_added = int(amount / 20000) # fallback exchange rate
+
+ # 3. Credit coins to company wallet
+ from app.models.employer import ClientAccount, Company
+ client_stmt = select(ClientAccount).where(ClientAccount.id == tx.client_id)
+ client_res = await self.db.execute(client_stmt)
+ client = client_res.scalar_one_or_none()
+
+ client_email = ""
+ if client:
+ client_email = client.email
+ company_stmt = select(Company).where(Company.id == client.company_id)
+ company_res = await self.db.execute(company_stmt)
+ company = company_res.scalar_one_or_none()
+ if company:
+ company.credit_balance = (company.credit_balance or 0) + coins_added
+ self.db.add(company)
+
+ # 4. Settle transaction in PostgreSQL
+ tx.status = "Settled"
+ self.db.add(tx)
+ await self.db.commit()
+
+ amount_formatted = f"Rp {int(amount):,}".replace(",", ".")
+ new_text = (
+ f"✅ *TRANSAKSI DISETUJUI & DIKREDITKAN*\n\n"
+ f"• ID Transaksi: *{tx_id}*\n"
+ f"• Koin telah dikreditkan ke: *{client_email or 'Unknown'}*\n"
+ f"• Koin ditambahkan: *{coins_added} Briga Coin*\n"
+ f"• Nominal: *{amount_formatted}*\n"
+ f"• Diverifikasi pada: *{datetime.now().strftime('%d %b %Y, %H:%M')} WIB*"
+ )
+ await self.edit_message_text(chat_id, message_id, new_text)
+ await self.answer_callback_query(callback_id, "🎉 Pembayaran sukses disetujui!")
+
+ # 5. Direct Write to Google Sheets via Sheets API (Direct backup)
+ try:
+ if settings.google_sheets_spreadsheet_id:
+ row_values = [
+ tx.id,
+ tx.client_id or "",
+ float(tx.amount),
+ tx.type or "TopUpManual",
+ "Settled",
+ tx.snap_token or "Telegram Verification",
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ ]
+ await spark_agent.append_row_to_sheet(
+ settings.google_sheets_spreadsheet_id,
+ "Transactions!A1",
+ row_values
+ )
+ except Exception as sheets_err:
+ logger.error(f"Failed to log transaction to Google Sheets: {sheets_err}")
+
+ # 6. Send HTML confirmation email
+ if client_email:
+ try:
+ tier_name = f"{coins_added} Coins"
+ subject = f"✅ Top Up Briga Coin Berhasil - {tier_name}"
+ html_body = f"""
+
+
+
+
BRIGAWAN. AI
+
Sustainability Career Center
+
+
+
+
🪙
+
Top Up Berhasil!
+
Saldo Briga Coin Anda telah ditambahkan.
+
+
+
Jumlah Koin Baru
+
+{coins_added}
+
Briga Coin
+
+
+
+ Paket Langganan
+ {tier_name}
+
+
+ Total Pembayaran
+ {amount_formatted}
+
+
+ Metode Pembayaran
+ Manual Transfer (Telegram Verified)
+
+
+ Waktu Transaksi
+ {datetime.now().strftime("%d %b %Y, %H:%M")} WIB
+
+
+
+
+
+
E-mail ini dikirimkan otomatis oleh sistem Brigawan AI. Jangan membalas email ini.
+
© 2026 Brigawan Sustainability Center. All Rights Reserved.
+
+
+
+ """
+ await asyncio.to_thread(email_service.send_html_email, client_email, subject, html_body)
+ except Exception as mail_err:
+ logger.error(f"Failed to send top-up email: {mail_err}")
+
+ # 7. Notify recruiter via Telegram
+ if user_chat_id:
+ await self.send_message(
+ user_chat_id,
+ f"✅ *Top-up Berhasil!*\n\nPembayaran manual Anda sebesar *{amount_formatted}* telah diverifikasi.\n*{coins_added} Briga Coin* telah ditambahkan ke akun Anda."
+ )
+ await self.delete_telegram_session(str(user_chat_id))
+ except Exception as ex:
+ logger.error(f"Error in approvepay native handler: {ex}")
+ await self.answer_callback_query(callback_id, f"❌ Error: {ex}")
+
+ elif action == "rejectpay":
+ await self.answer_callback_query(callback_id, "❌ Menolak transaksi...")
+ try:
+ # 1. Fetch transaction
+ stmt = select(Transaction).where(Transaction.id == tx_id)
+ tx_res = await self.db.execute(stmt)
+ tx = tx_res.scalar_one_or_none()
+ if tx:
+ tx.status = "Failed"
+ self.db.add(tx)
+ await self.db.commit()
+
+ new_text = (
+ f"❌ *TRANSAKSI DITOLAK*\n\n"
+ f"• ID Transaksi: *{tx_id}*\n"
+ f"• Status: Ditinjau & Ditolak oleh Admin\n"
+ f"• Waktu: *{datetime.now().strftime('%d %b %Y, %H:%M')} WIB*"
+ )
+ await self.edit_message_text(chat_id, message_id, new_text)
+ await self.answer_callback_query(callback_id, "❌ Transaksi berhasil ditolak.")
+
+ # 2. Direct Write to Google Sheets via Sheets API (Direct backup)
+ try:
+ if settings.google_sheets_spreadsheet_id:
+ row_values = [
+ tx.id,
+ tx.client_id or "",
+ float(tx.amount),
+ tx.type or "TopUpManual",
+ "Failed",
+ "Rejected by Admin",
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ ]
+ await spark_agent.append_row_to_sheet(
+ settings.google_sheets_spreadsheet_id,
+ "Transactions!A1",
+ row_values
+ )
+ except Exception as sheets_err:
+ logger.error(f"Failed to log transaction rejection to Google Sheets: {sheets_err}")
+
+ # 3. Notify recruiter via Telegram
+ if user_chat_id:
+ await self.send_message(
+ user_chat_id,
+ f"❌ *Top-up Ditolak*\n\nBukti transfer manual untuk ID Transaksi *{tx_id}* ditolak oleh CEO. Mohon periksa kembali nominal transfer Anda."
+ )
+ await self.delete_telegram_session(str(user_chat_id))
+ else:
+ await self.answer_callback_query(callback_id, "❌ Transaksi tidak ditemukan.")
+ except Exception as ex:
+ logger.error(f"Error in rejectpay native handler: {ex}")
+ await self.answer_callback_query(callback_id, f"❌ Error: {ex}")
+ return {"status": "success"}
+
+ # --- 2. HANDLE UNBLOCK ACTION ---
+ elif action == "unblock":
+ await self.answer_callback_query(callback_id, "🔓 Membuka blokir...")
+ clean_id = target_id.replace("_at_", "@")
+
+ try:
+ # Direct PostgreSQL local unblock if it is an email address
+ success = False
+ if "@" in clean_id:
+ from app.models.employer import ClientAccount
+ stmt = select(ClientAccount).where(ClientAccount.email == clean_id)
+ res = await self.db.execute(stmt)
+ client = res.scalar_one_or_none()
+ if client:
+ client.status = "Active"
+ self.db.add(client)
+ await self.db.commit()
+ success = True
+ logger.info(f"Unblocked client email locally: {clean_id}")
+
+ # Set message text to show success
+ new_text = (
+ f"🔓 *AKSES DI-UNBLOCK OLEH ADMIN*\n\n"
+ f"👤 *Aktor/Target:* `{clean_id}`\n\n"
+ f"Sesi keamanan untuk pengguna ini berhasil dipulihkan secara lokal!"
+ )
+ await self.edit_message_text(chat_id, message_id, new_text)
+ await self.answer_callback_query(callback_id, "🎉 Blokir berhasil dibuka!")
+ except Exception as ex:
+ logger.error(f"Exception during local unblock: {ex}")
+ await self.answer_callback_query(callback_id, f"❌ Gagal: {ex}")
+ return {"status": "success"}
+
+ # --- 3. HANDLE RECRUITER OUTREACH CALLBACK ACTIONS ---
+ elif action in ["approveoutreach", "rejectoutreach", "copypitch"]:
+ outreach_id = target_id
+ stmt = select(RecruiterOutreach).where(RecruiterOutreach.outreach_id == outreach_id)
+ outreach_res = await self.db.execute(stmt)
+ target_outreach = outreach_res.scalar_one_or_none()
+
+ if not target_outreach:
+ await self.answer_callback_query(callback_id, "❌ Error: Rekaman outreach tidak ditemukan.")
+ return {"status": "error", "message": "Outreach record not found"}
+
+ if action == "approveoutreach":
+ await self.answer_callback_query(callback_id, "⏳ Mengirim email outreach...")
+
+ if target_outreach.status == "sent":
+ await self.answer_callback_query(callback_id, "⚠️ Outreach ini sudah pernah dikirim.")
+ return {"status": "already_sent"}
+
+ try:
+ # Direct Python-native SMTP email dispatch
+ success = await asyncio.to_thread(
+ email_service.send_html_email,
+ target_outreach.recruiter_email,
+ target_outreach.outreach_subject,
+ target_outreach.outreach_body
+ )
+ if success:
+ # Update PostgreSQL status
+ target_outreach.status = "sent"
+ target_outreach.sent_at = datetime.now(timezone.utc)
+ await self.db.commit()
+
+ new_text = (
+ f"✅ *OUTREACH APPROVED & SENT*\n\n"
+ f"📌 *Outreach ID:* `{outreach_id}`\n"
+ f"💼 *Job ID:* `{target_outreach.job_id}`\n"
+ f"👤 *Talenta:* `{target_outreach.talent_email}`\n"
+ f"📊 *Skor Kecocokan:* `{target_outreach.match_score}%`\n"
+ f"🏢 *Penerima:* `{target_outreach.recruiter_email}`\n\n"
+ f"Email rekomendasi penawaran talenta berhasil dikirim resmi via SMTP!"
+ )
+ await self.edit_message_text(chat_id, message_id, new_text)
+ await self.answer_callback_query(callback_id, "🎉 Email berhasil terkirim!")
+ else:
+ await self.answer_callback_query(callback_id, "❌ Gagal mengirim email via SMTP.")
+ except Exception as ex:
+ logger.error(f"Exception during native outreach: {ex}")
+ await self.answer_callback_query(callback_id, f"❌ Error: {ex}")
+
+ elif action == "rejectoutreach":
+ target_outreach.status = "rejected"
+ await self.db.commit()
+ new_text = (
+ f"❌ *OUTREACH REJECTED/IGNORED*\n\n"
+ f"📌 *Outreach ID:* `{outreach_id}`\n"
+ f"💼 *Job ID:* `{target_outreach.job_id}`\n"
+ f"👤 *Talenta:* `{target_outreach.talent_email}`\n\n"
+ f"Rekomendasi outreach rekruter ini telah ditolak/diabaikan."
+ )
+ await self.edit_message_text(chat_id, message_id, new_text)
+ await self.answer_callback_query(callback_id, "❌ Outreach ditolak.")
+
+ elif action == "copypitch":
+ target_outreach.status = "manual_linkedin_copied"
+ target_outreach.sent_at = datetime.now(timezone.utc)
+ await self.db.commit()
+
+ new_text = (
+ f"📋 *LINKEDIN PITCH RETRIEVED*\n\n"
+ f"📌 *Outreach ID:* `{outreach_id}`\n"
+ f"💼 *Job ID:* `{target_outreach.job_id}`\n"
+ f"👤 *Talenta:* `{target_outreach.talent_email}`\n\n"
+ f"Pesan pitch LinkedIn telah dikirim di bawah ini. Silakan salin untuk melakukan outreach manual!"
+ )
+ await self.edit_message_text(chat_id, message_id, new_text)
+
+ pitch_msg = (
+ f"📋 *SALIN OUTREACH LINKEDIN ({outreach_id})*\n\n"
+ f"{target_outreach.outreach_body}"
+ )
+ await self.send_message(chat_id, pitch_msg)
+ await self.answer_callback_query(callback_id, "📋 Pitch LinkedIn terkirim!")
+
+ return {"status": "success"}
+
+ # --- 3.5. HANDLE SYSTEM AUTO-HEAL CALLBACK ACTIONS ---
+ elif action in ["approveheal", "rejectheal"]:
+ task_id = target_id
+
+ if action == "approveheal":
+ await self.answer_callback_query(callback_id, "⏳ Menjalankan perbaikan sistem (CTO Auto-Heal)...")
+
+ worker_url = os.getenv("AGENT_WORKER_URL", "https://yabeskn-briga-agent-worker.hf.space").rstrip("/")
+ target_url = f"{worker_url}/v1/agents/heal/approve"
+
+ payload = {
+ "task_id": task_id,
+ "approved": True
+ }
+
+ headers = {
+ "X-Webhook-Token": settings.webhook_secret or os.getenv("WEBHOOK_SECRET", "briga_secret_webhook_123_xyz"),
+ "Content-Type": "application/json"
+ }
+
+ try:
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ resp = await client.post(target_url, json=payload, headers=headers)
+
+ if resp.status_code == 200:
+ res_json = resp.json()
+ if res_json.get("success"):
+ new_text = (
+ f"✅ *CTO AUTO-HEAL APPROVED & EXECUTED*\n\n"
+ f"📌 *Task ID:* `{task_id}`\n\n"
+ f"Sistem telah berhasil diperbaiki, diverifikasi aman, dan disinkronisasikan ke seluruh microservices!"
+ )
+ await self.edit_message_text(chat_id, message_id, new_text)
+ await self.answer_callback_query(callback_id, "🎉 Sistem sukses dipulihkan!")
+ else:
+ err_detail = res_json.get("error", "Unknown error")
+ await self.answer_callback_query(callback_id, f"❌ Gagal: {err_detail}")
+ else:
+ await self.answer_callback_query(callback_id, f"❌ Worker HTTP Error {resp.status_code}")
+ except Exception as ex:
+ logger.error(f"Exception during worker heal call: {ex}")
+ await self.answer_callback_query(callback_id, f"❌ Koneksi Worker Gagal: {ex}")
+
+ elif action == "rejectheal":
+ await self.answer_callback_query(callback_id, "⏳ Membatalkan perbaikan...")
+ try:
+ stmt = update(KnowledgeQueue).where(KnowledgeQueue.id == task_id).values(status="Failed")
+ await self.db.execute(stmt)
+ await self.db.commit()
+
+ new_text = (
+ f"❌ *CTO AUTO-HEAL REJECTED/IGNORED*\n\n"
+ f"📌 *Task ID:* `{task_id}`\n\n"
+ f"Rekomendasi perbaikan sistem otomatis telah ditolak dan diabaikan."
+ )
+ await self.edit_message_text(chat_id, message_id, new_text)
+ await self.answer_callback_query(callback_id, "❌ Perbaikan ditolak.")
+ except Exception as ex:
+ logger.error(f"Exception during reject heal: {ex}")
+ await self.answer_callback_query(callback_id, f"❌ Gagal: {ex}")
+
+ return {"status": "success"}
+
+ # --- 4. HANDLE JOB APPROVAL CALLBACK ACTIONS ---
+ elif action in ["approve", "reject"]:
+ job_id = target_id
+ stmt = select(JobPosting).where(JobPosting.job_id == job_id)
+ job_res = await self.db.execute(stmt)
+ job = job_res.scalar_one_or_none()
+
+ if not job:
+ await self.answer_callback_query(callback_id, "❌ Error: Pekerjaan tidak ditemukan.")
+ return {"status": "error", "message": "Job not found"}
+
+ if action == "approve":
+ await self.answer_callback_query(callback_id, "⏳ Memproses postingan LinkedIn...")
+
+ if job.status == "posted":
+ await self.answer_callback_query(callback_id, "⚠️ Lowongan ini sudah diposting sebelumnya.")
+ return {"status": "already_posted"}
+
+ job.status = "posted"
+ job.is_active = True
+ job.posted_at = datetime.now(timezone.utc)
+
+ # Smart category resolution
+ company_category = job.company_category
+ if not company_category:
+ if job.company_name and "climatebase" in job.company_name.lower():
+ company_category = "Platform Karir & Edukasi Iklim"
+ else:
+ company_category = "Perusahaan Sektor Hijau"
+
+ # Post to LinkedIn Page
+ poster = LinkedInPoster()
+ skills = job.required_skills or ""
+ post_url, error_msg = await poster.post_job(
+ job_id=job_id,
+ title=job.title,
+ company_category=company_category,
+ location=job.location or "Indonesia",
+ skills=[s.strip() for s in skills.split(",") if s.strip()]
+ )
+
+ if post_url:
+ job.linkedin_post_url = post_url
+ new_text = (
+ f"✅ *APPROVED & POSTED TO LINKEDIN*\n\n"
+ f"📌 *ID:* `{job_id}`\n"
+ f"💼 *Posisi:* {job.title}\n"
+ f"🏢 *Industri:* {company_category}\n"
+ f"📍 *Lokasi:* {job.location or 'Indonesia'}\n\n"
+ f"🔗 [Lihat Postingan LinkedIn]({post_url})\n"
+ f"🌐 [Lihat Lowongan di Briga.id](https://briga.id/job?id={job_id})"
+ )
+ else:
+ reason = error_msg if error_msg else "Koneksi terputus atau token kadaluwarsa"
+ new_text = (
+ f"✅ *APPROVED & ACTIVE ON BRIGA.ID*\n⚠️ *LinkedIn Posting Failed:* {reason}\n\n"
+ f"📌 *ID:* `{job_id}`\n"
+ f"💼 *Posisi:* {job.title}\n"
+ f"🏢 *Industri:* {company_category}\n"
+ f"📍 *Lokasi:* {job.location or 'Indonesia'}\n\n"
+ f"🌐 [Lihat Lowongan di Briga.id](https://briga.id/job?id={job_id})"
+ )
+
+ await self.db.commit()
+ await self.edit_message_text(chat_id, message_id, new_text)
+ await self.answer_callback_query(callback_id, "🎉 Berhasil disetujui!")
+
+ # Trigger outreach swept in background
+ await self.delegate_task_to_queue("run_outreach_for_job", {"job_id": job_id})
+
+ elif action == "reject":
+ job.status = "rejected"
+ job.is_active = False
+ await self.db.commit()
+
+ new_text = (
+ f"❌ *LOWONGAN DITOLAK*\n\n"
+ f"📌 *ID:* `{job_id}`\n"
+ f"💼 *Posisi:* {job.title}\n"
+ f"🏢 *Perusahaan:* {job.company_name}\n\n"
+ f"Status lowongan ini telah diubah menjadi 'rejected' dan tidak akan dipublikasikan."
+ )
+ await self.edit_message_text(chat_id, message_id, new_text)
+ await self.answer_callback_query(callback_id, "❌ Lowongan ditolak.")
+
+ return {"status": "success"}
+
+ elif action == "menu":
+ if target_id == "briefing":
+ await self.answer_callback_query(callback_id, "⏳ Menghasilkan briefing...")
+ await self.generate_daily_briefing()
+ elif target_id == "health":
+ await self.answer_callback_query(callback_id, "⏳ Mengecek kesehatan...")
+ await self.check_system_health()
+ elif target_id == "pendingjobs":
+ await self.answer_callback_query(callback_id, "⏳ Mengambil lowongan pending...")
+ reply = await self.handle_ceo_command("/pending_jobs", chat_id)
+ if reply:
+ await self.send_message(chat_id, reply)
+ elif target_id == "pendingoutreach":
+ await self.answer_callback_query(callback_id, "⏳ Mengambil outreach pending...")
+ reply = await self.handle_ceo_command("/pending_outreach", chat_id)
+ if reply:
+ await self.send_message(chat_id, reply)
+ elif target_id == "finance":
+ await self.answer_callback_query(callback_id, "⏳ Mengambil data keuangan...")
+ reply = await self.handle_ceo_command("/finance", chat_id)
+ if reply:
+ await self.send_message(chat_id, reply)
+ return {"status": "success"}
+
+ # --- HANDLE MESSAGES (Incoming Chat / Receipt Uploads) ---
+ if "message" in data:
+ message = data["message"]
+ chat_id = message.get("chat", {}).get("id")
+ user_id = message.get("from", {}).get("id")
+ text = message.get("text", "")
+
+ # Strict access control verification for non-admin
+ is_admin = str(chat_id) == str(self.admin_chat_id)
+ is_pay_start = text.startswith("/start") and text[7:].strip().startswith("pay_")
+ is_verify = text.startswith("/verify")
+ is_photo = "photo" in message and len(message["photo"]) > 0
+ is_simple_start = text.strip() == "/start"
+
+ if not is_admin:
+ # Non-admin is strictly only allowed to access payment flows (start pay_, verify, photo upload) or generic /start hello
+ if not (is_pay_start or is_verify or is_photo or is_simple_start):
+ # Log attempt to security_audit_log
+ cmd_attempt = text.split(" ")[0] if text else "photo_or_other"
+ await self.log_security_audit(
+ action=cmd_attempt,
+ details=f"Unauthorized access attempt by non-admin chat_id {chat_id}. Message: {text[:200]}",
+ status="blocked"
+ )
+ # Reply with clear error
+ await self.send_message(chat_id, "❌ Anda tidak memiliki akses untuk fitur ini.")
+ return {"status": "unauthorized"}
+
+ # --- HANDLE START COMMAND (Deep link pay_TX-XXXXXX) ---
+ if text.startswith("/start"):
+ payload = text[7:].strip()
+ if payload.startswith("pay_"):
+ tx_id = payload[4:].upper()
+ await self.save_telegram_session(str(user_id), tx_id, state="waiting_receipt")
+ reply = (
+ f"👋 *Selamat datang di Brigawan Payment Bot!*\n\n"
+ f"Kami mendeteksi pengajuan Top-Up dengan ID Transaksi: *{tx_id}*.\n\n"
+ f"📌 *Langkah selanjutnya:*\n"
+ f"1. Transfer nominal paket sesuai invoice ke rekening:\n"
+ f" 🏦 *Bank BCA: 1234567890*\n"
+ f" 👤 *a/n PT Briga Energi Indonesia*\n"
+ f"2. *Unggah / Kirimkan foto bukti transfer* Anda langsung ke chat bot ini.\n\n"
+ f"Setelah foto dikirim, AI akan menganalisis dan Admin kami akan memverifikasi instan!"
+ )
+ await self.send_message(chat_id, reply)
+ return {"status": "success"}
+
+ if str(chat_id) == str(self.admin_chat_id):
+ reply = await self.handle_ceo_command("/menu", chat_id)
+ if reply:
+ await self.send_message(chat_id, reply)
+ return {"status": "success"}
+
+ await self.send_message(chat_id, "👋 *Halo!* Silakan mulai top-up koin dari Portal Rekruter Brigawan untuk menggunakan bot konfirmasi pembayaran ini.")
+ return {"status": "success"}
+
+ # --- HANDLE MANUAL VERIFY COMMAND (/verify TX-XXXXXX) ---
+ elif text.startswith("/verify"):
+ tx_id = text[8:].strip().upper()
+ if tx_id.startswith("TX-"):
+ await self.save_telegram_session(str(user_id), tx_id, state="waiting_receipt")
+ await self.send_message(chat_id, f"✅ ID Transaksi *{tx_id}* berhasil dikaitkan. Silakan kirimkan foto bukti transfer Anda sekarang.")
+ return {"status": "success"}
+ await self.send_message(chat_id, "❌ Format salah. Gunakan: `/verify TX-XXXXXX` untuk mengaitkan transaksi Anda.")
+ return {"status": "success"}
+
+ # --- HANDLE OTHER SLASH COMMANDS (Founder-facing) ---
+ elif text.startswith("/"):
+ if str(chat_id) != str(self.admin_chat_id):
+ await self.send_message(chat_id, "❌ Anda tidak memiliki akses untuk perintah ini.")
+ return {"status": "unauthorized"}
+
+ reply = await self.handle_ceo_command(text, chat_id)
+ if reply:
+ await self.send_message(chat_id, reply)
+ return {"status": "success"}
+
+ # --- HANDLE PHOTO UPLOAD (Receipt Verification via Gemini Vision) ---
+ elif "photo" in message and len(message["photo"]) > 0:
+ # Session validation
+ user_session = await self.get_telegram_session(str(user_id))
+ if not user_session:
+ await self.send_message(chat_id, "⚠️ ID Transaksi tidak ditemukan atau sesi kedaluwarsa. Silakan kirimkan kode transaksi Anda terlebih dahulu.\n\nContoh: `/verify TX-89A12B` lalu kirim bukti transfer.")
+ return {"status": "success"}
+
+ tx_id = user_session["tx_id"]
+ await self.send_message(chat_id, "⏳ *Membaca bukti transfer Anda menggunakan AI...*")
+
+ photo = message["photo"][-1]
+ file_id = photo["file_id"]
+
+ try:
+ photo_bytes = await self.download_file(file_id)
+ ocr_result = await self.run_vision_ocr(photo_bytes)
+ logger.info(f"👁️ OCR result for {tx_id}: {ocr_result}")
+
+ if ocr_result.get("is_blurry") or "error" in ocr_result:
+ await self.send_message(
+ chat_id,
+ "❌ *Gagal Membaca Bukti Transfer*\n\nGambar terdeteksi buram atau bukan merupakan bukti transfer yang valid. Silakan unggah ulang foto bukti transfer yang lebih jelas."
+ )
+ return {"status": "blurry_reprompt"}
+
+ # Get expected amount from database
+ stmt = select(Transaction).where(Transaction.id == tx_id)
+ tx_res = await self.db.execute(stmt)
+ target_tx = tx_res.scalar_one_or_none()
+
+ if not target_tx:
+ await self.send_message(chat_id, f"❌ ID Transaksi *{tx_id}* tidak terdaftar di database kami. Mohon periksa kembali.")
+ return {"status": "tx_not_found"}
+
+ expected_amount = int(float(target_tx.amount))
+ ocr_amount = int(ocr_result.get("amount", 0))
+ ocr_bank = ocr_result.get("bank", "Unknown Bank")
+ ocr_date = ocr_result.get("date", "Unknown Date")
+
+ discrepancy_alert = ""
+ amount_match = True
+ if abs(expected_amount - ocr_amount) > 1000:
+ amount_match = False
+ discrepancy_alert = f"⚠️ *PERINGATAN:* Nominal kuitansi (Rp {ocr_amount:,}) berbeda dengan tagihan invoice (Rp {expected_amount:,})!"
+ discrepancy_alert = discrepancy_alert.replace(",", ".")
+
+ user_feedback = (
+ f"ℹ️ *Informasi Terbaca oleh AI:*\n"
+ f"• Nominal: *Rp {ocr_amount:,}*\n"
+ f"• Bank Pengirim: *{ocr_bank}*\n"
+ f"• Tanggal: *{ocr_date}*\n\n"
+ f"Status: Bukti transfer berhasil dikirim ke Admin untuk verifikasi akhir."
+ )
+ user_feedback = user_feedback.replace(",", ".")
+ await self.send_message(chat_id, user_feedback)
+
+ if self.admin_chat_id:
+ admin_caption = (
+ f"📥 *BUKTI TRANSFER TOP-UP B2B*\n\n"
+ f"• ID Transaksi: *{tx_id}*\n"
+ f"• Rekruter ID: *{target_tx.client_id or 'Unknown'}*\n"
+ f"• Tagihan Invoice: *Rp {expected_amount:,}*\n"
+ f"• Terbaca oleh AI OCR: *Rp {ocr_amount:,}* ({ocr_bank})\n"
+ f"• Status Pencocokan: {'✅ COCOK' if amount_match else '❌ TIDAK COCOK'}\n"
+ f"{discrepancy_alert}\n\n"
+ f"Silakan lakukan tindakan:"
+ )
+ admin_caption = admin_caption.replace(",", ".")
+
+ url = f"{self.base_url}/sendPhoto"
+ payload = {
+ "chat_id": self.admin_chat_id,
+ "photo": file_id,
+ "caption": admin_caption,
+ "parse_mode": "Markdown",
+ "reply_markup": {
+ "inline_keyboard": [
+ [
+ {"text": "✅ Approve & Credit", "callback_data": f"approvepay_{tx_id}_{chat_id}"},
+ {"text": "❌ Reject", "callback_data": f"rejectpay_{tx_id}_{chat_id}"}
+ ]
+ ]
+ }
+ }
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ await client.post(url, json=payload, headers=self._proxy_headers())
+
+ except Exception as ex:
+ logger.error(f"Error processing payment photo: {ex}")
+ await self.send_message(chat_id, f"❌ Terjadi kesalahan saat membaca kuitansi: {ex}")
+ return {"status": "success"}
+
+ # --- HANDLE SEMANTIC INSTRUCTION (Founder chatting) ---
+ else:
+ if str(chat_id) == str(self.admin_chat_id) and text:
+ await self.send_message(chat_id, "⏳ *CEO Agent sedang memproses instruksi Anda...*")
+ # Run in background to avoid Telegram Webhook timeout using a fresh DB session
+ async def run_semantic_bg():
+ try:
+ from app.database import AsyncSessionLocal
+ async with AsyncSessionLocal() as session:
+ bg_service = TelegramCEOService(session)
+ await bg_service.process_semantic_instruction(text)
+ except Exception as bg_err:
+ logger.error(f"Error in background semantic instruction execution: {bg_err}")
+
+ asyncio.create_task(run_semantic_bg())
+ return {"status": "success"}
+
+ except Exception as e:
+ logger.error(f"❌ Webhook Error: {e}")
+ try:
+ if self.admin_chat_id:
+ await self.send_message(
+ self.admin_chat_id,
+ f"⚠️ *Sistem Bot Terkendala:*\n`{str(e)}`"
+ )
+ except Exception as send_err:
+ logger.error(f"Failed to send exception alert to admin: {send_err}")
+ return {"status": "error", "details": str(e)}
+
+ return {"status": "ignored"}
diff --git a/app/services/visual_content_service.py b/app/services/visual_content_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..989c804ebfdc1101ea09ad8333db259b152f59ef
--- /dev/null
+++ b/app/services/visual_content_service.py
@@ -0,0 +1,154 @@
+"""Visual Content Pipeline Service — Automated Carousel & Reels Generation.
+
+This service orchestrates the visual content creation workflow using
+AI agents and open-source libraries (Pillow, Playwright, Edge-TTS).
+"""
+
+import os
+import json
+import asyncio
+from typing import Any, Dict, List, Optional
+from loguru import logger
+from app.services.agent_service import call_agent_json, call_agent
+from app.config.settings import settings
+from app.utils.key_manager import APIKeyManager
+
+RAW_ELEVEN_KEYS = settings.elevenlabs_api_keys.split(",") if settings.elevenlabs_api_keys else []
+eleven_manager = APIKeyManager([k.strip() for k in RAW_ELEVEN_KEYS if k.strip()])
+
+class VisualContentService:
+ """Orchestrates automated visual content generation."""
+
+ @classmethod
+ async def generate_carousel(cls, topic: str):
+ """Workflow: Market Researcher (Niche Trends) -> Social Media Agent (Text) -> Fact Checker -> Style Designer (Visual) -> Renderer."""
+ logger.info(f"[VisualContent] Starting Carousel generation for topic: {topic}")
+
+ # 0. Niche Learning & Competitor Analysis (Market Researcher)
+ logger.info(f"[VisualContent] Analyzing niche trends for: {topic}...")
+ research_prompt = (
+ f"Lakukan riset tren terkini di LinkedIn dan media sosial terkait topik: '{topic}' di industri green jobs/ESG.\n"
+ "Apa sudut pandang (angle) yang sedang viral, kompetitor apa yang sedang dibicarakan, dan data pendukung apa yang relevan?\n"
+ "Berikan rangkuman insight yang bisa digunakan oleh Social Media Manager untuk membuat konten yang stand-out.\n"
+ "Kembalikan dalam format JSON: { 'trends': ['...'], 'viral_angles': ['...'], 'competitor_insights': '...', 'key_data': ['...'] }"
+ )
+ research_resp = await call_agent_json("market-researcher", research_prompt)
+ niche_context = json.dumps(research_resp["data"]) if research_resp["success"] else "Gunakan best practice umum industri green jobs."
+
+ # 1. Text Generation (Social Media Agent)
+ text_prompt = (
+ f"Buatlah konten Carousel LinkedIn/Instagram 5 slide untuk topik: '{topic}'.\n"
+ f"Gunakan INSIGHT TREN PASAR berikut agar konten relevan dengan niche saat ini:\n{niche_context}\n\n"
+ "Tiap slide harus memiliki: 'headline' dan 'body_text'.\n"
+ "Slide 1: Hook, Slide 2-4: Value/Edukasi, Slide 5: CTA.\n"
+ "Kembalikan dalam JSON."
+ )
+ text_resp = await call_agent_json("social-media-agent", text_prompt)
+ if not text_resp["success"]: return text_resp
+
+ content = text_resp["data"]
+
+ # Phrasing audit: ensure human-feel before fact-checking
+ from app.services.phrasing_audit_service import audit_text
+ passes, details = audit_text(json.dumps(content))
+ if not passes:
+ logger.warning(f"[VisualContent] Phrasing audit failed: {details}")
+ return {"success": False, "error": "phrasing_audit_failed", "details": details}
+
+ # 2. Fact Checking & Curation (Fact Checker)
+ logger.info(f"[VisualContent] Curating content with Fact Checker...")
+ fact_check_prompt = (
+ f"Evaluasi draf konten carousel berikut:\n{json.dumps(content)}\n\n"
+ "Periksa akurasi, ejaan, dan kesesuaian dengan brand (hindari greenwashing).\n"
+ "Kembalikan JSON dengan format: { 'approved': boolean, 'feedback': 'alasan/koreksi', 'corrected_content': {...} }"
+ )
+ fact_check_resp = await call_agent_json("fact-checker", fact_check_prompt)
+
+ if fact_check_resp["success"] and fact_check_resp["data"].get("approved", False):
+ content = fact_check_resp["data"].get("corrected_content", content)
+ logger.success("[VisualContent] Content APPROVED by Fact Checker.")
+ else:
+ feedback = fact_check_resp["data"].get("feedback", "Ditolak oleh editor tanpa alasan.") if fact_check_resp["success"] else "Gagal menghubungi Fact Checker."
+ logger.warning(f"[VisualContent] Content REJECTED by Fact Checker: {feedback}")
+ return {"success": False, "error": "Konten ditolak oleh Fact Checker", "feedback": feedback}
+
+ # 3. Visual Prompt Generation (Style Designer)
+ visual_prompt = (
+ f"Berdasarkan konten carousel yang telah disetujui ini: {json.dumps(content)}, "
+ "buatkan prompt gambar estetik untuk tiap slide yang akan dikirim ke API Pollinations.\n"
+ "Tentukan juga 'primary_color' dan 'font_style' yang cocok.\n"
+ "Kembalikan dalam JSON."
+ )
+ visual_resp = await call_agent_json("style-designer", visual_prompt)
+ if not visual_resp["success"]: return visual_resp
+
+ design = visual_resp["data"]
+
+ # 4. Rendering (Placeholder Logic)
+ logger.success(f"[VisualContent] Content and Design ready. Rendering slides...")
+ # Note: In implementation, this calls a Pillow/Playwright worker
+ return {
+ "success": True,
+ "topic": topic,
+ "slides_count": 5,
+ "preview": content,
+ "style": design
+ }
+
+ @classmethod
+ async def generate_reels_script(cls, topic: str):
+ """Workflow: Social Media Agent (Script) -> Fact Checker -> Style Designer (Visual Brief)."""
+ logger.info(f"[VisualContent] Generating Reels script for: {topic}")
+
+ script_prompt = (
+ f"Buatlah skrip video Reels/TikTok durasi 30 detik tentang: '{topic}'.\n"
+ "Format: { 'timestamp': '00:05', 'speech': '...', 'visual_brief': '...' }.\n"
+ "Gunakan gaya bahasa anak muda profesional."
+ )
+ script_resp = await call_agent_json("social-media-agent", script_prompt)
+
+ if not script_resp["success"]: return script_resp
+ script_data = script_resp["data"]
+
+ # Fact Checking
+ logger.info(f"[VisualContent] Curating script with Fact Checker...")
+ fact_check_prompt = (
+ f"Evaluasi skrip video berikut:\n{json.dumps(script_data)}\n\n"
+ "Periksa akurasi klaim, kesesuaian durasi, dan pastikan tidak ada bias atau greenwashing.\n"
+ "Kembalikan JSON dengan format: { 'approved': boolean, 'feedback': 'alasan/koreksi', 'corrected_script': [...] }"
+ )
+ fact_check_resp = await call_agent_json("fact-checker", fact_check_prompt)
+
+ if fact_check_resp["success"] and fact_check_resp["data"].get("approved", False):
+ script_data = fact_check_resp["data"].get("corrected_script", script_data)
+ logger.success("[VisualContent] Script APPROVED by Fact Checker.")
+ return {"success": True, "data": script_data}
+ else:
+ feedback = fact_check_resp["data"].get("feedback", "Skrip ditolak.") if fact_check_resp["success"] else "Gagal menghubungi Fact Checker."
+ logger.warning(f"[VisualContent] Script REJECTED: {feedback}")
+ return {"success": False, "error": "Skrip ditolak oleh Fact Checker", "feedback": feedback}
+
+
+ @classmethod
+ async def generate_voiceover(cls, text: str, output_path: str):
+ """Generates audio file from text using selected provider."""
+ provider = settings.voice_provider.lower()
+ logger.info(f"[VisualContent] Generating voiceover using: {provider}")
+
+ if provider == "elevenlabs" and eleven_manager.keys:
+ active_key = await eleven_manager.get_key()
+ if active_key:
+ logger.info("[Voiceover] Calling ElevenLabs API for Voice Cloning (Rotated Key)...")
+ # Implementation for httpx call to elevenlabs would go here
+ # Example: If HTTP 401 or 429 occurs, we would do:
+ # eleven_manager.mark_failed(active_key)
+ # and retry...
+ return {"success": True, "provider": "elevenlabs", "path": output_path, "key_used": f"{active_key[:5]}..."}
+ else:
+ logger.warning("[Voiceover] All ElevenLabs keys exhausted. Falling back to Edge-TTS.")
+ provider = "edge-tts"
+
+ # Fallback to free Edge-TTS
+ logger.info("[Voiceover] Using Edge-TTS (Free Standard Voice)...")
+ # implementation for edge-tts would go here
+ return {"success": True, "provider": "edge-tts", "path": output_path}
diff --git a/app/services/whatsapp/community_hunter.py b/app/services/whatsapp/community_hunter.py
index 017b412a79ea5985b50f31784d3c0c78366866ee..8fef884bbb8b54120f2e4fc35cf6e099a81d81ac 100644
--- a/app/services/whatsapp/community_hunter.py
+++ b/app/services/whatsapp/community_hunter.py
@@ -1,100 +1,100 @@
-"""Community Hunter Service — Proactive Group Engagement Logic.
-
-Handles the 'Soft-Selling' flow for talent recruitment in WhatsApp Groups:
-1. Detects new messages/members in groups.
-2. Initiates natural private chat (Intro).
-3. Transitions to career coaching & Briga.id talent onboarding.
-"""
-
-from loguru import logger
-from typing import Dict, Any
-from app.services.whatsapp_service import whatsapp_bot
-from app.services.ai_service import ai_orchestrator # Assume this exists for Gemini processing
-
-class CommunityHunterService:
- def __init__(self):
- self.engagement_state = {} # In-memory state tracking (Number -> Flow Step)
-
- async def handle_group_event(self, event_data: Dict[str, Any]):
- """Triggered when someone joins a group or sends a relevant keyword."""
- group_jid = event_data.get("group_jid")
- sender_number = event_data.get("sender_number")
- sender_name = event_data.get("sender_name", "Kak")
-
- # Logic: Only initiate if we haven't talked to them recently
- if sender_number not in self.engagement_state:
- logger.info(f"[Hunter] New lead detected in group: {sender_name} ({sender_number})")
- await self.initiate_intro(sender_number, sender_name)
-
- async def initiate_intro(self, number: str, name: str):
- """Phase 1: Natural Introduction (Private Message)."""
- intro_text = (
- f"Halo {name}, salam kenal ya! Saya lihat tadi di grup komunitas. "
- f"Senang bisa satu grup di sana. Saya lagi riset kecil-kecilan nih "
- f"tentang perkembangan karir teman-teman di bidang Green Jobs. "
- f"Boleh ngobrol sebentar?"
- )
- await whatsapp_bot.send_text(number, intro_text)
- self.engagement_state[number] = "INTRO_SENT"
-
- async def handle_user_reply(self, number: str, message: str):
- """Phase 2: Transition from small talk to Career Coaching, Recruitment, or CSR."""
- state = self.engagement_state.get(number)
-
- # Analyze intent using AI (Talent vs Recruiter vs Collaboration vs General)
- intent_data = await ai_orchestrator.classify_lead_intent(message)
- intent = intent_data.get("intent") # "talent", "recruiter", "collaboration", "general"
-
- if intent == "recruiter":
- await self.handle_recruiter_lead(number, message, intent_data)
- elif intent == "collaboration":
- await self.handle_collab_lead(number, message, intent_data)
- elif state == "INTRO_SENT":
- # Continue as Career Coach for Talents
- ai_reply = await ai_orchestrator.generate_coaching_reply(message)
- await whatsapp_bot.send_text(number, ai_reply)
- self.engagement_state[number] = "COACHING_ACTIVE"
- elif state == "COACHING_ACTIVE":
- await self.pitch_briga_platform(number)
-
- async def handle_recruiter_lead(self, number: str, message: str, data: Dict[str, Any]):
- """Handles potential employers/recruiters and notifies the Board."""
- await whatsapp_bot.send_text(number,
- "Wah, menarik sekali! Briga.id memang memiliki talent pool khusus di bidang sustainability. "
- "Boleh saya minta detail kebutuhan talent-nya? Akan segera saya teruskan ke tim Board kami."
- )
- await self.notify_board("RECRUITER_LEAD", number, message)
-
- async def handle_collab_lead(self, number: str, message: str, data: Dict[str, Any]):
- """Handles CSR/Sustainability campaign leads and notifies the Board."""
- await whatsapp_bot.send_text(number,
- "Kolaborasi CSR/Sustainability Campaign ya? Ini sangat sejalan dengan visi Briga.id. "
- "Saya akan sampaikan usulan ini ke Board untuk segera ditindaklanjuti. "
- "Mohon tunggu sebentar ya."
- )
- await self.notify_board("COLLAB_LEAD", number, message)
-
- async def notify_board(self, lead_type: str, contact: str, summary: str):
- """Sends a notification to the Board WhatsApp Group for confirmation."""
- # Replace with your actual Board Group JID
- board_group_jid = "BOARD_OFFICE@g.us"
-
- notification = (
- f"🔔 *NEW BUSINESS LEAD ({lead_type})*\n\n"
- f"👤 *Kontak:* wa.me/{contact}\n"
- f"📝 *Ringkasan:* {summary[:150]}...\n\n"
- f"Mohon konfirmasi di Command Center untuk instruksi selanjutnya."
- )
- await whatsapp_bot.send_group_message(board_group_jid, notification)
-
- async def pitch_briga_platform(self, number: str):
- pitch_text = (
- "Btw, setelah ngobrol, saya rasa kamu punya potensi besar di ekosistem Green Talent. "
- "Coba deh mampir ke Briga.id, di sana kita bantu matchmaking ke perusahaan yang "
- "butuh banget skill kayak kamu. "
- "Bisa daftar di sini ya (gratis): https://briga.id/talent/register"
- )
- await whatsapp_bot.send_text(number, pitch_text)
- self.engagement_state[number] = "PITCHED"
-
-hunter_service = CommunityHunterService()
+"""Community Hunter Service — Proactive Group Engagement Logic.
+
+Handles the 'Soft-Selling' flow for talent recruitment in WhatsApp Groups:
+1. Detects new messages/members in groups.
+2. Initiates natural private chat (Intro).
+3. Transitions to career coaching & Briga.id talent onboarding.
+"""
+
+from loguru import logger
+from typing import Dict, Any
+from app.services.whatsapp_service import whatsapp_bot
+from app.services.ai_service import ai_orchestrator # Assume this exists for Gemini processing
+
+class CommunityHunterService:
+ def __init__(self):
+ self.engagement_state = {} # In-memory state tracking (Number -> Flow Step)
+
+ async def handle_group_event(self, event_data: Dict[str, Any]):
+ """Triggered when someone joins a group or sends a relevant keyword."""
+ group_jid = event_data.get("group_jid")
+ sender_number = event_data.get("sender_number")
+ sender_name = event_data.get("sender_name", "Kak")
+
+ # Logic: Only initiate if we haven't talked to them recently
+ if sender_number not in self.engagement_state:
+ logger.info(f"[Hunter] New lead detected in group: {sender_name} ({sender_number})")
+ await self.initiate_intro(sender_number, sender_name)
+
+ async def initiate_intro(self, number: str, name: str):
+ """Phase 1: Natural Introduction (Private Message)."""
+ intro_text = (
+ f"Halo {name}, salam kenal ya! Saya lihat tadi di grup komunitas. "
+ f"Senang bisa satu grup di sana. Saya lagi riset kecil-kecilan nih "
+ f"tentang perkembangan karir teman-teman di bidang Green Jobs. "
+ f"Boleh ngobrol sebentar?"
+ )
+ await whatsapp_bot.send_text(number, intro_text)
+ self.engagement_state[number] = "INTRO_SENT"
+
+ async def handle_user_reply(self, number: str, message: str):
+ """Phase 2: Transition from small talk to Career Coaching, Recruitment, or CSR."""
+ state = self.engagement_state.get(number)
+
+ # Analyze intent using AI (Talent vs Recruiter vs Collaboration vs General)
+ intent_data = await ai_orchestrator.classify_lead_intent(message)
+ intent = intent_data.get("intent") # "talent", "recruiter", "collaboration", "general"
+
+ if intent == "recruiter":
+ await self.handle_recruiter_lead(number, message, intent_data)
+ elif intent == "collaboration":
+ await self.handle_collab_lead(number, message, intent_data)
+ elif state == "INTRO_SENT":
+ # Continue as Career Coach for Talents
+ ai_reply = await ai_orchestrator.generate_coaching_reply(message)
+ await whatsapp_bot.send_text(number, ai_reply)
+ self.engagement_state[number] = "COACHING_ACTIVE"
+ elif state == "COACHING_ACTIVE":
+ await self.pitch_briga_platform(number)
+
+ async def handle_recruiter_lead(self, number: str, message: str, data: Dict[str, Any]):
+ """Handles potential employers/recruiters and notifies the Board."""
+ await whatsapp_bot.send_text(number,
+ "Wah, menarik sekali! Briga.id memang memiliki talent pool khusus di bidang sustainability. "
+ "Boleh saya minta detail kebutuhan talent-nya? Akan segera saya teruskan ke tim Board kami."
+ )
+ await self.notify_board("RECRUITER_LEAD", number, message)
+
+ async def handle_collab_lead(self, number: str, message: str, data: Dict[str, Any]):
+ """Handles CSR/Sustainability campaign leads and notifies the Board."""
+ await whatsapp_bot.send_text(number,
+ "Kolaborasi CSR/Sustainability Campaign ya? Ini sangat sejalan dengan visi Briga.id. "
+ "Saya akan sampaikan usulan ini ke Board untuk segera ditindaklanjuti. "
+ "Mohon tunggu sebentar ya."
+ )
+ await self.notify_board("COLLAB_LEAD", number, message)
+
+ async def notify_board(self, lead_type: str, contact: str, summary: str):
+ """Sends a notification to the Board WhatsApp Group for confirmation."""
+ # Replace with your actual Board Group JID
+ board_group_jid = "BOARD_OFFICE@g.us"
+
+ notification = (
+ f"🔔 *NEW BUSINESS LEAD ({lead_type})*\n\n"
+ f"👤 *Kontak:* wa.me/{contact}\n"
+ f"📝 *Ringkasan:* {summary[:150]}...\n\n"
+ f"Mohon konfirmasi di Command Center untuk instruksi selanjutnya."
+ )
+ await whatsapp_bot.send_group_message(board_group_jid, notification)
+
+ async def pitch_briga_platform(self, number: str):
+ pitch_text = (
+ "Btw, setelah ngobrol, saya rasa kamu punya potensi besar di ekosistem Green Talent. "
+ "Coba deh mampir ke Briga.id, di sana kita bantu matchmaking ke perusahaan yang "
+ "butuh banget skill kayak kamu. "
+ "Bisa daftar di sini ya (gratis): https://briga.id/talent/register"
+ )
+ await whatsapp_bot.send_text(number, pitch_text)
+ self.engagement_state[number] = "PITCHED"
+
+hunter_service = CommunityHunterService()
diff --git a/app/services/whatsapp/flow_handler.py b/app/services/whatsapp/flow_handler.py
index 790911c03675bc1a5759c8d730746813cd1d9874..8380cb8a1dd06d9da2e21e443dbc808c1b692e46 100644
--- a/app/services/whatsapp/flow_handler.py
+++ b/app/services/whatsapp/flow_handler.py
@@ -1,241 +1,241 @@
-"""Flow Handler for WhatsApp — Briga.id.
-
-Manages the conversational state machine for the WhatsApp bot.
-Ensures a smooth onboarding experience and interactive career coaching.
-"""
-
-from app.services.whatsapp_service import whatsapp_bot
-from app.services.ai_service import call_gemini_tier
-from app.services.whatsapp.personas import get_bram_persona
-from app.services.job_service import get_job_postings
-from app.utils.cv_parser import cv_parser
-from sqlalchemy.ext.asyncio import AsyncSession
-from sqlalchemy import select, func
-from app.models.system import WhatsAppSession
-from app.models.talent import Talent
-from loguru import logger
-from typing import Optional, Dict, Any
-import json
-import re
-
-class WhatsAppFlowHandler:
- def __init__(self, db: AsyncSession):
- self.db = db
-
- async def handle_message(self, sender: str, message: str, media_info: Optional[Dict[str, Any]] = None):
- """Main entry point for processing incoming WhatsApp messages."""
- # Clean the sender phone number
- phone = sender.split("@")[0]
-
- # 1. Get or Create Session
- session = await self.get_session(phone)
-
- # 2. State Machine Logic
- try:
- # 2a. Handle Media (CV Upload)
- if media_info and media_info["type"] == "document":
- # Check for CV-like file names or mimetypes
- filename = media_info.get("title", "").lower()
- mimetype = media_info.get("mimetype", "").lower()
- if "pdf" in mimetype or "word" in mimetype or any(x in filename for x in ["cv", "resume", "biodata", "curriculum"]):
- return await self.handle_cv_upload(session, media_info)
-
- # 2b. Check for global commands/intents first if in IDLE state
- if session.state == "IDLE":
- if any(word in message.lower() for word in ["cari kerja", "lowongan", "job", "loker"]):
- return await self.handle_job_search(session)
-
- # 2c. Process based on current state
- if session.state == "START":
- return await self.handle_start(session, message)
- elif session.state == "ONBOARDING_NAME":
- return await self.handle_onboarding_name(session, message)
- elif session.state == "ONBOARDING_EMAIL":
- return await self.handle_onboarding_email(session, message)
-
- # Default: Chat with AI (IDLE state or unknown)
- return await self.handle_chat(session, message)
- except Exception as e:
- logger.error(f"[WhatsApp Flow] Error: {e}")
- await whatsapp_bot.send_text(phone, "Duh, maaf Kak, sepertinya Bram sedang sedikit pusing. Boleh coba lagi sebentar lagi?")
-
- async def handle_cv_upload(self, session: WhatsAppSession, media_info: Dict[str, Any]):
- """Acknowledges CV upload and initiates processing."""
- filename = media_info.get("title", "CV")
- message_id = media_info.get("message_id")
- instance = media_info.get("instance")
-
- await whatsapp_bot.send_text(session.phone, f"Wah, Kakak kirim dokumen ya? Bram terima file *{filename}* nya! 📄\n\nBeri Bram waktu sebentar untuk menganalisis CV Kakak menggunakan AI Briga ya. Nanti Bram kabari kalau sudah selesai!")
-
- # Download the file bytes
- file_bytes = await whatsapp_bot.download_media(message_id, instance)
- if not file_bytes:
- await whatsapp_bot.send_text(session.phone, "Aduh Kak, sepertinya Bram gagal mendownload file CV nya. Bisa coba kirim ulang?")
- return
-
- # 1. Convert PDF to Markdown & Extract Metadata
- result = await cv_parser.analyze_cv(file_bytes, filename)
-
- if "error" in result:
- await whatsapp_bot.send_text(session.phone, f"Maaf Kak, Bram gagal menganalisis CV nya: {result['error']}")
- return
-
- metadata = result["metadata"]
- score = metadata.get("green_readiness_score", 0)
- feedback = metadata.get("green_readiness_feedback", "CV Kakak sudah Bram terima!")
-
- # Save metadata to session context for later registration
- ctx = session.context or {}
- ctx["cv_metadata"] = metadata
- session.context = ctx
- await self.db.commit()
-
- # 2. Build Response
- response = f"✨ *Analisis AI Bram Selesai!* ✨\n\n"
- response += f"👤 Nama: {metadata.get('nama', '-')}\n"
- response += f"🎓 Edukasi: {metadata.get('universitas', '-')}\n"
- response += f"📈 Skor Kesiapan Hijau: *{score}/100*\n\n"
- response += f"💡 *Feedback Bram:* \n_{feedback}_\n\n"
-
- # Ask for confirmation to register
- session.state = "CONFIRM_REGISTRATION"
- await self.db.commit()
- response += f"Gimana Kak, datanya sudah benar? Kalau sudah oke, Bram bisa bantu daftarkan Kakak langsung ke Briga.id biar bisa masuk ke dashboard!\n\nKetik *'DAFTAR'* untuk lanjut atau kirim pesan lain untuk tanya-tanya."
-
- await whatsapp_bot.send_text(session.phone, response)
- logger.info(f"[WhatsApp Flow] CV Analysis complete for {session.phone}, score: {score}")
-
- async def get_session(self, phone: str) -> WhatsAppSession:
- """Retrieves an existing session or creates a new one for the phone number."""
- result = await self.db.execute(select(WhatsAppSession).where(WhatsAppSession.phone == phone))
- session = result.scalar_one_or_none()
- if not session:
- session = WhatsAppSession(phone=phone, state="START")
- self.db.add(session)
- await self.db.commit()
- await self.db.refresh(session)
- return session
-
- async def handle_start(self, session: WhatsAppSession, message: str):
- """Initial contact: Check if user exists or start onboarding."""
- talent = await self.get_talent_by_phone(session.phone)
- if talent:
- session.state = "IDLE"
- # Update context with talent name if possible
- session.context = {"name": talent.name}
- await self.db.commit()
- response = f"Halo Kak {talent.name}! Senang melihat Kakak kembali di Briga.id. Ada yang bisa Bram bantu hari ini?"
- await whatsapp_bot.send_text(session.phone, response)
- else:
- session.state = "ONBOARDING_NAME"
- await self.db.commit()
- response = "Halo! Saya Bram, asisten karir Kakak di Briga.id. 👋\n\nBram perhatikan Kakak belum terdaftar. Boleh tahu nama lengkap Kakak siapa? (Biar Bram nggak salah panggil hehe)"
- await whatsapp_bot.send_text(session.phone, response)
-
- async def handle_onboarding_name(self, session: WhatsAppSession, message: str):
- """Saves name and asks for email."""
- session.context = {"name": message.strip()}
- session.state = "ONBOARDING_EMAIL"
- await self.db.commit()
- response = f"Salam kenal, Kak {message.strip()}! Sekarang, boleh Bram minta alamat email Kakak yang aktif? Ini penting untuk sinkronisasi akun Kakak nanti."
- await whatsapp_bot.send_text(session.phone, response)
-
- async def handle_onboarding_email(self, session: WhatsAppSession, message: str):
- """Saves email and finishes onboarding."""
- email = message.strip().lower()
- if not "@" in email or not "." in email:
- await whatsapp_bot.send_text(session.phone, "Hmm, format emailnya sepertinya kurang tepat Kak. Boleh kirim ulang emailnya?")
- return
-
- result = await self.db.execute(select(Talent).where(func.lower(Talent.email) == email))
- existing_talent = result.scalar_one_or_none()
-
- if existing_talent:
- existing_talent.phone = session.phone
- session.state = "IDLE"
- session.context = {"name": existing_talent.name, "email": email}
- await self.db.commit()
- response = f"Ah, ternyata Kakak sudah punya akun dengan email {email}! Bram sudah hubungkan nomor WA ini ke akun Kakak. Sekarang Kakak bisa tanya apa saja seputar karir hijau!"
- else:
- ctx = session.context or {}
- ctx["email"] = email
- session.context = ctx
- session.state = "IDLE"
- await self.db.commit()
- response = f"Sip! Email {email} sudah Bram catat. Selamat datang di Briga.id! 🚀\n\nSekarang Kakak bisa tanya-tanya Bram apa saja. Misalnya: 'Gimana caranya dapet sertifikasi K3?' atau 'Ada lowongan apa hari ini?'"
-
- await whatsapp_bot.send_text(session.phone, response)
-
- async def handle_job_search(self, session: WhatsAppSession):
- """Fetches and displays active job postings."""
- await whatsapp_bot.send_text(session.phone, "Siap Kak! Bram carikan lowongan kerja hijau terbaru buat Kakak ya... Tunggu sebentar.")
-
- jobs_res = await get_job_postings(self.db, page=1, limit=5)
- if not jobs_res.get("success") or not jobs_res.get("data"):
- await whatsapp_bot.send_text(session.phone, "Aduh, sepertinya saat ini belum ada lowongan baru yang tersedia. Coba tanya lagi besok ya Kak!")
- return
-
- response = "Berikut adalah beberapa lowongan kerja hijau terbaru di Briga.id:\n\n"
- for i, job in enumerate(jobs_res["data"], 1):
- response += f"{i}. *{job['title']}*\n"
- response += f"📍 {job['location']}\n"
- response += f"💰 {job['salary_range']}\n"
- response += f"🔗 briga.id/job/{job['job_id']}\n\n"
-
- response += "Kakak bisa klik link di atas untuk detail dan melamar langsung ya!"
- await whatsapp_bot.send_text(session.phone, response)
-
- async def handle_chat(self, session: WhatsAppSession, message: str):
- """General AI conversation using the Bram Career Coach persona."""
- # Handle the special registration command
- if session.state == "CONFIRM_REGISTRATION" and message.strip().upper() == "DAFTAR":
- return await self.generate_registration_link(session)
-
- persona = get_bram_persona("COACH")
- if session.context and "name" in session.context:
- persona += f"\n\nUser yang sedang berbicara dengan Anda bernama {session.context['name']}."
-
- response, _ = await call_gemini_tier(
- prompt=message,
- system_instruction=persona,
- tier="MEDIUM"
- )
-
- if not response:
- response = "Aduh, maaf Kak, sinyal Bram lagi agak keganggu. Boleh tanya sekali lagi?"
-
- await whatsapp_bot.send_text(session.phone, response)
-
- async def generate_registration_link(self, session: WhatsAppSession):
- """Generates a unique registration link and sends it to the user."""
- import secrets
- import base64
-
- # Generate a temporary token for registration
- temp_token = secrets.token_hex(16)
- ctx = session.context or {}
- ctx["registration_token"] = temp_token
- session.context = ctx
- session.state = "AWAITING_CONFIRMATION"
- await self.db.commit()
-
- # Build the link (encoded with base64 for simplicity in the URL)
- # In a real app, this would be a frontend route that handles the registration
- metadata = ctx.get("cv_metadata", {})
- payload = {
- "token": temp_token,
- "email": ctx.get("email"),
- "name": ctx.get("name") or metadata.get("nama"),
- "phone": session.phone
- }
- encoded_payload = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
-
- # Production URL for registration
- reg_link = f"https://briga.id/register-confirm?data={encoded_payload}"
-
- response = f"Sip! Tinggal selangkah lagi Kak. Klik link di bawah ini untuk konfirmasi pendaftaran Kakak:\n\n🔗 {reg_link}\n\nSetelah diklik, Kakak akan langsung masuk ke Dashboard Talent Briga.id. Sampai jumpa di sana ya Kak! 🚀"
- await whatsapp_bot.send_text(session.phone, response)
-
- async def get_talent_by_phone(self, phone: str):
- result = await self.db.execute(select(Talent).where(Talent.phone == phone))
- return result.scalar_one_or_none()
+"""Flow Handler for WhatsApp — Briga.id.
+
+Manages the conversational state machine for the WhatsApp bot.
+Ensures a smooth onboarding experience and interactive career coaching.
+"""
+
+from app.services.whatsapp_service import whatsapp_bot
+from app.services.ai_service import call_gemini_tier
+from app.services.whatsapp.personas import get_bram_persona
+from app.services.job_service import get_job_postings
+from app.utils.cv_parser import cv_parser
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select, func
+from app.models.system import WhatsAppSession
+from app.models.talent import Talent
+from loguru import logger
+from typing import Optional, Dict, Any
+import json
+import re
+
+class WhatsAppFlowHandler:
+ def __init__(self, db: AsyncSession):
+ self.db = db
+
+ async def handle_message(self, sender: str, message: str, media_info: Optional[Dict[str, Any]] = None):
+ """Main entry point for processing incoming WhatsApp messages."""
+ # Clean the sender phone number
+ phone = sender.split("@")[0]
+
+ # 1. Get or Create Session
+ session = await self.get_session(phone)
+
+ # 2. State Machine Logic
+ try:
+ # 2a. Handle Media (CV Upload)
+ if media_info and media_info["type"] == "document":
+ # Check for CV-like file names or mimetypes
+ filename = media_info.get("title", "").lower()
+ mimetype = media_info.get("mimetype", "").lower()
+ if "pdf" in mimetype or "word" in mimetype or any(x in filename for x in ["cv", "resume", "biodata", "curriculum"]):
+ return await self.handle_cv_upload(session, media_info)
+
+ # 2b. Check for global commands/intents first if in IDLE state
+ if session.state == "IDLE":
+ if any(word in message.lower() for word in ["cari kerja", "lowongan", "job", "loker"]):
+ return await self.handle_job_search(session)
+
+ # 2c. Process based on current state
+ if session.state == "START":
+ return await self.handle_start(session, message)
+ elif session.state == "ONBOARDING_NAME":
+ return await self.handle_onboarding_name(session, message)
+ elif session.state == "ONBOARDING_EMAIL":
+ return await self.handle_onboarding_email(session, message)
+
+ # Default: Chat with AI (IDLE state or unknown)
+ return await self.handle_chat(session, message)
+ except Exception as e:
+ logger.error(f"[WhatsApp Flow] Error: {e}")
+ await whatsapp_bot.send_text(phone, "Duh, maaf Kak, sepertinya Bram sedang sedikit pusing. Boleh coba lagi sebentar lagi?")
+
+ async def handle_cv_upload(self, session: WhatsAppSession, media_info: Dict[str, Any]):
+ """Acknowledges CV upload and initiates processing."""
+ filename = media_info.get("title", "CV")
+ message_id = media_info.get("message_id")
+ instance = media_info.get("instance")
+
+ await whatsapp_bot.send_text(session.phone, f"Wah, Kakak kirim dokumen ya? Bram terima file *{filename}* nya! 📄\n\nBeri Bram waktu sebentar untuk menganalisis CV Kakak menggunakan AI Briga ya. Nanti Bram kabari kalau sudah selesai!")
+
+ # Download the file bytes
+ file_bytes = await whatsapp_bot.download_media(message_id, instance)
+ if not file_bytes:
+ await whatsapp_bot.send_text(session.phone, "Aduh Kak, sepertinya Bram gagal mendownload file CV nya. Bisa coba kirim ulang?")
+ return
+
+ # 1. Convert PDF to Markdown & Extract Metadata
+ result = await cv_parser.analyze_cv(file_bytes, filename)
+
+ if "error" in result:
+ await whatsapp_bot.send_text(session.phone, f"Maaf Kak, Bram gagal menganalisis CV nya: {result['error']}")
+ return
+
+ metadata = result["metadata"]
+ score = metadata.get("green_readiness_score", 0)
+ feedback = metadata.get("green_readiness_feedback", "CV Kakak sudah Bram terima!")
+
+ # Save metadata to session context for later registration
+ ctx = session.context or {}
+ ctx["cv_metadata"] = metadata
+ session.context = ctx
+ await self.db.commit()
+
+ # 2. Build Response
+ response = f"✨ *Analisis AI Bram Selesai!* ✨\n\n"
+ response += f"👤 Nama: {metadata.get('nama', '-')}\n"
+ response += f"🎓 Edukasi: {metadata.get('universitas', '-')}\n"
+ response += f"📈 Skor Kesiapan Hijau: *{score}/100*\n\n"
+ response += f"💡 *Feedback Bram:* \n_{feedback}_\n\n"
+
+ # Ask for confirmation to register
+ session.state = "CONFIRM_REGISTRATION"
+ await self.db.commit()
+ response += f"Gimana Kak, datanya sudah benar? Kalau sudah oke, Bram bisa bantu daftarkan Kakak langsung ke Briga.id biar bisa masuk ke dashboard!\n\nKetik *'DAFTAR'* untuk lanjut atau kirim pesan lain untuk tanya-tanya."
+
+ await whatsapp_bot.send_text(session.phone, response)
+ logger.info(f"[WhatsApp Flow] CV Analysis complete for {session.phone}, score: {score}")
+
+ async def get_session(self, phone: str) -> WhatsAppSession:
+ """Retrieves an existing session or creates a new one for the phone number."""
+ result = await self.db.execute(select(WhatsAppSession).where(WhatsAppSession.phone == phone))
+ session = result.scalar_one_or_none()
+ if not session:
+ session = WhatsAppSession(phone=phone, state="START")
+ self.db.add(session)
+ await self.db.commit()
+ await self.db.refresh(session)
+ return session
+
+ async def handle_start(self, session: WhatsAppSession, message: str):
+ """Initial contact: Check if user exists or start onboarding."""
+ talent = await self.get_talent_by_phone(session.phone)
+ if talent:
+ session.state = "IDLE"
+ # Update context with talent name if possible
+ session.context = {"name": talent.name}
+ await self.db.commit()
+ response = f"Halo Kak {talent.name}! Senang melihat Kakak kembali di Briga.id. Ada yang bisa Bram bantu hari ini?"
+ await whatsapp_bot.send_text(session.phone, response)
+ else:
+ session.state = "ONBOARDING_NAME"
+ await self.db.commit()
+ response = "Halo! Saya Bram, asisten karir Kakak di Briga.id. 👋\n\nBram perhatikan Kakak belum terdaftar. Boleh tahu nama lengkap Kakak siapa? (Biar Bram nggak salah panggil hehe)"
+ await whatsapp_bot.send_text(session.phone, response)
+
+ async def handle_onboarding_name(self, session: WhatsAppSession, message: str):
+ """Saves name and asks for email."""
+ session.context = {"name": message.strip()}
+ session.state = "ONBOARDING_EMAIL"
+ await self.db.commit()
+ response = f"Salam kenal, Kak {message.strip()}! Sekarang, boleh Bram minta alamat email Kakak yang aktif? Ini penting untuk sinkronisasi akun Kakak nanti."
+ await whatsapp_bot.send_text(session.phone, response)
+
+ async def handle_onboarding_email(self, session: WhatsAppSession, message: str):
+ """Saves email and finishes onboarding."""
+ email = message.strip().lower()
+ if not "@" in email or not "." in email:
+ await whatsapp_bot.send_text(session.phone, "Hmm, format emailnya sepertinya kurang tepat Kak. Boleh kirim ulang emailnya?")
+ return
+
+ result = await self.db.execute(select(Talent).where(func.lower(Talent.email) == email))
+ existing_talent = result.scalar_one_or_none()
+
+ if existing_talent:
+ existing_talent.phone = session.phone
+ session.state = "IDLE"
+ session.context = {"name": existing_talent.name, "email": email}
+ await self.db.commit()
+ response = f"Ah, ternyata Kakak sudah punya akun dengan email {email}! Bram sudah hubungkan nomor WA ini ke akun Kakak. Sekarang Kakak bisa tanya apa saja seputar karir hijau!"
+ else:
+ ctx = session.context or {}
+ ctx["email"] = email
+ session.context = ctx
+ session.state = "IDLE"
+ await self.db.commit()
+ response = f"Sip! Email {email} sudah Bram catat. Selamat datang di Briga.id! 🚀\n\nSekarang Kakak bisa tanya-tanya Bram apa saja. Misalnya: 'Gimana caranya dapet sertifikasi K3?' atau 'Ada lowongan apa hari ini?'"
+
+ await whatsapp_bot.send_text(session.phone, response)
+
+ async def handle_job_search(self, session: WhatsAppSession):
+ """Fetches and displays active job postings."""
+ await whatsapp_bot.send_text(session.phone, "Siap Kak! Bram carikan lowongan kerja hijau terbaru buat Kakak ya... Tunggu sebentar.")
+
+ jobs_res = await get_job_postings(self.db, page=1, limit=5)
+ if not jobs_res.get("success") or not jobs_res.get("data"):
+ await whatsapp_bot.send_text(session.phone, "Aduh, sepertinya saat ini belum ada lowongan baru yang tersedia. Coba tanya lagi besok ya Kak!")
+ return
+
+ response = "Berikut adalah beberapa lowongan kerja hijau terbaru di Briga.id:\n\n"
+ for i, job in enumerate(jobs_res["data"], 1):
+ response += f"{i}. *{job['title']}*\n"
+ response += f"📍 {job['location']}\n"
+ response += f"💰 {job['salary_range']}\n"
+ response += f"🔗 briga.id/job/{job['job_id']}\n\n"
+
+ response += "Kakak bisa klik link di atas untuk detail dan melamar langsung ya!"
+ await whatsapp_bot.send_text(session.phone, response)
+
+ async def handle_chat(self, session: WhatsAppSession, message: str):
+ """General AI conversation using the Bram Career Coach persona."""
+ # Handle the special registration command
+ if session.state == "CONFIRM_REGISTRATION" and message.strip().upper() == "DAFTAR":
+ return await self.generate_registration_link(session)
+
+ persona = get_bram_persona("COACH")
+ if session.context and "name" in session.context:
+ persona += f"\n\nUser yang sedang berbicara dengan Anda bernama {session.context['name']}."
+
+ response, _ = await call_gemini_tier(
+ prompt=message,
+ system_instruction=persona,
+ tier="MEDIUM"
+ )
+
+ if not response:
+ response = "Aduh, maaf Kak, sinyal Bram lagi agak keganggu. Boleh tanya sekali lagi?"
+
+ await whatsapp_bot.send_text(session.phone, response)
+
+ async def generate_registration_link(self, session: WhatsAppSession):
+ """Generates a unique registration link and sends it to the user."""
+ import secrets
+ import base64
+
+ # Generate a temporary token for registration
+ temp_token = secrets.token_hex(16)
+ ctx = session.context or {}
+ ctx["registration_token"] = temp_token
+ session.context = ctx
+ session.state = "AWAITING_CONFIRMATION"
+ await self.db.commit()
+
+ # Build the link (encoded with base64 for simplicity in the URL)
+ # In a real app, this would be a frontend route that handles the registration
+ metadata = ctx.get("cv_metadata", {})
+ payload = {
+ "token": temp_token,
+ "email": ctx.get("email"),
+ "name": ctx.get("name") or metadata.get("nama"),
+ "phone": session.phone
+ }
+ encoded_payload = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
+
+ # Production URL for registration
+ reg_link = f"https://briga.id/register-confirm?data={encoded_payload}"
+
+ response = f"Sip! Tinggal selangkah lagi Kak. Klik link di bawah ini untuk konfirmasi pendaftaran Kakak:\n\n🔗 {reg_link}\n\nSetelah diklik, Kakak akan langsung masuk ke Dashboard Talent Briga.id. Sampai jumpa di sana ya Kak! 🚀"
+ await whatsapp_bot.send_text(session.phone, response)
+
+ async def get_talent_by_phone(self, phone: str):
+ result = await self.db.execute(select(Talent).where(Talent.phone == phone))
+ return result.scalar_one_or_none()
diff --git a/app/services/whatsapp/personas.py b/app/services/whatsapp/personas.py
index 14f016236b27831a055776ae074ade6e2f945c84..a3dd40deb0bf37ea579d06978e458913520dc01a 100644
--- a/app/services/whatsapp/personas.py
+++ b/app/services/whatsapp/personas.py
@@ -1,31 +1,31 @@
-"""Persona Logic for Bramantya (Bram) AI.
-
-Defines the system prompts for different interaction tiers:
-1. EXECUTIVE (Board)
-2. SCOUT (Recruiters)
-3. COACH (Talents)
-"""
-
-PERSONA_PROMPTS = {
- "EXECUTIVE": (
- "Nama Anda adalah Bramantya (Bram), Executive Assistant untuk Board Briga.id. "
- "Tugas Anda adalah memberikan data akurat, ringkas, dan menjalankan perintah administratif. "
- "Gunakan bahasa formal Indonesia. Prioritaskan keamanan data dan efisiensi operasional."
- ),
- "SCOUT": (
- "Nama Anda adalah Bramantya (Bram), Recruitment Scout dari Briga.id. "
- "Tugas Anda adalah membantu Rekruter menemukan talenta terbaik. "
- "Fokus pada metrik kompetensi, ketersediaan kandidat, dan jadwal interview. "
- "Gunakan bahasa profesional yang membantu."
- ),
- "COACH": (
- "Nama Anda adalah Bramantya (Bram), Career Coach dari Briga.id. "
- "Gunakan gaya bahasa 'Kak' yang ramah, hangat, dan inspiratif. "
- "Tugas Anda adalah membimbing talenta untuk mengembangkan karir di bidang Green Jobs. "
- "Jangan kaku, berikan tips praktis tentang SKKNI dan sertifikasi."
- )
-}
-
-def get_bram_persona(sender_role: str) -> str:
- """Returns the system prompt based on the sender's role."""
- return PERSONA_PROMPTS.get(sender_role, PERSONA_PROMPTS["COACH"])
+"""Persona Logic for Bramantya (Bram) AI.
+
+Defines the system prompts for different interaction tiers:
+1. EXECUTIVE (Board)
+2. SCOUT (Recruiters)
+3. COACH (Talents)
+"""
+
+PERSONA_PROMPTS = {
+ "EXECUTIVE": (
+ "Nama Anda adalah Bramantya (Bram), Executive Assistant untuk Board Briga.id. "
+ "Tugas Anda adalah memberikan data akurat, ringkas, dan menjalankan perintah administratif. "
+ "Gunakan bahasa formal Indonesia. Prioritaskan keamanan data dan efisiensi operasional."
+ ),
+ "SCOUT": (
+ "Nama Anda adalah Bramantya (Bram), Recruitment Scout dari Briga.id. "
+ "Tugas Anda adalah membantu Rekruter menemukan talenta terbaik. "
+ "Fokus pada metrik kompetensi, ketersediaan kandidat, dan jadwal interview. "
+ "Gunakan bahasa profesional yang membantu."
+ ),
+ "COACH": (
+ "Nama Anda adalah Bramantya (Bram), Career Coach dari Briga.id. "
+ "Gunakan gaya bahasa 'Kak' yang ramah, hangat, dan inspiratif. "
+ "Tugas Anda adalah membimbing talenta untuk mengembangkan karir di bidang Green Jobs. "
+ "Jangan kaku, berikan tips praktis tentang SKKNI dan sertifikasi."
+ )
+}
+
+def get_bram_persona(sender_role: str) -> str:
+ """Returns the system prompt based on the sender's role."""
+ return PERSONA_PROMPTS.get(sender_role, PERSONA_PROMPTS["COACH"])
diff --git a/app/services/whatsapp_email_service.py b/app/services/whatsapp_email_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..6352af555a242883437a09580d09fe6db3993b76
--- /dev/null
+++ b/app/services/whatsapp_email_service.py
@@ -0,0 +1,138 @@
+"""
+WhatsApp Registration Email Service — Handles sending default credentials
+to talents who register via the WhatsApp natural flow.
+"""
+
+import os
+import asyncio
+from loguru import logger
+from app.services.email_service import email_service
+
+class WhatsAppRegistrationEmailService:
+ def __init__(self):
+ pass
+
+ async def send_welcome_email(self, email: str, name: str, default_password: str):
+ """Sends a welcome email with credentials to the newly registered talent."""
+ subject = "Konfirmasi Pendaftaran Briga.id — Akses Dashboard Anda"
+
+ dashboard_url = "https://briga.id/talent.html" # Arahkan ke dashboard
+
+ body_html = f"""
+
+
+
+
+
+
+
+
+
+
Selamat Datang di Ekosistem Karir Hijau, {name}!
+
+
+
+
+
Halo,
+
+ Saya Yabes , CEO Briga.id. Senang sekali menyambut Anda sebagai bagian dari misi kami untuk mempercepat transisi ekonomi berkelanjutan di Indonesia.
+
+
+ Pendaftaran Anda melalui Bramantya AI telah berhasil diverifikasi. Berikut adalah akses eksklusif ke Dashboard Talent Anda:
+
+
+
+
+
+
+
+ Email Terdaftar
+ {email}
+
+
+
+
+ Password Sementara
+ {default_password}
+
+
+
+
+
+
+
+
+ Akses Dashboard Saya
+
+
+ 🔒 Keamanan Anda prioritas kami. Mohon segera perbarui password Anda di menu Pengaturan.
+
+
+
+
+ Mari berkolaborasi untuk menciptakan masa depan yang lebih hijau. Jika ada kendala, tim kami siap membantu Anda kapan saja.
+
+
+
+
+
+
+
+ VERIFIED
+ BRIGAWAN
+ ★ GREEN TALENT ★
+
+
+
+
+
Salam hangat,
+
Yabes
+
CEO & Founder, Briga.id
+
+
+
+
+
+
+
+
+
+
+
+ Briga.id adalah platform pelopor karir hijau di Indonesia, menghubungkan talenta terbaik dengan industri masa depan.
+
+
+
+
+
+
+
+ © 2026 Briga.id. Semua Hak Dilindungi.
+
+
+
+ """
+
+ try:
+ success = await asyncio.to_thread(
+ email_service.send_html_email, email, subject, body_html
+ )
+ if success:
+ return {"success": True, "message": "Email welcome terkirim"}
+ return {"success": False, "error": "Failed to send email via SMTP service"}
+ except Exception as e:
+ logger.error(f"Failed to send welcome email: {e}")
+ return {"success": False, "error": str(e)}
+
+wa_email_service = WhatsAppRegistrationEmailService()
+
diff --git a/app/services/whatsapp_service.py b/app/services/whatsapp_service.py
index 241bb38e9a137af5b3944538a5d35099feb4f85a..e2559dd996ac9007a80f22dd0b5a0792c78e6a6d 100644
--- a/app/services/whatsapp_service.py
+++ b/app/services/whatsapp_service.py
@@ -1,189 +1,189 @@
-"""WhatsApp Service — Evolution API Integration for briga.id.
-
-Handles instance management, QR code generation, and automated messaging
-for the AI CEO and Support agents.
-"""
-
-import httpx
-import os
-from loguru import logger
-from typing import Optional, Dict, Any
-from app.config import settings
-
-class WhatsAppService:
- def __init__(self):
- self.api_url = os.getenv("WHATSAPP_API_URL") # e.g. https://briga-wa.up.railway.app
- self.api_key = os.getenv("WHATSAPP_API_KEY")
- self.instance_name = "CEO_OFFICE"
-
- async def get_status(self) -> Dict[str, Any]:
- """Checks if the WhatsApp instance is connected or needs QR."""
- if not self.api_url:
- return {"status": "not_configured", "message": "WHATSAPP_API_URL missing"}
-
- url = f"{self.api_url}/instance/connectionState/{self.instance_name}"
- headers = {"apikey": self.api_key}
-
- try:
- async with httpx.AsyncClient() as client:
- resp = await client.get(url, headers=headers)
- if resp.status_code == 404:
- # Instance doesn't exist yet, try creating it
- await self.create_instance()
- return {"status": "creating", "message": "Instance is being created..."}
-
- if resp.status_code >= 500:
- # Potential server issue or instance disconnected/down
- return {"status": "DISCONNECTED", "message": "Evolution API Error (500)"}
-
- return resp.json()
- except Exception as e:
- return {"status": "error", "message": str(e)}
-
- async def create_instance(self):
- """Initializes a new WhatsApp instance on the gateway."""
- url = f"{self.api_url}/instance/create"
- payload = {
- "instanceName": self.instance_name,
- "token": self.api_key,
- "qrcode": True
- }
- headers = {"apikey": self.api_key}
-
- async with httpx.AsyncClient() as client:
- resp = await client.post(url, json=payload, headers=headers)
- return resp.json()
-
- async def get_qr_base64(self) -> Optional[str]:
- """Retrieves the QR Code. If instance doesn't exist, creates it first."""
- url = f"{self.api_url}/instance/connect/{self.instance_name}"
- headers = {"apikey": self.api_key}
-
- try:
- async with httpx.AsyncClient(timeout=25.0) as client:
- resp = await client.get(url, headers=headers)
-
- # Case 1: Instance missing, create it
- if resp.status_code == 404:
- logger.info(f"[WhatsApp] Instance {self.instance_name} not found. Creating...")
- create_res = await self.create_instance()
- # Evolution API often returns the QR in the creation response
- # Format: { "qrcode": { "base64": "..." } }
- qr_data = create_res.get("qrcode", {})
- if isinstance(qr_data, dict) and qr_data.get("base64"):
- return qr_data.get("base64")
-
- # If not in create response, wait a bit and try connect URL again
- import asyncio
- await asyncio.sleep(3)
- resp = await client.get(url, headers=headers)
-
- data = resp.json()
- if resp.status_code == 200:
- return data.get("base64")
-
- logger.warning(f"[WhatsApp] QR Fetch failed (Code {resp.status_code}): {data}")
- except Exception as e:
- logger.error(f"[WhatsApp] QR Fetch Error: {e}")
- return None
-
- async def logout_instance(self) -> bool:
- """Logs out the session. If it fails, it tries to force delete the instance."""
- url = f"{self.api_url}/instance/logout/{self.instance_name}"
- headers = {"apikey": self.api_key}
-
- try:
- async with httpx.AsyncClient(timeout=10.0) as client:
- resp = await client.delete(url, headers=headers)
- if resp.status_code == 200:
- return True
-
- # If logout fails (maybe already logged out), try deleting instance entirely
- return await self.delete_instance()
- except Exception as e:
- logger.error(f"[WhatsApp] Logout failed: {e}")
- return await self.delete_instance()
-
- async def delete_instance(self) -> bool:
- """Force deletes the instance entirely from Evolution API."""
- url = f"{self.api_url}/instance/delete/{self.instance_name}"
- headers = {"apikey": self.api_key}
- try:
- async with httpx.AsyncClient(timeout=10.0) as client:
- resp = await client.delete(url, headers=headers)
- logger.info(f"[WhatsApp] Instance delete attempt: {resp.status_code}")
- return resp.status_code == 200
- except Exception as e:
- logger.error(f"[WhatsApp] Delete instance failed: {e}")
- return False
-
- async def download_media(self, message_id: str, instance_name: Optional[str] = None) -> Optional[bytes]:
- """Downloads media content (base64) from a specific message ID."""
- inst = instance_name or self.instance_name
- url = f"{self.api_url}/chat/getBase64FromMedia/{inst}"
- payload = {"message": {"key": {"id": message_id}}, "convertToMp4": False}
- headers = {"apikey": self.api_key}
-
- import base64
- try:
- async with httpx.AsyncClient(timeout=30.0) as client:
- resp = await client.post(url, json=payload, headers=headers)
- if resp.status_code == 200:
- data = resp.json()
- # Evolution API returns { "base64": "..." } or directly binary if configured differently
- b64_data = data.get("base64")
- if b64_data:
- # Handle potential data URI prefix
- if "," in b64_data:
- b64_data = b64_data.split(",")[1]
- return base64.b64decode(b64_data)
- except Exception as e:
- logger.error(f"[WhatsApp] Media download failed for {message_id}: {e}")
- return None
-
- async def send_text(self, number: str, text: str):
- """Sends a text message with human-like typing simulation."""
- url = f"{self.api_url}/message/sendText/{self.instance_name}"
-
- # Calculate typing delay: ~0.05s per character, min 1s, max 7s
- typing_time = min(max(len(text) * 0.05, 1), 7) * 1000 # in ms
-
- payload = {
- "number": number,
- "options": {
- "delay": int(typing_time),
- "presence": "composing", # Show "Typing..." status
- "linkPreview": True
- },
- "textMessage": {"text": text}
- }
- headers = {"apikey": self.api_key}
-
- try:
- async with httpx.AsyncClient() as client:
- # Add a small random pre-delay (thinking time)
- import random
- import asyncio
- await asyncio.sleep(random.uniform(0.5, 2.0))
-
- resp = await client.post(url, json=payload, headers=headers)
- return resp.json()
- except Exception as e:
- logger.error(f"[WhatsApp] Send failed: {e}")
- return {"status": "error"}
-
- async def send_group_message(self, group_jid: str, text: str):
- """Broadcasts a strategic update to a WhatsApp Group."""
- url = f"{self.api_url}/message/sendText/{self.instance_name}"
- payload = {
- "number": group_jid, # Group JID looks like: 123456789@g.us
- "textMessage": {"text": text}
- }
- headers = {"apikey": self.api_key}
-
- async with httpx.AsyncClient() as client:
- resp = await client.post(url, json=payload, headers=headers)
- return resp.json()
-
-# Singleton instance
-whatsapp_bot = WhatsAppService()
+"""WhatsApp Service — Evolution API Integration for briga.id.
+
+Handles instance management, QR code generation, and automated messaging
+for the AI CEO and Support agents.
+"""
+
+import httpx
+import os
+from loguru import logger
+from typing import Optional, Dict, Any
+from app.config import settings
+
+class WhatsAppService:
+ def __init__(self):
+ self.api_url = os.getenv("WHATSAPP_API_URL") # e.g. https://briga-wa.up.railway.app
+ self.api_key = os.getenv("WHATSAPP_API_KEY")
+ self.instance_name = "CEO_OFFICE"
+
+ async def get_status(self) -> Dict[str, Any]:
+ """Checks if the WhatsApp instance is connected or needs QR."""
+ if not self.api_url:
+ return {"status": "not_configured", "message": "WHATSAPP_API_URL missing"}
+
+ url = f"{self.api_url}/instance/connectionState/{self.instance_name}"
+ headers = {"apikey": self.api_key}
+
+ try:
+ async with httpx.AsyncClient() as client:
+ resp = await client.get(url, headers=headers)
+ if resp.status_code == 404:
+ # Instance doesn't exist yet, try creating it
+ await self.create_instance()
+ return {"status": "creating", "message": "Instance is being created..."}
+
+ if resp.status_code >= 500:
+ # Potential server issue or instance disconnected/down
+ return {"status": "DISCONNECTED", "message": "Evolution API Error (500)"}
+
+ return resp.json()
+ except Exception as e:
+ return {"status": "error", "message": str(e)}
+
+ async def create_instance(self):
+ """Initializes a new WhatsApp instance on the gateway."""
+ url = f"{self.api_url}/instance/create"
+ payload = {
+ "instanceName": self.instance_name,
+ "token": self.api_key,
+ "qrcode": True
+ }
+ headers = {"apikey": self.api_key}
+
+ async with httpx.AsyncClient() as client:
+ resp = await client.post(url, json=payload, headers=headers)
+ return resp.json()
+
+ async def get_qr_base64(self) -> Optional[str]:
+ """Retrieves the QR Code. If instance doesn't exist, creates it first."""
+ url = f"{self.api_url}/instance/connect/{self.instance_name}"
+ headers = {"apikey": self.api_key}
+
+ try:
+ async with httpx.AsyncClient(timeout=25.0) as client:
+ resp = await client.get(url, headers=headers)
+
+ # Case 1: Instance missing, create it
+ if resp.status_code == 404:
+ logger.info(f"[WhatsApp] Instance {self.instance_name} not found. Creating...")
+ create_res = await self.create_instance()
+ # Evolution API often returns the QR in the creation response
+ # Format: { "qrcode": { "base64": "..." } }
+ qr_data = create_res.get("qrcode", {})
+ if isinstance(qr_data, dict) and qr_data.get("base64"):
+ return qr_data.get("base64")
+
+ # If not in create response, wait a bit and try connect URL again
+ import asyncio
+ await asyncio.sleep(3)
+ resp = await client.get(url, headers=headers)
+
+ data = resp.json()
+ if resp.status_code == 200:
+ return data.get("base64")
+
+ logger.warning(f"[WhatsApp] QR Fetch failed (Code {resp.status_code}): {data}")
+ except Exception as e:
+ logger.error(f"[WhatsApp] QR Fetch Error: {e}")
+ return None
+
+ async def logout_instance(self) -> bool:
+ """Logs out the session. If it fails, it tries to force delete the instance."""
+ url = f"{self.api_url}/instance/logout/{self.instance_name}"
+ headers = {"apikey": self.api_key}
+
+ try:
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ resp = await client.delete(url, headers=headers)
+ if resp.status_code == 200:
+ return True
+
+ # If logout fails (maybe already logged out), try deleting instance entirely
+ return await self.delete_instance()
+ except Exception as e:
+ logger.error(f"[WhatsApp] Logout failed: {e}")
+ return await self.delete_instance()
+
+ async def delete_instance(self) -> bool:
+ """Force deletes the instance entirely from Evolution API."""
+ url = f"{self.api_url}/instance/delete/{self.instance_name}"
+ headers = {"apikey": self.api_key}
+ try:
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ resp = await client.delete(url, headers=headers)
+ logger.info(f"[WhatsApp] Instance delete attempt: {resp.status_code}")
+ return resp.status_code == 200
+ except Exception as e:
+ logger.error(f"[WhatsApp] Delete instance failed: {e}")
+ return False
+
+ async def download_media(self, message_id: str, instance_name: Optional[str] = None) -> Optional[bytes]:
+ """Downloads media content (base64) from a specific message ID."""
+ inst = instance_name or self.instance_name
+ url = f"{self.api_url}/chat/getBase64FromMedia/{inst}"
+ payload = {"message": {"key": {"id": message_id}}, "convertToMp4": False}
+ headers = {"apikey": self.api_key}
+
+ import base64
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.post(url, json=payload, headers=headers)
+ if resp.status_code == 200:
+ data = resp.json()
+ # Evolution API returns { "base64": "..." } or directly binary if configured differently
+ b64_data = data.get("base64")
+ if b64_data:
+ # Handle potential data URI prefix
+ if "," in b64_data:
+ b64_data = b64_data.split(",")[1]
+ return base64.b64decode(b64_data)
+ except Exception as e:
+ logger.error(f"[WhatsApp] Media download failed for {message_id}: {e}")
+ return None
+
+ async def send_text(self, number: str, text: str):
+ """Sends a text message with human-like typing simulation."""
+ url = f"{self.api_url}/message/sendText/{self.instance_name}"
+
+ # Calculate typing delay: ~0.05s per character, min 1s, max 7s
+ typing_time = min(max(len(text) * 0.05, 1), 7) * 1000 # in ms
+
+ payload = {
+ "number": number,
+ "options": {
+ "delay": int(typing_time),
+ "presence": "composing", # Show "Typing..." status
+ "linkPreview": True
+ },
+ "textMessage": {"text": text}
+ }
+ headers = {"apikey": self.api_key}
+
+ try:
+ async with httpx.AsyncClient() as client:
+ # Add a small random pre-delay (thinking time)
+ import random
+ import asyncio
+ await asyncio.sleep(random.uniform(0.5, 2.0))
+
+ resp = await client.post(url, json=payload, headers=headers)
+ return resp.json()
+ except Exception as e:
+ logger.error(f"[WhatsApp] Send failed: {e}")
+ return {"status": "error"}
+
+ async def send_group_message(self, group_jid: str, text: str):
+ """Broadcasts a strategic update to a WhatsApp Group."""
+ url = f"{self.api_url}/message/sendText/{self.instance_name}"
+ payload = {
+ "number": group_jid, # Group JID looks like: 123456789@g.us
+ "textMessage": {"text": text}
+ }
+ headers = {"apikey": self.api_key}
+
+ async with httpx.AsyncClient() as client:
+ resp = await client.post(url, json=payload, headers=headers)
+ return resp.json()
+
+# Singleton instance
+whatsapp_bot = WhatsAppService()
diff --git a/app/services/workflow_orchestrator_service.py b/app/services/workflow_orchestrator_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4362adbe3ef17a643ee1e9cab7f71f16e404427
--- /dev/null
+++ b/app/services/workflow_orchestrator_service.py
@@ -0,0 +1,128 @@
+"""Workflow Orchestrator Service — The Factory Floor.
+
+This service defines and executes the predefined macro-workflows
+that chain multiple agents together to accomplish complex tasks
+(e.g., Bug Fix, Daily Build, Release Prep).
+"""
+
+import asyncio
+from typing import Dict, Any, List
+from loguru import logger
+from app.services.agent_service import call_agent
+
+class WorkflowOrchestrator:
+ """Orchestrates chains of agents to complete standard workflows."""
+
+ @classmethod
+ async def run_pre_commit(cls, code_diff: str) -> Dict[str, Any]:
+ """Workflow: code-auditor -> test-runner"""
+ logger.info("[Workflow] Starting PRE-COMMIT workflow...")
+
+ # Step 1: Code Audit
+ logger.info("[Workflow] 1/2: Running Code Auditor...")
+ audit_res = await call_agent("code-auditor", f"Audit perubahan kode berikut:\n{code_diff}")
+ if not audit_res["success"]: return audit_res
+
+ # Step 2: Test Runner
+ logger.info("[Workflow] 2/2: Running Test Runner...")
+ test_context = f"Hasil audit:\n{audit_res['reply']}\nPastikan kode ini aman."
+ test_res = await call_agent("test-runner", "Verifikasi stabilitas kode ini.", context=test_context)
+
+ logger.success("[Workflow] PRE-COMMIT workflow completed.")
+ return {"success": True, "audit": audit_res, "test": test_res}
+
+ @classmethod
+ async def run_bug_fix(cls, bug_report: str) -> Dict[str, Any]:
+ """Workflow: test-writer -> code-fixer -> test-runner"""
+ logger.info(f"[Workflow] Starting BUG FIX workflow for: {bug_report[:50]}...")
+
+ # Step 1: Write failing test
+ logger.info("[Workflow] 1/3: Test Writer generating failing test...")
+ test_res = await call_agent("test-writer", f"Buat unit test yang gagal berdasarkan bug ini: {bug_report}")
+
+ # Step 2: Fix the code
+ logger.info("[Workflow] 2/3: Code Fixer implementing solution...")
+ fix_context = f"Laporan Bug: {bug_report}\nTest Case: {test_res.get('reply', '')}"
+ fix_res = await call_agent("code-fixer", "Implementasikan perbaikan kode yang membuat test case ini pass.", context=fix_context)
+
+ # Step 3: Run the tests
+ logger.info("[Workflow] 3/3: Test Runner validating fix...")
+ run_context = f"Perbaikan yang diterapkan:\n{fix_res.get('reply', '')}"
+ run_res = await call_agent("test-runner", "Jalankan semua test suite untuk memvalidasi perbaikan ini.", context=run_context)
+
+ logger.success("[Workflow] BUG FIX workflow completed.")
+ return {"success": True, "fix_proposed": fix_res, "validation": run_res}
+
+ @classmethod
+ async def run_pre_deploy(cls) -> Dict[str, Any]:
+ """Workflow: deploy-checker + env-validator + dep-auditor (Parallel)"""
+ logger.info("[Workflow] Starting PRE-DEPLOY validation (Parallel)...")
+
+ # Run all three low-level ops checks concurrently
+ task_deploy = call_agent("deploy-checker", "Periksa kesiapan deployment.")
+ task_env = call_agent("env-validator", "Validasi semua environment variables.")
+ task_dep = call_agent("dep-auditor", "Cek dependensi yang rentan (vulnerable).")
+
+ results = await asyncio.gather(task_deploy, task_env, task_dep)
+
+ logger.success("[Workflow] PRE-DEPLOY validation completed.")
+ return {
+ "success": True,
+ "deploy_check": results[0],
+ "env_check": results[1],
+ "dep_check": results[2]
+ }
+
+ @classmethod
+ async def run_daily_build(cls, feature_request: str) -> Dict[str, Any]:
+ """Workflow: (backend+frontend+style) -> auth -> trigger -> build-deployer"""
+ logger.info(f"[Workflow] Starting DAILY BUILD workflow for: {feature_request[:50]}...")
+
+ # Step 1: Parallel Builders
+ logger.info("[Workflow] 1/4: Builders assembling components (Parallel)...")
+ t_be = call_agent("backend-builder", f"Buat API backend untuk fitur: {feature_request}")
+ t_fe = call_agent("frontend-builder", f"Buat UI frontend untuk fitur: {feature_request}")
+ t_ui = call_agent("style-designer", f"Buat styling CSS/Tailwind untuk: {feature_request}")
+
+ build_results = await asyncio.gather(t_be, t_fe, t_ui)
+
+ build_context = (
+ f"Backend:\n{build_results[0].get('reply')}\n"
+ f"Frontend:\n{build_results[1].get('reply')}\n"
+ f"Styling:\n{build_results[2].get('reply')}"
+ )
+
+ # Step 2: Auth Check
+ logger.info("[Workflow] 2/4: Auth Manager checking RBAC...")
+ auth_res = await call_agent("auth-manager", "Pastikan endpoint baru memiliki proteksi JWT yang tepat.", context=build_context)
+
+ # Step 3: Trigger/Cron Check
+ logger.info("[Workflow] 3/4: Trigger Scheduler updating crons...")
+ trig_res = await call_agent("trigger-scheduler", "Apakah ada background task yang perlu dijadwalkan dari fitur ini?", context=build_context)
+
+ # Step 4: Deployer
+ logger.info("[Workflow] 4/4: Build Deployer packaging release...")
+ deploy_res = await call_agent("build-deployer", "Siapkan paket build dan generate script deploy untuk Cloudflare Pages.", context=build_context)
+
+ logger.success("[Workflow] DAILY BUILD workflow completed.")
+ return {"success": True, "build_components": build_results, "deploy_script": deploy_res}
+
+ @classmethod
+ async def run_migration_safely(cls, migration_goal: str) -> Dict[str, Any]:
+ """Workflow: backup-restorer -> migration-agent -> sheet-manager -> test-runner"""
+ logger.info(f"[Workflow] Starting MIGRATION workflow: {migration_goal}")
+
+ logger.info("[Workflow] 1/4: Backup Restorer securing data...")
+ backup = await call_agent("backup-restorer", "Lakukan full dump database sebelum migrasi.")
+
+ logger.info("[Workflow] 2/4: Migration Agent drafting scripts...")
+ migration = await call_agent("migration-agent", f"Buat skrip Alembic untuk: {migration_goal}")
+
+ logger.info("[Workflow] 3/4: Sheet Manager updating schemas...")
+ sheet = await call_agent("sheet-manager", "Sesuaikan column mapping di backend jika ada perubahan skema.", context=migration.get('reply', ''))
+
+ logger.info("[Workflow] 4/4: Test Runner verifying integrity...")
+ test = await call_agent("test-runner", "Jalankan sanity check pada database pasca migrasi.")
+
+ logger.success("[Workflow] MIGRATION workflow completed.")
+ return {"success": True, "backup": backup, "migration": migration, "test": test}
diff --git a/app/utils/__init__.py b/app/utils/__init__.py
index 20cad50379a4bc844183d919791e77017def1567..1b55ac117eed8a1ecc3d0ea4bb3da1c2f0a76226 100644
--- a/app/utils/__init__.py
+++ b/app/utils/__init__.py
@@ -3,6 +3,7 @@
from app.utils.security import (
create_access_token,
decode_access_token,
+ verify_supabase_token,
hash_legacy_gas_password,
hash_password,
rate_limiter,
@@ -21,6 +22,7 @@ __all__ = [
"hash_legacy_gas_password",
"create_access_token",
"decode_access_token",
+ "verify_supabase_token",
"rate_limiter",
"AppError",
"ErrorCode",
diff --git a/app/utils/cv_parser.py b/app/utils/cv_parser.py
index e2267959a6b4d39d941a71c4cedef0b788387ef9..9a575999bf323c4a205723ca0e870324ba627348 100644
--- a/app/utils/cv_parser.py
+++ b/app/utils/cv_parser.py
@@ -1,60 +1,60 @@
-import os
-import tempfile
-from markitdown import MarkItDown
-from app.services.ai_service import extract_cv_metadata
-from loguru import logger
-
-class CVParser:
- @staticmethod
- async def parse_to_markdown(file_bytes: bytes, filename: str) -> str:
- """Converts raw file bytes to Markdown text using MarkItDown."""
- ext = ".pdf"
- low_name = filename.lower()
- if low_name.endswith(".docx"):
- ext = ".docx"
- elif low_name.endswith(".doc"):
- ext = ".doc"
- elif low_name.endswith(".html") or low_name.endswith(".htm"):
- ext = ".html"
- elif low_name.endswith(".txt"):
- ext = ".txt"
-
- temp_path = None
- try:
- with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp_file:
- temp_file.write(file_bytes)
- temp_path = temp_file.name
-
- markitdown = MarkItDown()
- result = markitdown.convert(temp_path)
- return result.text_content
- except Exception as e:
- logger.error(f"CV conversion failed: {e}")
- raise e
- finally:
- if temp_path and os.path.exists(temp_path):
- try:
- os.remove(temp_path)
- except:
- pass
-
- @staticmethod
- async def analyze_cv(file_bytes: bytes, filename: str):
- """Full pipeline: Convert to MD -> Extract Metadata via Gemini."""
- try:
- markdown_text = await CVParser.parse_to_markdown(file_bytes, filename)
- if not markdown_text or len(markdown_text.strip()) < 50:
- return {"error": "Teks CV terlalu pendek atau tidak terbaca."}
-
- # Use the existing ai_service metadata extractor
- metadata = await extract_cv_metadata(markdown_text)
- return {
- "success": True,
- "markdown": markdown_text,
- "metadata": metadata
- }
- except Exception as e:
- logger.error(f"CV analysis pipeline failed: {e}")
- return {"error": str(e)}
-
-cv_parser = CVParser()
+import os
+import tempfile
+from markitdown import MarkItDown
+from app.services.ai_service import extract_cv_metadata
+from loguru import logger
+
+class CVParser:
+ @staticmethod
+ async def parse_to_markdown(file_bytes: bytes, filename: str) -> str:
+ """Converts raw file bytes to Markdown text using MarkItDown."""
+ ext = ".pdf"
+ low_name = filename.lower()
+ if low_name.endswith(".docx"):
+ ext = ".docx"
+ elif low_name.endswith(".doc"):
+ ext = ".doc"
+ elif low_name.endswith(".html") or low_name.endswith(".htm"):
+ ext = ".html"
+ elif low_name.endswith(".txt"):
+ ext = ".txt"
+
+ temp_path = None
+ try:
+ with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp_file:
+ temp_file.write(file_bytes)
+ temp_path = temp_file.name
+
+ markitdown = MarkItDown()
+ result = markitdown.convert(temp_path)
+ return result.text_content
+ except Exception as e:
+ logger.error(f"CV conversion failed: {e}")
+ raise e
+ finally:
+ if temp_path and os.path.exists(temp_path):
+ try:
+ os.remove(temp_path)
+ except:
+ pass
+
+ @staticmethod
+ async def analyze_cv(file_bytes: bytes, filename: str):
+ """Full pipeline: Convert to MD -> Extract Metadata via Gemini."""
+ try:
+ markdown_text = await CVParser.parse_to_markdown(file_bytes, filename)
+ if not markdown_text or len(markdown_text.strip()) < 50:
+ return {"error": "Teks CV terlalu pendek atau tidak terbaca."}
+
+ # Use the existing ai_service metadata extractor
+ metadata = await extract_cv_metadata(markdown_text)
+ return {
+ "success": True,
+ "markdown": markdown_text,
+ "metadata": metadata
+ }
+ except Exception as e:
+ logger.error(f"CV analysis pipeline failed: {e}")
+ return {"error": str(e)}
+
+cv_parser = CVParser()
diff --git a/app/utils/security.py b/app/utils/security.py
index ccbbe363a2fe0da96b5c1cd398c926709a12ee75..a634c9c2e19098377d4ee06099bfb7d29fdd84fc 100644
--- a/app/utils/security.py
+++ b/app/utils/security.py
@@ -1,126 +1,161 @@
-"""Security utilities — password hashing, JWT, rate limiting.
-
-Zero-cost: bcrypt, PyJWT, in-memory rate limiter.
-No Redis. No external services. Free for 10K users.
-"""
-
-import hashlib
-import secrets
-import time
-from datetime import datetime, timedelta, timezone
-from typing import Any, Dict, List, Optional
-
-import jwt as pyjwt
-from passlib.context import CryptContext
-
-from app.config.settings import settings
-
-
-# ─── Password Hashing ───────────────────────────────────────────────────────
-
-pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
-
-def hash_password(password: str) -> str:
- return pwd_context.hash(password)
-
-def verify_password(plain: str, hashed: str) -> bool:
- try:
- return pwd_context.verify(plain, hashed)
- except Exception:
- return False # Sentinel values like "GOOGLE_OAUTH" won't crash
-
-def hash_legacy_gas_password(password: str, email: str, salt: str = "BRIGAWAN_AUTH_SALT_2026") -> str:
- """Replicate GAS hashPassword() for backward compatibility."""
- pre_hash = hashlib.sha256((password + email.lower()).encode()).hexdigest()
- return hashlib.sha256((pre_hash + salt).encode()).hexdigest()
-
-
-# ─── JWT ────────────────────────────────────────────────────────────────────
-
-def create_access_token(subject: str, email: str, role: str = "talent",
- expires_delta: Optional[timedelta] = None) -> str:
- now = datetime.now(timezone.utc)
- payload = {
- "sub": subject, "email": email, "role": role,
- "iat": now, "exp": now + (expires_delta or timedelta(hours=settings.jwt_expiry_hours)),
- }
- return pyjwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
-
-def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
- try:
- return pyjwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
- except (pyjwt.ExpiredSignatureError, pyjwt.InvalidTokenError):
- return None
-
-def generate_session_token() -> str:
- return secrets.token_urlsafe(32)
-
-
-# ─── In-Memory Rate Limiter ─────────────────────────────────────────────────
-
-class RateLimiter:
- """Sliding-window in-memory rate limiter.
-
- Max 15K tracked IPs. Oldest entries evicted when limit exceeded.
- Free tier: 100 req/hr. Authenticated: up to 2000 req/hr.
- """
-
- def __init__(self, max_requests: int = 100, window_seconds: int = 3600, max_buckets: int = 15000):
- self.max_requests = max_requests
- self.window_seconds = window_seconds
- self.max_buckets = max_buckets
- self._buckets: Dict[str, list] = {}
- self._prune_counter = 0
- self._prune_threshold = 100
-
- def is_allowed(self, key: str, limit: Optional[int] = None) -> bool:
- """Check if request is allowed under the given (or default) limit.
-
- Args:
- key: The rate-limit bucket key (e.g. client IP).
- limit: Optional per-request limit override. If None, uses self.max_requests.
- """
- now = time.time()
- cutoff = now - self.window_seconds
- effective_limit = limit if limit is not None else self.max_requests
-
- # Evict oldest bucket if over limit
- if len(self._buckets) >= self.max_buckets and key not in self._buckets:
- oldest = min(self._buckets.keys(), key=lambda k: self._buckets[k][-1] if self._buckets[k] else 0)
- del self._buckets[oldest]
-
- if key not in self._buckets:
- self._buckets[key] = []
-
- # Prune expired timestamps
- bucket = [t for t in self._buckets[key] if t > cutoff]
- self._buckets[key] = bucket
-
- if len(bucket) >= effective_limit:
- return False
-
- self._buckets[key].append(now)
-
- self._prune_counter += 1
- if self._prune_counter >= self._prune_threshold:
- self._prune()
- self._prune_counter = 0
-
- return True
-
- def _prune(self):
- now = time.time()
- cutoff = now - self.window_seconds * 2
- stale = [k for k, v in self._buckets.items() if not v or max(v) < cutoff]
- for k in stale:
- del self._buckets[k]
-
- def get_remaining(self, key: str, limit: Optional[int] = None) -> int:
- effective_limit = limit if limit is not None else self.max_requests
- if key not in self._buckets:
- return effective_limit
- bucket = [t for t in self._buckets[key] if t > time.time() - self.window_seconds]
- return max(0, effective_limit - len(bucket))
-
-
-rate_limiter = RateLimiter(max_requests=100, window_seconds=3600)
+"""Security utilities — password hashing, JWT, rate limiting.
+
+Zero-cost: bcrypt, PyJWT, in-memory rate limiter.
+No Redis. No external services. Free for 10K users.
+"""
+
+import hashlib
+import secrets
+import time
+from datetime import datetime, timedelta, timezone
+from typing import Any, Dict, List, Optional
+
+import jwt as pyjwt
+import httpx
+from loguru import logger
+from passlib.context import CryptContext
+
+from app.config.settings import settings
+
+
+# ─── Password Hashing ───────────────────────────────────────────────────────
+
+pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
+
+def hash_password(password: str) -> str:
+ return pwd_context.hash(password)
+
+def verify_password(plain: str, hashed: str) -> bool:
+ try:
+ return pwd_context.verify(plain, hashed)
+ except Exception:
+ return False # Sentinel values like "GOOGLE_OAUTH" won't crash
+
+def hash_legacy_gas_password(password: str, email: str, salt: str = "BRIGAWAN_AUTH_SALT_2026") -> str:
+ """Replicate GAS hashPassword() for backward compatibility."""
+ pre_hash = hashlib.sha256((password + email.lower()).encode()).hexdigest()
+ return hashlib.sha256((pre_hash + salt).encode()).hexdigest()
+
+
+# ─── JWT ────────────────────────────────────────────────────────────────────
+
+def create_access_token(subject: str, email: str, role: str = "talent",
+ expires_delta: Optional[timedelta] = None) -> str:
+ now = datetime.now(timezone.utc)
+ payload = {
+ "sub": subject, "email": email, "role": role,
+ "iat": now, "exp": now + (expires_delta or timedelta(hours=settings.jwt_expiry_hours)),
+ }
+ return pyjwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
+
+def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
+ try:
+ return pyjwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
+ except (pyjwt.ExpiredSignatureError, pyjwt.InvalidTokenError):
+ return None
+
+async def verify_supabase_token(token: str) -> Optional[Dict[str, Any]]:
+ """Verify standard JWT token directly with Supabase Auth server."""
+ if not settings.supabase_url or not settings.supabase_anon_key:
+ logger.warning("Supabase URL or Anon Key is missing from settings")
+ return None
+ try:
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ headers = {
+ "apikey": settings.supabase_anon_key,
+ "Authorization": f"Bearer {token}"
+ }
+ response = await client.get(f"{settings.supabase_url}/auth/v1/user", headers=headers)
+ if response.status_code == 200:
+ data = response.json()
+ email = data.get("email")
+ user_id = data.get("id")
+
+ app_metadata = data.get("app_metadata", {})
+ user_metadata = data.get("user_metadata", {})
+ role = user_metadata.get("role") or app_metadata.get("role") or "talent"
+
+ return {
+ "sub": user_id,
+ "email": email,
+ "role": role,
+ "name": user_metadata.get("full_name") or user_metadata.get("name") or "User"
+ }
+ else:
+ logger.warning(f"Supabase auth check returned status {response.status_code}: {response.text}")
+ except Exception as e:
+ logger.error(f"Failed to verify token with Supabase: {str(e)}")
+ return None
+
+def generate_session_token() -> str:
+ return secrets.token_urlsafe(32)
+
+
+# ─── In-Memory Rate Limiter ─────────────────────────────────────────────────
+
+class RateLimiter:
+ """Sliding-window in-memory rate limiter.
+
+ Max 15K tracked IPs. Oldest entries evicted when limit exceeded.
+ Free tier: 100 req/hr. Authenticated: up to 2000 req/hr.
+ """
+
+ def __init__(self, max_requests: int = 100, window_seconds: int = 3600, max_buckets: int = 15000):
+ self.max_requests = max_requests
+ self.window_seconds = window_seconds
+ self.max_buckets = max_buckets
+ self._buckets: Dict[str, list] = {}
+ self._prune_counter = 0
+ self._prune_threshold = 100
+
+ def is_allowed(self, key: str, limit: Optional[int] = None) -> bool:
+ """Check if request is allowed under the given (or default) limit.
+
+ Args:
+ key: The rate-limit bucket key (e.g. client IP).
+ limit: Optional per-request limit override. If None, uses self.max_requests.
+ """
+ now = time.time()
+ cutoff = now - self.window_seconds
+ effective_limit = limit if limit is not None else self.max_requests
+
+ # Evict oldest bucket if over limit
+ if len(self._buckets) >= self.max_buckets and key not in self._buckets:
+ oldest = min(self._buckets.keys(), key=lambda k: self._buckets[k][-1] if self._buckets[k] else 0)
+ del self._buckets[oldest]
+
+ if key not in self._buckets:
+ self._buckets[key] = []
+
+ # Prune expired timestamps
+ bucket = [t for t in self._buckets[key] if t > cutoff]
+ self._buckets[key] = bucket
+
+ if len(bucket) >= effective_limit:
+ return False
+
+ self._buckets[key].append(now)
+
+ self._prune_counter += 1
+ if self._prune_counter >= self._prune_threshold:
+ self._prune()
+ self._prune_counter = 0
+
+ return True
+
+ def _prune(self):
+ now = time.time()
+ cutoff = now - self.window_seconds * 2
+ stale = [k for k, v in self._buckets.items() if not v or max(v) < cutoff]
+ for k in stale:
+ del self._buckets[k]
+
+ def get_remaining(self, key: str, limit: Optional[int] = None) -> int:
+ effective_limit = limit if limit is not None else self.max_requests
+ if key not in self._buckets:
+ return effective_limit
+ bucket = [t for t in self._buckets[key] if t > time.time() - self.window_seconds]
+ return max(0, effective_limit - len(bucket))
+
+
+rate_limiter = RateLimiter(max_requests=100, window_seconds=3600)
diff --git a/app/utils/wa_guardrail.py b/app/utils/wa_guardrail.py
index 4e60a5f980574004d5e88ca588e61c047b608b9c..c3b9ddf3220e4bb978e189ec02fd705268e7b605 100644
--- a/app/utils/wa_guardrail.py
+++ b/app/utils/wa_guardrail.py
@@ -1,68 +1,68 @@
-"""Security Guardrails for WhatsApp Hub — Briga.id.
-
-Mirrors web-app security standards:
-1. PII Redaction (Privacy protection).
-2. Rate Limiting (Anti-spam/Anti-ban).
-3. Session Hijacking Protection.
-4. Prompt Injection Defense (AI Safety).
-"""
-
-import re
-import time
-from loguru import logger
-from typing import Dict, Any, List
-
-class WhatsAppGuardrail:
- def __init__(self):
- # Rate limiting: Max 5 messages per 30 seconds per user
- self.message_history = {}
- # Sensitive patterns (Indonesian ID, Credit Cards, etc.)
- self.pii_patterns = [
- r'\d{16}', # Credit Card / KTP potential
- r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', # Email
- r'\b(08|628)\d{8,12}\b' # Phone numbers
- ]
-
- def is_rate_limited(self, sender_number: str) -> bool:
- """Checks if a user is spamming the bot."""
- now = time.time()
- if sender_number not in self.message_history:
- self.message_history[sender_number] = []
-
- # Keep only last 30 seconds
- self.message_history[sender_number] = [t for t in self.message_history[sender_number] if now - t < 30]
-
- if len(self.message_history[sender_number]) >= 5:
- logger.warning(f"[Guardrail] Rate limit hit for {sender_number}")
- return True
-
- self.message_history[sender_number].append(now)
- return False
-
- def sanitize_input(self, text: str) -> str:
- """Removes potential prompt injections or malicious scripts."""
- # Simple defense against prompt injection (e.g. 'ignore all previous instructions')
- injection_keywords = ["ignore previous", "system prompt", "developer mode", "override"]
- sanitized = text
- for word in injection_keywords:
- if word in sanitized.lower():
- logger.warning(f"[Guardrail] Possible injection detected: {word}")
- sanitized = sanitized.replace(word, "[REDACTED]")
- return sanitized
-
- def filter_pii_for_ai(self, text: str) -> str:
- """Redacts sensitive information before sending to Gemini AI."""
- redacted = text
- for pattern in self.pii_patterns:
- redacted = re.sub(pattern, "[DATA_SENSITIF]", redacted)
- return redacted
-
- def validate_session(self, sender_number: str, context: Dict[str, Any]) -> bool:
- """Ensures the message is coming from a valid source and matches state."""
- # Check if the number is blacklisted
- blacklist = os.getenv("WA_BLACKLIST", "").split(",")
- if sender_number in blacklist:
- return False
- return True
-
-guardrail = WhatsAppGuardrail()
+"""Security Guardrails for WhatsApp Hub — Briga.id.
+
+Mirrors web-app security standards:
+1. PII Redaction (Privacy protection).
+2. Rate Limiting (Anti-spam/Anti-ban).
+3. Session Hijacking Protection.
+4. Prompt Injection Defense (AI Safety).
+"""
+
+import re
+import time
+from loguru import logger
+from typing import Dict, Any, List
+
+class WhatsAppGuardrail:
+ def __init__(self):
+ # Rate limiting: Max 5 messages per 30 seconds per user
+ self.message_history = {}
+ # Sensitive patterns (Indonesian ID, Credit Cards, etc.)
+ self.pii_patterns = [
+ r'\d{16}', # Credit Card / KTP potential
+ r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', # Email
+ r'\b(08|628)\d{8,12}\b' # Phone numbers
+ ]
+
+ def is_rate_limited(self, sender_number: str) -> bool:
+ """Checks if a user is spamming the bot."""
+ now = time.time()
+ if sender_number not in self.message_history:
+ self.message_history[sender_number] = []
+
+ # Keep only last 30 seconds
+ self.message_history[sender_number] = [t for t in self.message_history[sender_number] if now - t < 30]
+
+ if len(self.message_history[sender_number]) >= 5:
+ logger.warning(f"[Guardrail] Rate limit hit for {sender_number}")
+ return True
+
+ self.message_history[sender_number].append(now)
+ return False
+
+ def sanitize_input(self, text: str) -> str:
+ """Removes potential prompt injections or malicious scripts."""
+ # Simple defense against prompt injection (e.g. 'ignore all previous instructions')
+ injection_keywords = ["ignore previous", "system prompt", "developer mode", "override"]
+ sanitized = text
+ for word in injection_keywords:
+ if word in sanitized.lower():
+ logger.warning(f"[Guardrail] Possible injection detected: {word}")
+ sanitized = sanitized.replace(word, "[REDACTED]")
+ return sanitized
+
+ def filter_pii_for_ai(self, text: str) -> str:
+ """Redacts sensitive information before sending to Gemini AI."""
+ redacted = text
+ for pattern in self.pii_patterns:
+ redacted = re.sub(pattern, "[DATA_SENSITIF]", redacted)
+ return redacted
+
+ def validate_session(self, sender_number: str, context: Dict[str, Any]) -> bool:
+ """Ensures the message is coming from a valid source and matches state."""
+ # Check if the number is blacklisted
+ blacklist = os.getenv("WA_BLACKLIST", "").split(",")
+ if sender_number in blacklist:
+ return False
+ return True
+
+guardrail = WhatsAppGuardrail()