"""Designer vizual: validare, salvare si randare pe eticheta."""
from __future__ import annotations
import json
import pytest
from cantarire import designer
def _designer_template(client, name="Designer test") -> int:
response = client.post("/sabloane/designer/nou", data={"name": name})
assert response.status_code == 302
with client.application.app_context():
from cantarire.repositories import list_templates
return [t for t in list_templates() if t["name"] == name][0]["id"]
def test_default_design_has_expected_blocks():
design = designer.default_design(100, 60)
types = [block["type"] for block in design["blocks"]]
assert "field" in types and "items" in types and "qr" in types
@pytest.mark.parametrize("width,height", [(100, 60), (80, 50), (60, 40), (150, 100)])
def test_default_design_stays_inside_safe_margin(width, height):
"""Elementele implicite trebuie sa fie in interiorul zonei sigure."""
margin = designer.SAFE_MARGIN_MM
design = designer.default_design(width, height)
for block in design["blocks"]:
assert block["x"] >= margin - 0.001, block
assert block["y"] >= margin - 0.001, block
assert block["x"] + block["w"] <= width - margin + 0.001, block
assert block["y"] + block["h"] <= height - margin + 0.001, block
def test_validate_design_clamps_out_of_bounds():
raw = {
"width_mm": 100,
"height_mm": 60,
"blocks": [
{"type": "text", "x": 200, "y": -5, "w": 500, "h": 999, "text": "X"},
{"type": "nope"},
{"type": "field", "field": "does.not.exist"},
],
}
design = designer.validate_design(raw, 100, 60)
assert len(design["blocks"]) == 2 # tipul necunoscut este ignorat
block = design["blocks"][0]
assert block["x"] <= 100 and block["y"] >= 0
assert block["w"] <= 100 and block["h"] <= 60
assert design["blocks"][1]["field"] == "recipe.name"
def test_validate_design_rejects_bad_json():
with pytest.raises(designer.ValidationError):
designer.validate_design("{not json", 100, 60)
def test_render_design_escapes_text_and_builds_fields():
design = designer.validate_design({
"width_mm": 100, "height_mm": 60,
"blocks": [
{"type": "text", "x": 1, "y": 1, "w": 50, "h": 5, "text": ""},
{"type": "field", "x": 1, "y": 7, "w": 50, "h": 8,
"field": "recipe.name", "prefix": "", "suffix": ""},
{"type": "items", "x": 1, "y": 16, "w": 50, "h": 20},
{"type": "qr", "x": 60, "y": 16, "w": 20, "h": 20, "field": "package.qr"},
],
}, 100, 60)
html = designer.render_design(design, designer.demo_fields(), designer.demo_items())
assert "<script>" in html and ""}])],
}, 100, 60)
html = designer.render_design(design, designer.demo_fields(), designer.demo_items())
assert "