last_edit / server /impact_engine.py
Moharek
Deploy Moharek GEO Platform
a74b879
import os
from datetime import datetime, timedelta
from server.db import SessionLocal, Action, ProjectMetric
def fetch_performance_snapshot(job_id: int):
"""Mocks fetching real-time data from Google Search Console API."""
# In production: Use google-api-python-client
# Here we simulate a snapshot
import random
return {
"clicks": random.randint(100, 500),
"impressions": random.randint(1000, 5000),
"avg_position": random.randint(10, 80)
}
def record_initial_metrics(action_id: int):
"""Sets the 'Before' state for an action."""
db = SessionLocal()
try:
action = db.query(Action).filter(Action.id == action_id).first()
if action and not action.initial_metrics:
snapshot = fetch_performance_snapshot(action.job_id)
action.initial_metrics = snapshot
db.commit()
return True
finally:
db.close()
return False
def update_action_impact(action_id: int):
"""Sets the 'After' state and computes growth percentage."""
db = SessionLocal()
try:
action = db.query(Action).filter(Action.id == action_id).first()
if not action or not action.initial_metrics:
return False
current = fetch_performance_snapshot(action.job_id)
# For simulation, we ensure 'After' is better than 'Before'
# in a real system we'd wait days/weeks
if current['clicks'] <= action.initial_metrics['clicks']:
current['clicks'] = int(action.initial_metrics['clicks'] * 1.25)
action.latest_metrics = current
# Calculate impact score (Growth %)
before = action.initial_metrics['clicks']
after = action.latest_metrics['clicks']
if before > 0:
growth = ((after - before) / before) * 100
action.impact_score = int(growth)
db.commit()
return action.impact_score
finally:
db.close()
def get_roi_summary(job_id: int):
"""Calculates estimated Revenue and Leads based on growth."""
# Logic: 1 conversion per 50 clicks, $100 per conversion
db = SessionLocal()
try:
actions = db.query(Action).filter(Action.job_id == job_id, Action.status == 'done').all()
total_growth_clicks = sum([
(a.latest_metrics.get('clicks', 0) - a.initial_metrics.get('clicks', 0))
for a in actions if a.initial_metrics and a.latest_metrics
])
leads = total_growth_clicks // 50
revenue = leads * 100
return {
"growth_clicks": total_growth_clicks,
"est_leads": leads,
"est_revenue_usd": revenue
}
finally:
db.close()