yabeskn commited on
Commit
9d2fd7a
·
1 Parent(s): a3398cd

feat: merge bot handler (Telegram & WhatsApp webhook routers and services) into core API

Browse files
app/api/telegram.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Telegram Webhook API — Executive Command Gateway."""
2
+
3
+ from fastapi import APIRouter, Depends, Request, Header, HTTPException, status
4
+ from sqlalchemy.ext.asyncio import AsyncSession
5
+ from app.database import get_db
6
+ from app.services.telegram_ceo_service import TelegramCEOService
7
+ from app.config.settings import settings
8
+ from typing import Optional
9
+ import httpx
10
+ from loguru import logger
11
+
12
+ router = APIRouter(tags=["Executive Control"])
13
+
14
+ @router.post("/webhook/telegram")
15
+ @router.post("/v1/webhook/telegram")
16
+ async def telegram_webhook(
17
+ request: Request,
18
+ db: AsyncSession = Depends(get_db),
19
+ x_webhook_token: Optional[str] = Header(None)
20
+ ):
21
+ """Receives commands/updates directly from Telegram or API clients."""
22
+ data = await request.json()
23
+
24
+ # Check if this is a standard Telegram payload
25
+ is_telegram_payload = ("message" in data or "callback_query" in data or "edited_message" in data)
26
+
27
+ # Security Check: Only enforce for non-Telegram clients
28
+ if not is_telegram_payload:
29
+ expected_secret = settings.webhook_secret or settings.security_webhook_token
30
+ if expected_secret and x_webhook_token != expected_secret:
31
+ logger.warning("[Telegram Webhook] Unauthorized access attempt.")
32
+ return {"status": "unauthorized"}
33
+
34
+ ceo_service = TelegramCEOService(db)
35
+
36
+ # Process webhook natively via the service
37
+ result = await ceo_service.handle_webhook(data)
38
+ return result
39
+
app/api/whatsapp.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WhatsApp Control API — Link your device and monitor status."""
2
+
3
+ from fastapi import APIRouter, Depends, Request, Header, HTTPException
4
+ from app.services.whatsapp_service import whatsapp_bot
5
+ from app.services.whatsapp.flow_handler import WhatsAppFlowHandler
6
+ from app.utils.wa_guardrail import guardrail
7
+ from app.database import get_db
8
+ from app.config.settings import settings
9
+ from sqlalchemy.ext.asyncio import AsyncSession
10
+ from typing import Dict, Any, Optional
11
+ from loguru import logger
12
+
13
+ router = APIRouter(prefix="/v1/whatsapp", tags=["WhatsApp Hub"])
14
+
15
+ @router.post("/webhook")
16
+ async def whatsapp_webhook(
17
+ request: Request,
18
+ db: AsyncSession = Depends(get_db),
19
+ x_webhook_token: Optional[str] = Header(None)
20
+ ):
21
+ """Receives and processes incoming WhatsApp messages with security."""
22
+ # 1. Security Check
23
+ if settings.webhook_secret and x_webhook_token != settings.webhook_secret:
24
+ logger.warning("[WhatsApp Webhook] Unauthorized access attempt.")
25
+ return {"status": "unauthorized"}
26
+
27
+ try:
28
+ data = await request.json()
29
+ # logger.info(f"[WhatsApp Webhook] Received payload: {data}") # SANITIZED: Removed full payload logging
30
+
31
+ sender = None
32
+ message = ""
33
+ media_info = None
34
+
35
+ # Evolution API Format
36
+ if data.get("event") == "messages.upsert":
37
+ msg_data = data.get("data", {})
38
+ sender = msg_data.get("key", {}).get("remoteJid")
39
+ message_id = msg_data.get("key", {}).get("id")
40
+ instance = data.get("instance")
41
+ msg_content = msg_data.get("message", {})
42
+
43
+ # Text Message
44
+ message = msg_content.get("conversation") or \
45
+ msg_content.get("extendedTextMessage", {}).get("text") or \
46
+ ""
47
+
48
+ # Media/Document Message (CV Upload)
49
+ if "documentMessage" in msg_content:
50
+ doc = msg_content["documentMessage"]
51
+ media_info = {
52
+ "type": "document",
53
+ "mimetype": doc.get("mimetype"),
54
+ "title": doc.get("title") or doc.get("fileName"),
55
+ "url": doc.get("url"),
56
+ "message_id": message_id,
57
+ "instance": instance
58
+ }
59
+ message = f"[Sent a document: {media_info['title']}]"
60
+
61
+ # Simplified Format
62
+ else:
63
+ sender = data.get("sender")
64
+ message = data.get("message", "")
65
+
66
+ if not sender:
67
+ return {"status": "ignored", "reason": "No sender found"}
68
+
69
+ # 2. Rate Limiting
70
+ if guardrail.is_rate_limited(sender):
71
+ return {"status": "error", "message": "Too many requests"}
72
+
73
+ # 3. Input Sanitization & Privacy (Skip for media info if needed, but safe for text)
74
+ clean_message = guardrail.sanitize_input(message)
75
+ safe_message = guardrail.filter_pii_for_ai(clean_message)
76
+
77
+ # 4. Process Flow
78
+ flow_handler = WhatsAppFlowHandler(db)
79
+ # We pass media_info to handle_message
80
+ await flow_handler.handle_message(sender, safe_message, media_info=media_info)
81
+
82
+ return {"status": "success"}
83
+ except Exception as e:
84
+ logger.error(f"[WhatsApp Webhook] Error: {e}")
85
+ return {"status": "error", "detail": str(e)}
86
+
87
+ @router.get("/status")
88
+ async def get_whatsapp_status():
89
+ """Checks the connection status of the WhatsApp bot."""
90
+ return await whatsapp_bot.get_status()
91
+
92
+ @router.get("/qr")
93
+ async def get_whatsapp_qr():
94
+ """Returns a base64 QR code for scanning."""
95
+ qr_base64 = await whatsapp_bot.get_qr_base64()
96
+ if qr_base64:
97
+ return {"status": "success", "qr": qr_base64}
98
+ return {"status": "error", "message": "Failed to generate QR or instance busy."}
99
+
100
+ @router.post("/logout")
101
+ async def logout_whatsapp():
102
+ """Logs out the current WhatsApp session."""
103
+ success = await whatsapp_bot.logout_instance()
104
+ if success:
105
+ return {"status": "success", "message": "Logged out successfully."}
106
+ return {"status": "error", "message": "Logout failed."}
app/main.py CHANGED
@@ -85,6 +85,8 @@ from app.api.academy import router as academy_router
85
  from app.api.admin import router as admin_router
86
  from app.api.legacy_compat import router as legacy_compat_router
87
  from app.api.debug_admin import router as debug_admin_router
 
 
88
  from app.middleware.ab_assign import ABAssignMiddleware
89
 
90
  app.add_middleware(ABAssignMiddleware)
@@ -101,3 +103,5 @@ app.include_router(academy_router)
101
  app.include_router(admin_router)
102
  app.include_router(legacy_compat_router)
103
  app.include_router(debug_admin_router)
 
 
 
85
  from app.api.admin import router as admin_router
86
  from app.api.legacy_compat import router as legacy_compat_router
87
  from app.api.debug_admin import router as debug_admin_router
88
+ from app.api.telegram import router as telegram_router
89
+ from app.api.whatsapp import router as whatsapp_router
90
  from app.middleware.ab_assign import ABAssignMiddleware
91
 
92
  app.add_middleware(ABAssignMiddleware)
 
103
  app.include_router(admin_router)
104
  app.include_router(legacy_compat_router)
105
  app.include_router(debug_admin_router)
