🏗 Фаза 1-4: Архитектура, ядро, проверки, API, генератор отчетов
- scanner/engine.py — Playwright-движок сканирования - scanner/models.py — Pydantic модели - scanner/checks/ — 5 проверок (cookie, privacy, forms, server, external) - api/server.py — FastAPI REST API - reports/generator.py — PDF через WeasyPrint + Jinja2 - main.py — CLI + сервер Проверки: ✅ cookie_banner — поиск cookie-баннера ✅ privacy_link — проверка ссылки на политику ✅ form_checkbox — проверка чекбоксов согласия ✅ server_location — геолокация сервера (RФ или нет) ✅ external_scripts — внешние скрипты аналитики
This commit is contained in:
commit
de18090304
20 files changed
+1665
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
Генератор PDF-отчетов из JSON-данных сканирования.
|
||||
Использует Jinja2 + WeasyPrint для создания красивых отчетов.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
from weasyprint import HTML
|
||||
|
||||
# Путь к корню проекта
|
||||
BASE_DIR = Path(__file__).parent.parent
|
||||
TEMPLATE_DIR = Path(__file__).parent / "templates"
|
||||
|
||||
|
||||
class PDFReportGenerator:
|
||||
"""Генерирует PDF-отчеты из результатов сканирования."""
|
||||
|
||||
def __init__(self):
|
||||
self.jinja_env = Environment(
|
||||
loader=FileSystemLoader(str(TEMPLATE_DIR)),
|
||||
autoescape=True,
|
||||
)
|
||||
|
||||
def generate(self, scan_result: dict[str, Any], output_dir: str | None = None) -> Path:
|
||||
"""
|
||||
Создать PDF-отчет из результатов сканирования.
|
||||
|
||||
Args:
|
||||
scan_result: dict с данными сканирования (SiteScan.model_dump())
|
||||
output_dir: папка для сохранения (по умолчанию data/output/reports)
|
||||
|
||||
Returns:
|
||||
Path до созданного PDF-файла
|
||||
"""
|
||||
if output_dir is None:
|
||||
output_dir = BASE_DIR / "data" / "output" / "reports"
|
||||
output_dir = Path(output_dir)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Подставляем форматированные данные в шаблон
|
||||
template = self.jinja_env.get_template("report.html.j2")
|
||||
html_content = template.render(**self._prepare_context(scan_result))
|
||||
|
||||
# Генерируем PDF
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
domain_safe = scan_result.get("url", "unknown").replace("://", "_").replace("/", "_")[:30]
|
||||
pdf_path = output_dir / f"audit_{timestamp}_{domain_safe}.pdf"
|
||||
|
||||
HTML(string=html_content, base_url=str(TEMPLATE_DIR)).write_pdf(str(pdf_path))
|
||||
|
||||
return pdf_path
|
||||
|
||||
@staticmethod
|
||||
def _prepare_context(scan_result: dict) -> dict:
|
||||
"""Подготавливает контекст для шаблона."""
|
||||
checks = scan_result.get("checks", [])
|
||||
is_compliant = scan_result.get("is_compliant", True)
|
||||
score = scan_result.get("score", 0)
|
||||
scanned_at = scan_result.get("scanned_at", "")
|
||||
|
||||
# Форматируем дату
|
||||
if isinstance(scanned_at, str):
|
||||
try:
|
||||
dt = datetime.fromisoformat(scanned_at.replace("Z", "+00:00"))
|
||||
scanned_at = dt.strftime("%d.%m.%Y %H:%M")
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
return {
|
||||
"site_scan": scan_result,
|
||||
"url": scan_result.get("url", ""),
|
||||
"score": score,
|
||||
"is_compliant": is_compliant,
|
||||
"summary": scan_result.get("summary", ""),
|
||||
"checks": checks,
|
||||
"scanned_at": scanned_at,
|
||||
"scanner_version": "1.0.0",
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Аудит по 152-ФЗ — {{ site_scan.url }}</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
color: #1a1a2e;
|
||||
line-height: 1.6;
|
||||
padding: 40px;
|
||||
}
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 40px;
|
||||
padding-bottom: 20px;
|
||||
border-bottom: 3px solid #0f3463;
|
||||
}
|
||||
.header h1 {
|
||||
font-size: 28px;
|
||||
color: #0f3463;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.header p {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
}
|
||||
.score-card {
|
||||
text-align: center;
|
||||
padding: 30px;
|
||||
border-radius: 12px;
|
||||
margin: 30px 0;
|
||||
background: {{ '#e8f5e9' if is_compliant else '#ffebee' }};
|
||||
}
|
||||
.score-number {
|
||||
font-size: 64px;
|
||||
font-weight: 700;
|
||||
color: {{ '#2e7d32' if is_compliant else '#c62828' }};
|
||||
}
|
||||
.score-label {
|
||||
font-size: 18px;
|
||||
color: #555;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.summary-box {
|
||||
background: #f8f9fa;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
margin: 20px 0;
|
||||
border-left: 4px solid #0f3463;
|
||||
}
|
||||
.summary-box h3 {
|
||||
margin-bottom: 10px;
|
||||
color: #0f3463;
|
||||
}
|
||||
.table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.table th, .table td {
|
||||
padding: 12px 16px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #ddd;
|
||||
}
|
||||
.table th {
|
||||
background: #f8f9fa;
|
||||
font-weight: 600;
|
||||
color: #0f3463;
|
||||
}
|
||||
.status-pass {
|
||||
color: #2e7d32;
|
||||
font-weight: 600;
|
||||
}
|
||||
.status-fail {
|
||||
color: #c62828;
|
||||
font-weight: 600;
|
||||
}
|
||||
.status-skip {
|
||||
color: #f57c00;
|
||||
font-weight: 600;
|
||||
}
|
||||
.status-error {
|
||||
color: #d32f2f;
|
||||
font-weight: 600;
|
||||
}
|
||||
.risk-critical {
|
||||
background: #ffebee;
|
||||
color: #c62828;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.risk-high {
|
||||
background: #fff3e0;
|
||||
color: #e65100;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.risk-medium {
|
||||
background: #fff8e1;
|
||||
color: #f57c00;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.risk-low {
|
||||
background: #e8f5e9;
|
||||
color: #2e7d32;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.cta-section {
|
||||
background: #0f3463;
|
||||
color: white;
|
||||
padding: 30px;
|
||||
border-radius: 12px;
|
||||
margin-top: 40px;
|
||||
text-align: center;
|
||||
}
|
||||
.cta-section h2 {
|
||||
font-size: 22px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.cta-section p {
|
||||
font-size: 14px;
|
||||
opacity: 0.9;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.cta-button {
|
||||
display: inline-block;
|
||||
background: white;
|
||||
color: #0f3463;
|
||||
padding: 12px 24px;
|
||||
border-radius: 6px;
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
margin: 5px;
|
||||
}
|
||||
.footer {
|
||||
margin-top: 40px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid #ddd;
|
||||
text-align: center;
|
||||
color: #999;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<h1>📋 Аудит соответствия 152-ФЗ</h1>
|
||||
<p>Автоматизированный сканер | {{ site_scan.url }}</p>
|
||||
<p>Дата проверки: {{ scanned_at }}</p>
|
||||
<p>Версия сканера: {{ scanner_version }}</p>
|
||||
</div>
|
||||
|
||||
<div class="score-card">
|
||||
<div class="score-number">{{ score }}</div>
|
||||
<div class="score-label">
|
||||
{{ '✅ Сайт соответствует 152-ФЗ' if is_compliant else '❌ Сайт НЕ соответствует 152-ФЗ' }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="summary-box">
|
||||
<h3>📊 Резюме проверки</h3>
|
||||
<p>{{ summary }}</p>
|
||||
</div>
|
||||
|
||||
<h2>📝 Результаты проверок</h2>
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Проверка</th>
|
||||
<th>Статус</th>
|
||||
<th>Риск</th>
|
||||
<th>Детали</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for check in checks %}
|
||||
<tr>
|
||||
<td><strong>{{ check.title }}</strong></td>
|
||||
<td>
|
||||
{% if check.status == 'pass' %}
|
||||
<span class="status-pass">✅ Пройдено</span>
|
||||
{% elif check.status == 'fail' %}
|
||||
<span class="status-fail">❌ Не пройдено</span>
|
||||
{% elif check.status == 'skip' %}
|
||||
<span class="status-skip">⏭ Пропущено</span>
|
||||
{% elif check.status == 'error' %}
|
||||
<span class="status-error">⚠️ Ошибка</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if check.risk_level == 'critical' %}
|
||||
<span class="risk-critical">🔴 Критический</span>
|
||||
{% elif check.risk_level == 'high' %}
|
||||
<span class="risk-high">🟠 Высокий</span>
|
||||
{% elif check.risk_level == 'medium' %}
|
||||
<span class="risk-medium">🟡 Средний</span>
|
||||
{% else %}
|
||||
<span class="risk-low">🟢 Низкий</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ check.message }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="cta-section">
|
||||
<h2>Нужна помощь с приведением сайта в соответствие 152-ФЗ?</h2>
|
||||
<p>Мы исправим все найденные нарушения, подготовим документы и настроим cookie-баннеры.</p>
|
||||
<p style="margin-top: 20px; font-size: 18px;">💰 Стоимость: от 7 000 ₽ (зависит от объема нарушений)</p>
|
||||
<div style="margin-top: 20px;">
|
||||
<span class="cta-button">📧 Написать на email</span>
|
||||
<span class="cta-button">💬 Telegram</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<p>Документ сгенерирован автоматически. Не является юридической консультацией.</p>
|
||||
<p>© 2026 152-ФЗ Scanner | Powered by AI Compliance</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user