import os import uuid from typing import Any from flask import jsonify, request from werkzeug.wrappers import Response import db import document_engine from core.flask_app import app @app.route("/document//elements//upload-attachment", methods=["POST"]) def document_element_upload_attachment(slug: str, element_id: int) -> Response | tuple[Response, int]: """Joint un fichier téléchargeable à un bouton (voir _render_button, document_engine/rendering/render_document_element.py) — mirroir de routes/uploads/upload_file.py côté jeu, mais stocké sous le dossier du SUPPORT (db.support_dir) et réservé au kind "bouton" (un fichier joint n'a de sens que pour déclencher un téléchargement au clic).""" element = document_engine.get_document_element(slug, element_id) if element is None: return jsonify({"error": "élément introuvable"}), 404 if element["kind"] != "bouton": return jsonify({"error": "seul un bouton peut recevoir un fichier joint"}), 400 f = request.files.get("file") if not f or not f.filename: return jsonify({"error": "Aucun fichier reçu"}), 400 original_filename = f.filename ext = "".join(c for c in os.path.splitext(original_filename)[1].lower() if c.isalnum() or c == ".")[:10] stored_name = uuid.uuid4().hex + ext attachments_dir = os.path.join(db.support_dir(slug), "attachments") os.makedirs(attachments_dir, exist_ok=True) f.save(os.path.join(attachments_dir, stored_name)) attributes = { **element["attributes"], "attachment_stored_name": stored_name, "attachment_filename": original_filename, } document_engine.update_document_element_attributes(slug, element_id, attributes) element = db.assert_not_none( document_engine.get_document_element(slug, element_id), "element_id verifie present juste au-dessus, aucune suppression concurrente possible entre-temps ici", ) elements_by_parent: dict[int | None, list[dict[str, Any]]] = {} for el in document_engine.list_document_elements(slug, element["page_id"]): elements_by_parent.setdefault(el["parent_id"], []).append(el) return jsonify( { "ok": True, "attributes": element["attributes"], "rendered_html": document_engine.render_document_element(element, elements_by_parent), } )