feat: add responsive anchored template layout #26
8 changed files with 2553 additions and 164 deletions
|
|
@ -54,6 +54,9 @@ PDF Renderer موجود
|
|||
- RTL/LTR و تراز متن؛
|
||||
- گرید میلیمتری یکپارچه روی کل سطح قابل چاپ؛
|
||||
- حرکت و تغییر اندازهٔ همهٔ بلوکها در دو محور؛
|
||||
- Anchor پایدار بلوکبهبلوک با فاصلهٔ میلیمتری و offset مستقل هر variant؛
|
||||
- Pin به چپ، راست، بالا، پایین و مرکز صفحهٔ قابل چاپ؛
|
||||
- زوم بوم با کنترلهای UI و `Ctrl + Wheel` بدون اثر بر اندازهٔ چاپ؛
|
||||
- HTML preview و PDF بر پایه compiler موجود؛
|
||||
- سازگاری با قالبهای قبلی.
|
||||
|
||||
|
|
@ -61,8 +64,6 @@ PDF Renderer موجود
|
|||
|
||||
- containerهای تودرتو؛
|
||||
- freeform layout محدود و امن؛
|
||||
- Snap هوشمند به عناصر، حاشیه و guideها؛
|
||||
- variant مستقل برای A4، A5 و رول؛
|
||||
- عملیات patch اتمیک و revision-based؛
|
||||
- API دامنهای مناسب برای اتصال MCP؛
|
||||
- audit منشأ تغییرات کاربر یا AI.
|
||||
|
|
@ -155,12 +156,14 @@ Design Document باید یک درخت از container و component باشد:
|
|||
|
||||
## ۵. محدودیت مهم محتوای پویا
|
||||
|
||||
همه اجزای فاکتور، از جمله جدول اقلام، روی گرید تمامصفحه جایگذاری میشوند. component پویا درون خانهٔ گرید میتواند از حداقل ارتفاع طراحیشده بزرگتر شود و موتور HTML/CSS باید ردیفهای بعدی را جابهجا کند.
|
||||
همه اجزای فاکتور، از جمله جدول اقلام، روی گرید تمامصفحه جایگذاری میشوند. component پویا درون خانهٔ گرید میتواند از حداقل ارتفاع طراحیشده بزرگتر شود. جابهجایی بلوکهای وابسته نباید به همپوشانی اتفاقی خانههای CSS Grid متکی باشد؛ رابطه باید بهصورت Anchor صریح در Design Document ذخیره شود.
|
||||
|
||||
قواعد پیشنهادی:
|
||||
|
||||
- جدول اقلام یک component پویا روی `page_grid` است و ارتفاع تنظیمشده برای آن حداقل ارتفاع محسوب میشود.
|
||||
- جمعبندی، توضیحات و امضا در خانههای بعدی گرید قرار میگیرند و با رشد جدول توسط CSS Grid جابهجا میشوند.
|
||||
- اتصال `top` یک بلوک به `bottom` بلوک دیگر یک زنجیرهٔ محتوایی میسازد؛ compiler آن را به ترتیب طبیعی HTML تبدیل میکند تا ارتفاع واقعی داده در زمان چاپ تعیینکننده باشد.
|
||||
- فاصلهٔ اتصال با `offset_mm` و override هر media profile ذخیره میشود؛ مثلاً پرداخت همیشه ۵ میلیمتر بعد از انتهای واقعی جدول قرار میگیرد.
|
||||
- جمعبندی، پرداخت، توضیحات و امضا میتوانند زنجیره شوند و بلوکهای مستقل همچنان مختصات آزاد خود را حفظ کنند.
|
||||
- header و footer تکرارشونده توسط compiler و CSS چاپ مدیریت شوند.
|
||||
- ردیف جدول تا حد امکان با `break-inside: avoid` نصف نشود.
|
||||
- عنوان ستونها در صفحه بعد تکرار شود.
|
||||
|
|
@ -248,7 +251,37 @@ Guide دستی
|
|||
→ گرید
|
||||
```
|
||||
|
||||
در MVP، نتیجه Snap به مختصات عددی تبدیل میشود. برای آینده یک فیلد اختیاری `constraints` در schema رزرو میشود، ولی constraint solver در MVP ساخته نمیشود.
|
||||
Snap معمولی همچنان فقط مختصات عددی تولید میکند. اتصال پایدار فقط از دستگیرههای Anchor ساخته میشود تا همترازی ساده ناخواسته به وابستگی تبدیل نشود. هر component میتواند یک `constraints` اختیاری داشته باشد:
|
||||
|
||||
```json
|
||||
{
|
||||
"constraints": {
|
||||
"links": [
|
||||
{
|
||||
"axis": "vertical",
|
||||
"source_anchor": "top",
|
||||
"target": {
|
||||
"type": "node",
|
||||
"id": "invoice-lines",
|
||||
"anchor": "bottom"
|
||||
},
|
||||
"offset_mm": 5,
|
||||
"variant_offsets": {
|
||||
"a4_portrait": 5,
|
||||
"roll_80": 2
|
||||
}
|
||||
}
|
||||
],
|
||||
"pins": {
|
||||
"left": true,
|
||||
"right": true
|
||||
},
|
||||
"keep_together": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
روابط یک گراف بدون دور هستند. validator هدف حذفشده، نقطهٔ نامعتبر، چند رابطهٔ متناقض روی یک محور و cycle را رد میکند. اتصال چپ و راست همزمان عرض responsive میسازد و اتصال بالا و پایین همزمان ارتفاع ناحیه را Stretch میکند.
|
||||
|
||||
## ۹. compiler رسمی HTML/CSS
|
||||
|
||||
|
|
|
|||
|
|
@ -227,6 +227,29 @@ class ReportTemplateService:
|
|||
return validate_v3_design(module_key, subtype, design)
|
||||
return validate_v2_design(module_key, subtype, design)
|
||||
|
||||
@staticmethod
|
||||
def _validate_v4_assets_before_write(
|
||||
module_key: str,
|
||||
subtype: Optional[str],
|
||||
assets: Any,
|
||||
) -> None:
|
||||
if not isinstance(assets, dict):
|
||||
return
|
||||
design = assets.get("template_design") or assets.get("design")
|
||||
if not isinstance(design, dict) or not is_v4_design(design):
|
||||
return
|
||||
validation = validate_v4_design(module_key, subtype, design)
|
||||
if validation.get("errors"):
|
||||
raise ApiError(
|
||||
"VALIDATION_ERROR",
|
||||
"Invalid template design v4: " + "; ".join(validation["errors"]),
|
||||
http_status=400,
|
||||
details={
|
||||
"errors": validation["errors"],
|
||||
"warnings": validation.get("warnings") or [],
|
||||
},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def validate_template_payload(data: Dict[str, Any], *, is_update: bool) -> None:
|
||||
"""اعتبارسنجی ورودی ایجاد/ویرایش قالب (واردات JSON و فرم)."""
|
||||
|
|
@ -350,6 +373,11 @@ class ReportTemplateService:
|
|||
str(data.get("module_key") or ""),
|
||||
(data.get("subtype") or None),
|
||||
)
|
||||
ReportTemplateService._validate_v4_assets_before_write(
|
||||
str(data.get("module_key") or ""),
|
||||
(data.get("subtype") or None),
|
||||
data.get("assets"),
|
||||
)
|
||||
entity = ReportTemplate(
|
||||
business_id=int(data["business_id"]),
|
||||
module_key=str(data["module_key"]),
|
||||
|
|
@ -386,6 +414,12 @@ class ReportTemplateService:
|
|||
next_module_key = str(data.get("module_key") if "module_key" in data else entity.module_key)
|
||||
next_subtype = (data.get("subtype") if "subtype" in data else entity.subtype) or None
|
||||
ReportTemplateService._validate_known_scope(next_module_key, next_subtype)
|
||||
if "assets" in data or "module_key" in data or "subtype" in data:
|
||||
ReportTemplateService._validate_v4_assets_before_write(
|
||||
next_module_key,
|
||||
next_subtype,
|
||||
data.get("assets") if "assets" in data else entity.assets,
|
||||
)
|
||||
for field in [
|
||||
"module_key", "subtype", "name", "description", "engine", "status",
|
||||
"content_html", "content_css", "header_html", "footer_html",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
import math
|
||||
from typing import Any, Iterable
|
||||
|
||||
from app.services.report_template_gallery import get_family
|
||||
|
|
@ -38,6 +39,8 @@ _FREEFORM_COMPONENTS = {
|
|||
"divider",
|
||||
"spacer",
|
||||
}
|
||||
_ANCHOR_POINTS = {"top", "right", "bottom", "left", "center_x", "center_y"}
|
||||
_PIN_EDGES = {"top", "right", "bottom", "left", "center_x", "center_y"}
|
||||
|
||||
|
||||
def is_v4_design(design: dict[str, Any]) -> bool:
|
||||
|
|
@ -155,6 +158,13 @@ def studio_v4_contract(module_key: str, subtype: str | None) -> dict[str, Any]:
|
|||
"snap_targets": ["grid", "safe_margin", "sibling_edge", "sibling_center"],
|
||||
"position_unit": "mm",
|
||||
"dynamic_components_allowed": True,
|
||||
"persistent_anchors": {
|
||||
"points": sorted(_ANCHOR_POINTS),
|
||||
"link_targets": ["node"],
|
||||
"offset_unit": "mm",
|
||||
"responsive_offsets": True,
|
||||
"page_pins": sorted(_PIN_EDGES),
|
||||
},
|
||||
},
|
||||
"components": component_catalog(module_key, subtype),
|
||||
"bindings": binding_catalog(module_key, subtype),
|
||||
|
|
@ -196,8 +206,54 @@ def _json_schema() -> dict[str, Any]:
|
|||
"component": {"type": "string"},
|
||||
"layout": {"type": "object"},
|
||||
"placement": {"type": "object"},
|
||||
"constraints": {"$ref": "#/$defs/constraints"},
|
||||
},
|
||||
},
|
||||
"anchor_target": {
|
||||
"type": "object",
|
||||
"required": ["type", "id", "anchor"],
|
||||
"properties": {
|
||||
"type": {"const": "node"},
|
||||
"id": {"type": "string", "pattern": "^[a-zA-Z0-9_-]{1,80}$"},
|
||||
"anchor": {"enum": sorted(_ANCHOR_POINTS)},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
"anchor_link": {
|
||||
"type": "object",
|
||||
"required": ["axis", "source_anchor", "target"],
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"axis": {"enum": ["horizontal", "vertical"]},
|
||||
"source_anchor": {"enum": sorted(_ANCHOR_POINTS)},
|
||||
"target": {"$ref": "#/$defs/anchor_target"},
|
||||
"offset_mm": {"type": "number", "minimum": -1000, "maximum": 1000},
|
||||
"variant_offsets": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "number", "minimum": -1000, "maximum": 1000},
|
||||
},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
"constraints": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"links": {"type": "array", "maxItems": 2, "items": {"$ref": "#/$defs/anchor_link"}},
|
||||
"pins": {
|
||||
"type": "object",
|
||||
"properties": {key: {"type": "boolean"} for key in sorted(_PIN_EDGES)},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
"pin_offsets_mm": {"type": "object", "additionalProperties": {"type": "number"}},
|
||||
"variant_pin_offsets": {
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "object", "additionalProperties": {"type": "number"}},
|
||||
},
|
||||
"bottom_mode": {"enum": ["last_page", "every_page"]},
|
||||
"keep_together": {"type": "boolean"},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
"variant": {
|
||||
"type": "object",
|
||||
"required": ["media", "node_overrides"],
|
||||
|
|
@ -481,12 +537,144 @@ def resolved_root(design: dict[str, Any]) -> dict[str, Any]:
|
|||
overrides = variant.get("node_overrides") or {}
|
||||
for node in _iter_nodes(root):
|
||||
override = overrides.get(str(node.get("id") or "")) or {}
|
||||
for key in ("layout", "placement", "style"):
|
||||
for key in ("layout", "placement", "style", "constraints"):
|
||||
if isinstance(override.get(key), dict):
|
||||
node[key] = {**(node.get(key) or {}), **deepcopy(override[key])}
|
||||
return root
|
||||
|
||||
|
||||
def _validate_constraints(root: dict[str, Any], component_ids: set[str]) -> tuple[list[str], list[str]]:
|
||||
errors: list[str] = []
|
||||
warnings: list[str] = []
|
||||
dependencies: dict[str, list[str]] = {}
|
||||
dynamic_followers: dict[str, list[str]] = {}
|
||||
for node in _iter_nodes(root):
|
||||
if node.get("kind") != "component":
|
||||
continue
|
||||
node_id = str(node.get("id") or "")
|
||||
constraints = node.get("constraints") or {}
|
||||
if not isinstance(constraints, dict):
|
||||
errors.append(f"Component '{node_id}' constraints must be an object")
|
||||
continue
|
||||
unknown_constraint_keys = set(constraints).difference(
|
||||
{"links", "pins", "pin_offsets_mm", "variant_pin_offsets", "bottom_mode", "keep_together"}
|
||||
)
|
||||
if unknown_constraint_keys:
|
||||
errors.append(f"Unknown constraint field in '{node_id}'")
|
||||
links = constraints.get("links") or []
|
||||
if not isinstance(links, list):
|
||||
errors.append(f"Component '{node_id}' constraint links must be a list")
|
||||
continue
|
||||
seen_axes: set[str] = set()
|
||||
for link in links:
|
||||
if not isinstance(link, dict):
|
||||
errors.append(f"Invalid anchor link in '{node_id}'")
|
||||
continue
|
||||
axis = str(link.get("axis") or "")
|
||||
if axis not in ("horizontal", "vertical"):
|
||||
errors.append(f"Invalid anchor axis in '{node_id}'")
|
||||
continue
|
||||
if axis in seen_axes:
|
||||
errors.append(f"Component '{node_id}' has more than one {axis} anchor")
|
||||
seen_axes.add(axis)
|
||||
source_anchor = str(link.get("source_anchor") or "")
|
||||
target = link.get("target") or {}
|
||||
target_anchor = str(target.get("anchor") or "") if isinstance(target, dict) else ""
|
||||
if source_anchor not in _ANCHOR_POINTS or target_anchor not in _ANCHOR_POINTS:
|
||||
errors.append(f"Invalid anchor point in '{node_id}'")
|
||||
continue
|
||||
if axis == "horizontal" and (
|
||||
source_anchor not in {"left", "right", "center_x"}
|
||||
or target_anchor not in {"left", "right", "center_x"}
|
||||
):
|
||||
errors.append(f"Horizontal anchor uses a vertical point in '{node_id}'")
|
||||
if axis == "vertical" and (
|
||||
source_anchor not in {"top", "bottom", "center_y"}
|
||||
or target_anchor not in {"top", "bottom", "center_y"}
|
||||
):
|
||||
errors.append(f"Vertical anchor uses a horizontal point in '{node_id}'")
|
||||
if not isinstance(target, dict) or target.get("type") != "node":
|
||||
errors.append(f"Anchor target in '{node_id}' must be a node")
|
||||
continue
|
||||
target_id = str(target.get("id") or "")
|
||||
if target_id == node_id or target_id not in component_ids:
|
||||
errors.append(f"Invalid anchor target '{target_id}' in '{node_id}'")
|
||||
continue
|
||||
dependencies.setdefault(node_id, []).append(target_id)
|
||||
if axis == "vertical" and source_anchor == "top" and target_anchor == "bottom":
|
||||
dynamic_followers.setdefault(target_id, []).append(node_id)
|
||||
for raw_offset in [link.get("offset_mm"), *((link.get("variant_offsets") or {}).values() if isinstance(link.get("variant_offsets"), dict) else [])]:
|
||||
try:
|
||||
offset = float(raw_offset or 0)
|
||||
except (TypeError, ValueError):
|
||||
offset = 1001
|
||||
if not math.isfinite(offset) or abs(offset) > 1000:
|
||||
errors.append(f"Invalid anchor offset in '{node_id}'")
|
||||
pins = constraints.get("pins") or {}
|
||||
if not isinstance(pins, dict):
|
||||
errors.append(f"Component '{node_id}' pins must be an object")
|
||||
else:
|
||||
unknown_pins = set(pins).difference(_PIN_EDGES)
|
||||
if unknown_pins:
|
||||
errors.append(f"Unknown page pin in '{node_id}'")
|
||||
if any(not isinstance(value, bool) for value in pins.values()):
|
||||
errors.append(f"Page pins in '{node_id}' must be booleans")
|
||||
if pins.get("left") and pins.get("right") and pins.get("center_x"):
|
||||
errors.append(f"Conflicting horizontal page pins in '{node_id}'")
|
||||
if pins.get("top") and pins.get("bottom") and pins.get("center_y"):
|
||||
errors.append(f"Conflicting vertical page pins in '{node_id}'")
|
||||
if pins.get("top") and pins.get("bottom") and node.get("component") in {
|
||||
"invoice_lines",
|
||||
"invoice_totals",
|
||||
"payments",
|
||||
"note",
|
||||
}:
|
||||
warnings.append(
|
||||
f"Dynamic component '{node_id}' is stretched between top and bottom pins"
|
||||
)
|
||||
for offsets in [
|
||||
constraints.get("pin_offsets_mm") or {},
|
||||
*((constraints.get("variant_pin_offsets") or {}).values() if isinstance(constraints.get("variant_pin_offsets"), dict) else []),
|
||||
]:
|
||||
if not isinstance(offsets, dict):
|
||||
errors.append(f"Invalid page pin offsets in '{node_id}'")
|
||||
continue
|
||||
for key, raw_offset in offsets.items():
|
||||
if key not in _PIN_EDGES:
|
||||
errors.append(f"Unknown page pin offset in '{node_id}'")
|
||||
continue
|
||||
try:
|
||||
offset = float(raw_offset)
|
||||
except (TypeError, ValueError):
|
||||
offset = math.inf
|
||||
if not math.isfinite(offset) or abs(offset) > 5000:
|
||||
errors.append(f"Invalid page pin offset in '{node_id}'")
|
||||
bottom_mode = str(constraints.get("bottom_mode") or "last_page")
|
||||
if bottom_mode not in ("last_page", "every_page"):
|
||||
errors.append(f"Invalid bottom pin mode in '{node_id}'")
|
||||
for target_id, followers in dynamic_followers.items():
|
||||
if len(followers) > 1:
|
||||
errors.append(
|
||||
f"Multiple dynamic followers of '{target_id}' must be chained explicitly"
|
||||
)
|
||||
visiting: set[str] = set()
|
||||
visited: set[str] = set()
|
||||
def visit(node_id: str) -> None:
|
||||
if node_id in visited:
|
||||
return
|
||||
if node_id in visiting:
|
||||
errors.append("Anchor constraints contain a cycle")
|
||||
return
|
||||
visiting.add(node_id)
|
||||
for target_id in dependencies.get(node_id, []):
|
||||
visit(target_id)
|
||||
visiting.remove(node_id)
|
||||
visited.add(node_id)
|
||||
for node_id in dependencies:
|
||||
visit(node_id)
|
||||
return errors, warnings
|
||||
|
||||
|
||||
def v4_to_v3_projection(design: dict[str, Any]) -> dict[str, Any]:
|
||||
root = resolved_root(design)
|
||||
regions: dict[str, list[dict[str, Any]]] = {key: [] for key in _REGIONS}
|
||||
|
|
@ -619,7 +807,7 @@ def validate_v4_design(module_key: str, subtype: str | None, design: dict[str, A
|
|||
errors.append("Page grid size must be 1, 3 or 5 millimeters")
|
||||
elif kind == "component":
|
||||
component = str(node.get("component") or "")
|
||||
for field in ("props", "style", "placement"):
|
||||
for field in ("props", "style", "placement", "constraints"):
|
||||
if node.get(field) is not None and not isinstance(node.get(field), dict):
|
||||
errors.append(f"Component '{node_id}' {field} must be an object")
|
||||
definition = definitions.get(component)
|
||||
|
|
@ -629,6 +817,14 @@ def validate_v4_design(module_key: str, subtype: str | None, design: dict[str, A
|
|||
component_counts[component] = component_counts.get(component, 0) + 1
|
||||
else:
|
||||
errors.append(f"Invalid node kind in '{node_id}'")
|
||||
component_ids = {
|
||||
str(node.get("id") or "")
|
||||
for node in _iter_nodes(root)
|
||||
if node.get("kind") == "component"
|
||||
}
|
||||
constraint_errors, constraint_warnings = _validate_constraints(root, component_ids)
|
||||
errors.extend(constraint_errors)
|
||||
warnings.extend(constraint_warnings)
|
||||
variants = design.get("variants")
|
||||
if not isinstance(variants, dict):
|
||||
errors.append("variants must be an object")
|
||||
|
|
|
|||
|
|
@ -138,6 +138,91 @@ def _page_grid_components(
|
|||
return items
|
||||
|
||||
|
||||
def _anchor_coordinate(rect: dict[str, float], anchor: str) -> float:
|
||||
if anchor == "left":
|
||||
return rect["x"]
|
||||
if anchor == "right":
|
||||
return rect["x"] + rect["width"]
|
||||
if anchor == "center_x":
|
||||
return rect["x"] + rect["width"] / 2
|
||||
if anchor == "top":
|
||||
return rect["y"]
|
||||
if anchor == "bottom":
|
||||
return rect["y"] + rect["height"]
|
||||
return rect["y"] + rect["height"] / 2
|
||||
|
||||
|
||||
def _link_offset(link: dict[str, Any], profile: str) -> float:
|
||||
variant_offsets = link.get("variant_offsets") or {}
|
||||
return _number(
|
||||
variant_offsets.get(profile) if isinstance(variant_offsets, dict) else None,
|
||||
_number(link.get("offset_mm"), 0, -1000, 1000),
|
||||
-1000,
|
||||
1000,
|
||||
)
|
||||
|
||||
|
||||
def _page_pin_offsets(constraints: dict[str, Any], profile: str) -> dict[str, float]:
|
||||
offsets = constraints.get("pin_offsets_mm") or {}
|
||||
variant_offsets = constraints.get("variant_pin_offsets") or {}
|
||||
if isinstance(variant_offsets, dict) and isinstance(variant_offsets.get(profile), dict):
|
||||
offsets = {**offsets, **variant_offsets[profile]}
|
||||
return {
|
||||
key: _number(offsets.get(key), 0, -5000, 5000)
|
||||
for key in ("left", "right", "top", "bottom", "center_x", "center_y")
|
||||
}
|
||||
|
||||
|
||||
def _resolved_page_rect(
|
||||
component: dict[str, Any],
|
||||
*,
|
||||
width_mm: float,
|
||||
height_mm: float,
|
||||
profile: str,
|
||||
) -> dict[str, float]:
|
||||
placement = component.get("placement") or {}
|
||||
rect = {
|
||||
"x": _number(placement.get("x_mm"), 0, 0, width_mm),
|
||||
"y": _number(placement.get("y_mm"), 0, 0, height_mm),
|
||||
"width": _number(placement.get("width_mm"), 30, 1, width_mm),
|
||||
"height": _number(placement.get("height_mm"), 15, 1, height_mm),
|
||||
}
|
||||
constraints = component.get("constraints") or {}
|
||||
pins = constraints.get("pins") or {}
|
||||
if not isinstance(pins, dict):
|
||||
return rect
|
||||
offsets = _page_pin_offsets(constraints, profile)
|
||||
if pins.get("left") and pins.get("right"):
|
||||
rect["x"] = offsets["left"]
|
||||
rect["width"] = max(1, width_mm - offsets["left"] - offsets["right"])
|
||||
elif pins.get("right"):
|
||||
rect["x"] = width_mm - offsets["right"] - rect["width"]
|
||||
elif pins.get("left"):
|
||||
rect["x"] = offsets["left"]
|
||||
elif pins.get("center_x"):
|
||||
rect["x"] = (width_mm - rect["width"]) / 2 + offsets["center_x"]
|
||||
if pins.get("top") and pins.get("bottom"):
|
||||
rect["y"] = offsets["top"]
|
||||
rect["height"] = max(1, height_mm - offsets["top"] - offsets["bottom"])
|
||||
elif pins.get("bottom"):
|
||||
rect["y"] = height_mm - offsets["bottom"] - rect["height"]
|
||||
elif pins.get("top"):
|
||||
rect["y"] = offsets["top"]
|
||||
elif pins.get("center_y"):
|
||||
rect["y"] = (height_mm - rect["height"]) / 2 + offsets["center_y"]
|
||||
rect["x"] = max(0, min(width_mm - rect["width"], rect["x"]))
|
||||
rect["y"] = max(0, min(height_mm - rect["height"], rect["y"]))
|
||||
return rect
|
||||
|
||||
|
||||
def _grid_position(rect: dict[str, float], *, grid_mm: float, columns: int, rows: int) -> tuple[int, int, int, int]:
|
||||
column_start = max(1, min(columns, math.floor(rect["x"] / grid_mm) + 1))
|
||||
row_start = max(1, min(rows, math.floor(rect["y"] / grid_mm) + 1))
|
||||
column_span = max(1, min(columns - column_start + 1, math.ceil(rect["width"] / grid_mm)))
|
||||
row_span = max(1, min(rows - row_start + 1, math.ceil(rect["height"] / grid_mm)))
|
||||
return column_start, row_start, column_span, row_span
|
||||
|
||||
|
||||
def _page_grid_container(design: dict[str, Any], root: dict[str, Any], *, receipt: bool) -> str:
|
||||
layout = root.get("layout") or {}
|
||||
grid_mm = int(_number(layout.get("grid_mm"), 1, 1, 5))
|
||||
|
|
@ -145,29 +230,139 @@ def _page_grid_container(design: dict[str, Any], root: dict[str, Any], *, receip
|
|||
height_mm = _number(layout.get("height_mm"), 277, 20, 5000)
|
||||
columns = max(1, math.ceil(width_mm / grid_mm))
|
||||
rows = max(1, math.ceil(height_mm / grid_mm))
|
||||
items: list[str] = []
|
||||
for region, component in _page_grid_components(root):
|
||||
if component.get("visible", True) is False:
|
||||
profile = active_variant_key(design)
|
||||
components = [
|
||||
(region, component)
|
||||
for region, component in _page_grid_components(root)
|
||||
if component.get("visible", True) is not False
|
||||
]
|
||||
by_id = {str(component.get("id") or ""): component for _, component in components}
|
||||
regions = {str(component.get("id") or ""): region for region, component in components}
|
||||
rects = {
|
||||
node_id: _resolved_page_rect(component, width_mm=width_mm, height_mm=height_mm, profile=profile)
|
||||
for node_id, component in by_id.items()
|
||||
}
|
||||
# Static sibling anchors are resolved from variant geometry. A top-to-bottom
|
||||
# vertical anchor is intentionally left for normal HTML flow below, because
|
||||
# the target may grow after Jinja data is rendered.
|
||||
for _ in range(max(1, len(by_id))):
|
||||
changed = False
|
||||
for node_id, component in by_id.items():
|
||||
constraints = component.get("constraints") or {}
|
||||
for link in constraints.get("links") or []:
|
||||
if not isinstance(link, dict):
|
||||
continue
|
||||
placement = component.get("placement") or {}
|
||||
x = _number(placement.get("x_mm"), 0, 0, width_mm)
|
||||
y = _number(placement.get("y_mm"), 0, 0, height_mm)
|
||||
width = _number(placement.get("width_mm"), 30, 1, width_mm)
|
||||
height = _number(placement.get("height_mm"), 15, 1, height_mm)
|
||||
column_start = max(1, min(columns, math.floor(x / grid_mm) + 1))
|
||||
row_start = max(1, min(rows, math.floor(y / grid_mm) + 1))
|
||||
column_span = max(1, min(columns - column_start + 1, math.ceil(width / grid_mm)))
|
||||
row_span = max(1, min(rows - row_start + 1, math.ceil(height / grid_mm)))
|
||||
target = link.get("target") or {}
|
||||
target_id = str(target.get("id") or "")
|
||||
if target_id not in rects:
|
||||
continue
|
||||
axis = str(link.get("axis") or "")
|
||||
source_anchor = str(link.get("source_anchor") or "")
|
||||
target_anchor = str(target.get("anchor") or "")
|
||||
if axis == "vertical" and source_anchor == "top" and target_anchor == "bottom":
|
||||
continue
|
||||
desired = _anchor_coordinate(rects[target_id], target_anchor) + _link_offset(link, profile)
|
||||
current = _anchor_coordinate(rects[node_id], source_anchor)
|
||||
if abs(desired - current) < 0.001:
|
||||
continue
|
||||
if axis == "horizontal":
|
||||
rects[node_id]["x"] += desired - current
|
||||
rects[node_id]["x"] = max(0, min(width_mm - rects[node_id]["width"], rects[node_id]["x"]))
|
||||
elif axis == "vertical":
|
||||
rects[node_id]["y"] += desired - current
|
||||
rects[node_id]["y"] = max(0, min(height_mm - rects[node_id]["height"], rects[node_id]["y"]))
|
||||
changed = True
|
||||
if not changed:
|
||||
break
|
||||
# Dynamic follow links form normal-flow chains. This is the essential part:
|
||||
# a follower is emitted after the target, so rendered content height—not the
|
||||
# design-time rectangle—determines its print position.
|
||||
follows: dict[str, tuple[str, dict[str, Any]]] = {}
|
||||
followers: dict[str, list[str]] = {}
|
||||
for node_id, component in by_id.items():
|
||||
for link in (component.get("constraints") or {}).get("links") or []:
|
||||
if not isinstance(link, dict) or link.get("axis") != "vertical":
|
||||
continue
|
||||
target = link.get("target") or {}
|
||||
if link.get("source_anchor") == "top" and target.get("anchor") == "bottom":
|
||||
target_id = str(target.get("id") or "")
|
||||
if target_id in by_id:
|
||||
follows[node_id] = (target_id, link)
|
||||
followers.setdefault(target_id, []).append(node_id)
|
||||
emitted: set[str] = set()
|
||||
items: list[str] = []
|
||||
def component_markup(node_id: str, *, chain_x: float | None = None, gap: float = 0) -> str:
|
||||
component = by_id[node_id]
|
||||
component_html = _component_html(design, component, receipt=receipt)
|
||||
if not component_html:
|
||||
continue
|
||||
return ""
|
||||
component_type = str(component.get("component") or "")
|
||||
dynamic_class = " rt-page-grid-item-dynamic" if component_type in ("invoice_lines", "invoice_totals", "payments", "note") else ""
|
||||
items.append(
|
||||
f'<div class="rt-page-grid-item{dynamic_class}" data-template-region="{escape(region, quote=True)}" '
|
||||
f'style="grid-column:{column_start}/span {column_span};grid-row:{row_start}/span {row_span};'
|
||||
f'min-height:{height:g}mm;">{component_html}</div>'
|
||||
rect = rects[node_id]
|
||||
keep_together = (component.get("constraints") or {}).get("keep_together")
|
||||
if keep_together is None:
|
||||
keep_together = component_type in ("invoice_totals", "payments", "signatures")
|
||||
keep = " rt-anchor-keep-together" if keep_together else ""
|
||||
if chain_x is not None:
|
||||
return (
|
||||
f'<div class="rt-anchor-chain-member{dynamic_class}{keep}" data-template-node-ref="{escape(node_id, quote=True)}" '
|
||||
f'style="margin-top:{gap:g}mm;margin-left:{rect["x"] - chain_x:g}mm;width:{rect["width"]:g}mm;'
|
||||
f'min-height:{rect["height"]:g}mm;">{component_html}</div>'
|
||||
)
|
||||
column_start, row_start, column_span, row_span = _grid_position(rect, grid_mm=grid_mm, columns=columns, rows=rows)
|
||||
constraints = component.get("constraints") or {}
|
||||
bottom_mode = str(constraints.get("bottom_mode") or "last_page")
|
||||
bottom_pinned = (constraints.get("pins") or {}).get("bottom")
|
||||
bottom_class = f" rt-pin-bottom-{bottom_mode.replace('_', '-')}" if bottom_pinned else ""
|
||||
fixed_style = ""
|
||||
if bottom_pinned and bottom_mode == "every_page":
|
||||
bottom_offset = _page_pin_offsets(constraints, profile)["bottom"]
|
||||
fixed_style = f"left:{rect['x']:g}mm;bottom:{bottom_offset:g}mm;width:{rect['width']:g}mm;"
|
||||
return (
|
||||
f'<div class="rt-page-grid-item{dynamic_class}{keep}{bottom_class}" data-template-region="{escape(regions[node_id], quote=True)}" '
|
||||
f'style="grid-column:{column_start}/span {column_span};grid-row:{row_start}/span {row_span};'
|
||||
f'min-height:{rect["height"]:g}mm;{fixed_style}">{component_html}</div>'
|
||||
)
|
||||
|
||||
for node_id in by_id:
|
||||
if node_id in emitted or node_id in follows:
|
||||
continue
|
||||
chain = [node_id]
|
||||
cursor = node_id
|
||||
while len(followers.get(cursor, [])) == 1:
|
||||
next_id = followers[cursor][0]
|
||||
if next_id in chain:
|
||||
break
|
||||
chain.append(next_id)
|
||||
cursor = next_id
|
||||
if len(chain) == 1:
|
||||
markup = component_markup(node_id)
|
||||
if markup:
|
||||
items.append(markup)
|
||||
emitted.add(node_id)
|
||||
continue
|
||||
chain_x = min(rects[item_id]["x"] for item_id in chain)
|
||||
chain_right = max(rects[item_id]["x"] + rects[item_id]["width"] for item_id in chain)
|
||||
root_rect = rects[node_id]
|
||||
chain_rect = {"x": chain_x, "y": root_rect["y"], "width": chain_right - chain_x, "height": root_rect["height"]}
|
||||
column_start, row_start, column_span, row_span = _grid_position(chain_rect, grid_mm=grid_mm, columns=columns, rows=rows)
|
||||
members: list[str] = []
|
||||
for index, item_id in enumerate(chain):
|
||||
gap = 0 if index == 0 else _link_offset(follows[item_id][1], profile)
|
||||
members.append(component_markup(item_id, chain_x=chain_x, gap=gap))
|
||||
emitted.add(item_id)
|
||||
items.append(
|
||||
f'<div class="rt-page-grid-item rt-anchor-chain" data-template-anchor-chain="{escape(node_id, quote=True)}" '
|
||||
f'style="grid-column:{column_start}/span {column_span};grid-row:{row_start}/span {row_span};'
|
||||
f'min-height:{root_rect["height"]:g}mm;">{"".join(members)}</div>'
|
||||
)
|
||||
# Invalid/legacy branched followers are emitted independently as a safe
|
||||
# fallback. Validation requires authors to express them as a serial chain.
|
||||
for node_id in by_id:
|
||||
if node_id not in emitted:
|
||||
markup = component_markup(node_id)
|
||||
if markup:
|
||||
items.append(markup)
|
||||
return (
|
||||
f'<main class="rt-layout rt-layout-v4 rt-page-grid" data-template-node-id="{escape(str(root.get("id") or ""), quote=True)}" '
|
||||
f'style="--rt-page-grid-mm:{grid_mm};--rt-page-grid-width:{width_mm:g}mm;--rt-page-grid-height:{height_mm:g}mm;'
|
||||
|
|
@ -231,6 +426,15 @@ def compile_v4_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, s
|
|||
.rt-page-grid-item { min-width:0; overflow:visible; align-self:stretch; }
|
||||
.rt-page-grid-item > .rt-component { width:100%; min-height:100%; }
|
||||
.rt-page-grid-item-dynamic { height:auto; align-self:start; }
|
||||
.rt-anchor-chain { display:block; align-self:start; overflow:visible; }
|
||||
.rt-anchor-chain-member { display:block; box-sizing:border-box; }
|
||||
.rt-anchor-chain-member:first-child { margin-top:0 !important; }
|
||||
.rt-anchor-chain-member > .rt-component { width:100%; min-height:100%; }
|
||||
.rt-anchor-keep-together { break-inside:avoid; page-break-inside:avoid; }
|
||||
.rt-pin-bottom-every-page { position:fixed; bottom:0; }
|
||||
.rt-component-invoice-lines thead { display:table-header-group; }
|
||||
.rt-component-invoice-lines tfoot { display:table-footer-group; }
|
||||
.rt-component-invoice-lines tr { break-inside:avoid; page-break-inside:avoid; }
|
||||
@media screen and (max-width:720px) {
|
||||
.rt-layout-v4 { max-width:100%; overflow-x:auto; }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,15 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
import re
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from jinja2 import BaseLoader, StrictUndefined
|
||||
from jinja2.sandbox import SandboxedEnvironment
|
||||
import pytest
|
||||
|
||||
from app.core.responses import ApiError
|
||||
from app.services.report_template_gallery import default_design_for_family, list_gallery_items
|
||||
from app.services.report_template_service import ReportTemplateService
|
||||
from app.services.report_template_v2_service import migrate_builder_design_to_v2, validate_v2_design
|
||||
|
|
@ -489,3 +496,542 @@ def test_v4_full_page_grid_keeps_long_invoice_on_existing_pdf_pipeline():
|
|||
rendered = ReportTemplateService.render_with_template(template, context)
|
||||
document = HTML(string=rendered).render()
|
||||
assert len(document.pages) >= 2
|
||||
|
||||
|
||||
def test_v4_dynamic_anchor_chain_keeps_followers_after_growing_invoice_lines():
|
||||
from weasyprint import HTML
|
||||
|
||||
design_v2 = default_design_for_family("invoice_classic")
|
||||
assert design_v2 is not None
|
||||
design = migrate_v3_design_to_v4(migrate_v2_design_to_v3(design_v2))
|
||||
def walk(node):
|
||||
yield node
|
||||
for child in node.get("children") or []:
|
||||
yield from walk(child)
|
||||
nodes = {str(node.get("id") or ""): node for node in walk(design["root"])}
|
||||
def follow(source_id: str, target_id: str, gap_mm: float) -> None:
|
||||
nodes[source_id]["constraints"] = {
|
||||
"links": [
|
||||
{
|
||||
"id": "vertical-anchor",
|
||||
"axis": "vertical",
|
||||
"source_anchor": "top",
|
||||
"target": {"type": "node", "id": target_id, "anchor": "bottom"},
|
||||
"offset_mm": gap_mm,
|
||||
"variant_offsets": {"a4_portrait": gap_mm, "roll_80": 2},
|
||||
}
|
||||
],
|
||||
"keep_together": source_id != "invoice-lines",
|
||||
}
|
||||
follow("invoice-totals", "invoice-lines", 5)
|
||||
follow("payments", "invoice-totals", 3)
|
||||
assert validate_v4_design("invoices", "detail", design)["errors"] == []
|
||||
html, css, _, _ = compile_v4_design_to_jinja_html(design)
|
||||
assert 'data-template-anchor-chain="invoice-lines"' in html
|
||||
assert 'data-template-node-ref="invoice-totals"' in html
|
||||
assert "margin-top:5mm" in html
|
||||
assert "margin-top:3mm" in html
|
||||
assert ".rt-anchor-keep-together" in css
|
||||
|
||||
template = type(
|
||||
"Template",
|
||||
(),
|
||||
{
|
||||
"engine": "template_v2",
|
||||
"assets": {"template_design": design},
|
||||
"content_html": "",
|
||||
"content_css": "",
|
||||
"header_html": "",
|
||||
"footer_html": "",
|
||||
"paper_size": "A4",
|
||||
"orientation": "portrait",
|
||||
"margins": None,
|
||||
},
|
||||
)()
|
||||
context = _sample_invoice_context()
|
||||
base_line = context["lines"][0]
|
||||
context["lines"] = [{**base_line, "product_name": f"کالای شماره {index}"} for index in range(1, 41)]
|
||||
context["payments"] = [{"method_name": "نقدی", "amount": 100}]
|
||||
document = HTML(string=ReportTemplateService.render_with_template(template, context)).render()
|
||||
assert len(document.pages) >= 2
|
||||
last_page_classes: list[tuple[str, float, float]] = []
|
||||
def collect(box) -> None:
|
||||
element = getattr(box, "element", None)
|
||||
if element is not None:
|
||||
classes = element.get("class", "")
|
||||
if any(name in classes for name in ("rt-component-invoice-lines", "rt-component-invoice-totals", "rt-component-payments")):
|
||||
last_page_classes.append((classes, box.position_y, box.height))
|
||||
for child in getattr(box, "children", []):
|
||||
collect(child)
|
||||
collect(document.pages[-1]._page_box)
|
||||
line_box = next(item for item in last_page_classes if "rt-component-invoice-lines" in item[0])
|
||||
total_box = next(item for item in last_page_classes if "rt-component-invoice-totals" in item[0])
|
||||
payment_box = next(item for item in last_page_classes if "rt-component-payments" in item[0])
|
||||
assert total_box[1] >= line_box[1] + line_box[2]
|
||||
assert payment_box[1] >= total_box[1] + total_box[2]
|
||||
|
||||
design["media"] = __import__("copy").deepcopy(design["variants"]["roll_80"]["media"])
|
||||
roll_html, _, _, _ = compile_v4_design_to_jinja_html(design)
|
||||
assert 'data-template-variant="roll_80"' in roll_html
|
||||
assert "margin-top:2mm" in roll_html
|
||||
|
||||
|
||||
def test_v4_anchor_validation_rejects_cycles_and_bad_points():
|
||||
design_v2 = default_design_for_family("invoice_classic")
|
||||
assert design_v2 is not None
|
||||
design = migrate_v3_design_to_v4(migrate_v2_design_to_v3(design_v2))
|
||||
def walk(node):
|
||||
yield node
|
||||
for child in node.get("children") or []:
|
||||
yield from walk(child)
|
||||
nodes = {str(node.get("id") or ""): node for node in walk(design["root"])}
|
||||
nodes["invoice-lines"]["constraints"] = {
|
||||
"links": [{"axis": "vertical", "source_anchor": "top", "target": {"type": "node", "id": "payments", "anchor": "bottom"}}]
|
||||
}
|
||||
nodes["payments"]["constraints"] = {
|
||||
"links": [{"axis": "vertical", "source_anchor": "left", "target": {"type": "node", "id": "invoice-lines", "anchor": "bottom"}}]
|
||||
}
|
||||
errors = validate_v4_design("invoices", "detail", design)["errors"]
|
||||
assert "Anchor constraints contain a cycle" in errors
|
||||
assert any("horizontal point" in error.lower() for error in errors)
|
||||
|
||||
|
||||
def _service_v4_design() -> dict:
|
||||
design_v2 = default_design_for_family("invoice_classic")
|
||||
assert design_v2 is not None
|
||||
return migrate_v3_design_to_v4(migrate_v2_design_to_v3(design_v2))
|
||||
|
||||
|
||||
def _service_v4_nodes(design: dict) -> dict[str, dict]:
|
||||
def walk(node):
|
||||
yield node
|
||||
for child in node.get("children") or []:
|
||||
yield from walk(child)
|
||||
|
||||
return {str(node.get("id") or ""): node for node in walk(design["root"])}
|
||||
|
||||
|
||||
def _anchor_link(target_id: str, *, axis: str = "vertical", source: str = "top", target: str = "bottom") -> dict:
|
||||
return {
|
||||
"id": f"{axis}-anchor",
|
||||
"axis": axis,
|
||||
"source_anchor": source,
|
||||
"target": {"type": "node", "id": target_id, "anchor": target},
|
||||
"offset_mm": 5,
|
||||
}
|
||||
|
||||
|
||||
def _invalid_service_v4_design(case: str) -> dict:
|
||||
design = _service_v4_design()
|
||||
nodes = _service_v4_nodes(design)
|
||||
if case == "cycle":
|
||||
nodes["invoice-lines"]["constraints"] = {"links": [_anchor_link("payments")]}
|
||||
nodes["payments"]["constraints"] = {"links": [_anchor_link("invoice-lines")]}
|
||||
elif case == "missing_target":
|
||||
nodes["payments"]["constraints"] = {"links": [_anchor_link("deleted-node")]}
|
||||
elif case == "duplicate_axis":
|
||||
nodes["payments"]["constraints"] = {
|
||||
"links": [_anchor_link("invoice-lines"), _anchor_link("invoice-totals")],
|
||||
}
|
||||
elif case == "multiple_followers":
|
||||
nodes["invoice-totals"]["constraints"] = {"links": [_anchor_link("invoice-lines")]}
|
||||
nodes["payments"]["constraints"] = {"links": [_anchor_link("invoice-lines")]}
|
||||
elif case == "invalid_axis":
|
||||
nodes["payments"]["constraints"] = {"links": [_anchor_link("invoice-lines", axis="diagonal")]}
|
||||
elif case == "invalid_point":
|
||||
nodes["payments"]["constraints"] = {
|
||||
"links": [_anchor_link("invoice-lines", source="left")],
|
||||
}
|
||||
else:
|
||||
raise AssertionError(case)
|
||||
return design
|
||||
|
||||
|
||||
def _valid_service_anchor_chain() -> dict:
|
||||
design = _service_v4_design()
|
||||
nodes = _service_v4_nodes(design)
|
||||
for source_id, target_id, gap in (
|
||||
("invoice-totals", "invoice-lines", 5),
|
||||
("payments", "invoice-totals", 3),
|
||||
("signatures", "payments", 5),
|
||||
):
|
||||
link = _anchor_link(target_id)
|
||||
link["offset_mm"] = gap
|
||||
link["variant_offsets"] = {"a4_portrait": gap, "roll_80": 2}
|
||||
nodes[source_id]["constraints"] = {"links": [link], "keep_together": True}
|
||||
return design
|
||||
|
||||
|
||||
def _node_by_component(design: dict, component: str) -> dict:
|
||||
return next(
|
||||
node
|
||||
for node in _service_v4_nodes(design).values()
|
||||
if node.get("component") == component
|
||||
)
|
||||
|
||||
|
||||
def _template_for_v4_design(design: dict, *, paper_size: str = "A4") -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
engine="template_v2",
|
||||
assets={"template_design": design},
|
||||
content_html="",
|
||||
content_css="",
|
||||
header_html="",
|
||||
footer_html="",
|
||||
paper_size=paper_size,
|
||||
orientation="portrait",
|
||||
margins=None,
|
||||
)
|
||||
|
||||
|
||||
def _context_with_line_count(count: int) -> dict:
|
||||
context = _sample_invoice_context()
|
||||
base_line = context["lines"][0]
|
||||
context["lines"] = [
|
||||
{**base_line, "product_name": f"کالای شماره {index}"}
|
||||
for index in range(1, count + 1)
|
||||
]
|
||||
context["payments"] = [{"method_name": "نقدی", "amount": 100}]
|
||||
return context
|
||||
|
||||
|
||||
def _render_v4_pdf(design: dict, line_count: int):
|
||||
from weasyprint import HTML
|
||||
|
||||
rendered = ReportTemplateService.render_with_template(
|
||||
_template_for_v4_design(design),
|
||||
_context_with_line_count(line_count),
|
||||
)
|
||||
return HTML(string=rendered).render()
|
||||
|
||||
|
||||
def _boxes_with_attribute(document, attribute: str, value: str):
|
||||
result = []
|
||||
for page_index, page in enumerate(document.pages):
|
||||
def collect(box) -> None:
|
||||
element = getattr(box, "element", None)
|
||||
if element is not None and element.get(attribute) == value:
|
||||
result.append((page_index, box))
|
||||
for child in getattr(box, "children", []):
|
||||
collect(child)
|
||||
collect(page._page_box)
|
||||
return result
|
||||
|
||||
|
||||
def _page_text(page) -> str:
|
||||
parts: list[str] = []
|
||||
def collect(box) -> None:
|
||||
text = getattr(box, "text", None)
|
||||
if text:
|
||||
parts.append(str(text))
|
||||
for child in getattr(box, "children", []):
|
||||
collect(child)
|
||||
collect(page._page_box)
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def _service_template_payload(design: dict) -> dict:
|
||||
return {
|
||||
"business_id": 1,
|
||||
"module_key": "invoices",
|
||||
"subtype": "detail",
|
||||
"name": "قالب تست",
|
||||
"engine": "template_v2",
|
||||
"content_html": "generated by template design",
|
||||
"assets": {"template_design": design},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case",
|
||||
("cycle", "missing_target", "duplicate_axis", "multiple_followers", "invalid_axis", "invalid_point"),
|
||||
)
|
||||
@pytest.mark.parametrize("operation", ("create", "update"))
|
||||
def test_v4_invalid_assets_are_rejected_before_create_or_update(case, operation, monkeypatch):
|
||||
db = MagicMock()
|
||||
invalid_assets = {"template_design": _invalid_service_v4_design(case)}
|
||||
if operation == "create":
|
||||
payload = _service_template_payload(invalid_assets["template_design"])
|
||||
with pytest.raises(ApiError) as exc:
|
||||
ReportTemplateService.create_template(db, payload, user_id=1)
|
||||
else:
|
||||
original_assets = {"template_design": _service_v4_design()}
|
||||
entity = SimpleNamespace(
|
||||
module_key="invoices",
|
||||
subtype="detail",
|
||||
assets=deepcopy(original_assets),
|
||||
version=7,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ReportTemplateService,
|
||||
"get_template",
|
||||
staticmethod(lambda _db, _template_id, _business_id: entity),
|
||||
)
|
||||
with pytest.raises(ApiError) as exc:
|
||||
ReportTemplateService.update_template(
|
||||
db,
|
||||
template_id=10,
|
||||
data={"assets": invalid_assets},
|
||||
business_id=1,
|
||||
)
|
||||
assert entity.assets == original_assets
|
||||
assert entity.version == 7
|
||||
assert exc.value.code == "VALIDATION_ERROR"
|
||||
db.add.assert_not_called()
|
||||
db.commit.assert_not_called()
|
||||
|
||||
|
||||
def test_v4_after_content_bottom_mode_is_rejected_before_write():
|
||||
design = _service_v4_design()
|
||||
nodes = _service_v4_nodes(design)
|
||||
nodes["payments"]["constraints"] = {
|
||||
"pins": {"bottom": True},
|
||||
"bottom_mode": "after_content",
|
||||
}
|
||||
assert any(
|
||||
"Invalid bottom pin mode" in error
|
||||
for error in validate_v4_design("invoices", "detail", design)["errors"]
|
||||
)
|
||||
db = MagicMock()
|
||||
with pytest.raises(ApiError) as exc:
|
||||
ReportTemplateService.create_template(db, _service_template_payload(design), user_id=1)
|
||||
assert exc.value.code == "VALIDATION_ERROR"
|
||||
db.add.assert_not_called()
|
||||
db.commit.assert_not_called()
|
||||
|
||||
|
||||
def test_v4_explicit_anchor_chain_is_accepted_and_stored():
|
||||
design = _valid_service_anchor_chain()
|
||||
assert validate_v4_design("invoices", "detail", design)["errors"] == []
|
||||
db = MagicMock()
|
||||
entity = ReportTemplateService.create_template(
|
||||
db,
|
||||
_service_template_payload(design),
|
||||
user_id=1,
|
||||
)
|
||||
assert entity.assets == {"template_design": design}
|
||||
db.add.assert_called_once_with(entity)
|
||||
db.commit.assert_called_once()
|
||||
html, _, _, _ = compile_v4_design_to_jinja_html(entity.assets["template_design"])
|
||||
assert 'data-template-anchor-chain="invoice-lines"' in html
|
||||
assert 'data-template-node-ref="signatures"' in html
|
||||
|
||||
|
||||
@pytest.mark.parametrize("schema_version", (3, 4))
|
||||
def test_service_still_accepts_constraintless_v3_and_v4_designs(schema_version):
|
||||
design_v2 = default_design_for_family("invoice_classic")
|
||||
assert design_v2 is not None
|
||||
design_v3 = migrate_v2_design_to_v3(design_v2)
|
||||
design = design_v3 if schema_version == 3 else migrate_v3_design_to_v4(design_v3)
|
||||
assert all("constraints" not in node for node in _service_v4_nodes(design)) if schema_version == 4 else True
|
||||
db = MagicMock()
|
||||
entity = ReportTemplateService.create_template(
|
||||
db,
|
||||
_service_template_payload(design),
|
||||
user_id=1,
|
||||
)
|
||||
rendered = ReportTemplateService.render_with_template(entity, _sample_invoice_context())
|
||||
assert "INV-1" in rendered
|
||||
db.commit.assert_called_once()
|
||||
|
||||
|
||||
def test_service_v3_to_v4_copy_on_write_remains_intact_during_update(monkeypatch):
|
||||
design_v2 = default_design_for_family("invoice_classic")
|
||||
assert design_v2 is not None
|
||||
design_v3 = migrate_v2_design_to_v3(design_v2)
|
||||
original_v3 = deepcopy(design_v3)
|
||||
design_v4 = migrate_v3_design_to_v4(design_v3)
|
||||
assert design_v3 == original_v3
|
||||
entity = SimpleNamespace(
|
||||
module_key="invoices",
|
||||
subtype="detail",
|
||||
assets={"template_design": design_v3},
|
||||
version=3,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ReportTemplateService,
|
||||
"get_template",
|
||||
staticmethod(lambda _db, _template_id, _business_id: entity),
|
||||
)
|
||||
db = MagicMock()
|
||||
ReportTemplateService.update_template(
|
||||
db,
|
||||
template_id=11,
|
||||
data={"assets": {"template_design": design_v4}},
|
||||
business_id=1,
|
||||
)
|
||||
assert design_v3 == original_v3
|
||||
assert entity.assets["template_design"]["schema_version"] == 4
|
||||
assert entity.assets["template_design"] is design_v4
|
||||
db.commit.assert_called_once()
|
||||
|
||||
|
||||
def test_v4_compiler_contract_is_exact():
|
||||
design = _service_v4_design()
|
||||
assert design["schema_version"] == 4
|
||||
assert design["compiler_contract"] == {
|
||||
"name": "hesabix-template-html-css",
|
||||
"version": 1,
|
||||
"output": "html_css",
|
||||
}
|
||||
contract = studio_v4_contract("invoices", "detail")
|
||||
assert contract["schema_version"] == 4
|
||||
assert contract["compiler"] == design["compiler_contract"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("line_count", (1, 5, 40))
|
||||
def test_v4_complete_dynamic_chain_follows_real_table_height(line_count):
|
||||
design = _valid_service_anchor_chain()
|
||||
document = _render_v4_pdf(design, line_count)
|
||||
chain = (
|
||||
("invoice-lines", None),
|
||||
("invoice-totals", 5),
|
||||
("payments", 3),
|
||||
("signatures", 5),
|
||||
)
|
||||
previous_last = None
|
||||
for node_id, gap_mm in chain:
|
||||
boxes = _boxes_with_attribute(document, "data-template-node-ref", node_id)
|
||||
assert boxes, f"{node_id} was not rendered"
|
||||
first = min(boxes, key=lambda item: (item[0], item[1].position_y))
|
||||
last = max(boxes, key=lambda item: (item[0], item[1].position_y))
|
||||
if gap_mm is not None:
|
||||
assert first[1].margin_top * 25.4 / 96 == pytest.approx(gap_mm, abs=0.15)
|
||||
assert previous_last is not None
|
||||
assert first[0] > previous_last[0] or (
|
||||
first[0] == previous_last[0]
|
||||
and first[1].position_y >= previous_last[1].position_y + previous_last[1].height
|
||||
)
|
||||
previous_last = last
|
||||
|
||||
|
||||
def test_v4_dynamic_table_grows_beyond_its_designed_minimum_height():
|
||||
design = _valid_service_anchor_chain()
|
||||
line_node = _node_by_component(design, "invoice_lines")
|
||||
minimum_mm = float(line_node["placement"]["height_mm"])
|
||||
one_line = _render_v4_pdf(design, 1)
|
||||
forty_lines = _render_v4_pdf(design, 40)
|
||||
one_boxes = _boxes_with_attribute(one_line, "data-template-node-ref", "invoice-lines")
|
||||
forty_boxes = _boxes_with_attribute(forty_lines, "data-template-node-ref", "invoice-lines")
|
||||
assert sum(box.height for _, box in one_boxes) * 25.4 / 96 >= minimum_mm - 0.2
|
||||
assert sum(box.height for _, box in forty_boxes) > sum(box.height for _, box in one_boxes)
|
||||
|
||||
|
||||
def test_v4_roll_80_uses_two_millimeter_offsets_for_the_same_chain():
|
||||
design = _valid_service_anchor_chain()
|
||||
design["media"] = deepcopy(design["variants"]["roll_80"]["media"])
|
||||
html, _, _, _ = compile_v4_design_to_jinja_html(design)
|
||||
assert 'data-template-variant="roll_80"' in html
|
||||
assert html.count("margin-top:2mm") == 3
|
||||
assert "margin-top:5mm" not in html
|
||||
assert "margin-top:3mm" not in html
|
||||
|
||||
|
||||
def test_v4_horizontal_anchor_stays_geometric_when_invoice_lines_grow():
|
||||
design = _service_v4_design()
|
||||
payments = _node_by_component(design, "payments")
|
||||
payments["constraints"] = {
|
||||
"links": [{
|
||||
"id": "horizontal-anchor",
|
||||
"axis": "horizontal",
|
||||
"source_anchor": "left",
|
||||
"target": {"type": "node", "id": "invoice-lines", "anchor": "right"},
|
||||
"offset_mm": 2,
|
||||
}],
|
||||
}
|
||||
assert validate_v4_design("invoices", "detail", design)["errors"] == []
|
||||
one_line = _render_v4_pdf(design, 1)
|
||||
forty_lines = _render_v4_pdf(design, 40)
|
||||
positions = []
|
||||
for document in (one_line, forty_lines):
|
||||
boxes = _boxes_with_attribute(document, "data-template-node-id", "payments")
|
||||
assert boxes
|
||||
positions.append((boxes[0][0], boxes[0][1].position_x, boxes[0][1].position_y))
|
||||
assert positions[1] == pytest.approx(positions[0], abs=0.2)
|
||||
|
||||
|
||||
def test_v4_left_and_right_pins_stretch_width_per_variant():
|
||||
design = _service_v4_design()
|
||||
totals = _node_by_component(design, "invoice_totals")
|
||||
totals["constraints"] = {
|
||||
"pins": {"left": True, "right": True},
|
||||
"pin_offsets_mm": {"left": 5, "right": 5},
|
||||
"variant_pin_offsets": {
|
||||
"a4_portrait": {"left": 5, "right": 5},
|
||||
"roll_80": {"left": 2, "right": 2},
|
||||
},
|
||||
}
|
||||
a4_html, _, _, _ = compile_v4_design_to_jinja_html(design)
|
||||
assert "grid-column:6/span 180" in a4_html
|
||||
design["media"] = deepcopy(design["variants"]["roll_80"]["media"])
|
||||
roll_html, _, _, _ = compile_v4_design_to_jinja_html(design)
|
||||
assert "grid-column:3/span 72" in roll_html
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("bottom_mode", "expected_pages"),
|
||||
(("last_page", "last"), ("every_page", "all")),
|
||||
)
|
||||
def test_v4_bottom_pin_modes_place_footer_on_expected_pages(bottom_mode, expected_pages):
|
||||
design = _service_v4_design()
|
||||
footer = _node_by_component(design, "footer_meta")
|
||||
footer["placement"] = {
|
||||
**footer["placement"],
|
||||
"x_mm": 10,
|
||||
"y_mm": 260,
|
||||
"width_mm": 100,
|
||||
"height_mm": 12,
|
||||
}
|
||||
footer["constraints"] = {
|
||||
"pins": {"bottom": True},
|
||||
"pin_offsets_mm": {"bottom": 5},
|
||||
"bottom_mode": bottom_mode,
|
||||
"keep_together": True,
|
||||
}
|
||||
document = _render_v4_pdf(design, 80)
|
||||
assert len(document.pages) >= 2
|
||||
boxes = _boxes_with_attribute(document, "data-template-node-id", footer["id"])
|
||||
pages = sorted({page for page, _ in boxes})
|
||||
assert pages == ([len(document.pages) - 1] if expected_pages == "last" else list(range(len(document.pages))))
|
||||
|
||||
|
||||
def test_v4_keep_together_css_covers_totals_payments_and_signatures():
|
||||
design = _service_v4_design()
|
||||
html, css, _, _ = compile_v4_design_to_jinja_html(design)
|
||||
assert ".rt-anchor-keep-together { break-inside:avoid; page-break-inside:avoid; }" in css
|
||||
for node_id in ("invoice-totals", "payments", "signatures"):
|
||||
pattern = rf'class="[^"]*rt-anchor-keep-together[^"]*"[^>]*>.*?data-template-node-id="{node_id}"'
|
||||
assert re.search(pattern, html, re.DOTALL), node_id
|
||||
|
||||
|
||||
def test_v4_table_header_repeats_and_designed_height_is_a_minimum():
|
||||
design = _valid_service_anchor_chain()
|
||||
header = str(_node_by_component(design, "invoice_lines")["props"]["columns"][0]["title"])
|
||||
document = _render_v4_pdf(design, 80)
|
||||
assert len(document.pages) >= 2
|
||||
line_pages = []
|
||||
for page_index, page in enumerate(document.pages):
|
||||
if _boxes_with_attribute(type("D", (), {"pages": [page]})(), "data-template-node-id", "invoice-lines"):
|
||||
line_pages.append(page_index)
|
||||
assert header in _page_text(page)
|
||||
assert len(line_pages) >= 2
|
||||
|
||||
|
||||
def test_v4_editor_zoom_metadata_does_not_change_html_or_css():
|
||||
design = _service_v4_design()
|
||||
baseline = compile_v4_design_to_jinja_html(design)
|
||||
zoomed = deepcopy(design)
|
||||
zoomed["editor_state"] = {"zoom": 2.0}
|
||||
assert compile_v4_design_to_jinja_html(zoomed) == baseline
|
||||
|
||||
|
||||
def test_v4_direction_does_not_mirror_physical_grid_geometry():
|
||||
rtl = _service_v4_design()
|
||||
ltr = deepcopy(rtl)
|
||||
ltr["theme"] = {**ltr.get("theme", {}), "direction": "ltr"}
|
||||
rtl_html, _, _, _ = compile_v4_design_to_jinja_html(rtl)
|
||||
ltr_html, _, _, _ = compile_v4_design_to_jinja_html(ltr)
|
||||
assert '<html dir="rtl"' in rtl_html
|
||||
assert '<html dir="ltr"' in ltr_html
|
||||
geometry = re.compile(r"style=\"grid-column:[^\"]+;grid-row:[^\"]+;min-height:[^\"]+\"")
|
||||
assert geometry.findall(ltr_html) == geometry.findall(rtl_html)
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -99,7 +99,7 @@ Map<String, dynamic> _mergedNode(
|
|||
) {
|
||||
final result = _cloneMap(node);
|
||||
final override = _map(overrides[(node['id'] ?? '').toString()]);
|
||||
for (final key in const ['layout', 'placement', 'style']) {
|
||||
for (final key in const ['layout', 'placement', 'style', 'constraints']) {
|
||||
if (override[key] is Map) {
|
||||
result[key] = <String, dynamic>{
|
||||
..._map(result[key]),
|
||||
|
|
@ -151,6 +151,7 @@ Map<String, dynamic> reportTemplateV4StudioProjection(
|
|||
final fallbackWidth = pageWidth * span / 60;
|
||||
final style = <String, dynamic>{
|
||||
..._map(component['style']),
|
||||
'anchor_constraints': _cloneMap(_map(component['constraints'])),
|
||||
'row_id': row['id'],
|
||||
'layout_type': 'page_grid',
|
||||
'grid_span': placement['column_span'] ?? 60,
|
||||
|
|
@ -239,6 +240,7 @@ Map<String, dynamic> _layoutFromBlocks(List<Map<String, dynamic>> blocks) {
|
|||
|
||||
Map<String, dynamic> _componentFromBlock(Map<String, dynamic> block) {
|
||||
final style = _cloneMap(_map(block['style']));
|
||||
final constraints = _cloneMap(_map(style.remove('anchor_constraints')));
|
||||
final layoutType = (style['layout_type'] ?? 'grid').toString();
|
||||
final placement = layoutType == 'freeform' || layoutType == 'page_grid'
|
||||
? <String, dynamic>{
|
||||
|
|
@ -277,6 +279,7 @@ Map<String, dynamic> _componentFromBlock(Map<String, dynamic> block) {
|
|||
'props': _cloneMap(_map(block['props'])),
|
||||
'style': style,
|
||||
'placement': placement,
|
||||
if (constraints.isNotEmpty) 'constraints': constraints,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -468,8 +471,10 @@ Map<String, dynamic> applyStudioProjectionToReportTemplateV4(
|
|||
'height_mm': height,
|
||||
};
|
||||
}
|
||||
final constraints = _cloneMap(_map(node['constraints']));
|
||||
nextOverrides[nodeEntry.key] = <String, dynamic>{
|
||||
'placement': placement,
|
||||
if (constraints.isNotEmpty) 'constraints': constraints,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:hesabix_ui/widgets/report_template/studio/report_template_snap_engine.dart';
|
||||
import 'package:hesabix_ui/widgets/report_template/studio/report_template_studio_v3_builder.dart';
|
||||
|
|
@ -50,6 +52,15 @@ Map<String, dynamic> _design() {
|
|||
'style': <String, dynamic>{},
|
||||
'placement': placement,
|
||||
},
|
||||
{
|
||||
'id': 'text-two',
|
||||
'kind': 'component',
|
||||
'component': 'custom_text',
|
||||
'visible': true,
|
||||
'props': {'text': 'متن دوم'},
|
||||
'style': <String, dynamic>{},
|
||||
'placement': {...placement, 'y_mm': 50},
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
|
@ -80,6 +91,9 @@ Map<String, dynamic> _design() {
|
|||
'text-one': {
|
||||
'placement': {...placement, 'x_mm': x, 'width_mm': width},
|
||||
},
|
||||
'text-two': {
|
||||
'placement': {...placement, 'x_mm': x, 'y_mm': 50, 'width_mm': width},
|
||||
},
|
||||
};
|
||||
return <String, dynamic>{
|
||||
'schema_version': 4,
|
||||
|
|
@ -109,6 +123,73 @@ Map<String, dynamic> _design() {
|
|||
};
|
||||
}
|
||||
|
||||
Map<String, dynamic>? _findNode(Map<String, dynamic> node, String id) {
|
||||
if (node['id'] == id) return node;
|
||||
for (final child in (node['children'] as List?) ?? const []) {
|
||||
if (child is Map) {
|
||||
final found = _findNode(child.cast<String, dynamic>(), id);
|
||||
if (found != null) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Map<String, dynamic> _designWithExistingAnchor() {
|
||||
final design = _design();
|
||||
final node = _findNode(
|
||||
(design['root'] as Map).cast<String, dynamic>(),
|
||||
'text-two',
|
||||
)!;
|
||||
node['constraints'] = {
|
||||
'links': [
|
||||
{
|
||||
'id': 'vertical-anchor',
|
||||
'axis': 'vertical',
|
||||
'source_anchor': 'top',
|
||||
'target': {'type': 'node', 'id': 'text-one', 'anchor': 'bottom'},
|
||||
'offset_mm': 5,
|
||||
'variant_offsets': {'a4_portrait': 5, 'roll_80': 2},
|
||||
},
|
||||
],
|
||||
};
|
||||
return design;
|
||||
}
|
||||
|
||||
Map<String, dynamic> _designWithThirdBlock() {
|
||||
final design = _designWithExistingAnchor();
|
||||
final row = _findNode(
|
||||
(design['root'] as Map).cast<String, dynamic>(),
|
||||
'row-text',
|
||||
)!;
|
||||
(row['children'] as List).add({
|
||||
'id': 'text-three',
|
||||
'kind': 'component',
|
||||
'component': 'custom_text',
|
||||
'visible': true,
|
||||
'props': {'text': 'متن سوم'},
|
||||
'style': <String, dynamic>{},
|
||||
'placement': {
|
||||
'column_span': 30,
|
||||
'x_mm': 80,
|
||||
'y_mm': 80,
|
||||
'width_mm': 60,
|
||||
'height_mm': 24,
|
||||
},
|
||||
});
|
||||
for (final variant in (design['variants'] as Map).values) {
|
||||
((variant as Map)['node_overrides'] as Map)['text-three'] = {
|
||||
'placement': {
|
||||
'column_span': 30,
|
||||
'x_mm': 80,
|
||||
'y_mm': 80,
|
||||
'width_mm': 60,
|
||||
'height_mm': 24,
|
||||
},
|
||||
};
|
||||
}
|
||||
return design;
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('responsive paper variants are projected and edited independently', () {
|
||||
final design = _design();
|
||||
|
|
@ -226,6 +307,21 @@ void main() {
|
|||
final block = find.byKey(const ValueKey('freeform-block-text-one'));
|
||||
expect(block, findsOneWidget);
|
||||
expect(find.text('متن تست'), findsOneWidget);
|
||||
final beforeZoom = tester.getSize(block);
|
||||
await tester.tap(find.byKey(const ValueKey('studio-zoom-in')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('110٪'), findsOneWidget);
|
||||
expect(tester.getSize(block).width, greaterThan(beforeZoom.width));
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.sendEventToBinding(
|
||||
PointerScrollEvent(
|
||||
position: tester.getCenter(block),
|
||||
scrollDelta: const Offset(0, -20),
|
||||
),
|
||||
);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('120٪'), findsOneWidget);
|
||||
final beforeMove = tester.getTopLeft(block);
|
||||
final moveGesture = await tester.startGesture(tester.getCenter(block));
|
||||
await moveGesture.moveBy(const Offset(30, 0));
|
||||
|
|
@ -249,4 +345,410 @@ void main() {
|
|||
expect(changed, isNotNull);
|
||||
expect(changed!['schema_version'], 4);
|
||||
});
|
||||
|
||||
testWidgets('anchor handles persist a responsive node constraint', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.binding.setSurfaceSize(const Size(1600, 1000));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
Map<String, dynamic>? changed;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 1500,
|
||||
height: 900,
|
||||
child: ReportTemplateStudioV3Builder(
|
||||
design: _design(),
|
||||
blockCatalog: const [
|
||||
{
|
||||
'type': 'custom_text',
|
||||
'label_fa': 'متن دلخواه',
|
||||
'allowed_regions': ['header', 'body', 'footer'],
|
||||
'default_props': {'text': 'متن'},
|
||||
},
|
||||
],
|
||||
onDesignChanged: (value) => changed = value,
|
||||
previewPane: const ColoredBox(color: Colors.white),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final second = find.byKey(const ValueKey('freeform-block-text-two'));
|
||||
await tester.tapAt(tester.getCenter(second));
|
||||
await tester.pump();
|
||||
await tester.tap(find.byKey(const ValueKey('anchor-handle-text-two-top')));
|
||||
await tester.pump();
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey('anchor-handle-text-one-bottom')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(changed, isNotNull);
|
||||
|
||||
Map? findNode(Map node, String id) {
|
||||
if (node['id'] == id) return node;
|
||||
for (final child in (node['children'] as List?) ?? const []) {
|
||||
if (child is Map) {
|
||||
final found = findNode(child, id);
|
||||
if (found != null) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
final node = findNode(changed!['root'] as Map, 'text-two')!;
|
||||
final links = ((node['constraints'] as Map)['links'] as List);
|
||||
expect(links, hasLength(1));
|
||||
expect((links.first as Map)['source_anchor'], 'top');
|
||||
expect(((links.first as Map)['target'] as Map)['id'], 'text-one');
|
||||
expect(
|
||||
((links.first as Map)['variant_offsets'] as Map),
|
||||
contains('a4_portrait'),
|
||||
);
|
||||
final variants = changed!['variants'] as Map;
|
||||
for (final variant in variants.values) {
|
||||
final overrides = (variant as Map)['node_overrides'] as Map;
|
||||
final responsiveConstraints =
|
||||
(overrides['text-two'] as Map)['constraints'] as Map;
|
||||
final responsiveLink =
|
||||
(responsiveConstraints['links'] as List).single as Map;
|
||||
expect(responsiveLink['source_anchor'], 'top');
|
||||
expect((responsiveLink['target'] as Map)['id'], 'text-one');
|
||||
expect(responsiveLink['variant_offsets'], contains('a4_portrait'));
|
||||
}
|
||||
});
|
||||
|
||||
test('grid snapping supports 1, 3, and 5 millimeters and hard bounds', () {
|
||||
for (final grid in const [1.0, 3.0, 5.0]) {
|
||||
final result = snapStudioMove(
|
||||
proposed: const StudioMmRect(107.8, 107.8, 10, 10),
|
||||
siblings: const [],
|
||||
containerWidthMm: 1000,
|
||||
containerHeightMm: 1000,
|
||||
gridMm: grid,
|
||||
thresholdMm: grid,
|
||||
);
|
||||
expect(result.rect.x % grid, closeTo(0, 0.0001));
|
||||
expect(result.rect.y % grid, closeTo(0, 0.0001));
|
||||
}
|
||||
|
||||
final exactBoundary = snapStudioMove(
|
||||
proposed: const StudioMmRect(70, 30, 10, 10),
|
||||
siblings: const [],
|
||||
containerWidthMm: 80,
|
||||
containerHeightMm: 40,
|
||||
gridMm: 1,
|
||||
thresholdMm: 0,
|
||||
enabled: false,
|
||||
);
|
||||
expect(exactBoundary.rect.x, 70);
|
||||
expect(exactBoundary.rect.y, 30);
|
||||
|
||||
final outsideBoundary = snapStudioResize(
|
||||
proposed: const StudioMmRect(70, 30, 11, 11),
|
||||
siblings: const [],
|
||||
containerWidthMm: 80,
|
||||
containerHeightMm: 40,
|
||||
gridMm: 1,
|
||||
thresholdMm: 0,
|
||||
enabled: false,
|
||||
);
|
||||
expect(outsideBoundary.rect.right, 80);
|
||||
expect(outsideBoundary.rect.bottom, 40);
|
||||
});
|
||||
|
||||
testWidgets('page grid keeps sibling blocks side by side', (tester) async {
|
||||
await tester.binding.setSurfaceSize(const Size(1600, 1000));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
final design = _design();
|
||||
for (final variant in (design['variants'] as Map).values) {
|
||||
final overrides = (variant as Map)['node_overrides'] as Map;
|
||||
(overrides['text-one'] as Map)['placement'] = <String, dynamic>{
|
||||
...Map<String, dynamic>.from(
|
||||
(overrides['text-one'] as Map)['placement'] as Map,
|
||||
),
|
||||
'x_mm': 5,
|
||||
'y_mm': 8,
|
||||
'width_mm': 60,
|
||||
};
|
||||
(overrides['text-two'] as Map)['placement'] = <String, dynamic>{
|
||||
...Map<String, dynamic>.from(
|
||||
(overrides['text-two'] as Map)['placement'] as Map,
|
||||
),
|
||||
'x_mm': 70,
|
||||
'y_mm': 8,
|
||||
'width_mm': 60,
|
||||
};
|
||||
}
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ReportTemplateStudioV3Builder(
|
||||
design: design,
|
||||
blockCatalog: const [
|
||||
{
|
||||
'type': 'custom_text',
|
||||
'label_fa': 'متن دلخواه',
|
||||
'allowed_regions': ['header', 'body', 'footer'],
|
||||
'default_props': {'text': 'متن'},
|
||||
},
|
||||
],
|
||||
onDesignChanged: (_) {},
|
||||
previewPane: const ColoredBox(color: Colors.white),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final first = find.byKey(const ValueKey('freeform-block-text-one'));
|
||||
final second = find.byKey(const ValueKey('freeform-block-text-two'));
|
||||
expect(
|
||||
tester.getTopLeft(first).dy,
|
||||
closeTo(tester.getTopLeft(second).dy, 0.5),
|
||||
);
|
||||
expect(tester.getTopLeft(first).dx, lessThan(tester.getTopLeft(second).dx));
|
||||
});
|
||||
|
||||
testWidgets('studio persists page grid choices 1, 3, and 5', (tester) async {
|
||||
await tester.binding.setSurfaceSize(const Size(1600, 1000));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
var current = _design();
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: StatefulBuilder(
|
||||
builder: (context, setState) => Scaffold(
|
||||
body: ReportTemplateStudioV3Builder(
|
||||
design: current,
|
||||
blockCatalog: const [
|
||||
{
|
||||
'type': 'custom_text',
|
||||
'label_fa': 'متن دلخواه',
|
||||
'allowed_regions': ['header', 'body', 'footer'],
|
||||
'default_props': {'text': 'متن'},
|
||||
},
|
||||
],
|
||||
onDesignChanged: (value) => setState(() => current = value),
|
||||
previewPane: const ColoredBox(color: Colors.white),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tapAt(
|
||||
tester.getCenter(find.byKey(const ValueKey('freeform-block-text-one'))),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
for (final grid in const [3, 5, 1]) {
|
||||
await tester.tap(
|
||||
find.text(
|
||||
'$grid mm'
|
||||
.replaceAll('1', '۱')
|
||||
.replaceAll('3', '۳')
|
||||
.replaceAll('5', '۵'),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(((current['root'] as Map)['layout'] as Map)['grid_mm'], grid);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('anchor can be removed from settings and persisted document', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.binding.setSurfaceSize(const Size(1600, 1000));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
var current = _designWithExistingAnchor();
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: StatefulBuilder(
|
||||
builder: (context, setState) => Scaffold(
|
||||
body: ReportTemplateStudioV3Builder(
|
||||
design: current,
|
||||
blockCatalog: const [
|
||||
{
|
||||
'type': 'custom_text',
|
||||
'label_fa': 'متن دلخواه',
|
||||
'allowed_regions': ['header', 'body', 'footer'],
|
||||
'default_props': {'text': 'متن'},
|
||||
},
|
||||
],
|
||||
onDesignChanged: (value) => setState(() => current = value),
|
||||
previewPane: const ColoredBox(color: Colors.white),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tapAt(
|
||||
tester.getCenter(find.byKey(const ValueKey('freeform-block-text-two'))),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byTooltip('قطع اتصال'));
|
||||
await tester.pumpAndSettle();
|
||||
final node = _findNode(
|
||||
(current['root'] as Map).cast<String, dynamic>(),
|
||||
'text-two',
|
||||
)!;
|
||||
expect(((node['constraints'] as Map)['links'] as List), isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('anchor UI rejects cycles and a second direct follower', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.binding.setSurfaceSize(const Size(1600, 1000));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
var current = _designWithThirdBlock();
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: StatefulBuilder(
|
||||
builder: (context, setState) => Scaffold(
|
||||
body: ReportTemplateStudioV3Builder(
|
||||
design: current,
|
||||
blockCatalog: const [
|
||||
{
|
||||
'type': 'custom_text',
|
||||
'label_fa': 'متن دلخواه',
|
||||
'allowed_regions': ['header', 'body', 'footer'],
|
||||
'default_props': {'text': 'متن'},
|
||||
},
|
||||
],
|
||||
onDesignChanged: (value) => setState(() => current = value),
|
||||
previewPane: const ColoredBox(color: Colors.white),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tapAt(
|
||||
tester.getCenter(find.byKey(const ValueKey('freeform-block-text-one'))),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.tap(find.byKey(const ValueKey('anchor-handle-text-one-top')));
|
||||
await tester.pump();
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey('anchor-handle-text-two-bottom')),
|
||||
);
|
||||
await tester.pump();
|
||||
expect(find.text('این اتصال یک چرخه ایجاد میکند.'), findsOneWidget);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tapAt(
|
||||
tester.getCenter(find.byKey(const ValueKey('freeform-block-text-three'))),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey('anchor-handle-text-three-top')),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey('anchor-handle-text-one-bottom')),
|
||||
);
|
||||
await tester.pump();
|
||||
final third = _findNode(
|
||||
(current['root'] as Map).cast<String, dynamic>(),
|
||||
'text-three',
|
||||
)!;
|
||||
final constraints = (third['constraints'] as Map?) ?? const {};
|
||||
expect((constraints['links'] as List?) ?? const [], isEmpty);
|
||||
expect(find.byType(SnackBar), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('zoom is clamped, resets, and never changes the design', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.binding.setSurfaceSize(const Size(1600, 1000));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
var changes = 0;
|
||||
final design = _design();
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ReportTemplateStudioV3Builder(
|
||||
design: design,
|
||||
blockCatalog: const [
|
||||
{
|
||||
'type': 'custom_text',
|
||||
'label_fa': 'متن دلخواه',
|
||||
'allowed_regions': ['header', 'body', 'footer'],
|
||||
'default_props': {'text': 'متن'},
|
||||
},
|
||||
],
|
||||
onDesignChanged: (_) => changes++,
|
||||
previewPane: const ColoredBox(color: Colors.white),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
for (var index = 0; index < 20; index++) {
|
||||
await tester.tap(find.byKey(const ValueKey('studio-zoom-in')));
|
||||
await tester.pump();
|
||||
}
|
||||
expect(find.text('250٪'), findsOneWidget);
|
||||
await tester.tap(find.byKey(const ValueKey('studio-zoom-in')));
|
||||
await tester.pump();
|
||||
expect(find.text('250٪'), findsOneWidget);
|
||||
await tester.tap(find.byKey(const ValueKey('studio-zoom-reset')));
|
||||
await tester.pump();
|
||||
expect(find.text('100٪'), findsOneWidget);
|
||||
for (var index = 0; index < 20; index++) {
|
||||
await tester.tap(find.byKey(const ValueKey('studio-zoom-out')));
|
||||
await tester.pump();
|
||||
}
|
||||
expect(find.text('50٪'), findsOneWidget);
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.sendEventToBinding(
|
||||
PointerScrollEvent(
|
||||
position: tester.getCenter(
|
||||
find.byKey(const ValueKey('freeform-block-text-one')),
|
||||
),
|
||||
scrollDelta: const Offset(0, 30),
|
||||
),
|
||||
);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.pump();
|
||||
expect(find.text('50٪'), findsOneWidget);
|
||||
expect(changes, 0);
|
||||
expect(design.toString(), isNot(contains('zoom')));
|
||||
});
|
||||
|
||||
testWidgets('viewport resize does not change the print media profile', (
|
||||
tester,
|
||||
) async {
|
||||
var changes = 0;
|
||||
final design = _design();
|
||||
await tester.binding.setSurfaceSize(const Size(1600, 1000));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ReportTemplateStudioV3Builder(
|
||||
design: design,
|
||||
blockCatalog: const [
|
||||
{
|
||||
'type': 'custom_text',
|
||||
'label_fa': 'متن دلخواه',
|
||||
'allowed_regions': ['header', 'body', 'footer'],
|
||||
'default_props': {'text': 'متن'},
|
||||
},
|
||||
],
|
||||
onDesignChanged: (_) => changes++,
|
||||
previewPane: const ColoredBox(color: Colors.white),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(reportTemplateV4ProfileKey(design), 'a4_portrait');
|
||||
await tester.binding.setSurfaceSize(const Size(700, 900));
|
||||
await tester.pumpAndSettle();
|
||||
expect(reportTemplateV4ProfileKey(design), 'a4_portrait');
|
||||
expect(changes, 0);
|
||||
});
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue