134 lines
4.9 KiB
Python
134 lines
4.9 KiB
Python
import json
|
||
import io
|
||
import os
|
||
from datetime import datetime
|
||
|
||
from flask import Flask, request, jsonify
|
||
from flask_cors import CORS
|
||
import requests as http_requests
|
||
|
||
app = Flask(__name__)
|
||
CORS(app)
|
||
|
||
HSE_API_URL = "https://hse.sk.kz/api/v1"
|
||
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
|
||
os.makedirs(DATA_DIR, exist_ok=True)
|
||
|
||
|
||
def make_docx(report):
|
||
from docx import Document
|
||
from docx.shared import Pt
|
||
doc = Document()
|
||
doc.styles["Normal"].font.size = Pt(11)
|
||
doc.add_heading("План ПБ — Казахтелеком", level=1)
|
||
s = report.get("summary", {})
|
||
doc.add_paragraph(
|
||
f"Дата: {datetime.now().strftime('%d.%m.%Y')} | "
|
||
f"Всего: {s.get('total', 0)} | "
|
||
f"Выполнено: {s.get('done', 0)} ({s.get('pct', 0)}%)"
|
||
)
|
||
events = report.get("events", [])
|
||
table = doc.add_table(rows=1, cols=6)
|
||
table.style = "Light Grid Accent 1"
|
||
for i, h in enumerate(["N", "Мероприятие", "Филиал", "Срок", "Статус", "%"]):
|
||
table.rows[0].cells[i].text = h
|
||
for e in events:
|
||
row = table.add_row().cells
|
||
row[0].text = str(e.get("id", ""))
|
||
row[1].text = str(e.get("title", ""))[:100]
|
||
row[2].text = str(e.get("branch", ""))
|
||
row[3].text = str(e.get("deadline", ""))
|
||
row[4].text = str(e.get("status", ""))
|
||
row[5].text = str(e.get("progress", 0)) + "%"
|
||
buf = io.BytesIO()
|
||
doc.save(buf)
|
||
buf.seek(0)
|
||
return buf
|
||
|
||
|
||
def make_pdf(report):
|
||
from reportlab.lib.pagesizes import A4
|
||
from reportlab.lib.styles import getSampleStyleSheet
|
||
from reportlab.lib.units import mm
|
||
from reportlab.lib.colors import HexColor
|
||
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
|
||
|
||
buf = io.BytesIO()
|
||
doc = SimpleDocTemplate(buf, pagesize=A4, rightMargin=20 * mm, leftMargin=20 * mm,
|
||
topMargin=20 * mm, bottomMargin=20 * mm)
|
||
styles = getSampleStyleSheet()
|
||
story = [Paragraph("План ПБ — Казахтелеком", styles["Title"]), Spacer(1, 10)]
|
||
s = report.get("summary", {})
|
||
story.append(Paragraph(
|
||
f"Всего: {s.get('total', 0)} | Выполнено: {s.get('done', 0)} ({s.get('pct', 0)}%)",
|
||
styles["Normal"]
|
||
))
|
||
story.append(Spacer(1, 10))
|
||
data = [["N", "Мероприятие", "Филиал", "Срок", "Статус", "%"]]
|
||
for e in report.get("events", []):
|
||
data.append([
|
||
str(e.get("id", "")), str(e.get("title", ""))[:80],
|
||
str(e.get("branch", ""))[:25], str(e.get("deadline", "")),
|
||
str(e.get("status", "")), str(e.get("progress", 0)) + "%",
|
||
])
|
||
table = Table(data, colWidths=[20, 220, 80, 50, 60, 40])
|
||
table.setStyle(TableStyle([
|
||
("FONTSIZE", (0, 0), (-1, 0), 9), ("FONTSIZE", (0, 1), (-1, -1), 8),
|
||
("BACKGROUND", (0, 0), (-1, 0), HexColor("#003366")),
|
||
("TEXTCOLOR", (0, 0), (-1, 0), HexColor("#FFFFFF")),
|
||
("GRID", (0, 0), (-1, -1), 0.5, HexColor("#CCCCCC")),
|
||
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||
]))
|
||
story.append(table)
|
||
doc.build(story)
|
||
buf.seek(0)
|
||
return buf
|
||
|
||
|
||
@app.route("/api/hse/send", methods=["POST"])
|
||
def hse_send():
|
||
data = request.get_json()
|
||
month = data.get("month", "")
|
||
api_key = data.get("api_key", "")
|
||
fmt = data.get("format", "word")
|
||
report = data.get("report", {})
|
||
endpoint = data.get("endpoint", f"{HSE_API_URL}/documents/upload")
|
||
|
||
if not api_key:
|
||
return jsonify({"ok": False, "error": "API key required"}), 400
|
||
|
||
if fmt == "pdf":
|
||
buf = make_pdf(report)
|
||
mime = "application/pdf"
|
||
ext = "pdf"
|
||
else:
|
||
buf = make_docx(report)
|
||
mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||
ext = "docx"
|
||
|
||
try:
|
||
files = {"file": (f"hse_report_{month}.{ext}", buf.getvalue(), mime)}
|
||
headers = {"Authorization": f"Bearer {api_key}"}
|
||
payload = {
|
||
"title": f"Сводный отчет по ПБ за {month}",
|
||
"description": "Автоматический отчет платформы мониторинга ПБ",
|
||
"type": "safety_report",
|
||
"period": month,
|
||
}
|
||
r = http_requests.post(endpoint, files=files, data=payload, headers=headers, timeout=30)
|
||
if r.ok:
|
||
return jsonify({"ok": True, "hse_response": r.json() if r.text else {"status": r.status_code}})
|
||
return jsonify({"ok": False, "error": f"HSE API error: {r.status_code}", "detail": r.text[:500]}), 502
|
||
except Exception as e:
|
||
return jsonify({"ok": False, "error": str(e)}), 502
|
||
|
||
|
||
@app.route("/api/health", methods=["GET"])
|
||
def health():
|
||
return jsonify({"ok": True, "time": datetime.now().isoformat()})
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print("HSE Integration Server — http://0.0.0.0:5000")
|
||
app.run(host="0.0.0.0", port=5000, debug=False)
|