106
+ app.include_router(telegram_router)
107
+ app.include_router(whatsapp_router)
app/services/telegram_ceo_service.py ADDED
@@ -0,0 +1,1688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Telegram CEO Service — Direct Founder Line to AI CEO and Payment Verification Bot."""
2
+
3
+ import os
4
+ import json
5
+ import httpx
6
+ import base64
7
+ import re
8
+ import asyncio
9
+ from datetime import datetime, timedelta, timezone
10
+ from typing import Optional, Dict, Any
11
+ from loguru import logger
12
+ from zoneinfo import ZoneInfo
13
+
14
+ from sqlalchemy import select, update, func, cast, String, or_, text
15
+ from sqlalchemy.ext.asyncio import AsyncSession
16
+
17
+ from app.config.settings import settings
18
+ from app.services.antigravity import AntigravityOrchestrator
19
+ from app.services.linkedin_service import LinkedInPoster
20
+ from app.services import ai_service
21
+ from app.services.email_service import email_service
22
+ from app.services.google_workspace_service import spark_agent
23
+
24
+ # Models
25
+ from app.models.job import JobPosting, RecruiterOutreach
26
+ from app.models.finance import Transaction
27
+ from app.models.talent import Talent
28
+ from app.models.content import KnowledgeQueue
29
+ from app.models.system import ActivityLog, SecurityAuditLog, PrivacyAuditLog, TelegramSession
30
+
31
+
32
+ class TelegramCEOService:
33
+ def __init__(self, db: AsyncSession):
34
+ self.db = db
35
+ self.token = settings.telegram_bot_token or os.getenv("TELEGRAM_BOT_TOKEN")
36
+ self.admin_chat_id = settings.telegram_admin_chat_id or os.getenv("TELEGRAM_ADMIN_CHAT_ID")
37
+
38
+ # Proxy routing: HF Spaces blocks direct egress to api.telegram.org.
39
+ # Support two modes:
40
+ # 1. Transparent Proxy (Cloudflare): proxy_url + "/method"
41
+ # 2. RPC Proxy (Google Apps Script): proxy_url with action="proxyTelegram"
42
+ self._proxy_url = (settings.telegram_proxy_url or os.getenv("TELEGRAM_PROXY_URL", "")).rstrip("/")
43
+ self._proxy_secret = settings.telegram_proxy_secret or os.getenv("TELEGRAM_PROXY_SECRET", "")
44
+ self._use_proxy = bool(self._proxy_url and self._proxy_secret)
45
+ self._is_gas_proxy = "script.google.com" in self._proxy_url
46
+
47
+ 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}"
48
+ self.api_url = self.base_url # Compatibility alias
49
+ self.orchestrator = AntigravityOrchestrator(db)
50
+ self.tz = ZoneInfo("Asia/Jakarta")
51
+
52
+ def _proxy_headers(self) -> dict:
53
+ """Returns auth headers required when using the CF proxy."""
54
+ if self._use_proxy and not self._is_gas_proxy:
55
+ return {"X-Proxy-Secret": self._proxy_secret, "Content-Type": "application/json"}
56
+ return {"Content-Type": "application/json"}
57
+
58
+ async def get_telegram_session(self, chat_id: str) -> Optional[dict]:
59
+ """Fetch active session from database, checking TTL of 30 minutes."""
60
+ try:
61
+ stmt = select(TelegramSession).where(TelegramSession.chat_id == chat_id)
62
+ res = await self.db.execute(stmt)
63
+ session = res.scalar_one_or_none()
64
+ if session and session.last_context:
65
+ ctx = session.last_context
66
+ ts_str = ctx.get("timestamp")
67
+ if ts_str:
68
+ ts = datetime.fromisoformat(ts_str)
69
+ if (datetime.now(timezone.utc) - ts).total_seconds() < 1800:
70
+ return ctx
71
+ except Exception as e:
72
+ logger.error(f"Error fetching Telegram session: {e}")
73
+ return None
74
+
75
+ async def save_telegram_session(self, chat_id: str, tx_id: str, state: Optional[str] = None):
76
+ """Save/update verification session in database."""
77
+ try:
78
+ stmt = select(TelegramSession).where(TelegramSession.chat_id == chat_id)
79
+ res = await self.db.execute(stmt)
80
+ session = res.scalar_one_or_none()
81
+ ctx = {
82
+ "tx_id": tx_id,
83
+ "timestamp": datetime.now(timezone.utc).isoformat()
84
+ }
85
+ if session:
86
+ session.last_context = ctx
87
+ if state:
88
+ session.state = state
89
+ session.updated_at = datetime.now(timezone.utc)
90
+ else:
91
+ session = TelegramSession(
92
+ chat_id=chat_id,
93
+ state=state,
94
+ last_context=ctx,
95
+ created_at=datetime.now(timezone.utc),
96
+ updated_at=datetime.now(timezone.utc)
97
+ )
98
+ self.db.add(session)
99
+ await self.db.commit()
100
+ logger.info(f"Telegram session saved for chat {chat_id}, tx_id {tx_id}")
101
+ except Exception as e:
102
+ logger.error(f"Error saving Telegram session: {e}")
103
+
104
+ async def delete_telegram_session(self, chat_id: str):
105
+ """Clear active session from database."""
106
+ try:
107
+ stmt = select(TelegramSession).where(TelegramSession.chat_id == chat_id)
108
+ res = await self.db.execute(stmt)
109
+ session = res.scalar_one_or_none()
110
+ if session:
111
+ session.last_context = None
112
+ session.state = None
113
+ session.updated_at = datetime.now(timezone.utc)
114
+ await self.db.commit()
115
+ logger.info(f"Telegram session cleared for chat {chat_id}")
116
+ except Exception as e:
117
+ logger.error(f"Error clearing Telegram session: {e}")
118
+
119
+ async def log_privacy_audit(self, query: str, user_email: str, risk_score: int = 10):
120
+ """Log privacy sensitive actions to privacy_audit_log table."""
121
+ try:
122
+ # Simple automatic risk score adjustment based on PII triggers
123
+ kw_lower = query.lower()
124
+ if any(kw in kw_lower for kw in ["cv", "ktp", "nik", "telepon", "phone", "email", "nama", "name"]):
125
+ risk_score = 30 # Medium risk if querying PII keywords
126
+
127
+ audit = PrivacyAuditLog(
128
+ query=query,
129
+ user_email=user_email,
130
+ risk_score=risk_score,
131
+ timestamp=datetime.now(timezone.utc)
132
+ )
133
+ self.db.add(audit)
134
+ await self.db.commit()
135
+ logger.info(f"Privacy audit logged: {query} by {user_email}")
136
+ except Exception as e:
137
+ logger.error(f"Failed to log privacy audit: {e}")
138
+
139
+ async def log_security_audit(self, action: str, details: str, status: str = "success"):
140
+ """Log security critical events to security_audit_log table."""
141
+ try:
142
+ audit = SecurityAuditLog(
143
+ page_type="Telegram_Bot",
144
+ target_url=f"Telegram_Command/{action}",
145
+ status=status,
146
+ details=details,
147
+ timestamp=datetime.now(timezone.utc)
148
+ )
149
+ self.db.add(audit)
150
+ await self.db.commit()
151
+ logger.info(f"Security audit logged: {action} - {status}")
152
+ except Exception as e:
153
+ logger.error(f"Failed to log security audit: {e}")
154
+
155
+ async def log_activity(self, actor: str, action: str, metadata: str = "-"):
156
+ """Log administrative activities to activity_logs table."""
157
+ try:
158
+ log = ActivityLog(
159
+ actor=actor,
160
+ action=action,
161
+ log_metadata=metadata,
162
+ timestamp=datetime.now(timezone.utc)
163
+ )
164
+ self.db.add(log)
165
+ await self.db.commit()
166
+ logger.info(f"Activity log registered: {action} by {actor}")
167
+ except Exception as e:
168
+ logger.error(f"Failed to register activity log: {e}")
169
+
170
+ async def send_executive_alert(self, message: str, urgent: bool = False):
171
+
172
+ """Sends a proactive alert to the Founder."""
173
+ if not self.token or not self.admin_chat_id:
174
+ logger.warning("Telegram credentials missing, skipping executive alert.")
175
+ return False
176
+
177
+ prefix = "🚨 *URGENT CEO ALERT*" if urgent else "ℹ️ *AI CEO UPDATE*"
178
+ text = f"{prefix}\n\n{message}"
179
+
180
+ return await self.send_message(self.admin_chat_id, text)
181
+
182
+ async def send_message(self, chat_id: Any, text: str, parse_mode: str = "Markdown", reply_markup: Optional[dict] = None) -> bool:
183
+ """Sends a generic text message to a specified chat."""
184
+ if not self.token:
185
+ logger.warning("Telegram token missing, cannot send message.")
186
+ return False
187
+
188
+ payload = {
189
+ "chat_id": chat_id,
190
+ "text": text,
191
+ "parse_mode": parse_mode
192
+ }
193
+ if reply_markup:
194
+ payload["reply_markup"] = reply_markup
195
+
196
+ if self._use_proxy and self._is_gas_proxy:
197
+ # RPC Proxy Mode (GAS)
198
+ target_url = self._proxy_url
199
+ rpc_payload = {
200
+ "action": "proxyTelegram",
201
+ "params": ["sendMessage", payload, self._proxy_secret]
202
+ }
203
+ async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
204
+ try:
205
+ response = await client.post(target_url, json=rpc_payload)
206
+ if response.status_code == 200:
207
+ res_json = response.json()
208
+ if res_json.get("success"):
209
+ return True
210
+ logger.warning(f"GAS Telegram Proxy returned failure: {res_json}")
211
+ else:
212
+ logger.warning(f"GAS Telegram Proxy HTTP {response.status_code}: {response.text[:200]}")
213
+ return False
214
+ except Exception as e:
215
+ logger.error(f"Error calling GAS Telegram proxy: {e}")
216
+ return False
217
+
218
+ # Default or Transparent Proxy Mode
219
+ url = f"{self.base_url}/sendMessage"
220
+ async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:
221
+ try:
222
+ response = await client.post(url, json=payload, headers=self._proxy_headers())
223
+ if response.status_code != 200:
224
+ logger.warning(f"Telegram sendMessage returned {response.status_code}: {response.text[:200]}")
225
+ return response.status_code == 200
226
+ except Exception as e:
227
+ logger.error(f"Error sending Telegram message: {e}")
228
+ return False
229
+
230
+ async def answer_callback_query(self, callback_query_id: str, text: str):
231
+ if not self.token: return
232
+ url = f"{self.base_url}/answerCallbackQuery"
233
+ payload = {
234
+ "callback_query_id": callback_query_id,
235
+ "text": text
236
+ }
237
+ async with httpx.AsyncClient(timeout=15.0) as client:
238
+ try:
239
+ await client.post(url, json=payload, headers=self._proxy_headers())
240
+ except Exception as e:
241
+ logger.error(f"Error answering callback query: {e}")
242
+
243
+ async def edit_message_text(self, chat_id: Any, message_id: int, new_text: str):
244
+ if not self.token: return
245
+ url = f"{self.base_url}/editMessageText"
246
+ payload = {
247
+ "chat_id": chat_id,
248
+ "message_id": message_id,
249
+ "text": new_text,
250
+ "parse_mode": "Markdown"
251
+ }
252
+ async with httpx.AsyncClient(timeout=15.0) as client:
253
+ try:
254
+ await client.post(url, json=payload, headers=self._proxy_headers())
255
+ except Exception as e:
256
+ logger.error(f"Error editing message: {e}")
257
+
258
+ async def download_file(self, file_id: str) -> bytes:
259
+ """Downloads a file from Telegram using its file_id."""
260
+ if not self.token:
261
+ raise Exception("Telegram token missing")
262
+ # Step 1: getFile API call (via proxy if enabled)
263
+ get_file_url = f"{self.base_url}/getFile"
264
+ async with httpx.AsyncClient(timeout=20.0) as client:
265
+ resp = await client.post(get_file_url, json={"file_id": file_id}, headers=self._proxy_headers())
266
+ if resp.status_code == 200:
267
+ file_path = resp.json().get("result", {}).get("file_path")
268
+ if file_path:
269
+ # Step 2: Download actual file bytes
270
+ if self._use_proxy:
271
+ # Route file download through CF proxy: /api/telegram-proxy/file/{path}
272
+ download_url = f"{self._proxy_url}/file/{file_path}"
273
+ file_resp = await client.get(download_url, headers=self._proxy_headers())
274
+ else:
275
+ download_url = f"https://api.telegram.org/file/bot{self.token}/{file_path}"
276
+ file_resp = await client.get(download_url)
277
+ if file_resp.status_code == 200:
278
+ return file_resp.content
279
+ raise Exception("Gagal mengunduh file dari Telegram")
280
+
281
+ async def run_vision_ocr(self, photo_bytes: bytes) -> dict:
282
+ """Sends photo bytes to Gemini Vision to extract payment receipt details."""
283
+ from app.services.ai_service import RAW_KEYS
284
+ api_key = RAW_KEYS[0] if (RAW_KEYS and RAW_KEYS[0]) else settings.gemini_api_key
285
+ if not api_key:
286
+ return {"error": "GEMINI_API_KEY not configured"}
287
+
288
+ encoded_image = base64.b64encode(photo_bytes).decode("utf-8")
289
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={api_key}"
290
+
291
+ prompt = (
292
+ "Analyze this receipt image. Extract: 1. Nominal / total amount transferred (integer, e.g. 450000 or 1200000. Ignore cent digits if it's 450000.00), "
293
+ "2. Sender Bank Name (e.g. BCA, Mandiri, BNI, etc.), "
294
+ "3. Date and time of transfer. "
295
+ "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)."
296
+ )
297
+
298
+ payload = {
299
+ "contents": [
300
+ {
301
+ "parts": [
302
+ {"text": prompt},
303
+ {
304
+ "inlineData": {
305
+ "mimeType": "image/jpeg",
306
+ "data": encoded_image
307
+ }
308
+ }
309
+ ]
310
+ }
311
+ ],
312
+ "generationConfig": {
313
+ "responseMimeType": "application/json"
314
+ }
315
+ }
316
+
317
+ async with httpx.AsyncClient(timeout=30.0) as client:
318
+ try:
319
+ resp = await client.post(url, json=payload)
320
+ if resp.status_code == 200:
321
+ data = resp.json()
322
+ text = data["candidates"][0]["content"]["parts"][0]["text"].strip()
323
+ if text.startswith("```"):
324
+ text = re.sub(r"^```[a-z]*\n|```$", "", text).strip()
325
+ parsed = json.loads(text)
326
+ return parsed
327
+ else:
328
+ logger.error(f"Gemini Vision API error: {resp.status_code} - {resp.text}")
329
+ return {"error": f"Gemini Vision API error: {resp.status_code}"}
330
+ except Exception as e:
331
+ logger.error(f"Gemini Vision call failed: {e}")
332
+ return {"error": f"Gemini Vision call failed: {e}"}
333
+
334
+ async def get_system_health_stats(self) -> dict:
335
+ """Helper to calculate real-time platform statistics directly from DB."""
336
+ yesterday = datetime.now(timezone.utc) - timedelta(days=1)
337
+
338
+ total_jobs = (await self.db.execute(select(func.count(JobPosting.id)))).scalar() or 0
339
+ pending_jobs = (await self.db.execute(select(func.count(JobPosting.id)).where(cast(JobPosting.status, String).in_(["scraped", "analyzed", "draft"])))).scalar() or 0
340
+ new_jobs = (await self.db.execute(select(func.count(JobPosting.id)).where(JobPosting.timestamp >= yesterday))).scalar() or 0
341
+
342
+ total_outreach = (await self.db.execute(select(func.count(RecruiterOutreach.id)))).scalar() or 0
343
+ stale_outreach = (await self.db.execute(select(func.count(RecruiterOutreach.id)).where(cast(RecruiterOutreach.status, String) == "pending_approval"))).scalar() or 0
344
+ 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
345
+
346
+ total_talents = (await self.db.execute(select(func.count(Talent.id)))).scalar() or 0
347
+ total_transactions = (await self.db.execute(select(func.count(Transaction.id)))).scalar() or 0
348
+ total_revenue = (await self.db.execute(select(func.sum(Transaction.amount)).where(cast(Transaction.status, String) == "Settled"))).scalar() or 0
349
+
350
+ return {
351
+ "total_jobs": total_jobs,
352
+ "pending_jobs": pending_jobs,
353
+ "new_jobs_today": new_jobs,
354
+ "total_outreach": total_outreach,
355
+ "stale_outreach": stale_outreach,
356
+ "sent_outreach_today": sent_outreach_today,
357
+ "total_talents": total_talents,
358
+ "total_transactions": total_transactions,
359
+ "total_revenue": float(total_revenue or 0)
360
+ }
361
+
362
+ async def generate_daily_briefing(self) -> str:
363
+ """Generate and send comprehensive daily briefing to Telegram admin."""
364
+ stats = await self.get_system_health_stats()
365
+
366
+ summary = (
367
+ f"📊 *BRIGAWAN CEO BRIEFING* — {datetime.now(self.tz).strftime('%Y-%m-%d %H:%M')}\n\n"
368
+ f"📌 *Ringkasan 24 Jam Terakhir*\n"
369
+ f"━━━━━━━━━━━━━━━━━━\n"
370
+ f"• *Jobs Baru:* {stats['new_jobs_today']} lowongan\n"
371
+ f"• *Outreach Pending:* {stats['stale_outreach']} rekomendasi\n"
372
+ f"• *Outreach Terkirim:* {stats['sent_outreach_today']} email\n"
373
+ f"• *Total Talent:* {stats['total_talents']} terdaftar\n\n"
374
+ )
375
+
376
+ prompt = f"""Kamu adalah CEO Agent dari platform Brigawan — platform karir hijau Indonesia.
377
+
378
+ DATA OPERASIONAL 24 JAM TERAKHIR:
379
+ - Jobs baru di-scrape: {stats['new_jobs_today']} (total database: {stats['total_jobs']})
380
+ - Outreach pending approval: {stats['stale_outreach']}
381
+ - Outreach terkirim hari ini: {stats['sent_outreach_today']}
382
+ - Total talent di database: {stats['total_talents']}
383
+
384
+ TUGAS:
385
+ 1. Analisis singkat: apakah performa platform sehat?
386
+ 2. Berikan 2-3 rekomendasi strategis untuk hari ini
387
+ 3. Jika ada anomali (semua metrik 0, atau lonjakan), highlight
388
+
389
+ Format jawaban dalam JSON:
390
+ {{
391
+ "health_status": "healthy|needs_attention|critical",
392
+ "analysis": "1-2 kalimat analisis",
393
+ "recommendations": ["rekomendasi 1", "rekomendasi 2"],
394
+ "anomalies": ["anomali jika ada"],
395
+ "priority_action": "satu tindakan prioritas hari ini"
396
+ }}"""
397
+
398
+ analysis, _ = await ai_service.call_gemini_json(prompt, temperature=0.2)
399
+
400
+ if "error" not in analysis:
401
+ health_emoji = {"healthy": "✅", "needs_attention": "⚠️", "critical": "🚨"}
402
+ health = analysis.get("health_status", "healthy")
403
+ emoji = health_emoji.get(health, "✅")
404
+
405
+ summary += (
406
+ f"🤖 *CEO Analysis:* {emoji} *{health.upper()}*\n"
407
+ f"➡️ {analysis.get('analysis', '')}\n\n"
408
+ f"🎯 *Rekomendasi Hari Ini:*\n"
409
+ )
410
+ for rec in analysis.get("recommendations", []):
411
+ summary += f" • {rec}\n"
412
+
413
+ anomalies = analysis.get("anomalies", [])
414
+ if anomalies:
415
+ summary += f"\n🚩 *Anomali Terdeteksi:*\n"
416
+ for a in anomalies:
417
+ summary += f" • ⚠️ {a}\n"
418
+
419
+ priority = analysis.get("priority_action", "")
420
+ if priority:
421
+ summary += f"\n🔥 *Prioritas:* {priority}\n"
422
+
423
+ await self.send_message(self.admin_chat_id, summary)
424
+ return summary
425
+
426
+ async def check_system_health(self):
427
+ """Check all Brigawan subsystems and report to admin."""
428
+ stats = await self.get_system_health_stats()
429
+
430
+ issues = []
431
+ if stats["pending_jobs"] > 5:
432
+ issues.append(f"{stats['pending_jobs']} jobs menunggu approval admin")
433
+ if stats["stale_outreach"] > 10:
434
+ issues.append(f"{stats['stale_outreach']} outreach pending > 24 jam")
435
+ if stats["total_talents"] == 0:
436
+ issues.append("Database talent kosong")
437
+
438
+ status = "healthy" if not issues else "needs_attention" if len(issues) <= 2 else "critical"
439
+
440
+ emoji = "✅" if status == "healthy" else "⚠️" if status == "needs_attention" else "🚨"
441
+ msg = (
442
+ f"🩹 *CEO SYSTEM HEALTH CHECK*\n\n"
443
+ f"📊 *Status:* {emoji} {status.upper()}\n\n"
444
+ f"*Issues:*\n"
445
+ )
446
+ if issues:
447
+ for iss in issues:
448
+ msg += f" • ❌ {iss}\n"
449
+ else:
450
+ msg += " • ✅ Tidak ada isu operasional kritis terdeteksi.\n"
451
+
452
+ rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
453
+ msg += f"\n🤖 Total Jobs: {stats['total_jobs']} | Outreach: {stats['total_outreach']} | Talent: {stats['total_talents']} | Revenue: {rev_formatted}"
454
+
455
+ await self.send_message(self.admin_chat_id, msg)
456
+ return stats
457
+
458
+ async def delegate_task_to_queue(self, action: str, params: dict):
459
+ """Insert task into knowledge_queue in PostgreSQL."""
460
+ try:
461
+ task = KnowledgeQueue(
462
+ category="AGENT_TASK",
463
+ fact=json.dumps({"action": action, "params": params}),
464
+ status="Pending",
465
+ source_email="ceo-agent@briga.id"
466
+ )
467
+ self.db.add(task)
468
+ await self.db.commit()
469
+ logger.info(f"CEO Delegated {action} to knowledge_queue.")
470
+ except Exception as e:
471
+ logger.error(f"Failed to delegate task to knowledge_queue: {e}")
472
+
473
+ async def process_semantic_instruction(self, text: str):
474
+ """Parse natural language from admin and delegate tasks (Two-Stage Query System)."""
475
+ stats = await self.get_system_health_stats()
476
+ rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
477
+
478
+ # --- STAGE 1: INTENT & PARAMETER EXTRACTION ---
479
+ 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.
480
+
481
+ Pesan Founder: "{text}"
482
+
483
+ Tentukan aksi database (db_lookup) apa yang dibutuhkan.
484
+ Pilihan `db_lookup_type`:
485
+ - "talent_search": Jika Founder mencari talenta/kandidat dengan kriteria/keahlian/lokasi tertentu. (Contoh: "cari ahli solar panel di Bandung")
486
+ - "pending_jobs": Jika Founder menanyakan tentang lowongan yang butuh persetujuan atau baru masuk. (Contoh: "apa ada lowongan baru?")
487
+ - "pending_outreach": Jika Founder menanyakan tentang outreach yang pending atau rekomendasi email.
488
+ - "finance": Jika Founder menanyakan tentang keuangan, pendapatan, transaksi.
489
+ - "job_detail": Jika Founder menanyakan rincian dari suatu lowongan tertentu (sertakan parameter `job_id`).
490
+ - "none": Jika pesan hanya berupa obrolan santai, diskusi ide bisnis, atau tidak membutuhkan query database khusus.
491
+
492
+ Tentukan juga jika ada perintah operasional untuk dijalankan (delegated_task):
493
+ - action: "bulk_sourcing", "nurture_dormant", "run_scrape_cycle", "run_outreach_sweep", "run_outreach_for_job" (sertakan job_id di params), atau "none".
494
+
495
+ FORMAT OUTPUT JSON:
496
+ {{
497
+ "db_lookup": {{
498
+ "type": "talent_search|pending_jobs|pending_outreach|finance|job_detail|none",
499
+ "params": {{
500
+ "keyword": "kata kunci pencarian talenta jika ada",
501
+ "job_id": "job id jika ada"
502
+ }}
503
+ }},
504
+ "delegated_task": {{
505
+ "action": "action_name_or_none",
506
+ "params": {{}}
507
+ }}
508
+ }}"""
509
+
510
+ analysis, _ = await ai_service.call_gemini_json(stage1_prompt, temperature=0.2)
511
+
512
+ if "error" in analysis:
513
+ await self.send_message(self.admin_chat_id, f"❌ Gagal menganalisis instruksi: {analysis['error']}")
514
+ return
515
+
516
+ db_lookup = analysis.get("db_lookup", {})
517
+ db_type = db_lookup.get("type", "none")
518
+ db_params = db_lookup.get("params", {})
519
+
520
+ retrieved_data_str = ""
521
+
522
+ # --- DATABASE QUERY EXECUTION ---
523
+ try:
524
+ if db_type == "talent_search":
525
+ kw = db_params.get("keyword", "")
526
+ if kw:
527
+ kw_wildcard = f"%{kw}%"
528
+ stmt = select(Talent).where(
529
+ or_(
530
+ Talent.name.ilike(kw_wildcard),
531
+ Talent.skill_tags.ilike(kw_wildcard),
532
+ Talent.experience.ilike(kw_wildcard),
533
+ Talent.location.ilike(kw_wildcard),
534
+ Talent.category.ilike(kw_wildcard)
535
+ )
536
+ ).limit(5)
537
+ res = await self.db.execute(stmt)
538
+ talents = res.scalars().all()
539
+
540
+ if talents:
541
+ retrieved_data_str = "Hasil Pencarian Talenta:\n"
542
+ for t in talents:
543
+ 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"
544
+ else:
545
+ retrieved_data_str = f"Tidak ditemukan talenta dengan kata kunci '{kw}'."
546
+ else:
547
+ retrieved_data_str = "Kata kunci pencarian talenta tidak disediakan."
548
+
549
+ elif db_type == "pending_jobs":
550
+ stmt = select(JobPosting).where(cast(JobPosting.status, String).in_(["scraped", "analyzed", "draft"])).order_by(JobPosting.timestamp.asc()).limit(5)
551
+ res = await self.db.execute(stmt)
552
+ jobs = res.scalars().all()
553
+ if jobs:
554
+ retrieved_data_str = "Daftar Lowongan Pekerjaan Pending (Menunggu Approval):\n"
555
+ for j in jobs:
556
+ 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"
557
+ else:
558
+ retrieved_data_str = "Tidak ada lowongan pekerjaan yang pending."
559
+
560
+ elif db_type == "pending_outreach":
561
+ stmt = select(RecruiterOutreach).where(cast(RecruiterOutreach.status, String) == "pending_approval").order_by(RecruiterOutreach.triggered_at.asc()).limit(5)
562
+ res = await self.db.execute(stmt)
563
+ outreaches = res.scalars().all()
564
+ if outreaches:
565
+ retrieved_data_str = "Daftar Outreach Pending (Menunggu Approval):\n"
566
+ for o in outreaches:
567
+ retrieved_data_str += f"- ID: {o.outreach_id}, Talent: {o.talent_email}, Recruiter: {o.recruiter_email}, Match Score: {o.match_score}%\n"
568
+ else:
569
+ retrieved_data_str = "Tidak ada email outreach yang pending."
570
+
571
+ elif db_type == "finance":
572
+ stmt = select(Transaction).order_by(Transaction.created_at.desc()).limit(5)
573
+ res = await self.db.execute(stmt)
574
+ txs = res.scalars().all()
575
+ retrieved_data_str = f"Laporan Keuangan Singkat:\n- Total Pendapatan Settled: {rev_formatted}\n- Total Transaksi: {stats['total_transactions']}\n"
576
+ if txs:
577
+ retrieved_data_str += "5 Transaksi Terakhir:\n"
578
+ for t in txs:
579
+ retrieved_data_str += f" - ID: {t.id}, Client: {t.client_id}, Amount: Rp {int(t.amount):,}, Status: {t.status}, Date: {t.created_at}\n"
580
+ else:
581
+ retrieved_data_str += "Tidak ada riwayat transaksi."
582
+ retrieved_data_str = retrieved_data_str.replace(",", ".")
583
+
584
+ elif db_type == "job_detail":
585
+ jid = db_params.get("job_id", "")
586
+ if jid:
587
+ stmt = select(JobPosting).where(JobPosting.job_id == jid)
588
+ res = await self.db.execute(stmt)
589
+ job = res.scalar_one_or_none()
590
+ if job:
591
+ retrieved_data_str = (
592
+ f"Detail Lowongan Pekerjaan:\n"
593
+ f"- ID: {job.job_id}\n"
594
+ f"- Title: {job.title}\n"
595
+ f"- Company: {job.company_name}\n"
596
+ f"- Location: {job.location}\n"
597
+ f"- Sektor: {job.company_category}\n"
598
+ f"- Required Skills: {job.required_skills}\n"
599
+ f"- Description: {job.description[:500] if job.description else ''}\n"
600
+ f"- Status: {job.status}\n"
601
+ )
602
+ else:
603
+ retrieved_data_str = f"Pekerjaan dengan ID '{jid}' tidak ditemukan."
604
+ else:
605
+ retrieved_data_str = "Job ID tidak disediakan untuk pencarian rincian lowongan."
606
+ else:
607
+ retrieved_data_str = "Tidak ada pencarian database khusus yang diperlukan."
608
+ except Exception as q_err:
609
+ logger.error(f"Error executing semantic database query: {q_err}")
610
+ retrieved_data_str = f"Gagal mengambil data dari database karena kesalahan teknis: {q_err}"
611
+
612
+ # --- STAGE 2: RESPONSE SYNTHESIS ---
613
+ synthesis_prompt = f"""Kamu adalah CEO Agent Brigawan, rekan diskusi strategis bagi Founder.
614
+ Founder menanyakan: "{text}"
615
+
616
+ BERKAS/DATA TERBARU DARI DATABASE:
617
+ {retrieved_data_str}
618
+
619
+ STATISTIK UMUM PLATFORM:
620
+ - Total Jobs: {stats['total_jobs']}
621
+ - Total Talent: {stats['total_talents']}
622
+ - Outreach Pending: {stats['stale_outreach']}
623
+ - Total Transaksi B2B: {stats['total_transactions']}
624
+ - Total Pendapatan Settled: {rev_formatted}
625
+
626
+ TUGASMU:
627
+ 1. Berikan tanggapan/jawaban yang sangat solutif, berbasis data (data-driven), dan relevan dalam Bahasa Indonesia yang elegan.
628
+ 2. Jika data yang dicari Founder ada di atas, jabarkan dengan rapi dan berikan rekomendasi tindakan berikutnya.
629
+ 3. Jika data tidak ditemukan, katakan dengan sopan dan berikan saran pencarian yang lebih baik.
630
+ 4. Gunakan gaya penulisan profesional namun suportif seorang partner bisnis terpercaya (C-Level).
631
+ 5. Jangan menyebutkan detail teknis SQL atau internal database, fokuslah pada nilai bisnis dan operasional.
632
+
633
+ Jawab langsung berupa teks pesan Telegram (mendukung format Markdown)."""
634
+
635
+ response_text, _ = await ai_service.call_medium(synthesis_prompt)
636
+
637
+ if not response_text:
638
+ response_text = "Maaf, saya gagal mensintesis tanggapan strategis."
639
+
640
+ # Send response to founder
641
+ await self.send_message(self.admin_chat_id, response_text)
642
+
643
+ # --- TASK DELEGATION HANDLER ---
644
+ task = analysis.get("delegated_task", {})
645
+ if task.get("action") and task.get("action") != "none":
646
+ await self.delegate_task_to_queue(task["action"], task.get("params", {}))
647
+
648
+ async def handle_ceo_command(self, text: str, chat_id: Any) -> str:
649
+ """Processes incoming executive commands (slash commands) from Telegram."""
650
+ cmd = text.split(" ")[0].lower()
651
+
652
+ if cmd in ["/menu", "/help"]:
653
+ menu_text = (
654
+ f"⚡ *BRIGAWAN CEO COMMAND CENTER* ⚡\n\n"
655
+ f"Selamat datang, Founder. Silakan gunakan menu tombol cepat di bawah ini untuk berinteraksi dengan sistem, "
656
+ f"atau ketik instruksi Anda dalam bahasa natural.\n\n"
657
+ f"*Daftar Perintah Manual:*\n"
658
+ f"• `/menu` atau `/help` - Menampilkan menu ini\n"
659
+ f"• `/status` - Menampilkan status kesehatan sistem secara ringkas\n"
660
+ f"• `/search_talent <kata kunci>` - Mencari talent berdasarkan skill/lokasi (Contoh: `/search_talent AMDAL`)\n"
661
+ f"• `/job_detail <job_id>` - Menampilkan rincian lowongan (Contoh: `/job_detail JB-001`)\n"
662
+ f"• `/pending_jobs` - Menampilkan lowongan yang menunggu persetujuan\n"
663
+ f"• `/pending_outreach` - Menampilkan email outreach yang menunggu persetujuan\n"
664
+ f"• `/match_job <job_id>` - Memicu pencocokan kandidat untuk lowongan secara langsung\n"
665
+ f"• `/finance` - Menampilkan laporan keuangan platform\n"
666
+ f"• `/scrape` - Memulai siklus scraping lowongan baru\n"
667
+ f"• `/outreach` - Memulai pencocokan outreach di background\n"
668
+ f"• `/debate <ide bisnis>` - Diskusi strategis AI CEO"
669
+ )
670
+ reply_markup = {
671
+ "inline_keyboard": [
672
+ [
673
+ {"text": "📊 CEO Briefing", "callback_data": "menu_briefing"},
674
+ {"text": "🩹 Health Check", "callback_data": "menu_health"}
675
+ ],
676
+ [
677
+ {"text": "💼 Jobs Pending", "callback_data": "menu_pendingjobs"},
678
+ {"text": "📧 Outreach Pending", "callback_data": "menu_pendingoutreach"}
679
+ ],
680
+ [
681
+ {"text": "💰 Laporan Keuangan", "callback_data": "menu_finance"}
682
+ ]
683
+ ]
684
+ }
685
+ await self.send_message(chat_id, menu_text, reply_markup=reply_markup)
686
+ return ""
687
+
688
+ elif cmd in ["/status", "/ceo_status"]:
689
+ stats = await self.get_system_health_stats()
690
+ emoji = "✅" if stats["pending_jobs"] == 0 else "⚠️"
691
+ rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
692
+
693
+ reply = (
694
+ f"⚙️ *BRIGAWAN SYSTEM STATUS*\n\n"
695
+ f"📊 *Health Check:* {emoji} ONLINE\n"
696
+ f"• Total Jobs: *{stats['total_jobs']}*\n"
697
+ f"• Pending Jobs: *{stats['pending_jobs']}*\n"
698
+ f"• Total Outreach: *{stats['total_outreach']}*\n"
699
+ f"• Stale Outreach: *{stats['stale_outreach']}*\n"
700
+ f"• Total Talent: *{stats['total_talents']}*\n"
701
+ f"• Total Revenue: *{rev_formatted}*\n\n"
702
+ f"Semua operasional berjalan lancar."
703
+ )
704
+ return reply.replace(",", ".")
705
+
706
+ elif cmd == "/briefing":
707
+ await self.generate_daily_briefing()
708
+ return "✅ *CEO Daily Briefing harian Anda berhasil dikirim!*"
709
+
710
+ elif cmd in ["/debate", "/ceo_debate"]:
711
+ idea = text[8:].strip() if cmd == "/debate" else text[12:].strip()
712
+ if not idea:
713
+ return f"❌ Perintah salah. Gunakan: `{cmd} <ide bisnis>`"
714
+
715
+ res = await self.orchestrator.execute_task(
716
+ agent_name="AntigravityCEO",
717
+ task_name="strategic_debate",
718
+ payload={"idea": idea}
719
+ )
720
+ return res.get("data", {}).get("debate_result", "Maaf, saya sedang gagal berpikir.")
721
+
722
+ elif cmd == "/scrape":
723
+ await self.delegate_task_to_queue("run_scrape_cycle", {})
724
+ return "⚡ *Memulai proses scraping lowongan hijau baru di background...*"
725
+
726
+ elif cmd == "/outreach":
727
+ await self.delegate_task_to_queue("run_outreach_sweep", {})
728
+ return "🧹 *Memulai pencocokan kandidat dan pengiriman outreach di background...*"
729
+
730
+ elif cmd == "/search_talent":
731
+ keyword = text[14:].strip()
732
+ if not keyword:
733
+ return f"❌ Silakan sertakan kata kunci. Contoh: `/search_talent AMDAL` atau `/search_talent Jakarta`"
734
+
735
+ # Log privacy audit (UU PDP Compliance)
736
+ await self.log_privacy_audit(
737
+ query=f"/search_talent {keyword}",
738
+ user_email=f"telegram_{chat_id}",
739
+ risk_score=10
740
+ )
741
+
742
+ kw_wildcard = f"%{keyword}%"
743
+ stmt = select(Talent).where(
744
+ or_(
745
+ Talent.name.ilike(kw_wildcard),
746
+ Talent.skill_tags.ilike(kw_wildcard),
747
+ Talent.experience.ilike(kw_wildcard),
748
+ Talent.location.ilike(kw_wildcard),
749
+ Talent.category.ilike(kw_wildcard)
750
+ )
751
+ ).limit(5)
752
+
753
+ res = await self.db.execute(stmt)
754
+ talents = res.scalars().all()
755
+
756
+ if not talents:
757
+ return f"🔍 Tidak ditemukan talenta dengan kata kunci *'{keyword}'*."
758
+
759
+ reply = f"🔍 *HASIL PENCARIAN TALENTA ({len(talents)})* untuk *'{keyword}'*:\n━━━━━━━━━━━━━━━━━━\n"
760
+ for t in talents:
761
+ reply += (
762
+ f"👤 *{t.name}* (`{t.talent_id}`)\n"
763
+ f"• Kategori: {t.category or '-'}\n"
764
+ f"• Lokasi: {t.location or '-'}\n"
765
+ f"• Green Score: {t.green_score}\n"
766
+ f"• Skills: `{t.skill_tags or '-'}`\n"
767
+ f"• Status Verifikasi: *{t.verification_status}*\n"
768
+ f"• CV Link: {t.cv_link or '-'}\n"
769
+ f"━━━━━━━━━━━━━━━━━━\n"
770
+ )
771
+ return reply
772
+
773
+ elif cmd == "/job_detail":
774
+ job_id = text[11:].strip()
775
+ if not job_id:
776
+ return f"❌ Silakan sertakan Job ID. Contoh: `/job_detail JB-001`"
777
+
778
+ # Log privacy audit (UU PDP Compliance)
779
+ await self.log_privacy_audit(
780
+ query=f"/job_detail {job_id}",
781
+ user_email=f"telegram_{chat_id}",
782
+ risk_score=5
783
+ )
784
+
785
+ stmt = select(JobPosting).where(JobPosting.job_id == job_id)
786
+ res = await self.db.execute(stmt)
787
+ job = res.scalar_one_or_none()
788
+
789
+ if not job:
790
+ return f"❌ Pekerjaan dengan ID *{job_id}* tidak ditemukan."
791
+
792
+ reply = (
793
+ f"💼 *RINCIAN PEKERJAAN: {job.title}*\n"
794
+ f"• ID Lowongan: `{job.job_id}`\n"
795
+ f"• Perusahaan: *{job.company_name or '-'}*\n"
796
+ f"• Lokasi: {job.location or '-'}\n"
797
+ f"• Sektor Hijau: {job.company_category or '-'}\n"
798
+ f"• Status: *{job.status.upper()}*\n"
799
+ f"• Link Sumber: {job.source_url or '-'}\n"
800
+ f"• LinkedIn Post: {job.linkedin_post_url or '-'}\n"
801
+ f"• Tanggal Dibuat: {job.timestamp.strftime('%Y-%m-%d %H:%M') if job.timestamp else '-'}\n"
802
+ f"━━━━━━━━━━━━━━━━━━\n"
803
+ f"📝 *Deskripsi Singkat:*\n{job.description[:400] + '...' if job.description and len(job.description) > 400 else job.description or '-'}\n\n"
804
+ f"⚙️ *Skill yang Dibutuhkan:*\n`{job.required_skills or '-'}`"
805
+ )
806
+ return reply
807
+
808
+ elif cmd in ["/approve", "/reject"]:
809
+ activity_id_prefix = text.split(" ")[1].strip() if len(text.split(" ")) > 1 else ""
810
+ if not activity_id_prefix:
811
+ return f"❌ Gunakan format: `{cmd} <activity_id_awal>`"
812
+
813
+ try:
814
+ from app.models.system import AgentActivity # Needs to be defined or use raw SQL
815
+ # Let's use raw SQL for simplicity to match prefix
816
+ stmt = text("SELECT id, status FROM agent_activities WHERE id::text LIKE :id_prefix LIMIT 1")
817
+ res = await self.db.execute(stmt, {"id_prefix": f"{activity_id_prefix}%"})
818
+ row = res.fetchone()
819
+
820
+ if not row:
821
+ return f"❌ Tidak ada aktivitas yang cocok dengan ID `{activity_id_prefix}`."
822
+
823
+ full_id, current_status = row[0], row[1]
824
+
825
+ if current_status != 'BLOCKED':
826
+ return f"⚠️ Aktivitas `{full_id}` tidak dalam status BLOCKED (Status saat ini: {current_status})."
827
+
828
+ new_status = 'APPROVED' if cmd == '/approve' else 'REJECTED'
829
+
830
+ upd_stmt = text("UPDATE agent_activities SET status = :status, updated_at = NOW() WHERE id = :id")
831
+ await self.db.execute(upd_stmt, {"status": new_status, "id": full_id})
832
+ await self.db.commit()
833
+
834
+ icon = "✅" if new_status == 'APPROVED' else "❌"
835
+ return f"{icon} *Tindakan {new_status}* berhasil dicatat untuk aktivitas `{full_id}`. Workflow agent akan segera merespons."
836
+
837
+ except Exception as e:
838
+ logger.error(f"Error handling intervention command: {e}")
839
+ return f"❌ Gagal memproses persetujuan: {e}"
840
+
841
+ elif cmd == "/pending_jobs":
842
+ stmt = select(JobPosting).where(cast(JobPosting.status, String).in_(["scraped", "analyzed", "draft"])).order_by(JobPosting.timestamp.asc()).limit(5)
843
+ res = await self.db.execute(stmt)
844
+ jobs = res.scalars().all()
845
+
846
+ if not jobs:
847
+ return "✅ Tidak ada lowongan pekerjaan yang menunggu persetujuan (status: scraped/analyzed/draft)."
848
+
849
+ await self.send_message(chat_id, f"📋 *DAFTAR PEKERJAAN MENUNGGU PERSETUJUAN ({len(jobs)})*:")
850
+
851
+ for j in jobs:
852
+ caption = (
853
+ f"💼 *{j.title}* at *{j.company_name or 'Unknown'}*\n"
854
+ f"• Job ID: `{j.job_id}`\n"
855
+ f"• Lokasi: {j.location or '-'}\n"
856
+ f"• Skills: `{j.required_skills or '-'}`\n"
857
+ f"• Sumber: {j.source or '-'}\n"
858
+ )
859
+ markup = {
860
+ "inline_keyboard": [
861
+ [
862
+ {"text": "✅ Approve & Post", "callback_data": f"approve_{j.job_id}"},
863
+ {"text": "❌ Reject", "callback_data": f"reject_{j.job_id}"}
864
+ ]
865
+ ]
866
+ }
867
+ await self.send_message(chat_id, caption, reply_markup=markup)
868
+ return "Gunakan tombol di atas untuk menyetujui atau menolak lowongan."
869
+
870
+ elif cmd == "/pending_outreach":
871
+ stmt = select(RecruiterOutreach).where(cast(RecruiterOutreach.status, String) == "pending_approval").order_by(RecruiterOutreach.triggered_at.asc()).limit(5)
872
+ res = await self.db.execute(stmt)
873
+ outreaches = res.scalars().all()
874
+
875
+ if not outreaches:
876
+ return "✅ Tidak ada email outreach rekruter yang menunggu persetujuan."
877
+
878
+ await self.send_message(chat_id, f"📧 *DAFTAR OUTREACH MENUNGGU PERSETUJUAN ({len(outreaches)})*:")
879
+
880
+ for o in outreaches:
881
+ caption = (
882
+ f"📧 *Outreach ID:* `{o.outreach_id}`\n"
883
+ f"👤 *Talenta:* `{o.talent_email}`\n"
884
+ f"🏢 *Rekruter:* `{o.recruiter_email}`\n"
885
+ f"📊 *Skor Kecocokan:* `{o.match_score}%`\n"
886
+ f"📝 *Subjek:* {o.outreach_subject or '-'}\n"
887
+ )
888
+ markup = {
889
+ "inline_keyboard": [
890
+ [
891
+ {"text": "✅ Approve & Send", "callback_data": f"approveoutreach_{o.outreach_id}"},
892
+ {"text": "❌ Reject", "callback_data": f"rejectoutreach_{o.outreach_id}"}
893
+ ],
894
+ [
895
+ {"text": "📋 Copy LinkedIn Pitch", "callback_data": f"copypitch_{o.outreach_id}"}
896
+ ]
897
+ ]
898
+ }
899
+ await self.send_message(chat_id, caption, reply_markup=markup)
900
+ return "Gunakan tombol di atas untuk mengelola rekomendasi outreach."
901
+
902
+ elif cmd == "/match_job":
903
+ job_id = text[11:].strip()
904
+ if not job_id:
905
+ return "❌ Silakan sertakan Job ID. Contoh: `/match_job JB-001`"
906
+
907
+ stmt = select(JobPosting).where(JobPosting.job_id == job_id)
908
+ res = await self.db.execute(stmt)
909
+ job = res.scalar_one_or_none()
910
+
911
+ if not job:
912
+ return f"❌ Pekerjaan dengan ID *{job_id}* tidak ditemukan."
913
+
914
+ await self.delegate_task_to_queue("run_outreach_for_job", {"job_id": job_id})
915
+ return f"⚡ *Memulai pencocokan kandidat dan draf outreach untuk lowongan {job_id} ({job.title}) di background...*"
916
+
917
+ elif cmd == "/finance":
918
+ # Log privacy audit (UU PDP Compliance)
919
+ await self.log_privacy_audit(
920
+ query="/finance",
921
+ user_email=f"telegram_{chat_id}",
922
+ risk_score=5
923
+ )
924
+ stats = await self.get_system_health_stats()
925
+ rev_formatted = f"Rp {int(stats['total_revenue']):,}".replace(",", ".")
926
+
927
+ stmt = select(Transaction).order_by(Transaction.created_at.desc()).limit(5)
928
+ res = await self.db.execute(stmt)
929
+ txs = res.scalars().all()
930
+
931
+ reply = (
932
+ f"💰 *LAPORAN KEUANGAN PLATFORM (B2B)*\n"
933
+ f"━━━━━━━━━━━━━━━━━━\n"
934
+ f"• Total Transaksi: *{stats['total_transactions']}*\n"
935
+ f"• Total Pendapatan Settled: *{rev_formatted}*\n\n"
936
+ f"📊 *5 Transaksi Terakhir:*\n"
937
+ )
938
+
939
+ if not txs:
940
+ reply += "_(Tidak ada riwayat transaksi)_"
941
+ else:
942
+ for t in txs:
943
+ amount_formatted = f"Rp {int(t.amount):,}".replace(",", ".")
944
+ status_emoji = "✅" if t.status == "Settled" else "❌" if t.status in ["Failed", "Rejected"] else "⏳"
945
+ reply += (
946
+ f"• {status_emoji} *{t.id}* - {amount_formatted}\n"
947
+ f" Client: `{t.client_id or '-'}` | Status: *{t.status}*\n"
948
+ f" Tanggal: {t.created_at.strftime('%d %b %Y, %H:%M') if t.created_at else '-'}\n"
949
+ )
950
+
951
+ stmt_pending = select(Transaction).where(cast(Transaction.status, String) == "Pending")
952
+ res_pending = await self.db.execute(stmt_pending)
953
+ pending_txs = res_pending.scalars().all()
954
+ if pending_txs:
955
+ reply += f"\n⏳ *Ada {len(pending_txs)} Transaksi Pending yang Butuh Bukti Transfer:*\n"
956
+ for pt in pending_txs:
957
+ reply += f" - `{pt.id}` | Nominal: Rp {int(pt.amount):,}\n"
958
+ reply = reply.replace(",", ".")
959
+ reply += "\n_Gunakan `/verify <ID>` diikuti upload foto bukti transfer untuk verifikasi._"
960
+ else:
961
+ reply = reply.replace(",", ".")
962
+
963
+ return reply
964
+
965
+ return "Perintah tidak dikenal. Gunakan `/menu` untuk melihat daftar perintah lengkap."
966
+
967
+ async def handle_webhook(self, data: dict) -> dict:
968
+ """Main entry point for incoming Telegram updates."""
969
+ try:
970
+ # --- HANDLE CALLBACK QUERIES (Inline Button Clicks) ---
971
+ if "callback_query" in data:
972
+ callback_query = data["callback_query"]
973
+ callback_id = callback_query["id"]
974
+ callback_data = callback_query["data"]
975
+ message = callback_query.get("message", {})
976
+ message_id = message.get("message_id")
977
+ chat_id = message.get("chat", {}).get("id")
978
+
979
+ logger.info(f"⚡ Processing Telegram callback: {callback_data}")
980
+
981
+ action, target_id = callback_data.split("_", 1)
982
+
983
+ # Verify that callback is from the Admin/Founder
984
+ if str(chat_id) != str(self.admin_chat_id):
985
+ await self.answer_callback_query(callback_id, "❌ Anda tidak memiliki akses.")
986
+ await self.log_security_audit(
987
+ action=f"callback_{action}",
988
+ details=f"Unauthorized callback attempt by non-admin chat_id {chat_id} on target {target_id}",
989
+ status="blocked"
990
+ )
991
+ return {"status": "unauthorized"}
992
+
993
+ # Log administrative activity (UU PDP & Security Compliance)
994
+ await self.log_activity(
995
+ actor=str(chat_id),
996
+ action=action,
997
+ metadata=target_id
998
+ )
999
+
1000
+ # --- 1. HANDLE B2B PAYMENT APPROVALS/REJECTIONS ---
1001
+ if action in ["approvepay", "rejectpay"]:
1002
+ parts_pay = target_id.split("_")
1003
+ tx_id = parts_pay[0]
1004
+ user_chat_id = parts_pay[1] if len(parts_pay) > 1 else None
1005
+
1006
+ if action == "approvepay":
1007
+ await self.answer_callback_query(callback_id, "⏳ Memproses pembayaran...")
1008
+ try:
1009
+ # 1. Fetch transaction
1010
+ stmt = select(Transaction).where(Transaction.id == tx_id)
1011
+ tx_res = await self.db.execute(stmt)
1012
+ tx = tx_res.scalar_one_or_none()
1013
+ if not tx:
1014
+ await self.answer_callback_query(callback_id, "❌ Transaksi tidak ditemukan.")
1015
+ return {"status": "error", "message": "Transaction not found"}
1016
+
1017
+ if tx.status == "Settled":
1018
+ await self.answer_callback_query(callback_id, "❌ Transaksi sudah disetujui.")
1019
+ return {"status": "error", "message": "Already settled"}
1020
+
1021
+ # 2. Determine coins to add
1022
+ amount = float(tx.amount)
1023
+ coins_added = 20 if (450000 <= amount < 451000) else (60 if (1200000 <= amount < 1201000) else (200 if (3500000 <= amount < 3501000) else 0))
1024
+ if coins_added == 0:
1025
+ from app.services.employer_service import COIN_BUNDLES
1026
+ bundle_id = [k for k, v in COIN_BUNDLES.items() if abs(v["idr_price"] - amount) < 10000]
1027
+ coins_added = COIN_BUNDLES[bundle_id[0]]["coins"] if bundle_id else 0
1028
+ if coins_added == 0:
1029
+ coins_added = int(amount / 20000) # fallback exchange rate
1030
+
1031
+ # 3. Credit coins to company wallet
1032
+ from app.models.employer import ClientAccount, Company
1033
+ client_stmt = select(ClientAccount).where(ClientAccount.id == tx.client_id)
1034
+ client_res = await self.db.execute(client_stmt)
1035
+ client = client_res.scalar_one_or_none()
1036
+
1037
+ client_email = ""
1038
+ if client:
1039
+ client_email = client.email
1040
+ company_stmt = select(Company).where(Company.id == client.company_id)
1041
+ company_res = await self.db.execute(company_stmt)
1042
+ company = company_res.scalar_one_or_none()
1043
+ if company:
1044
+ company.credit_balance = (company.credit_balance or 0) + coins_added
1045
+ self.db.add(company)
1046
+
1047
+ # 4. Settle transaction in PostgreSQL
1048
+ tx.status = "Settled"
1049
+ self.db.add(tx)
1050
+ await self.db.commit()
1051
+
1052
+ amount_formatted = f"Rp {int(amount):,}".replace(",", ".")
1053
+ new_text = (
1054
+ f"✅ *TRANSAKSI DISETUJUI & DIKREDITKAN*\n\n"
1055
+ f"• ID Transaksi: *{tx_id}*\n"
1056
+ f"• Koin telah dikreditkan ke: *{client_email or 'Unknown'}*\n"
1057
+ f"• Koin ditambahkan: *{coins_added} Briga Coin*\n"
1058
+ f"• Nominal: *{amount_formatted}*\n"
1059
+ f"• Diverifikasi pada: *{datetime.now().strftime('%d %b %Y, %H:%M')} WIB*"
1060
+ )
1061
+ await self.edit_message_text(chat_id, message_id, new_text)
1062
+ await self.answer_callback_query(callback_id, "🎉 Pembayaran sukses disetujui!")
1063
+
1064
+ # 5. Direct Write to Google Sheets via Sheets API (Direct backup)
1065
+ try:
1066
+ if settings.google_sheets_spreadsheet_id:
1067
+ row_values = [
1068
+ tx.id,
1069
+ tx.client_id or "",
1070
+ float(tx.amount),
1071
+ tx.type or "TopUpManual",
1072
+ "Settled",
1073
+ tx.snap_token or "Telegram Verification",
1074
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1075
+ ]
1076
+ await spark_agent.append_row_to_sheet(
1077
+ settings.google_sheets_spreadsheet_id,
1078
+ "Transactions!A1",
1079
+ row_values
1080
+ )
1081
+ except Exception as sheets_err:
1082
+ logger.error(f"Failed to log transaction to Google Sheets: {sheets_err}")
1083
+
1084
+ # 6. Send HTML confirmation email
1085
+ if client_email:
1086
+ try:
1087
+ tier_name = f"{coins_added} Coins"
1088
+ subject = f"✅ Top Up Briga Coin Berhasil - {tier_name}"
1089
+ html_body = f"""
1090
+ <div style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 600px; margin: 0 auto; padding: 40px 20px; background-color: #f0f4f1;">
1091
+ <div style="background-color: #ffffff; border-radius: 24px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.05); border: 1px solid #e1e8e2;">
1092
+ <div style="background-color: #1a5a26; padding: 32px; text-align: center;">
1093
+ <div style="font-size: 28px; font-weight: 800; color: #ffffff; letter-spacing: -0.5px;">BRIGAWAN<span style="color: #F9A825;">.</span>AI</div>
1094
+ <div style="color: #a5d6a7; font-size: 12px; font-weight: 600; margin-top: 4px; text-transform: uppercase; letter-spacing: 2px;">Sustainability Career Center</div>
1095
+ </div>
1096
+ <div style="padding: 40px;">
1097
+ <div style="text-align: center; margin-bottom: 32px;">
1098
+ <div style="width: 64px; height: 64px; background-color: #f9fbf9; border-radius: 20px; display: inline-flex; align-items: center; justify-content: center; font-size: 32px; margin-bottom: 16px; border: 1px solid #eef2ef; line-height: 64px;">🪙</div>
1099
+ <h2 style="color: #1a5a26; font-size: 24px; font-weight: 800; margin: 0;">Top Up Berhasil!</h2>
1100
+ <p style="color: #667c69; font-size: 14px; margin-top: 8px;">Saldo Briga Coin Anda telah ditambahkan.</p>
1101
+ </div>
1102
+ <div style="background-color: #f9fbf9; border-radius: 20px; padding: 24px; border: 1px solid #eef2ef; margin-bottom: 32px; text-align: center;">
1103
+ <p style="color: #667c69; font-size: 12px; font-weight: 700; text-transform: uppercase; margin: 0 0 8px 0; letter-spacing: 1px;">Jumlah Koin Baru</p>
1104
+ <p style="color: #1a5a26; font-size: 48px; font-weight: 900; margin: 0;">+{coins_added}</p>
1105
+ <p style="color: #1a5a26; font-size: 14px; font-weight: 600; margin: 4px 0 0 0;">Briga Coin</p>
1106
+ </div>
1107
+ <table style="width: 100%; border-collapse: collapse;">
1108
+ <tr>
1109
+ <td style="padding: 12px 0; color: #667c69; font-size: 14px;">Paket Langganan</td>
1110
+ <td style="padding: 12px 0; color: #1a5a26; font-size: 14px; font-weight: 700; text-align: right;">{tier_name}</td>
1111
+ </tr>
1112
+ <tr>
1113
+ <td style="padding: 12px 0; color: #667c69; font-size: 14px; border-bottom: 1px solid #eef2ef;">Total Pembayaran</td>
1114
+ <td style="padding: 12px 0; color: #1a5a26; font-size: 14px; font-weight: 700; text-align: right; border-bottom: 1px solid #eef2ef;">{amount_formatted}</td>
1115
+ </tr>
1116
+ <tr>
1117
+ <td style="padding: 12px 0; color: #667c69; font-size: 14px;">Metode Pembayaran</td>
1118
+ <td style="padding: 12px 0; color: #1a5a26; font-size: 14px; font-weight: 700; text-align: right;">Manual Transfer (Telegram Verified)</td>
1119
+ </tr>
1120
+ <tr>
1121
+ <td style="padding: 12px 0; color: #667c69; font-size: 14px;">Waktu Transaksi</td>
1122
+ <td style="padding: 12px 0; color: #1a5a26; font-size: 14px; font-weight: 700; text-align: right;">{datetime.now().strftime("%d %b %Y, %H:%M")} WIB</td>
1123
+ </tr>
1124
+ </table>
1125
+ <div style="margin-top: 40px; text-align: center;">
1126
+ <a href="https://briga.id?view=employer" style="background-color: #F9A825; color: #1a5a26; padding: 16px 32px; border-radius: 14px; text-decoration: none; font-weight: 800; font-size: 14px; display: inline-block;">Mulai Cari Talenta →</a>
1127
+ </div>
1128
+ </div>
1129
+ <div style="background-color: #f9fbf9; padding: 24px; text-align: center; border-top: 1px solid #eef2ef;">
1130
+ <p style="color: #667c69; font-size: 11px; margin: 0;">E-mail ini dikirimkan otomatis oleh sistem Brigawan AI. Jangan membalas email ini.</p>
1131
+ <p style="color: #1a5a26; font-size: 11px; font-weight: 700; margin: 8px 0 0 0;">&copy; 2026 Brigawan Sustainability Center. All Rights Reserved.</p>
1132
+ </div>
1133
+ </div>
1134
+ </div>
1135
+ """
1136
+ await asyncio.to_thread(email_service.send_html_email, client_email, subject, html_body)
1137
+ except Exception as mail_err:
1138
+ logger.error(f"Failed to send top-up email: {mail_err}")
1139
+
1140
+ # 7. Notify recruiter via Telegram
1141
+ if user_chat_id:
1142
+ await self.send_message(
1143
+ user_chat_id,
1144
+ f"✅ *Top-up Berhasil!*\n\nPembayaran manual Anda sebesar *{amount_formatted}* telah diverifikasi.\n*{coins_added} Briga Coin* telah ditambahkan ke akun Anda."
1145
+ )
1146
+ await self.delete_telegram_session(str(user_chat_id))
1147
+ except Exception as ex:
1148
+ logger.error(f"Error in approvepay native handler: {ex}")
1149
+ await self.answer_callback_query(callback_id, f"❌ Error: {ex}")
1150
+
1151
+ elif action == "rejectpay":
1152
+ await self.answer_callback_query(callback_id, "❌ Menolak transaksi...")
1153
+ try:
1154
+ # 1. Fetch transaction
1155
+ stmt = select(Transaction).where(Transaction.id == tx_id)
1156
+ tx_res = await self.db.execute(stmt)
1157
+ tx = tx_res.scalar_one_or_none()
1158
+ if tx:
1159
+ tx.status = "Failed"
1160
+ self.db.add(tx)
1161
+ await self.db.commit()
1162
+
1163
+ new_text = (
1164
+ f"❌ *TRANSAKSI DITOLAK*\n\n"
1165
+ f"• ID Transaksi: *{tx_id}*\n"
1166
+ f"• Status: Ditinjau & Ditolak oleh Admin\n"
1167
+ f"• Waktu: *{datetime.now().strftime('%d %b %Y, %H:%M')} WIB*"
1168
+ )
1169
+ await self.edit_message_text(chat_id, message_id, new_text)
1170
+ await self.answer_callback_query(callback_id, "❌ Transaksi berhasil ditolak.")
1171
+
1172
+ # 2. Direct Write to Google Sheets via Sheets API (Direct backup)
1173
+ try:
1174
+ if settings.google_sheets_spreadsheet_id:
1175
+ row_values = [
1176
+ tx.id,
1177
+ tx.client_id or "",
1178
+ float(tx.amount),
1179
+ tx.type or "TopUpManual",
1180
+ "Failed",
1181
+ "Rejected by Admin",
1182
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1183
+ ]
1184
+ await spark_agent.append_row_to_sheet(
1185
+ settings.google_sheets_spreadsheet_id,
1186
+ "Transactions!A1",
1187
+ row_values
1188
+ )
1189
+ except Exception as sheets_err:
1190
+ logger.error(f"Failed to log transaction rejection to Google Sheets: {sheets_err}")
1191
+
1192
+ # 3. Notify recruiter via Telegram
1193
+ if user_chat_id:
1194
+ await self.send_message(
1195
+ user_chat_id,
1196
+ f"❌ *Top-up Ditolak*\n\nBukti transfer manual untuk ID Transaksi *{tx_id}* ditolak oleh CEO. Mohon periksa kembali nominal transfer Anda."
1197
+ )
1198
+ await self.delete_telegram_session(str(user_chat_id))
1199
+ else:
1200
+ await self.answer_callback_query(callback_id, "❌ Transaksi tidak ditemukan.")
1201
+ except Exception as ex:
1202
+ logger.error(f"Error in rejectpay native handler: {ex}")
1203
+ await self.answer_callback_query(callback_id, f"❌ Error: {ex}")
1204
+ return {"status": "success"}
1205
+
1206
+ # --- 2. HANDLE UNBLOCK ACTION ---
1207
+ elif action == "unblock":
1208
+ await self.answer_callback_query(callback_id, "🔓 Membuka blokir...")
1209
+ clean_id = target_id.replace("_at_", "@")
1210
+
1211
+ try:
1212
+ # Direct PostgreSQL local unblock if it is an email address
1213
+ success = False
1214
+ if "@" in clean_id:
1215
+ from app.models.employer import ClientAccount
1216
+ stmt = select(ClientAccount).where(ClientAccount.email == clean_id)
1217
+ res = await self.db.execute(stmt)
1218
+ client = res.scalar_one_or_none()
1219
+ if client:
1220
+ client.status = "Active"
1221
+ self.db.add(client)
1222
+ await self.db.commit()
1223
+ success = True
1224
+ logger.info(f"Unblocked client email locally: {clean_id}")
1225
+
1226
+ # Set message text to show success
1227
+ new_text = (
1228
+ f"🔓 *AKSES DI-UNBLOCK OLEH ADMIN*\n\n"
1229
+ f"👤 *Aktor/Target:* `{clean_id}`\n\n"
1230
+ f"Sesi keamanan untuk pengguna ini berhasil dipulihkan secara lokal!"
1231
+ )
1232
+ await self.edit_message_text(chat_id, message_id, new_text)
1233
+ await self.answer_callback_query(callback_id, "🎉 Blokir berhasil dibuka!")
1234
+ except Exception as ex:
1235
+ logger.error(f"Exception during local unblock: {ex}")
1236
+ await self.answer_callback_query(callback_id, f"❌ Gagal: {ex}")
1237
+ return {"status": "success"}
1238
+
1239
+ # --- 3. HANDLE RECRUITER OUTREACH CALLBACK ACTIONS ---
1240
+ elif action in ["approveoutreach", "rejectoutreach", "copypitch"]:
1241
+ outreach_id = target_id
1242
+ stmt = select(RecruiterOutreach).where(RecruiterOutreach.outreach_id == outreach_id)
1243
+ outreach_res = await self.db.execute(stmt)
1244
+ target_outreach = outreach_res.scalar_one_or_none()
1245
+
1246
+ if not target_outreach:
1247
+ await self.answer_callback_query(callback_id, "❌ Error: Rekaman outreach tidak ditemukan.")
1248
+ return {"status": "error", "message": "Outreach record not found"}
1249
+
1250
+ if action == "approveoutreach":
1251
+ await self.answer_callback_query(callback_id, "⏳ Mengirim email outreach...")
1252
+
1253
+ if target_outreach.status == "sent":
1254
+ await self.answer_callback_query(callback_id, "⚠️ Outreach ini sudah pernah dikirim.")
1255
+ return {"status": "already_sent"}
1256
+
1257
+ try:
1258
+ # Direct Python-native SMTP email dispatch
1259
+ success = await asyncio.to_thread(
1260
+ email_service.send_html_email,
1261
+ target_outreach.recruiter_email,
1262
+ target_outreach.outreach_subject,
1263
+ target_outreach.outreach_body
1264
+ )
1265
+ if success:
1266
+ # Update PostgreSQL status
1267
+ target_outreach.status = "sent"
1268
+ target_outreach.sent_at = datetime.now(timezone.utc)
1269
+ await self.db.commit()
1270
+
1271
+ new_text = (
1272
+ f"✅ *OUTREACH APPROVED & SENT*\n\n"
1273
+ f"📌 *Outreach ID:* `{outreach_id}`\n"
1274
+ f"💼 *Job ID:* `{target_outreach.job_id}`\n"
1275
+ f"👤 *Talenta:* `{target_outreach.talent_email}`\n"
1276
+ f"📊 *Skor Kecocokan:* `{target_outreach.match_score}%`\n"
1277
+ f"🏢 *Penerima:* `{target_outreach.recruiter_email}`\n\n"
1278
+ f"Email rekomendasi penawaran talenta berhasil dikirim resmi via SMTP!"
1279
+ )
1280
+ await self.edit_message_text(chat_id, message_id, new_text)
1281
+ await self.answer_callback_query(callback_id, "🎉 Email berhasil terkirim!")
1282
+ else:
1283
+ await self.answer_callback_query(callback_id, "❌ Gagal mengirim email via SMTP.")
1284
+ except Exception as ex:
1285
+ logger.error(f"Exception during native outreach: {ex}")
1286
+ await self.answer_callback_query(callback_id, f"❌ Error: {ex}")
1287
+
1288
+ elif action == "rejectoutreach":
1289
+ target_outreach.status = "rejected"
1290
+ await self.db.commit()
1291
+ new_text = (
1292
+ f"❌ *OUTREACH REJECTED/IGNORED*\n\n"
1293
+ f"📌 *Outreach ID:* `{outreach_id}`\n"
1294
+ f"💼 *Job ID:* `{target_outreach.job_id}`\n"
1295
+ f"👤 *Talenta:* `{target_outreach.talent_email}`\n\n"
1296
+ f"Rekomendasi outreach rekruter ini telah ditolak/diabaikan."
1297
+ )
1298
+ await self.edit_message_text(chat_id, message_id, new_text)
1299
+ await self.answer_callback_query(callback_id, "❌ Outreach ditolak.")
1300
+
1301
+ elif action == "copypitch":
1302
+ target_outreach.status = "manual_linkedin_copied"
1303
+ target_outreach.sent_at = datetime.now(timezone.utc)
1304
+ await self.db.commit()
1305
+
1306
+ new_text = (
1307
+ f"📋 *LINKEDIN PITCH RETRIEVED*\n\n"
1308
+ f"📌 *Outreach ID:* `{outreach_id}`\n"
1309
+ f"💼 *Job ID:* `{target_outreach.job_id}`\n"
1310
+ f"👤 *Talenta:* `{target_outreach.talent_email}`\n\n"
1311
+ f"Pesan pitch LinkedIn telah dikirim di bawah ini. Silakan salin untuk melakukan outreach manual!"
1312
+ )
1313
+ await self.edit_message_text(chat_id, message_id, new_text)
1314
+
1315
+ pitch_msg = (
1316
+ f"📋 *SALIN OUTREACH LINKEDIN ({outreach_id})*\n\n"
1317
+ f"{target_outreach.outreach_body}"
1318
+ )
1319
+ await self.send_message(chat_id, pitch_msg)
1320
+ await self.answer_callback_query(callback_id, "📋 Pitch LinkedIn terkirim!")
1321
+
1322
+ return {"status": "success"}
1323
+
1324
+ # --- 3.5. HANDLE SYSTEM AUTO-HEAL CALLBACK ACTIONS ---
1325
+ elif action in ["approveheal", "rejectheal"]:
1326
+ task_id = target_id
1327
+
1328
+ if action == "approveheal":
1329
+ await self.answer_callback_query(callback_id, "⏳ Menjalankan perbaikan sistem (CTO Auto-Heal)...")
1330
+
1331
+ worker_url = os.getenv("AGENT_WORKER_URL", "https://yabeskn-briga-agent-worker.hf.space").rstrip("/")
1332
+ target_url = f"{worker_url}/v1/agents/heal/approve"
1333
+
1334
+ payload = {
1335
+ "task_id": task_id,
1336
+ "approved": True
1337
+ }
1338
+
1339
+ headers = {
1340
+ "X-Webhook-Token": settings.webhook_secret or os.getenv("WEBHOOK_SECRET", "briga_secret_webhook_123_xyz"),
1341
+ "Content-Type": "application/json"
1342
+ }
1343
+
1344
+ try:
1345
+ async with httpx.AsyncClient(timeout=60.0) as client:
1346
+ resp = await client.post(target_url, json=payload, headers=headers)
1347
+
1348
+ if resp.status_code == 200:
1349
+ res_json = resp.json()
1350
+ if res_json.get("success"):
1351
+ new_text = (
1352
+ f"✅ *CTO AUTO-HEAL APPROVED & EXECUTED*\n\n"
1353
+ f"📌 *Task ID:* `{task_id}`\n\n"
1354
+ f"Sistem telah berhasil diperbaiki, diverifikasi aman, dan disinkronisasikan ke seluruh microservices!"
1355
+ )
1356
+ await self.edit_message_text(chat_id, message_id, new_text)
1357
+ await self.answer_callback_query(callback_id, "🎉 Sistem sukses dipulihkan!")
1358
+ else:
1359
+ err_detail = res_json.get("error", "Unknown error")
1360
+ await self.answer_callback_query(callback_id, f"❌ Gagal: {err_detail}")
1361
+ else:
1362
+ await self.answer_callback_query(callback_id, f"❌ Worker HTTP Error {resp.status_code}")
1363
+ except Exception as ex:
1364
+ logger.error(f"Exception during worker heal call: {ex}")
1365
+ await self.answer_callback_query(callback_id, f"❌ Koneksi Worker Gagal: {ex}")
1366
+
1367
+ elif action == "rejectheal":
1368
+ await self.answer_callback_query(callback_id, "⏳ Membatalkan perbaikan...")
1369
+ try:
1370
+ stmt = update(KnowledgeQueue).where(KnowledgeQueue.id == task_id).values(status="Failed")
1371
+ await self.db.execute(stmt)
1372
+ await self.db.commit()
1373
+
1374
+ new_text = (
1375
+ f"❌ *CTO AUTO-HEAL REJECTED/IGNORED*\n\n"
1376
+ f"📌 *Task ID:* `{task_id}`\n\n"
1377
+ f"Rekomendasi perbaikan sistem otomatis telah ditolak dan diabaikan."
1378
+ )
1379
+ await self.edit_message_text(chat_id, message_id, new_text)
1380
+ await self.answer_callback_query(callback_id, "❌ Perbaikan ditolak.")
1381
+ except Exception as ex:
1382
+ logger.error(f"Exception during reject heal: {ex}")
1383
+ await self.answer_callback_query(callback_id, f"❌ Gagal: {ex}")
1384
+
1385
+ return {"status": "success"}
1386
+
1387
+ # --- 4. HANDLE JOB APPROVAL CALLBACK ACTIONS ---
1388
+ elif action in ["approve", "reject"]:
1389
+ job_id = target_id
1390
+ stmt = select(JobPosting).where(JobPosting.job_id == job_id)
1391
+ job_res = await self.db.execute(stmt)
1392
+ job = job_res.scalar_one_or_none()
1393
+
1394
+ if not job:
1395
+ await self.answer_callback_query(callback_id, "❌ Error: Pekerjaan tidak ditemukan.")
1396
+ return {"status": "error", "message": "Job not found"}
1397
+
1398
+ if action == "approve":
1399
+ await self.answer_callback_query(callback_id, "⏳ Memproses postingan LinkedIn...")
1400
+
1401
+ if job.status == "posted":
1402
+ await self.answer_callback_query(callback_id, "⚠️ Lowongan ini sudah diposting sebelumnya.")
1403
+ return {"status": "already_posted"}
1404
+
1405
+ job.status = "posted"
1406
+ job.is_active = True
1407
+ job.posted_at = datetime.now(timezone.utc)
1408
+
1409
+ # Smart category resolution
1410
+ company_category = job.company_category
1411
+ if not company_category:
1412
+ if job.company_name and "climatebase" in job.company_name.lower():
1413
+ company_category = "Platform Karir & Edukasi Iklim"
1414
+ else:
1415
+ company_category = "Perusahaan Sektor Hijau"
1416
+
1417
+ # Post to LinkedIn Page
1418
+ poster = LinkedInPoster()
1419
+ skills = job.required_skills or ""
1420
+ post_url, error_msg = await poster.post_job(
1421
+ job_id=job_id,
1422
+ title=job.title,
1423
+ company_category=company_category,
1424
+ location=job.location or "Indonesia",
1425
+ skills=[s.strip() for s in skills.split(",") if s.strip()]
1426
+ )
1427
+
1428
+ if post_url:
1429
+ job.linkedin_post_url = post_url
1430
+ new_text = (
1431
+ f"✅ *APPROVED & POSTED TO LINKEDIN*\n\n"
1432
+ f"📌 *ID:* `{job_id}`\n"
1433
+ f"💼 *Posisi:* {job.title}\n"
1434
+ f"🏢 *Industri:* {company_category}\n"
1435
+ f"📍 *Lokasi:* {job.location or 'Indonesia'}\n\n"
1436
+ f"🔗 [Lihat Postingan LinkedIn]({post_url})\n"
1437
+ f"🌐 [Lihat Lowongan di Briga.id](https://briga.id/job?id={job_id})"
1438
+ )
1439
+ else:
1440
+ reason = error_msg if error_msg else "Koneksi terputus atau token kadaluwarsa"
1441
+ new_text = (
1442
+ f"✅ *APPROVED & ACTIVE ON BRIGA.ID*\n⚠️ *LinkedIn Posting Failed:* {reason}\n\n"
1443
+ f"📌 *ID:* `{job_id}`\n"
1444
+ f"💼 *Posisi:* {job.title}\n"
1445
+ f"🏢 *Industri:* {company_category}\n"
1446
+ f"📍 *Lokasi:* {job.location or 'Indonesia'}\n\n"
1447
+ f"🌐 [Lihat Lowongan di Briga.id](https://briga.id/job?id={job_id})"
1448
+ )
1449
+
1450
+ await self.db.commit()
1451
+ await self.edit_message_text(chat_id, message_id, new_text)
1452
+ await self.answer_callback_query(callback_id, "🎉 Berhasil disetujui!")
1453
+
1454
+ # Trigger outreach swept in background
1455
+ await self.delegate_task_to_queue("run_outreach_for_job", {"job_id": job_id})
1456
+
1457
+ elif action == "reject":
1458
+ job.status = "rejected"
1459
+ job.is_active = False
1460
+ await self.db.commit()
1461
+
1462
+ new_text = (
1463
+ f"❌ *LOWONGAN DITOLAK*\n\n"
1464
+ f"📌 *ID:* `{job_id}`\n"
1465
+ f"💼 *Posisi:* {job.title}\n"
1466
+ f"🏢 *Perusahaan:* {job.company_name}\n\n"
1467
+ f"Status lowongan ini telah diubah menjadi 'rejected' dan tidak akan dipublikasikan."
1468
+ )
1469
+ await self.edit_message_text(chat_id, message_id, new_text)
1470
+ await self.answer_callback_query(callback_id, "❌ Lowongan ditolak.")
1471
+
1472
+ return {"status": "success"}
1473
+
1474
+ elif action == "menu":
1475
+ if target_id == "briefing":
1476
+ await self.answer_callback_query(callback_id, "⏳ Menghasilkan briefing...")
1477
+ await self.generate_daily_briefing()
1478
+ elif target_id == "health":
1479
+ await self.answer_callback_query(callback_id, "⏳ Mengecek kesehatan...")
1480
+ await self.check_system_health()
1481
+ elif target_id == "pendingjobs":
1482
+ await self.answer_callback_query(callback_id, "⏳ Mengambil lowongan pending...")
1483
+ reply = await self.handle_ceo_command("/pending_jobs", chat_id)
1484
+ if reply:
1485
+ await self.send_message(chat_id, reply)
1486
+ elif target_id == "pendingoutreach":
1487
+ await self.answer_callback_query(callback_id, "⏳ Mengambil outreach pending...")
1488
+ reply = await self.handle_ceo_command("/pending_outreach", chat_id)
1489
+ if reply:
1490
+ await self.send_message(chat_id, reply)
1491
+ elif target_id == "finance":
1492
+ await self.answer_callback_query(callback_id, "⏳ Mengambil data keuangan...")
1493
+ reply = await self.handle_ceo_command("/finance", chat_id)
1494
+ if reply:
1495
+ await self.send_message(chat_id, reply)
1496
+ return {"status": "success"}
1497
+
1498
+ # --- HANDLE MESSAGES (Incoming Chat / Receipt Uploads) ---
1499
+ if "message" in data:
1500
+ message = data["message"]
1501
+ chat_id = message.get("chat", {}).get("id")
1502
+ user_id = message.get("from", {}).get("id")
1503
+ text = message.get("text", "")
1504
+
1505
+ # Strict access control verification for non-admin
1506
+ is_admin = str(chat_id) == str(self.admin_chat_id)
1507
+ is_pay_start = text.startswith("/start") and text[7:].strip().startswith("pay_")
1508
+ is_verify = text.startswith("/verify")
1509
+ is_photo = "photo" in message and len(message["photo"]) > 0
1510
+ is_simple_start = text.strip() == "/start"
1511
+
1512
+ if not is_admin:
1513
+ # Non-admin is strictly only allowed to access payment flows (start pay_, verify, photo upload) or generic /start hello
1514
+ if not (is_pay_start or is_verify or is_photo or is_simple_start):
1515
+ # Log attempt to security_audit_log
1516
+ cmd_attempt = text.split(" ")[0] if text else "photo_or_other"
1517
+ await self.log_security_audit(
1518
+ action=cmd_attempt,
1519
+ details=f"Unauthorized access attempt by non-admin chat_id {chat_id}. Message: {text[:200]}",
1520
+ status="blocked"
1521
+ )
1522
+ # Reply with clear error
1523
+ await self.send_message(chat_id, "❌ Anda tidak memiliki akses untuk fitur ini.")
1524
+ return {"status": "unauthorized"}
1525
+
1526
+ # --- HANDLE START COMMAND (Deep link pay_TX-XXXXXX) ---
1527
+ if text.startswith("/start"):
1528
+ payload = text[7:].strip()
1529
+ if payload.startswith("pay_"):
1530
+ tx_id = payload[4:].upper()
1531
+ await self.save_telegram_session(str(user_id), tx_id, state="waiting_receipt")
1532
+ reply = (
1533
+ f"👋 *Selamat datang di Brigawan Payment Bot!*\n\n"
1534
+ f"Kami mendeteksi pengajuan Top-Up dengan ID Transaksi: *{tx_id}*.\n\n"
1535
+ f"📌 *Langkah selanjutnya:*\n"
1536
+ f"1. Transfer nominal paket sesuai invoice ke rekening:\n"
1537
+ f" 🏦 *Bank BCA: 1234567890*\n"
1538
+ f" 👤 *a/n PT Briga Energi Indonesia*\n"
1539
+ f"2. *Unggah / Kirimkan foto bukti transfer* Anda langsung ke chat bot ini.\n\n"
1540
+ f"Setelah foto dikirim, AI akan menganalisis dan Admin kami akan memverifikasi instan!"
1541
+ )
1542
+ await self.send_message(chat_id, reply)
1543
+ return {"status": "success"}
1544
+
1545
+ if str(chat_id) == str(self.admin_chat_id):
1546
+ reply = await self.handle_ceo_command("/menu", chat_id)
1547
+ if reply:
1548
+ await self.send_message(chat_id, reply)
1549
+ return {"status": "success"}
1550
+
1551
+ await self.send_message(chat_id, "👋 *Halo!* Silakan mulai top-up koin dari Portal Rekruter Brigawan untuk menggunakan bot konfirmasi pembayaran ini.")
1552
+ return {"status": "success"}
1553
+
1554
+ # --- HANDLE MANUAL VERIFY COMMAND (/verify TX-XXXXXX) ---
1555
+ elif text.startswith("/verify"):
1556
+ tx_id = text[8:].strip().upper()
1557
+ if tx_id.startswith("TX-"):
1558
+ await self.save_telegram_session(str(user_id), tx_id, state="waiting_receipt")
1559
+ await self.send_message(chat_id, f"✅ ID Transaksi *{tx_id}* berhasil dikaitkan. Silakan kirimkan foto bukti transfer Anda sekarang.")
1560
+ return {"status": "success"}
1561
+ await self.send_message(chat_id, "❌ Format salah. Gunakan: `/verify TX-XXXXXX` untuk mengaitkan transaksi Anda.")
1562
+ return {"status": "success"}
1563
+
1564
+ # --- HANDLE OTHER SLASH COMMANDS (Founder-facing) ---
1565
+ elif text.startswith("/"):
1566
+ if str(chat_id) != str(self.admin_chat_id):
1567
+ await self.send_message(chat_id, "❌ Anda tidak memiliki akses untuk perintah ini.")
1568
+ return {"status": "unauthorized"}
1569
+
1570
+ reply = await self.handle_ceo_command(text, chat_id)
1571
+ if reply:
1572
+ await self.send_message(chat_id, reply)
1573
+ return {"status": "success"}
1574
+
1575
+ # --- HANDLE PHOTO UPLOAD (Receipt Verification via Gemini Vision) ---
1576
+ elif "photo" in message and len(message["photo"]) > 0:
1577
+ # Session validation
1578
+ user_session = await self.get_telegram_session(str(user_id))
1579
+ if not user_session:
1580
+ 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.")
1581
+ return {"status": "success"}
1582
+
1583
+ tx_id = user_session["tx_id"]
1584
+ await self.send_message(chat_id, "⏳ *Membaca bukti transfer Anda menggunakan AI...*")
1585
+
1586
+ photo = message["photo"][-1]
1587
+ file_id = photo["file_id"]
1588
+
1589
+ try:
1590
+ photo_bytes = await self.download_file(file_id)
1591
+ ocr_result = await self.run_vision_ocr(photo_bytes)
1592
+ logger.info(f"👁️ OCR result for {tx_id}: {ocr_result}")
1593
+
1594
+ if ocr_result.get("is_blurry") or "error" in ocr_result:
1595
+ await self.send_message(
1596
+ chat_id,
1597
+ "❌ *Gagal Membaca Bukti Transfer*\n\nGambar terdeteksi buram atau bukan merupakan bukti transfer yang valid. Silakan unggah ulang foto bukti transfer yang lebih jelas."
1598
+ )
1599
+ return {"status": "blurry_reprompt"}
1600
+
1601
+ # Get expected amount from database
1602
+ stmt = select(Transaction).where(Transaction.id == tx_id)
1603
+ tx_res = await self.db.execute(stmt)
1604
+ target_tx = tx_res.scalar_one_or_none()
1605
+
1606
+ if not target_tx:
1607
+ await self.send_message(chat_id, f"❌ ID Transaksi *{tx_id}* tidak terdaftar di database kami. Mohon periksa kembali.")
1608
+ return {"status": "tx_not_found"}
1609
+
1610
+ expected_amount = int(float(target_tx.amount))
1611
+ ocr_amount = int(ocr_result.get("amount", 0))
1612
+ ocr_bank = ocr_result.get("bank", "Unknown Bank")
1613
+ ocr_date = ocr_result.get("date", "Unknown Date")
1614
+
1615
+ discrepancy_alert = ""
1616
+ amount_match = True
1617
+ if abs(expected_amount - ocr_amount) > 1000:
1618
+ amount_match = False
1619
+ discrepancy_alert = f"⚠️ *PERINGATAN:* Nominal kuitansi (Rp {ocr_amount:,}) berbeda dengan tagihan invoice (Rp {expected_amount:,})!"
1620
+ discrepancy_alert = discrepancy_alert.replace(",", ".")
1621
+
1622
+ user_feedback = (
1623
+ f"ℹ️ *Informasi Terbaca oleh AI:*\n"
1624
+ f"• Nominal: *Rp {ocr_amount:,}*\n"
1625
+ f"• Bank Pengirim: *{ocr_bank}*\n"
1626
+ f"• Tanggal: *{ocr_date}*\n\n"
1627
+ f"Status: Bukti transfer berhasil dikirim ke Admin untuk verifikasi akhir."
1628
+ )
1629
+ user_feedback = user_feedback.replace(",", ".")
1630
+ await self.send_message(chat_id, user_feedback)
1631
+
1632
+ if self.admin_chat_id:
1633
+ admin_caption = (
1634
+ f"📥 *BUKTI TRANSFER TOP-UP B2B*\n\n"
1635
+ f"• ID Transaksi: *{tx_id}*\n"
1636
+ f"• Rekruter ID: *{target_tx.client_id or 'Unknown'}*\n"
1637
+ f"• Tagihan Invoice: *Rp {expected_amount:,}*\n"
1638
+ f"• Terbaca oleh AI OCR: *Rp {ocr_amount:,}* ({ocr_bank})\n"
1639
+ f"• Status Pencocokan: {'✅ COCOK' if amount_match else '❌ TIDAK COCOK'}\n"
1640
+ f"{discrepancy_alert}\n\n"
1641
+ f"Silakan lakukan tindakan:"
1642
+ )
1643
+ admin_caption = admin_caption.replace(",", ".")
1644
+
1645
+ url = f"{self.base_url}/sendPhoto"
1646
+ payload = {
1647
+ "chat_id": self.admin_chat_id,
1648
+ "photo": file_id,
1649
+ "caption": admin_caption,
1650
+ "parse_mode": "Markdown",
1651
+ "reply_markup": {
1652
+ "inline_keyboard": [
1653
+ [
1654
+ {"text": "✅ Approve & Credit", "callback_data": f"approvepay_{tx_id}_{chat_id}"},
1655
+ {"text": "❌ Reject", "callback_data": f"rejectpay_{tx_id}_{chat_id}"}
1656
+ ]
1657
+ ]
1658
+ }
1659
+ }
1660
+ async with httpx.AsyncClient(timeout=15.0) as client:
1661
+ await client.post(url, json=payload, headers=self._proxy_headers())
1662
+
1663
+ except Exception as ex:
1664
+ logger.error(f"Error processing payment photo: {ex}")
1665
+ await self.send_message(chat_id, f"❌ Terjadi kesalahan saat membaca kuitansi: {ex}")
1666
+ return {"status": "success"}
1667
+
1668
+ # --- HANDLE SEMANTIC INSTRUCTION (Founder chatting) ---
1669
+ else:
1670
+ if str(chat_id) == str(self.admin_chat_id) and text:
1671
+ await self.send_message(chat_id, "⏳ *CEO Agent sedang memproses instruksi Anda...*")
1672
+ # Run in background to avoid Telegram Webhook timeout
1673
+ asyncio.create_task(self.process_semantic_instruction(text))
1674
+ return {"status": "success"}
1675
+
1676
+ except Exception as e:
1677
+ logger.error(f"❌ Webhook Error: {e}")
1678
+ try:
1679
+ if self.admin_chat_id:
1680
+ await self.send_message(
1681
+ self.admin_chat_id,
1682
+ f"⚠️ *Sistem Bot Terkendala:*\n`{str(e)}`"
1683
+ )
1684
+ except Exception as send_err:
1685
+ logger.error(f"Failed to send exception alert to admin: {send_err}")
1686
+ return {"status": "error", "details": str(e)}
1687
+
1688
+ return {"status": "ignored"}
app/services/whatsapp/community_hunter.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Community Hunter Service — Proactive Group Engagement Logic.
2
+
3
+ Handles the 'Soft-Selling' flow for talent recruitment in WhatsApp Groups:
4
+ 1. Detects new messages/members in groups.
5
+ 2. Initiates natural private chat (Intro).
6
+ 3. Transitions to career coaching & Briga.id talent onboarding.
7
+ """
8
+
9
+ from loguru import logger
10
+ from typing import Dict, Any
11
+ from app.services.whatsapp_service import whatsapp_bot
12
+ from app.services.ai_service import ai_orchestrator # Assume this exists for Gemini processing
13
+
14
+ class CommunityHunterService:
15
+ def __init__(self):
16
+ self.engagement_state = {} # In-memory state tracking (Number -> Flow Step)
17
+
18
+ async def handle_group_event(self, event_data: Dict[str, Any]):
19
+ """Triggered when someone joins a group or sends a relevant keyword."""
20
+ group_jid = event_data.get("group_jid")
21
+ sender_number = event_data.get("sender_number")
22
+ sender_name = event_data.get("sender_name", "Kak")
23
+
24
+ # Logic: Only initiate if we haven't talked to them recently
25
+ if sender_number not in self.engagement_state:
26
+ logger.info(f"[Hunter] New lead detected in group: {sender_name} ({sender_number})")
27
+ await self.initiate_intro(sender_number, sender_name)
28
+
29
+ async def initiate_intro(self, number: str, name: str):
30
+ """Phase 1: Natural Introduction (Private Message)."""
31
+ intro_text = (
32
+ f"Halo {name}, salam kenal ya! Saya lihat tadi di grup komunitas. "
33
+ f"Senang bisa satu grup di sana. Saya lagi riset kecil-kecilan nih "
34
+ f"tentang perkembangan karir teman-teman di bidang Green Jobs. "
35
+ f"Boleh ngobrol sebentar?"
36
+ )
37
+ await whatsapp_bot.send_text(number, intro_text)
38
+ self.engagement_state[number] = "INTRO_SENT"
39
+
40
+ async def handle_user_reply(self, number: str, message: str):
41
+ """Phase 2: Transition from small talk to Career Coaching, Recruitment, or CSR."""
42
+ state = self.engagement_state.get(number)
43
+
44
+ # Analyze intent using AI (Talent vs Recruiter vs Collaboration vs General)
45
+ intent_data = await ai_orchestrator.classify_lead_intent(message)
46
+ intent = intent_data.get("intent") # "talent", "recruiter", "collaboration", "general"
47
+
48
+ if intent == "recruiter":
49
+ await self.handle_recruiter_lead(number, message, intent_data)
50
+ elif intent == "collaboration":
51
+ await self.handle_collab_lead(number, message, intent_data)
52
+ elif state == "INTRO_SENT":
53
+ # Continue as Career Coach for Talents
54
+ ai_reply = await ai_orchestrator.generate_coaching_reply(message)
55
+ await whatsapp_bot.send_text(number, ai_reply)
56
+ self.engagement_state[number] = "COACHING_ACTIVE"
57
+ elif state == "COACHING_ACTIVE":
58
+ await self.pitch_briga_platform(number)
59
+
60
+ async def handle_recruiter_lead(self, number: str, message: str, data: Dict[str, Any]):
61
+ """Handles potential employers/recruiters and notifies the Board."""
62
+ await whatsapp_bot.send_text(number,
63
+ "Wah, menarik sekali! Briga.id memang memiliki talent pool khusus di bidang sustainability. "
64
+ "Boleh saya minta detail kebutuhan talent-nya? Akan segera saya teruskan ke tim Board kami."
65
+ )
66
+ await self.notify_board("RECRUITER_LEAD", number, message)
67
+
68
+ async def handle_collab_lead(self, number: str, message: str, data: Dict[str, Any]):
69
+ """Handles CSR/Sustainability campaign leads and notifies the Board."""
70
+ await whatsapp_bot.send_text(number,
71
+ "Kolaborasi CSR/Sustainability Campaign ya? Ini sangat sejalan dengan visi Briga.id. "
72
+ "Saya akan sampaikan usulan ini ke Board untuk segera ditindaklanjuti. "
73
+ "Mohon tunggu sebentar ya."
74
+ )
75
+ await self.notify_board("COLLAB_LEAD", number, message)
76
+
77
+ async def notify_board(self, lead_type: str, contact: str, summary: str):
78
+ """Sends a notification to the Board WhatsApp Group for confirmation."""
79
+ # Replace with your actual Board Group JID
80
+ board_group_jid = "BOARD_OFFICE@g.us"
81
+
82
+ notification = (
83
+ f"🔔 *NEW BUSINESS LEAD ({lead_type})*\n\n"
84
+ f"👤 *Kontak:* wa.me/{contact}\n"
85
+ f"📝 *Ringkasan:* {summary[:150]}...\n\n"
86
+ f"Mohon konfirmasi di Command Center untuk instruksi selanjutnya."
87
+ )
88
+ await whatsapp_bot.send_group_message(board_group_jid, notification)
89
+
90
+ async def pitch_briga_platform(self, number: str):
91
+ pitch_text = (
92
+ "Btw, setelah ngobrol, saya rasa kamu punya potensi besar di ekosistem Green Talent. "
93
+ "Coba deh mampir ke Briga.id, di sana kita bantu matchmaking ke perusahaan yang "
94
+ "butuh banget skill kayak kamu. "
95
+ "Bisa daftar di sini ya (gratis): https://briga.id/talent/register"
96
+ )
97
+ await whatsapp_bot.send_text(number, pitch_text)
98
+ self.engagement_state[number] = "PITCHED"
99
+
100
+ hunter_service = CommunityHunterService()
app/services/whatsapp/flow_handler.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Flow Handler for WhatsApp — Briga.id.
2
+
3
+ Manages the conversational state machine for the WhatsApp bot.
4
+ Ensures a smooth onboarding experience and interactive career coaching.
5
+ """
6
+
7
+ from app.services.whatsapp_service import whatsapp_bot
8
+ from app.services.ai_service import call_gemini_tier
9
+ from app.services.whatsapp.personas import get_bram_persona
10
+ from app.services.job_service import get_job_postings
11
+ from app.utils.cv_parser import cv_parser
12
+ from sqlalchemy.ext.asyncio import AsyncSession
13
+ from sqlalchemy import select, func
14
+ from app.models.system import WhatsAppSession
15
+ from app.models.talent import Talent
16
+ from loguru import logger
17
+ from typing import Optional, Dict, Any
18
+ import json
19
+ import re
20
+
21
+ class WhatsAppFlowHandler:
22
+ def __init__(self, db: AsyncSession):
23
+ self.db = db
24
+
25
+ async def handle_message(self, sender: str, message: str, media_info: Optional[Dict[str, Any]] = None):
26
+ """Main entry point for processing incoming WhatsApp messages."""
27
+ # Clean the sender phone number
28
+ phone = sender.split("@")[0]
29
+
30
+ # 1. Get or Create Session
31
+ session = await self.get_session(phone)
32
+
33
+ # 2. State Machine Logic
34
+ try:
35
+ # 2a. Handle Media (CV Upload)
36
+ if media_info and media_info["type"] == "document":
37
+ # Check for CV-like file names or mimetypes
38
+ filename = media_info.get("title", "").lower()
39
+ mimetype = media_info.get("mimetype", "").lower()
40
+ if "pdf" in mimetype or "word" in mimetype or any(x in filename for x in ["cv", "resume", "biodata", "curriculum"]):
41
+ return await self.handle_cv_upload(session, media_info)
42
+
43
+ # 2b. Check for global commands/intents first if in IDLE state
44
+ if session.state == "IDLE":
45
+ if any(word in message.lower() for word in ["cari kerja", "lowongan", "job", "loker"]):
46
+ return await self.handle_job_search(session)
47
+
48
+ # 2c. Process based on current state
49
+ if session.state == "START":
50
+ return await self.handle_start(session, message)
51
+ elif session.state == "ONBOARDING_NAME":
52
+ return await self.handle_onboarding_name(session, message)
53
+ elif session.state == "ONBOARDING_EMAIL":
54
+ return await self.handle_onboarding_email(session, message)
55
+
56
+ # Default: Chat with AI (IDLE state or unknown)
57
+ return await self.handle_chat(session, message)
58
+ except Exception as e:
59
+ logger.error(f"[WhatsApp Flow] Error: {e}")
60
+ await whatsapp_bot.send_text(phone, "Duh, maaf Kak, sepertinya Bram sedang sedikit pusing. Boleh coba lagi sebentar lagi?")
61
+
62
+ async def handle_cv_upload(self, session: WhatsAppSession, media_info: Dict[str, Any]):
63
+ """Acknowledges CV upload and initiates processing."""
64
+ filename = media_info.get("title", "CV")
65
+ message_id = media_info.get("message_id")
66
+ instance = media_info.get("instance")
67
+
68
+ 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!")
69
+
70
+ # Download the file bytes
71
+ file_bytes = await whatsapp_bot.download_media(message_id, instance)
72
+ if not file_bytes:
73
+ await whatsapp_bot.send_text(session.phone, "Aduh Kak, sepertinya Bram gagal mendownload file CV nya. Bisa coba kirim ulang?")
74
+ return
75
+
76
+ # 1. Convert PDF to Markdown & Extract Metadata
77
+ result = await cv_parser.analyze_cv(file_bytes, filename)
78
+
79
+ if "error" in result:
80
+ await whatsapp_bot.send_text(session.phone, f"Maaf Kak, Bram gagal menganalisis CV nya: {result['error']}")
81
+ return
82
+
83
+ metadata = result["metadata"]
84
+ score = metadata.get("green_readiness_score", 0)
85
+ feedback = metadata.get("green_readiness_feedback", "CV Kakak sudah Bram terima!")
86
+
87
+ # Save metadata to session context for later registration
88
+ ctx = session.context or {}
89
+ ctx["cv_metadata"] = metadata
90
+ session.context = ctx
91
+ await self.db.commit()
92
+
93
+ # 2. Build Response
94
+ response = f"✨ *Analisis AI Bram Selesai!* ✨\n\n"
95
+ response += f"👤 Nama: {metadata.get('nama', '-')}\n"
96
+ response += f"🎓 Edukasi: {metadata.get('universitas', '-')}\n"
97
+ response += f"📈 Skor Kesiapan Hijau: *{score}/100*\n\n"
98
+ response += f"💡 *Feedback Bram:* \n_{feedback}_\n\n"
99
+
100
+ # Ask for confirmation to register
101
+ session.state = "CONFIRM_REGISTRATION"
102
+ await self.db.commit()
103
+ 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."
104
+
105
+ await whatsapp_bot.send_text(session.phone, response)
106
+ logger.info(f"[WhatsApp Flow] CV Analysis complete for {session.phone}, score: {score}")
107
+
108
+ async def get_session(self, phone: str) -> WhatsAppSession:
109
+ """Retrieves an existing session or creates a new one for the phone number."""
110
+ result = await self.db.execute(select(WhatsAppSession).where(WhatsAppSession.phone == phone))
111
+ session = result.scalar_one_or_none()
112
+ if not session:
113
+ session = WhatsAppSession(phone=phone, state="START")
114
+ self.db.add(session)
115
+ await self.db.commit()
116
+ await self.db.refresh(session)
117
+ return session
118
+
119
+ async def handle_start(self, session: WhatsAppSession, message: str):
120
+ """Initial contact: Check if user exists or start onboarding."""
121
+ talent = await self.get_talent_by_phone(session.phone)
122
+ if talent:
123
+ session.state = "IDLE"
124
+ # Update context with talent name if possible
125
+ session.context = {"name": talent.name}
126
+ await self.db.commit()
127
+ response = f"Halo Kak {talent.name}! Senang melihat Kakak kembali di Briga.id. Ada yang bisa Bram bantu hari ini?"
128
+ await whatsapp_bot.send_text(session.phone, response)
129
+ else:
130
+ session.state = "ONBOARDING_NAME"
131
+ await self.db.commit()
132
+ 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)"
133
+ await whatsapp_bot.send_text(session.phone, response)
134
+
135
+ async def handle_onboarding_name(self, session: WhatsAppSession, message: str):
136
+ """Saves name and asks for email."""
137
+ session.context = {"name": message.strip()}
138
+ session.state = "ONBOARDING_EMAIL"
139
+ await self.db.commit()
140
+ response = f"Salam kenal, Kak {message.strip()}! Sekarang, boleh Bram minta alamat email Kakak yang aktif? Ini penting untuk sinkronisasi akun Kakak nanti."
141
+ await whatsapp_bot.send_text(session.phone, response)
142
+
143
+ async def handle_onboarding_email(self, session: WhatsAppSession, message: str):
144
+ """Saves email and finishes onboarding."""
145
+ email = message.strip().lower()
146
+ if not "@" in email or not "." in email:
147
+ await whatsapp_bot.send_text(session.phone, "Hmm, format emailnya sepertinya kurang tepat Kak. Boleh kirim ulang emailnya?")
148
+ return
149
+
150
+ result = await self.db.execute(select(Talent).where(func.lower(Talent.email) == email))
151
+ existing_talent = result.scalar_one_or_none()
152
+
153
+ if existing_talent:
154
+ existing_talent.phone = session.phone
155
+ session.state = "IDLE"
156
+ session.context = {"name": existing_talent.name, "email": email}
157
+ await self.db.commit()
158
+ 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!"
159
+ else:
160
+ ctx = session.context or {}
161
+ ctx["email"] = email
162
+ session.context = ctx
163
+ session.state = "IDLE"
164
+ await self.db.commit()
165
+ 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?'"
166
+
167
+ await whatsapp_bot.send_text(session.phone, response)
168
+
169
+ async def handle_job_search(self, session: WhatsAppSession):
170
+ """Fetches and displays active job postings."""
171
+ await whatsapp_bot.send_text(session.phone, "Siap Kak! Bram carikan lowongan kerja hijau terbaru buat Kakak ya... Tunggu sebentar.")
172
+
173
+ jobs_res = await get_job_postings(self.db, page=1, limit=5)
174
+ if not jobs_res.get("success") or not jobs_res.get("data"):
175
+ await whatsapp_bot.send_text(session.phone, "Aduh, sepertinya saat ini belum ada lowongan baru yang tersedia. Coba tanya lagi besok ya Kak!")
176
+ return
177
+
178
+ response = "Berikut adalah beberapa lowongan kerja hijau terbaru di Briga.id:\n\n"
179
+ for i, job in enumerate(jobs_res["data"], 1):
180
+ response += f"{i}. *{job['title']}*\n"
181
+ response += f"📍 {job['location']}\n"
182
+ response += f"💰 {job['salary_range']}\n"
183
+ response += f"🔗 briga.id/job/{job['job_id']}\n\n"
184
+
185
+ response += "Kakak bisa klik link di atas untuk detail dan melamar langsung ya!"
186
+ await whatsapp_bot.send_text(session.phone, response)
187
+
188
+ async def handle_chat(self, session: WhatsAppSession, message: str):
189
+ """General AI conversation using the Bram Career Coach persona."""
190
+ # Handle the special registration command
191
+ if session.state == "CONFIRM_REGISTRATION" and message.strip().upper() == "DAFTAR":
192
+ return await self.generate_registration_link(session)
193
+
194
+ persona = get_bram_persona("COACH")
195
+ if session.context and "name" in session.context:
196
+ persona += f"\n\nUser yang sedang berbicara dengan Anda bernama {session.context['name']}."
197
+
198
+ response, _ = await call_gemini_tier(
199
+ prompt=message,
200
+ system_instruction=persona,
201
+ tier="MEDIUM"
202
+ )
203
+
204
+ if not response:
205
+ response = "Aduh, maaf Kak, sinyal Bram lagi agak keganggu. Boleh tanya sekali lagi?"
206
+
207
+ await whatsapp_bot.send_text(session.phone, response)
208
+
209
+ async def generate_registration_link(self, session: WhatsAppSession):
210
+ """Generates a unique registration link and sends it to the user."""
211
+ import secrets
212
+ import base64
213
+
214
+ # Generate a temporary token for registration
215
+ temp_token = secrets.token_hex(16)
216
+ ctx = session.context or {}
217
+ ctx["registration_token"] = temp_token
218
+ session.context = ctx
219
+ session.state = "AWAITING_CONFIRMATION"
220
+ await self.db.commit()
221
+
222
+ # Build the link (encoded with base64 for simplicity in the URL)
223
+ # In a real app, this would be a frontend route that handles the registration
224
+ metadata = ctx.get("cv_metadata", {})
225
+ payload = {
226
+ "token": temp_token,
227
+ "email": ctx.get("email"),
228
+ "name": ctx.get("name") or metadata.get("nama"),
229
+ "phone": session.phone
230
+ }
231
+ encoded_payload = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
232
+
233
+ # Production URL for registration
234
+ reg_link = f"https://briga.id/register-confirm?data={encoded_payload}"
235
+
236
+ 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! 🚀"
237
+ await whatsapp_bot.send_text(session.phone, response)
238
+
239
+ async def get_talent_by_phone(self, phone: str):
240
+ result = await self.db.execute(select(Talent).where(Talent.phone == phone))
241
+ return result.scalar_one_or_none()
app/services/whatsapp/personas.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persona Logic for Bramantya (Bram) AI.
2
+
3
+ Defines the system prompts for different interaction tiers:
4
+ 1. EXECUTIVE (Board)
5
+ 2. SCOUT (Recruiters)
6
+ 3. COACH (Talents)
7
+ """
8
+
9
+ PERSONA_PROMPTS = {
10
+ "EXECUTIVE": (
11
+ "Nama Anda adalah Bramantya (Bram), Executive Assistant untuk Board Briga.id. "
12
+ "Tugas Anda adalah memberikan data akurat, ringkas, dan menjalankan perintah administratif. "
13
+ "Gunakan bahasa formal Indonesia. Prioritaskan keamanan data dan efisiensi operasional."
14
+ ),
15
+ "SCOUT": (
16
+ "Nama Anda adalah Bramantya (Bram), Recruitment Scout dari Briga.id. "
17
+ "Tugas Anda adalah membantu Rekruter menemukan talenta terbaik. "
18
+ "Fokus pada metrik kompetensi, ketersediaan kandidat, dan jadwal interview. "
19
+ "Gunakan bahasa profesional yang membantu."
20
+ ),
21
+ "COACH": (
22
+ "Nama Anda adalah Bramantya (Bram), Career Coach dari Briga.id. "
23
+ "Gunakan gaya bahasa 'Kak' yang ramah, hangat, dan inspiratif. "
24
+ "Tugas Anda adalah membimbing talenta untuk mengembangkan karir di bidang Green Jobs. "
25
+ "Jangan kaku, berikan tips praktis tentang SKKNI dan sertifikasi."
26
+ )
27
+ }
28
+
29
+ def get_bram_persona(sender_role: str) -> str:
30
+ """Returns the system prompt based on the sender's role."""
31
+ return PERSONA_PROMPTS.get(sender_role, PERSONA_PROMPTS["COACH"])
app/services/whatsapp_service.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WhatsApp Service — Evolution API Integration for briga.id.
2
+
3
+ Handles instance management, QR code generation, and automated messaging
4
+ for the AI CEO and Support agents.
5
+ """
6
+
7
+ import httpx
8
+ import os
9
+ from loguru import logger
10
+ from typing import Optional, Dict, Any
11
+ from app.config import settings
12
+
13
+ class WhatsAppService:
14
+ def __init__(self):
15
+ self.api_url = os.getenv("WHATSAPP_API_URL") # e.g. https://briga-wa.up.railway.app
16
+ self.api_key = os.getenv("WHATSAPP_API_KEY")
17
+ self.instance_name = "CEO_OFFICE"
18
+
19
+ async def get_status(self) -> Dict[str, Any]:
20
+ """Checks if the WhatsApp instance is connected or needs QR."""
21
+ if not self.api_url:
22
+ return {"status": "not_configured", "message": "WHATSAPP_API_URL missing"}
23
+
24
+ url = f"{self.api_url}/instance/connectionState/{self.instance_name}"
25
+ headers = {"apikey": self.api_key}
26
+
27
+ try:
28
+ async with httpx.AsyncClient() as client:
29
+ resp = await client.get(url, headers=headers)
30
+ if resp.status_code == 404:
31
+ # Instance doesn't exist yet, try creating it
32
+ await self.create_instance()
33
+ return {"status": "creating", "message": "Instance is being created..."}
34
+
35
+ if resp.status_code >= 500:
36
+ # Potential server issue or instance disconnected/down
37
+ return {"status": "DISCONNECTED", "message": "Evolution API Error (500)"}
38
+
39
+ return resp.json()
40
+ except Exception as e:
41
+ return {"status": "error", "message": str(e)}
42
+
43
+ async def create_instance(self):
44
+ """Initializes a new WhatsApp instance on the gateway."""
45
+ url = f"{self.api_url}/instance/create"
46
+ payload = {
47
+ "instanceName": self.instance_name,
48
+ "token": self.api_key,
49
+ "qrcode": True
50
+ }
51
+ headers = {"apikey": self.api_key}
52
+
53
+ async with httpx.AsyncClient() as client:
54
+ resp = await client.post(url, json=payload, headers=headers)
55
+ return resp.json()
56
+
57
+ async def get_qr_base64(self) -> Optional[str]:
58
+ """Retrieves the QR Code. If instance doesn't exist, creates it first."""
59
+ url = f"{self.api_url}/instance/connect/{self.instance_name}"
60
+ headers = {"apikey": self.api_key}
61
+
62
+ try:
63
+ async with httpx.AsyncClient(timeout=25.0) as client:
64
+ resp = await client.get(url, headers=headers)
65
+
66
+ # Case 1: Instance missing, create it
67
+ if resp.status_code == 404:
68
+ logger.info(f"[WhatsApp] Instance {self.instance_name} not found. Creating...")
69
+ create_res = await self.create_instance()
70
+ # Evolution API often returns the QR in the creation response
71
+ # Format: { "qrcode": { "base64": "..." } }
72
+ qr_data = create_res.get("qrcode", {})
73
+ if isinstance(qr_data, dict) and qr_data.get("base64"):
74
+ return qr_data.get("base64")
75
+
76
+ # If not in create response, wait a bit and try connect URL again
77
+ import asyncio
78
+ await asyncio.sleep(3)
79
+ resp = await client.get(url, headers=headers)
80
+
81
+ data = resp.json()
82
+ if resp.status_code == 200:
83
+ return data.get("base64")
84
+
85
+ logger.warning(f"[WhatsApp] QR Fetch failed (Code {resp.status_code}): {data}")
86
+ except Exception as e:
87
+ logger.error(f"[WhatsApp] QR Fetch Error: {e}")
88
+ return None
89
+
90
+ async def logout_instance(self) -> bool:
91
+ """Logs out the session. If it fails, it tries to force delete the instance."""
92
+ url = f"{self.api_url}/instance/logout/{self.instance_name}"
93
+ headers = {"apikey": self.api_key}
94
+
95
+ try:
96
+ async with httpx.AsyncClient(timeout=10.0) as client:
97
+ resp = await client.delete(url, headers=headers)
98
+ if resp.status_code == 200:
99
+ return True
100
+
101
+ # If logout fails (maybe already logged out), try deleting instance entirely
102
+ return await self.delete_instance()
103
+ except Exception as e:
104
+ logger.error(f"[WhatsApp] Logout failed: {e}")
105
+ return await self.delete_instance()
106
+
107
+ async def delete_instance(self) -> bool:
108
+ """Force deletes the instance entirely from Evolution API."""
109
+ url = f"{self.api_url}/instance/delete/{self.instance_name}"
110
+ headers = {"apikey": self.api_key}
111
+ try:
112
+ async with httpx.AsyncClient(timeout=10.0) as client:
113
+ resp = await client.delete(url, headers=headers)
114
+ logger.info(f"[WhatsApp] Instance delete attempt: {resp.status_code}")
115
+ return resp.status_code == 200
116
+ except Exception as e:
117
+ logger.error(f"[WhatsApp] Delete instance failed: {e}")
118
+ return False
119
+
120
+ async def download_media(self, message_id: str, instance_name: Optional[str] = None) -> Optional[bytes]:
121
+ """Downloads media content (base64) from a specific message ID."""
122
+ inst = instance_name or self.instance_name
123
+ url = f"{self.api_url}/chat/getBase64FromMedia/{inst}"
124
+ payload = {"message": {"key": {"id": message_id}}, "convertToMp4": False}
125
+ headers = {"apikey": self.api_key}
126
+
127
+ import base64
128
+ try:
129
+ async with httpx.AsyncClient(timeout=30.0) as client:
130
+ resp = await client.post(url, json=payload, headers=headers)
131
+ if resp.status_code == 200:
132
+ data = resp.json()
133
+ # Evolution API returns { "base64": "..." } or directly binary if configured differently
134
+ b64_data = data.get("base64")
135
+ if b64_data:
136
+ # Handle potential data URI prefix
137
+ if "," in b64_data:
138
+ b64_data = b64_data.split(",")[1]
139
+ return base64.b64decode(b64_data)
140
+ except Exception as e:
141
+ logger.error(f"[WhatsApp] Media download failed for {message_id}: {e}")
142
+ return None
143
+
144
+ async def send_text(self, number: str, text: str):
145
+ """Sends a text message with human-like typing simulation."""
146
+ url = f"{self.api_url}/message/sendText/{self.instance_name}"
147
+
148
+ # Calculate typing delay: ~0.05s per character, min 1s, max 7s
149
+ typing_time = min(max(len(text) * 0.05, 1), 7) * 1000 # in ms
150
+
151
+ payload = {
152
+ "number": number,
153
+ "options": {
154
+ "delay": int(typing_time),
155
+ "presence": "composing", # Show "Typing..." status
156
+ "linkPreview": True
157
+ },
158
+ "textMessage": {"text": text}
159
+ }
160
+ headers = {"apikey": self.api_key}
161
+
162
+ try:
163
+ async with httpx.AsyncClient() as client:
164
+ # Add a small random pre-delay (thinking time)
165
+ import random
166
+ import asyncio
167
+ await asyncio.sleep(random.uniform(0.5, 2.0))
168
+
169
+ resp = await client.post(url, json=payload, headers=headers)
170
+ return resp.json()
171
+ except Exception as e:
172
+ logger.error(f"[WhatsApp] Send failed: {e}")
173
+ return {"status": "error"}
174
+
175
+ async def send_group_message(self, group_jid: str, text: str):
176
+ """Broadcasts a strategic update to a WhatsApp Group."""
177
+ url = f"{self.api_url}/message/sendText/{self.instance_name}"
178
+ payload = {
179
+ "number": group_jid, # Group JID looks like: 123456789@g.us
180
+ "textMessage": {"text": text}
181
+ }
182
+ headers = {"apikey": self.api_key}
183
+
184
+ async with httpx.AsyncClient() as client:
185
+ resp = await client.post(url, json=payload, headers=headers)
186
+ return resp.json()
187
+
188
+ # Singleton instance
189
+ whatsapp_bot = WhatsAppService()