ii-assistent/hunter/web.py

763 lines
25 KiB
Python

import io
import json
import os
import sqlite3
import threading
from datetime import datetime, timedelta, timezone
from functools import wraps
from flask import (
Blueprint,
abort,
current_app,
flash,
g,
redirect,
render_template,
request,
send_file,
session,
url_for,
)
from werkzeug.security import check_password_hash, generate_password_hash
from .analysis import (
CATEGORIES,
CRITERIA,
FIELDS,
analyze_materials,
answer_question,
business_case,
)
from .db import get_db, now, setting
from .monitor import collect
from .network import public_url
bp = Blueprint("web", __name__)
STATES = ("new", "reviewing", "pilot_status", "implementing", "rejected")
def require(*roles):
def decorate(function):
@wraps(function)
def checked(*args, **kwargs):
if not g.user or g.user["role"] not in roles:
abort(403)
return function(*args, **kwargs)
return checked
return decorate
def rows(sql, args=()):
return get_db().execute(sql, args).fetchall()
def one(sql, args=()):
result = get_db().execute(sql, args).fetchone()
if result is None:
abort(404)
return result
def mutate(sql, args=()):
with get_db() as db:
return db.execute(sql, args)
def title_for(signal):
return signal["translated_title"] or signal["title"]
@bp.app_context_processor
def helpers():
return dict(
categories=CATEGORIES,
states=STATES,
fields=FIELDS,
criteria=CRITERIA,
title_for=title_for,
json_load=json.loads,
day=lambda value: value[:10] if value else g.t("date_unknown"),
)
@bp.get("/healthz")
def health():
get_db().execute("SELECT 1").fetchone()
return {"status": "ok"}
@bp.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form.get("email", "").strip().lower()[:254]
user = get_db().execute("SELECT * FROM users WHERE email=?", (email,)).fetchone()
if user and check_password_hash(user["password"], request.form.get("password", "")[:500]):
lang = session.get("lang", "ru")
session.clear()
session["lang"] = lang
session["user_id"] = user["id"]
session.permanent = True
return redirect(url_for("web.dashboard"))
flash(g.t("auth_error"), "error")
return render_template("auth.html", page="login")
@bp.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
email = request.form.get("email", "").strip().lower()
password = request.form.get("password", "")
try:
if not 3 <= len(email) <= 254 or "@" not in email or not 12 <= len(password) <= 500:
raise ValueError("invalid_registration")
mutate(
"INSERT INTO users(email,password,created) VALUES(?,?,?)",
(email, generate_password_hash(password), now()),
)
return redirect(url_for("web.login"))
except (ValueError, sqlite3.IntegrityError):
flash(g.t("register_error"), "error")
return render_template("auth.html", page="register")
@bp.post("/logout")
def logout():
session.clear()
return redirect(url_for("web.login"))
@bp.post("/language")
def language():
code = request.form.get("lang", "")
if code not in ("ru", "kk", "en"):
abort(400)
session["lang"] = code
return redirect(url_for("web.dashboard" if g.user else "web.login"))
def period_start(default=30):
try:
days = int(request.args.get("days", default))
except ValueError:
abort(400)
if days not in (1, 7, 30, 90):
abort(400)
return (datetime.now(timezone.utc) - timedelta(days=days)).isoformat(timespec="seconds")
def signals_query(limit=100):
query = request.args.get("q", "").strip()[:200].casefold()
filters = [
request.args.get(key, "")[:100]
for key in ("category", "country", "stage", "potential", "competition")
]
since = period_start() if request.args.get("days") else ""
return rows(
"""SELECT s.*,src.name source_name FROM signals s JOIN sources src ON s.source_id=src.id
WHERE CASEFOLD(s.title||s.summary||coalesce(s.translated_title,'')||coalesce(s.translated_summary,'')||s.category) LIKE ?
AND (?='' OR s.category=?) AND (?='' OR s.country=?) AND (?='' OR s.stage=?)
AND (?='' OR s.potential=?) AND (?='' OR s.competition=?) AND (?='' OR s.published>=?)
ORDER BY coalesce(s.published,s.collected) DESC LIMIT ?""",
(
"%" + query + "%",
*(value for val in filters for value in (val, val)),
since,
since,
limit,
),
)
def favorite_ids(kind):
return {
row[0]
for row in rows(
"SELECT item_id FROM favorites WHERE user_id=? AND kind=?", (g.user["id"], kind)
)
}
def track(kind, item_id):
mutate(
"INSERT INTO history VALUES(?,?,?,?) ON CONFLICT(user_id,kind,item_id) DO UPDATE SET viewed=excluded.viewed",
(g.user["id"], kind, item_id, now()),
)
@bp.get("/")
def dashboard():
end = datetime.now(timezone.utc)
start = (end - timedelta(days=7)).isoformat(timespec="seconds")
previous = (end - timedelta(days=14)).isoformat(timespec="seconds")
total = one("SELECT count(*) n FROM signals")["n"]
analyzed = one("SELECT count(*) n FROM signals WHERE analyzed_at IS NOT NULL")["n"]
recent = one("SELECT count(*) n FROM signals WHERE published>=?", (start,))["n"]
prior = one(
"SELECT count(*) n FROM signals WHERE published>=? AND published<?", (previous, start)
)["n"]
new_trends = one(
"SELECT count(*) n FROM (SELECT category FROM signals GROUP BY category HAVING min(published)>=?)",
(start,),
)["n"]
directions = one("SELECT count(DISTINCT category) n FROM signals")["n"]
ideas_count = one("SELECT count(*) n FROM ideas")["n"]
top = rows("SELECT * FROM ideas WHERE created>=? ORDER BY mock, score DESC LIMIT 5", (start,))
grouped = rows("SELECT category,count(*) n FROM signals GROUP BY category ORDER BY n DESC")
news = rows(
"SELECT s.*,src.name source_name FROM signals s JOIN sources src ON s.source_id=src.id ORDER BY coalesce(s.published,s.collected) DESC LIMIT 6"
)
running = rows("SELECT id FROM runs WHERE status='running'")
return render_template(
"dashboard.html",
page="home",
total=total,
analyzed=analyzed,
recent=recent,
prior=prior,
new_trends=new_trends,
directions=directions,
ideas_count=ideas_count,
top=top,
grouped=grouped,
news=news,
running=running,
)
@bp.get("/trends")
def trends():
return render_template(
"catalog.html",
page="trends",
signals=signals_query(),
countries=rows("SELECT DISTINCT country FROM signals ORDER BY country"),
grouped=rows("SELECT category,count(*) n FROM signals GROUP BY category ORDER BY n DESC"),
)
@bp.get("/trend/<category>")
def trend(category):
if category not in CATEGORIES:
abort(404)
category_index = CATEGORIES.index(category) + 1
track("trend", category_index)
material = rows(
"SELECT s.*,src.name source_name FROM signals s JOIN sources src ON src.id=s.source_id WHERE s.category=? ORDER BY coalesce(s.published,s.collected) DESC LIMIT 100",
(category,),
)
months = rows(
"SELECT substr(published,1,7) label,count(*) n FROM signals WHERE category=? AND published IS NOT NULL GROUP BY label ORDER BY label",
(category,),
)
return render_template(
"trend.html",
page="trends",
category=category,
category_index=category_index,
signals=material,
months=months,
following=category_index in favorite_ids("trend"),
related=rows(
"SELECT * FROM ideas WHERE category=? ORDER BY mock,score DESC LIMIT 5", (category,)
),
)
@bp.get("/ideas")
def ideas():
query = request.args.get("q", "").strip()[:200]
category = request.args.get("category", "")[:100]
result = rows(
"SELECT * FROM ideas WHERE (title LIKE ? OR data LIKE ?) AND (?='' OR category=?) ORDER BY mock,score DESC,created DESC LIMIT 100",
("%" + query + "%", "%" + query + "%", category, category),
)
return render_template("ideas.html", page="ideas", ideas=result)
@bp.get("/idea/<int:item_id>")
def idea(item_id):
item = one("SELECT * FROM ideas WHERE id=?", (item_id,))
data = json.loads(item["data"])
track("idea", item_id)
signals = rows(
"SELECT s.*,src.name source_name FROM signals s JOIN sources src ON s.source_id=src.id WHERE s.id IN (SELECT value FROM json_each(?))",
(json.dumps(data["signal_ids"]),),
)
state = rows(
"SELECT status FROM idea_states WHERE user_id=? AND idea_id=?", (g.user["id"], item_id)
)
case = rows("SELECT * FROM cases WHERE user_id=? AND idea_id=?", (g.user["id"], item_id))
return render_template(
"idea.html",
page="ideas",
idea=item,
data=data,
signals=signals,
saved=item_id in favorite_ids("idea"),
state=state[0][0] if state else "new",
case=case[0] if case else None,
weights=json.loads(setting("weights")),
comments=rows(
"SELECT c.*,u.email FROM comments c JOIN users u ON c.user_id=u.id WHERE c.idea_id=? ORDER BY c.id DESC",
(item_id,),
),
)
@bp.post("/favorite/<kind>/<int:item_id>")
def favorite(kind, item_id):
if kind == "idea":
one("SELECT id FROM ideas WHERE id=?", (item_id,))
target = url_for("web.idea", item_id=item_id)
elif kind == "trend" and 1 <= item_id <= len(CATEGORIES):
target = url_for("web.trend", category=CATEGORIES[item_id - 1])
else:
abort(404)
if item_id in favorite_ids(kind):
mutate(
"DELETE FROM favorites WHERE user_id=? AND kind=? AND item_id=?",
(g.user["id"], kind, item_id),
)
else:
mutate("INSERT INTO favorites VALUES(?,?,?)", (g.user["id"], kind, item_id))
return redirect(target)
@bp.post("/idea/<int:item_id>/state")
def idea_state(item_id):
one("SELECT id FROM ideas WHERE id=?", (item_id,))
status = request.form.get("status")
if status not in STATES:
abort(400)
mutate(
"INSERT INTO idea_states VALUES(?,?,?) ON CONFLICT(user_id,idea_id) DO UPDATE SET status=excluded.status",
(g.user["id"], item_id, status),
)
return redirect(url_for("web.idea", item_id=item_id))
@bp.post("/idea/<int:item_id>/comment")
def comment(item_id):
one("SELECT id FROM ideas WHERE id=?", (item_id,))
body = request.form.get("body", "").strip()
try:
rating = int(request.form.get("rating", "0"))
except ValueError:
abort(400)
if not 1 <= len(body) <= 2000 or not 1 <= rating <= 5:
abort(400)
mutate(
"INSERT INTO comments(user_id,idea_id,body,rating,created) VALUES(?,?,?,?,?)",
(g.user["id"], item_id, body, rating, now()),
)
return redirect(url_for("web.idea", item_id=item_id))
@bp.post("/idea/<int:item_id>/case")
def case(item_id):
item = one("SELECT * FROM ideas WHERE id=?", (item_id,))
try:
result = business_case(item)
mutate(
"INSERT INTO cases VALUES(?,?,?,?,?) ON CONFLICT(user_id,idea_id) DO UPDATE SET body=excluded.body,mock=excluded.mock,created=excluded.created",
(g.user["id"], item_id, result["text"], result["mock"], now()),
)
except Exception:
flash(g.t("failed"), "error")
return redirect(url_for("web.idea", item_id=item_id))
@bp.get("/saved")
def saved():
result = rows(
"SELECT i.* FROM ideas i JOIN favorites f ON f.item_id=i.id AND f.kind='idea' WHERE f.user_id=? ORDER BY i.score DESC",
(g.user["id"],),
)
followed = [CATEGORIES[i - 1] for i in favorite_ids("trend") if 1 <= i <= len(CATEGORIES)]
return render_template("ideas.html", page="favorites", ideas=result, followed=followed)
@bp.get("/history")
def history():
result = rows(
"SELECT i.* FROM ideas i JOIN history h ON h.item_id=i.id AND h.kind='idea' WHERE h.user_id=? ORDER BY h.viewed DESC",
(g.user["id"],),
)
return render_template(
"ideas.html",
page="history",
ideas=result,
followed=[
CATEGORIES[r[0] - 1]
for r in rows(
"SELECT item_id FROM history WHERE user_id=? AND kind='trend' ORDER BY viewed DESC",
(g.user["id"],),
)
if 1 <= r[0] <= len(CATEGORIES)
],
)
@bp.route("/competitors", methods=["GET", "POST"])
def competitors():
if request.method == "POST":
if g.user["role"] not in ("admin", "analyst"):
abort(403)
try:
name = request.form.get("name", "").strip()
if not 1 <= len(name) <= 100:
raise ValueError("invalid_name")
url, _ = public_url(request.form.get("url", ""))
mutate("INSERT INTO companies(name,url) VALUES(?,?)", (name, url))
except (ValueError, OSError, sqlite3.IntegrityError):
flash(g.t("invalid"), "error")
return redirect(url_for("web.competitors"))
return render_template(
"competitors.html",
page="competitors",
companies=rows("SELECT * FROM companies ORDER BY name"),
changes=rows(
"SELECT c.*,p.name,p.url FROM changes c JOIN companies p ON c.company_id=p.id ORDER BY c.id DESC LIMIT 50"
),
)
@bp.route("/sources", methods=["GET", "POST"])
def sources():
if request.method == "POST":
if g.user["role"] != "admin":
abort(403)
try:
name = request.form.get("name", "").strip()
category = request.form.get("category", "")
country = request.form.get("country", "").strip()
if (
not 1 <= len(name) <= 100
or category not in CATEGORIES
or not 1 <= len(country) <= 60
):
raise ValueError("invalid_source")
url, _ = public_url(request.form.get("url", ""))
mutate(
"INSERT INTO sources(name,url,category,country) VALUES(?,?,?,?)",
(name, url, category, country),
)
except (ValueError, OSError, sqlite3.IntegrityError):
flash(g.t("invalid"), "error")
return redirect(url_for("web.sources"))
return render_template(
"sources.html",
page="sources",
sources=rows("SELECT * FROM sources ORDER BY id"),
logs=rows("SELECT * FROM logs ORDER BY id DESC LIMIT 30"),
)
@bp.post("/source/<int:item_id>/toggle")
@require("admin")
def toggle_source(item_id):
one("SELECT id FROM sources WHERE id=?", (item_id,))
mutate("UPDATE sources SET enabled=1-enabled WHERE id=?", (item_id,))
return redirect(url_for("web.sources"))
@bp.post("/refresh")
@require("admin", "analyst")
def refresh():
path = current_app.config["DATABASE"]
def run():
try:
collect(path)
except Exception:
current_app_logger.exception("Collection failed")
current_app_logger = current_app.logger
threading.Thread(target=run, daemon=True).start()
flash(g.t("updated"))
return redirect(url_for("web.dashboard"))
@bp.post("/analyze")
@require("admin", "analyst")
def analyze():
try:
count = analyze_materials(current_app.config["DATABASE"])
flash(g.t("analysis_done") if count else g.t("no_data_answer"))
except Exception:
flash(g.t("failed"), "error")
return redirect(url_for("web.ideas"))
def analytics_data():
since = period_start()
groups = rows(
"SELECT category label,count(*) n FROM signals WHERE published>=? GROUP BY category ORDER BY n DESC",
(since,),
)
months = rows(
"SELECT substr(published,1,7) label,count(*) n FROM signals WHERE published>=? GROUP BY label ORDER BY label",
(since,),
)
geography = rows(
"SELECT country label,count(*) n FROM signals WHERE published>=? GROUP BY country ORDER BY n DESC",
(since,),
)
# Actual observed counts, never extrapolated interest or market share.
start = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat(timespec="seconds")
previous = (datetime.now(timezone.utc) - timedelta(days=60)).isoformat(timespec="seconds")
growth = rows(
"SELECT category label,sum(CASE WHEN published>=? THEN 1 ELSE 0 END) current,sum(CASE WHEN published>=? AND published<? THEN 1 ELSE 0 END) previous FROM signals GROUP BY category ORDER BY current DESC",
(start, previous, start),
)
return groups, months, geography, growth
@bp.get("/analytics")
def analytics():
groups, months, geography, growth = analytics_data()
return render_template(
"analytics.html",
page="analytics",
groups=groups,
months=months,
geography=geography,
growth=growth,
top=rows("SELECT * FROM ideas ORDER BY mock,score DESC LIMIT 10"),
)
@bp.route("/assistant", methods=["GET", "POST"])
def assistant():
if request.method == "POST":
question = request.form.get("question", "").strip()
if not 1 <= len(question) <= 2000:
abort(400)
try:
result = answer_question(current_app.config["DATABASE"], question)
mutate(
"INSERT INTO chats(user_id,question,answer,created) VALUES(?,?,?,?)",
(g.user["id"], question, json.dumps(result, ensure_ascii=False), now()),
)
except Exception:
flash(g.t("failed"), "error")
return redirect(url_for("web.assistant"))
chats = []
for row in rows(
"SELECT * FROM chats WHERE user_id=? ORDER BY id DESC LIMIT 20", (g.user["id"],)
):
item = dict(row)
item["response"] = json.loads(item["answer"])
ids = item["response"]["signal_ids"]
item["sources"] = (
rows(
"SELECT title,url,translated_title FROM signals WHERE id IN (SELECT value FROM json_each(?))",
(json.dumps(ids),),
)
if ids
else []
)
chats.append(item)
return render_template("assistant.html", page="assistant", chats=chats)
@bp.route("/settings", methods=["GET", "POST"])
@require("admin")
def settings():
if request.method == "POST":
try:
interval = int(request.form.get("interval", "6"))
weights = [int(request.form.get(key, "0")) for key in CRITERIA]
if (
not 1 <= interval <= 168
or sum(weights) != 100
or any(w < 0 or w > 100 for w in weights)
):
raise ValueError("invalid_weights")
with get_db() as db:
db.execute("UPDATE settings SET value=? WHERE key='interval'", (str(interval),))
db.execute(
"UPDATE settings SET value=? WHERE key='weights'", (json.dumps(weights),)
)
flash(g.t("saved"))
except ValueError:
flash(g.t("bad_request"), "error")
return redirect(url_for("web.settings"))
return render_template(
"settings.html",
page="settings",
interval=setting("interval"),
weights=json.loads(setting("weights")),
users=rows("SELECT id,email,role FROM users ORDER BY id"),
)
@bp.post("/user/<int:item_id>/role")
@require("admin")
def user_role(item_id):
role = request.form.get("role")
if role not in ("admin", "analyst", "user") or item_id == g.user["id"]:
abort(400)
one("SELECT id FROM users WHERE id=?", (item_id,))
mutate("UPDATE users SET role=? WHERE id=?", (role, item_id))
return redirect(url_for("web.settings"))
@bp.get("/reports")
def reports():
day_start = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat(timespec="seconds")
week_start = (datetime.now(timezone.utc) - timedelta(days=7)).isoformat(timespec="seconds")
month_start = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat(timespec="seconds")
return render_template(
"reports.html",
page="reports",
signals=rows(
"SELECT s.*,src.name source_name FROM signals s JOIN sources src ON s.source_id=src.id WHERE s.published>=? ORDER BY s.published DESC LIMIT 5",
(day_start,),
),
top=rows(
"SELECT * FROM ideas WHERE created>=? ORDER BY mock,score DESC LIMIT 5", (week_start,)
),
groups=rows(
"SELECT category label,count(*) n FROM signals WHERE published>=? GROUP BY category ORDER BY n DESC",
(month_start,),
),
)
@bp.get("/export.xlsx")
def export_excel():
from openpyxl import Workbook
workbook = Workbook()
sheet = workbook.active
sheet.title = "Signals"
sheet.append([g.t(key) for key in ("name", "category", "country", "published", "url")])
for signal in signals_query(limit=5000):
# Prevent spreadsheet formula injection in third-party titles.
sheet.append(
[
safe_cell(value)
for value in (
title_for(signal),
signal["category"],
signal["country"],
signal["published"],
signal["url"],
)
]
)
idea_sheet = workbook.create_sheet("Ideas")
idea_sheet.append([g.t(key) for key in ("name", "category", "score", "hypothesis", "sources")])
for item in rows("SELECT * FROM ideas ORDER BY mock,score DESC"):
data = json.loads(item["data"])
urls = [
r[0]
for r in rows(
"SELECT url FROM signals WHERE id IN (SELECT value FROM json_each(?))",
(json.dumps(data["signal_ids"]),),
)
]
idea_sheet.append(
[
safe_cell(value)
for value in (
item["title"],
item["category"],
item["score"],
g.t("demo") if item["mock"] else g.t("hypothesis"),
"\n".join(urls),
)
]
)
stream = io.BytesIO()
workbook.save(stream)
stream.seek(0)
return send_file(
stream,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
as_attachment=True,
download_name="trend-hunter.xlsx",
)
def safe_cell(value):
if isinstance(value, str) and value.lstrip().startswith(("=", "+", "-", "@")):
return "'" + value
return value
@bp.get("/idea/<int:item_id>/export.pdf")
def export_pdf(item_id):
from xml.sax.saxutils import escape
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
item = one("SELECT * FROM ideas WHERE id=?", (item_id,))
data = json.loads(item["data"])
font = next(
(
path
for path in (
os.getenv("PDF_FONT", ""),
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
)
if path and os.path.isfile(path)
),
None,
)
if not font:
abort(503)
if "Hunter" not in pdfmetrics.getRegisteredFontNames():
pdfmetrics.registerFont(TTFont("Hunter", font))
style = ParagraphStyle(
"body", fontName="Hunter", fontSize=10, leading=16, spaceAfter=10, wordWrap="CJK"
)
stream = io.BytesIO()
content = [
Paragraph(escape(item["title"]), style),
Paragraph(escape(g.t("demo") if item["mock"] else g.t("hypothesis")), style),
Paragraph(escape(g.t("assumptions")), style),
]
for field in FIELDS[1:]:
label = "next_steps" if field == "recommendation" else field
content.extend(
[
Spacer(1, 8),
Paragraph(escape(g.t(label)), style),
Paragraph(escape(data[field]), style),
]
)
ids = data["signal_ids"]
for source in rows(
"SELECT title,url FROM signals WHERE id IN (SELECT value FROM json_each(?))",
(json.dumps(ids),),
):
content.append(Paragraph(escape(source["title"] + " — " + source["url"]), style))
cases = rows("SELECT * FROM cases WHERE user_id=? AND idea_id=?", (g.user["id"], item_id))
if cases:
content.append(Paragraph(escape(g.t("case_title")), style))
content.append(Paragraph(escape(cases[0]["body"]).replace("\n", "<br/>"), style))
SimpleDocTemplate(stream).build(content)
stream.seek(0)
return send_file(
stream, mimetype="application/pdf", as_attachment=True, download_name="business-idea.pdf"
)
@bp.app_errorhandler(400)
@bp.app_errorhandler(403)
@bp.app_errorhandler(404)
@bp.app_errorhandler(413)
@bp.app_errorhandler(500)
@bp.app_errorhandler(503)
def error_page(error):
key = {400: "bad_request", 403: "forbidden", 404: "not_found"}.get(error.code, "failed")
return render_template("error.html", page="home", message=g.t(key)), error.code