feat(report-templates): add block-based invoice studio #22

Merged
morrning merged 1 commit from Seyyed/Seyyed_arc:feature/report-template-studio into master 2026-10-19 22:40:59 +03:30
18 changed files with 3125 additions and 245 deletions

View file

@ -19,6 +19,11 @@ from app.services.report_template_scope_registry import (
) )
from app.services.report_template_gallery import list_gallery_items from app.services.report_template_gallery import list_gallery_items
from app.services.report_template_v2_service import migrate_builder_design_to_v2 from app.services.report_template_v2_service import migrate_builder_design_to_v2
from app.services.report_template_v3_service import (
migrate_v2_design_to_v3,
studio_block_catalog,
)
from app.services.template_design_v3_compiler import compile_template_design_to_jinja_html
router = APIRouter(prefix="/report-templates", tags=["قالب‌های گزارش", "گزارش‌ها"]) router = APIRouter(prefix="/report-templates", tags=["قالب‌های گزارش", "گزارش‌ها"])
@ -599,6 +604,46 @@ async def preview_report_template(
raise ApiError("PDF_ERROR", f"PDF generation error: {e}", http_status=400) from e raise ApiError("PDF_ERROR", f"PDF generation error: {e}", http_status=400) from e
@router.post(
"/business/{business_id}/preview-html",
summary="پیش‌نمایش سریع HTML قالب",
description="بدون ذخیره‌سازی و بدون تولید PDF؛ برای پیش‌نمایش زنده Studio.",
)
@require_business_access("business_id")
async def preview_report_template_html(
request: Request,
business_id: int,
body: Dict[str, Any] = Body(...),
ctx: AuthContext = Depends(get_current_user),
db: Session = Depends(get_db),
):
if not ctx.can_write_section("report_templates"):
raise ApiError("FORBIDDEN", "Missing permission: report_templates.write", http_status=403)
engine = str((body or {}).get("engine") or "").lower() or "jinja2"
content_html = (body or {}).get("content_html") or ""
content_css = (body or {}).get("content_css") or ""
if len(content_html) > 1_000_000 or len(content_css) > 1_000_000:
raise ApiError("PAYLOAD_TOO_LARGE", "HTML/CSS too large for preview", http_status=413)
temp = type("T", (), {
"engine": engine,
"content_html": content_html,
"content_css": content_css,
"header_html": (body or {}).get("header_html") or "",
"footer_html": (body or {}).get("footer_html") or "",
"paper_size": (body or {}).get("paper_size") or None,
"orientation": (body or {}).get("orientation") or None,
"margins": (body or {}).get("margins") or None,
"assets": _preview_assets(body or {}, engine),
})()
try:
rendered = ReportTemplateService.render_with_template(temp, (body or {}).get("context") or {})
except ApiError:
raise
except Exception as ex:
raise ApiError("TEMPLATE_ERROR", f"Render error: {ex}", http_status=400) from ex
return {"ok": True, "html": rendered}
@router.post( @router.post(
"/business/{business_id}/preview-pdf", "/business/{business_id}/preview-pdf",
summary="پیش‌نمایش PDF قالب (فقط سازندگان)", summary="پیش‌نمایش PDF قالب (فقط سازندگان)",
@ -715,6 +760,13 @@ async def report_template_schema(
{"name": "business_logo_data_uri", "desc": "لوگوی کسب‌وکار"}, {"name": "business_logo_data_uri", "desc": "لوگوی کسب‌وکار"},
{"name": "invoice_footer_note", "desc": "یادداشت پاورقی"}, {"name": "invoice_footer_note", "desc": "یادداشت پاورقی"},
{"name": "invoice_verify_qr_data_uri", "desc": "QR تأیید فاکتور"}, {"name": "invoice_verify_qr_data_uri", "desc": "QR تأیید فاکتور"},
{"name": "show_line_discount_column", "desc": "نمایش ستون تخفیف سطری"},
{"name": "show_line_tax_column", "desc": "نمایش ستون مالیات سطری"},
{"name": "show_line_amount_before_discount_column", "desc": "نمایش مبلغ پیش از تخفیف"},
{"name": "show_line_amount_before_tax_column", "desc": "نمایش مبلغ پیش از مالیات"},
{"name": "show_summary_discount", "desc": "نمایش تخفیف در جمع‌بندی"},
{"name": "show_summary_tax", "desc": "نمایش مالیات در جمع‌بندی"},
{"name": "show_summary_amount_without_tax", "desc": "نمایش مبلغ بدون مالیات در جمع‌بندی"},
] ]
data["sample_context"].update( data["sample_context"].update(
{ {
@ -727,6 +779,8 @@ async def report_template_schema(
"issue_date": "1403/10/01", "issue_date": "1403/10/01",
"subtotal": 1000000, "subtotal": 1000000,
"discount_total": 50000, "discount_total": 50000,
"discount_summary_display": "۵٪ (50,000)",
"amount_without_tax": 950000,
"tax_total": 85500, "tax_total": 85500,
"payable_total": 1035500, "payable_total": 1035500,
}, },
@ -738,7 +792,12 @@ async def report_template_schema(
"quantity_display": "2", "quantity_display": "2",
"unit_display": "عدد", "unit_display": "عدد",
"unit_price": 250000, "unit_price": 250000,
"line_total": 500000, "discount": 25000,
"discount_display": "۵٪ (25,000)",
"amount_before_discount": 500000,
"amount_before_tax": 475000,
"tax_amount": 42750,
"line_total": 517750,
}, },
{ {
"product_name": "کالای نمونه ۲", "product_name": "کالای نمونه ۲",
@ -747,7 +806,12 @@ async def report_template_schema(
"quantity_display": "1", "quantity_display": "1",
"unit_display": "عدد", "unit_display": "عدد",
"unit_price": 500000, "unit_price": 500000,
"line_total": 500000, "discount": 25000,
"discount_display": "۵٪ (25,000)",
"amount_before_discount": 500000,
"amount_before_tax": 475000,
"tax_amount": 42750,
"line_total": 517750,
}, },
], ],
"buyer": {"name": "مشتری نمونه"}, "buyer": {"name": "مشتری نمونه"},
@ -755,6 +819,15 @@ async def report_template_schema(
"payments": [{"method_name": "نقد", "amount": 500000}], "payments": [{"method_name": "نقد", "amount": 500000}],
"invoice_footer_note": "این یک پیش‌نمایش نمونه است.", "invoice_footer_note": "این یک پیش‌نمایش نمونه است.",
"show_invoice_verify_qr": False, "show_invoice_verify_qr": False,
"show_line_discount_column": True,
"show_line_tax_column": True,
"show_line_amount_before_discount_column": True,
"show_line_amount_before_tax_column": True,
"show_summary_discount": True,
"show_summary_tax": True,
"show_summary_amount_without_tax": True,
"has_line_discount": True,
"has_line_tax": True,
"generated_at": "1403/10/01 12:00", "generated_at": "1403/10/01 12:00",
"issuer_name": "کاربر نمونه", "issuer_name": "کاربر نمونه",
"is_fa": True, "is_fa": True,
@ -1015,7 +1088,30 @@ async def report_template_gallery(
ctx: AuthContext = Depends(get_current_user), ctx: AuthContext = Depends(get_current_user),
db: Session = Depends(get_db), db: Session = Depends(get_db),
): ):
return {"items": list_gallery_items(module_key=module_key, subtype=subtype)} items = list_gallery_items(module_key=module_key, subtype=subtype)
for item in items:
try:
item["studio_design"] = migrate_v2_design_to_v3(item["default_design"])
except ValueError:
# Scopeهایی که هنوز وارد Studio v3 نشده‌اند، با ویرایشگر v2 باز می‌شوند.
pass
return {"items": items}
@router.get(
"/business/{business_id}/studio-blocks",
summary="کاتالوگ بلوک‌های Studio v3",
)
@require_business_access("business_id")
async def report_template_studio_blocks(
request: Request,
business_id: int,
module_key: str,
subtype: Optional[str] = None,
ctx: AuthContext = Depends(get_current_user),
db: Session = Depends(get_db),
):
return {"items": studio_block_catalog(module_key, subtype)}
@router.post( @router.post(
@ -1060,10 +1156,8 @@ async def compile_v2_design_endpoint(
design = (body or {}).get("design") or {} design = (body or {}).get("design") or {}
if not isinstance(design, dict): if not isinstance(design, dict):
raise ApiError("VALIDATION_ERROR", "design must be an object", http_status=400) raise ApiError("VALIDATION_ERROR", "design must be an object", http_status=400)
from app.services.template_design_v2_compiler import compile_v2_design_to_jinja_html
try: try:
html, css, header, footer = compile_v2_design_to_jinja_html(design) html, css, header, footer = compile_template_design_to_jinja_html(design)
except Exception as ex: except Exception as ex:
raise ApiError("COMPILE_ERROR", str(ex), http_status=400) raise ApiError("COMPILE_ERROR", str(ex), http_status=400)
return { return {
@ -1074,6 +1168,82 @@ async def compile_v2_design_endpoint(
} }
@router.post(
"/business/{business_id}/validate-studio-design",
summary="اعتبارسنجی طراحی Studio",
)
@require_business_access("business_id")
async def validate_studio_design_endpoint(
request: Request,
business_id: int,
body: Dict[str, Any] = Body(...),
ctx: AuthContext = Depends(get_current_user),
db: Session = Depends(get_db),
):
if not ctx.can_write_section("report_templates"):
raise ApiError("FORBIDDEN", "Missing permission: report_templates.write", http_status=403)
module_key = str((body or {}).get("module_key") or "")
subtype_raw = (body or {}).get("subtype")
subtype = str(subtype_raw) if subtype_raw not in (None, "") else None
design = (body or {}).get("design") or {}
if not isinstance(design, dict):
raise ApiError("VALIDATION_ERROR", "design must be an object", http_status=400)
return ReportTemplateService.validate_template_v2_design_scope(module_key, subtype, design)
@router.post(
"/business/{business_id}/compile-studio-design",
summary="کامپایل طراحی Studio به HTML/CSS",
)
@require_business_access("business_id")
async def compile_studio_design_endpoint(
request: Request,
business_id: int,
body: Dict[str, Any] = Body(...),
ctx: AuthContext = Depends(get_current_user),
db: Session = Depends(get_db),
):
if not ctx.can_write_section("report_templates"):
raise ApiError("FORBIDDEN", "Missing permission: report_templates.write", http_status=403)
design = (body or {}).get("design") or {}
if not isinstance(design, dict):
raise ApiError("VALIDATION_ERROR", "design must be an object", http_status=400)
try:
html, css, header, footer = compile_template_design_to_jinja_html(design)
except Exception as ex:
raise ApiError("COMPILE_ERROR", str(ex), http_status=400)
return {
"content_html": html,
"content_css": css,
"header_html": header,
"footer_html": footer,
}
@router.post(
"/business/{business_id}/migrate-v2-to-v3",
summary="تبدیل طراحی Studio v2 به v3",
)
@require_business_access("business_id")
async def migrate_v2_to_v3_endpoint(
request: Request,
business_id: int,
body: Dict[str, Any] = Body(...),
ctx: AuthContext = Depends(get_current_user),
db: Session = Depends(get_db),
):
if not ctx.can_write_section("report_templates"):
raise ApiError("FORBIDDEN", "Missing permission: report_templates.write", http_status=403)
design = (body or {}).get("design") or {}
if not isinstance(design, dict):
raise ApiError("VALIDATION_ERROR", "design must be an object", http_status=400)
try:
migrated = migrate_v2_design_to_v3(design)
except Exception as ex:
raise ApiError("MIGRATION_ERROR", str(ex), http_status=400)
return {"design": migrated}
@router.post( @router.post(
"/business/{business_id}/migrate-builder-to-v2", "/business/{business_id}/migrate-builder-to-v2",
summary="تبدیل طراحی Builder قدیمی به Studio v2", summary="تبدیل طراحی Builder قدیمی به Studio v2",
@ -1101,5 +1271,3 @@ async def migrate_builder_to_v2(
raise ApiError("MIGRATION_ERROR", str(ex), http_status=400) raise ApiError("MIGRATION_ERROR", str(ex), http_status=400)
validation = ReportTemplateService.validate_template_v2_design_scope(module_key, subtype, design) validation = ReportTemplateService.validate_template_v2_design_scope(module_key, subtype, design)
return {"design": design, **validation} return {"design": design, **validation}

View file

@ -16,9 +16,10 @@ from adapters.db.models.report_template import ReportTemplate
from adapters.db.models.report_template_status_event import ReportTemplateStatusEvent from adapters.db.models.report_template_status_event import ReportTemplateStatusEvent
from app.core.responses import ApiError from app.core.responses import ApiError
from app.services.template_builder_compiler import compile_design_to_jinja_html from app.services.template_builder_compiler import compile_design_to_jinja_html
from app.services.template_design_v2_compiler import compile_v2_design_to_jinja_html from app.services.template_design_v3_compiler import compile_template_design_to_jinja_html
from app.services.report_template_scope_registry import get_scope_meta, is_known_scope from app.services.report_template_scope_registry import get_scope_meta, is_known_scope
from app.services.report_template_v2_service import validate_v2_design from app.services.report_template_v2_service import validate_v2_design
from app.services.report_template_v3_service import is_v3_design, validate_v3_design
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -219,6 +220,8 @@ class ReportTemplateService:
subtype: Optional[str], subtype: Optional[str],
design: Dict[str, Any], design: Dict[str, Any],
) -> Dict[str, List[str]]: ) -> Dict[str, List[str]]:
if is_v3_design(design):
return validate_v3_design(module_key, subtype, design)
return validate_v2_design(module_key, subtype, design) return validate_v2_design(module_key, subtype, design)
@staticmethod @staticmethod
@ -527,7 +530,7 @@ class ReportTemplateService:
assets = getattr(template, "assets", None) or {} assets = getattr(template, "assets", None) or {}
if engine_name == "template_v2": if engine_name == "template_v2":
design = assets.get("template_design") or assets.get("design") or {} design = assets.get("template_design") or assets.get("design") or {}
html, css, header_html, footer_html = compile_v2_design_to_jinja_html(design) html, css, header_html, footer_html = compile_template_design_to_jinja_html(design)
else: else:
design = assets.get("builder_design") or assets.get("design") or {} design = assets.get("builder_design") or assets.get("design") or {}
html, css, header_html, footer_html = compile_design_to_jinja_html(design) html, css, header_html, footer_html = compile_design_to_jinja_html(design)
@ -893,4 +896,3 @@ class ReportTemplateService:
errors.append(f"خطای رندر: {str(e)}") errors.append(f"خطای رندر: {str(e)}")
return errors return errors

View file

@ -0,0 +1,297 @@
from __future__ import annotations
import re
from copy import deepcopy
from typing import Any
from jinja2 import BaseLoader, TemplateSyntaxError
from jinja2.sandbox import SandboxedEnvironment
from app.services.report_template_gallery import get_family, is_v2_design
_HEX_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{3,8}$")
_ID_RE = re.compile(r"^[a-zA-Z0-9_-]{1,80}$")
_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
_BLOCKS: dict[str, dict[str, Any]] = {
"brand_header": {
"label_fa": "سربرگ و برند",
"allowed_regions": ["header"],
"max_instances": 1,
"default_props": {},
},
"party_info": {
"label_fa": "اطلاعات طرف حساب",
"allowed_regions": ["body"],
"max_instances": 2,
"default_props": {"role": "buyer", "title": "خریدار"},
},
"invoice_lines": {
"label_fa": "جدول اقلام",
"allowed_regions": ["body"],
"max_instances": 1,
"required": True,
"default_props": {},
},
"invoice_totals": {
"label_fa": "جمع‌بندی مالی",
"allowed_regions": ["body"],
"max_instances": 1,
"default_props": {},
},
"payments": {
"label_fa": "پرداخت‌ها",
"allowed_regions": ["body"],
"max_instances": 1,
"default_props": {},
},
"note": {
"label_fa": "یادداشت فاکتور",
"allowed_regions": ["body", "footer"],
"max_instances": 1,
"default_props": {},
},
"signatures": {
"label_fa": "امضاها",
"allowed_regions": ["body", "footer"],
"max_instances": 1,
"default_props": {"show_seller": True, "show_buyer": True},
},
"qr": {
"label_fa": "کد QR",
"allowed_regions": ["body", "footer"],
"max_instances": 1,
"default_props": {},
},
"footer_meta": {
"label_fa": "اطلاعات چاپ",
"allowed_regions": ["footer"],
"max_instances": 1,
"default_props": {"show_print_time": True, "show_preparer": True},
},
"custom_text": {
"label_fa": "متن دلخواه",
"allowed_regions": ["header", "body", "footer"],
"default_props": {"text": "متن دلخواه"},
},
"divider": {
"label_fa": "خط جداکننده",
"allowed_regions": ["header", "body", "footer"],
"default_props": {"style": "solid"},
},
"spacer": {
"label_fa": "فاصله",
"allowed_regions": ["header", "body", "footer"],
"default_props": {"height": 12},
},
}
def is_v3_design(design: dict[str, Any]) -> bool:
try:
return int(design.get("schema_version") or 0) == 3
except Exception:
return False
def studio_block_catalog(module_key: str, subtype: str | None) -> list[dict[str, Any]]:
if module_key != "invoices" or (subtype or "") not in ("detail", "receipt"):
return []
return [
{"type": block_type, **deepcopy(definition)}
for block_type, definition in _BLOCKS.items()
]
def _block(block_id: str, block_type: str, props: dict[str, Any] | None = None) -> dict[str, Any]:
return {
"id": block_id,
"type": block_type,
"visible": True,
"props": deepcopy(props or {}),
"style": {},
}
def migrate_v2_design_to_v3(design: dict[str, Any]) -> dict[str, Any]:
if is_v3_design(design):
return deepcopy(design)
if not is_v2_design(design):
raise ValueError("Only template design v2 can be migrated to v3")
family_id = str(design.get("family_id") or "")
family = get_family(family_id)
if not family:
raise ValueError(f"Unknown template family: {family_id}")
if family.layout not in ("invoice_detail", "invoice_receipt"):
raise ValueError(f"Studio v3 does not support layout: {family.layout}")
sections = design.get("sections") or {}
header = [_block("brand-header", "brand_header")]
body: list[dict[str, Any]] = []
footer: list[dict[str, Any]] = []
if sections.get("show_seller_info", family.layout == "invoice_detail"):
body.append(_block("seller-info", "party_info", {"role": "seller", "title": "فروشنده"}))
if sections.get("show_buyer_info", True):
body.append(_block("buyer-info", "party_info", {"role": "buyer", "title": "خریدار"}))
table_props = deepcopy(design.get("table") or {})
table_props["show_unit_price"] = sections.get("show_unit_price", True)
body.append(_block("invoice-lines", "invoice_lines", table_props))
body.append(_block("invoice-totals", "invoice_totals", deepcopy(design.get("totals") or {})))
if sections.get("show_payments", True):
body.append(_block("payments", "payments"))
if sections.get("show_footer_note", True):
body.append(_block("invoice-note", "note"))
if sections.get("show_signatures", family.layout == "invoice_detail"):
body.append(
_block(
"signatures",
"signatures",
{
"show_seller": sections.get("show_seller_signature", True),
"show_buyer": sections.get("show_buyer_signature", True),
},
)
)
if sections.get("show_qr", False):
body.append(_block("invoice-qr", "qr"))
show_print_time = sections.get("show_print_time", True)
show_preparer = sections.get("show_preparer", family.layout == "invoice_detail")
if show_print_time or show_preparer:
footer.append(
_block(
"footer-meta",
"footer_meta",
{"show_print_time": show_print_time, "show_preparer": show_preparer},
)
)
theme = deepcopy(design.get("theme") or {})
theme.setdefault("direction", "rtl")
return {
"schema_version": 3,
"family_id": family_id,
"layout": family.layout,
"theme": theme,
"branding": deepcopy(design.get("branding") or {}),
"custom_css": str(design.get("custom_css") or ""),
"regions": {"header": header, "body": body, "footer": footer},
}
def validate_v3_design(
module_key: str,
subtype: str | None,
design: dict[str, Any],
) -> dict[str, list[str]]:
errors: list[str] = []
warnings: list[str] = []
if not isinstance(design, dict) or not is_v3_design(design):
return {"errors": ["schema_version must be 3"], "warnings": []}
family_id = str(design.get("family_id") or "").strip()
family = get_family(family_id)
if not family:
return {"errors": [f"Unknown family_id: {family_id}"], "warnings": []}
if family.module_key != module_key or (family.subtype or None) != (subtype or None):
errors.append("family_id does not match template scope")
if family.layout not in ("invoice_detail", "invoice_receipt"):
errors.append("Studio v3 currently supports invoice detail and receipt layouts")
theme = design.get("theme") or {}
direction = str(theme.get("direction") or "rtl").strip().lower()
if direction not in ("rtl", "ltr"):
errors.append("Invalid theme.direction")
for key in ("primary_color", "accent_color", "text_color"):
value = str(theme.get(key) or "").strip()
if value and not _HEX_COLOR_RE.fullmatch(value):
errors.append(f"Invalid theme.{key}")
regions = design.get("regions")
if not isinstance(regions, dict):
return {"errors": errors + ["regions must be an object"], "warnings": warnings}
seen_ids: set[str] = set()
counts: dict[str, int] = {}
for region_name in ("header", "body", "footer"):
blocks = regions.get(region_name) or []
if not isinstance(blocks, list):
errors.append(f"regions.{region_name} must be a list")
continue
for index, block in enumerate(blocks):
if not isinstance(block, dict):
errors.append(f"Invalid block in {region_name} at index {index}")
continue
block_id = str(block.get("id") or "").strip()
block_type = str(block.get("type") or "").strip()
definition = _BLOCKS.get(block_type)
if not block_id or not _ID_RE.fullmatch(block_id):
errors.append(f"Invalid block id in {region_name} at index {index}")
elif block_id in seen_ids:
errors.append(f"Duplicate block id: {block_id}")
seen_ids.add(block_id)
if not definition:
errors.append(f"Unknown block type: {block_type}")
continue
if region_name not in definition["allowed_regions"]:
errors.append(f"Block '{block_type}' is not allowed in region '{region_name}'")
counts[block_type] = counts.get(block_type, 0) + 1
props = block.get("props") or {}
if not isinstance(props, dict):
errors.append(f"Block '{block_id}' props must be an object")
continue
style = block.get("style") or {}
if not isinstance(style, dict):
errors.append(f"Block '{block_id}' style must be an object")
continue
text_align = str(style.get("text_align") or "").strip().lower()
if text_align and text_align not in ("right", "center", "left"):
errors.append(f"Invalid text alignment in block '{block_id}'")
if block_type == "invoice_lines":
items_var = str(props.get("items_var") or "lines")
if not _KEY_RE.fullmatch(items_var):
errors.append(f"Invalid invoice items variable: {items_var}")
columns = props.get("columns") or []
visible_columns = [c for c in columns if isinstance(c, dict) and c.get("visible", True) is not False]
if not visible_columns:
errors.append("Invoice lines must have at least one visible column")
for column in visible_columns:
key = str(column.get("key") or "")
if not _KEY_RE.fullmatch(key):
errors.append(f"Invalid invoice column key: {key}")
if block_type == "party_info" and str(props.get("role") or "") not in ("seller", "buyer"):
errors.append(f"Invalid party role in block '{block_id}'")
if block_type == "invoice_totals":
for row_index, row in enumerate(props.get("rows") or [], start=1):
if not isinstance(row, dict) or row.get("visible", True) is False:
continue
expr = str(row.get("expr") or "").strip()
if not expr:
errors.append(f"Totals row {row_index} is missing expr")
continue
try:
SandboxedEnvironment(loader=BaseLoader(), autoescape=True).from_string(f"{{{{ {expr} }}}}")
except TemplateSyntaxError as ex:
errors.append(f"Invalid totals expression in row {row_index}: {ex.message}")
if block_type == "custom_text" and len(str(props.get("text") or "")) > 2000:
errors.append(f"Custom text is too long in block '{block_id}'")
for block_type, definition in _BLOCKS.items():
count = counts.get(block_type, 0)
max_instances = definition.get("max_instances")
if max_instances is not None and count > int(max_instances):
errors.append(f"Block '{block_type}' exceeds its maximum instances")
if definition.get("required") and count == 0:
errors.append(f"Required block is missing: {block_type}")
try:
from app.services.template_design_v3_compiler import compile_v3_design_to_jinja_html
compile_v3_design_to_jinja_html(design)
except Exception as ex:
errors.append(f"Compile error: {ex}")
return {"errors": errors, "warnings": warnings}

View file

@ -69,7 +69,11 @@ def _total_display_flag(row: Dict[str, Any]) -> str | None:
def _wrap_if_flag(flag: str | None, inner: str) -> str: def _wrap_if_flag(flag: str | None, inner: str) -> str:
if not flag: if not flag:
return inner return inner
return f"{{% if {flag} %}}{inner}{{% endif %}}" # A Studio preview can be rendered with a sample/legacy context that does not
# yet contain the business print-display flags. The design itself marks the
# column/row as visible, so an absent runtime flag must not make the whole
# template fail under StrictUndefined.
return f"{{% if {flag} | default(true) %}}{inner}{{% endif %}}"
def _cell_expr(col: Dict[str, Any]) -> str: def _cell_expr(col: Dict[str, Any]) -> str:
@ -113,6 +117,10 @@ def _total_expr(row: Dict[str, Any]) -> str:
def _theme_css(design: Dict[str, Any], family_id: str) -> str: def _theme_css(design: Dict[str, Any], family_id: str) -> str:
theme = design.get("theme") or {} theme = design.get("theme") or {}
direction = str(theme.get("direction") or "rtl").strip().lower()
if direction not in ("rtl", "ltr"):
direction = "rtl"
default_align = "right" if direction == "rtl" else "left"
primary = _color(theme.get("primary_color"), "#1e3a5f") primary = _color(theme.get("primary_color"), "#1e3a5f")
accent = _color(theme.get("accent_color"), "#366092") accent = _color(theme.get("accent_color"), "#366092")
text = _color(theme.get("text_color"), "#212529") text = _color(theme.get("text_color"), "#212529")
@ -128,6 +136,10 @@ def _theme_css(design: Dict[str, Any], family_id: str) -> str:
--rt-base: {base_font}px; --rt-base: {base_font}px;
--rt-table: {table_font}px; --rt-table: {table_font}px;
}} }}
html, body {{
direction: {direction};
text-align: {default_align};
}}
.rt-layout {{ .rt-layout {{
font-size: var(--rt-base); font-size: var(--rt-base);
color: var(--rt-text); color: var(--rt-text);
@ -872,14 +884,18 @@ def _compile_invoice_receipt(design: Dict[str, Any]) -> Tuple[str, str, str, str
if key == "product_name": if key == "product_name":
inner = ( inner = (
"<div class='rt-item-name'>" "<div class='rt-item-name'>"
"{% if row.product_code %}{{ row.product_code }} — {% endif %}{{ row.product_name | default('-') }}" "{% if row.product_code is defined and row.product_code %}{{ row.product_code }} — {% endif %}"
"{{ row.product_name | default('-') }}"
"</div>" "</div>"
"{% if row.description %}<div class='rt-item-meta'>{{ row.description }}</div>{% endif %}" "{% if row.description is defined and row.description %}"
"<div class='rt-item-meta'>{{ row.description }}</div>{% endif %}"
) )
if sections.get("show_unit_price", True): if sections.get("show_unit_price", True):
inner += ( inner += (
"{% if row.unit_price %}<div class='rt-item-meta'>{{ row.unit_price | money }}" "{% if row.unit_price is defined and row.unit_price %}"
"{% if row.unit_display %} / {{ row.unit_display }}{% endif %}</div>{% endif %}" "<div class='rt-item-meta'>{{ row.unit_price | money }}"
"{% if row.unit_display is defined and row.unit_display %}"
" / {{ row.unit_display }}{% endif %}</div>{% endif %}"
) )
return inner return inner
if key in ("quantity", "quantity_display"): if key in ("quantity", "quantity_display"):

View file

@ -0,0 +1,302 @@
from __future__ import annotations
from copy import deepcopy
from typing import Any
from app.services import template_design_v2_compiler as v2
from app.services.report_template_gallery import get_family
from app.services.report_template_v3_service import is_v3_design
def _blocks(design: dict[str, Any], region: str) -> list[dict[str, Any]]:
regions = design.get("regions") or {}
return [
block
for block in (regions.get(region) or [])
if isinstance(block, dict) and block.get("visible", True) is not False
]
def _block_by_type(design: dict[str, Any], block_type: str) -> dict[str, Any] | None:
for region in ("header", "body", "footer"):
for block in _blocks(design, region):
if str(block.get("type") or "") == block_type:
return block
return None
def _v2_projection(design: dict[str, Any]) -> dict[str, Any]:
lines = _block_by_type(design, "invoice_lines") or {}
totals = _block_by_type(design, "invoice_totals") or {}
return {
"schema_version": 2,
"family_id": design.get("family_id"),
"layout": design.get("layout"),
"theme": deepcopy(design.get("theme") or {}),
"branding": deepcopy(design.get("branding") or {}),
"custom_css": str(design.get("custom_css") or ""),
"sections": {},
"table": deepcopy(lines.get("props") or {}),
"totals": deepcopy(totals.get("props") or {}),
}
def _header_block(design: dict[str, Any], *, receipt: bool) -> str:
family_id = str(design.get("family_id") or "")
logo_html = v2._logo_html(design, style="max-height:28px;max-width:72px;" if receipt else "")
business_name = v2._business_name_expr(design)
if receipt:
return f"""
<div class="rt-receipt">
{logo_html}
{f'<div class="rt-receipt-biz">{business_name}</div>' if business_name else ''}
<div class="rt-receipt-title">{{{{ title_text | default('فاکتور') }}}}</div>
<div class="rt-receipt-meta"><strong>{{{{ invoice.code | default('-') }}}}</strong> — {v2._jinja_first_of("invoice.issue_date", "invoice_date_jalali")}</div>
</div>
<hr class="rt-rule" />
""".strip()
if family_id == "invoice_modern":
return f"""
<div class="rt-header-band">
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;">
<div>
<h1 class="rt-title">{{{{ title_text | default('فاکتور') }}}}</h1>
<div class="rt-subtitle">{{{{ invoice.code | default('-') }}}} — {v2._jinja_first_of("invoice.issue_date", "invoice_date_jalali")}</div>
</div>
{logo_html}
</div>
</div>
""".strip()
name_html = f"<div style='font-weight:700;font-size:14px;'>{business_name}</div>" if business_name else ""
return f"""
<div class="rt-classic-header">
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;">
<div><h1 class="rt-title">{{{{ title_text | default('فاکتور') }}}}</h1>{name_html}</div>
{logo_html}
</div>
<div class="rt-meta-row">
<div class="rt-meta-item"><strong>کد:</strong> {{{{ invoice.code | default('-') }}}}</div>
<div class="rt-meta-item"><strong>تاریخ:</strong> {v2._jinja_first_of("invoice.issue_date", "invoice_date_jalali")}</div>
</div>
</div>
""".strip()
def _party_block(props: dict[str, Any], *, receipt: bool) -> str:
role = str(props.get("role") or "buyer")
title = v2._esc(props.get("title") or ("فروشنده" if role == "seller" else "خریدار"))
expr = v2._jinja_first_of("seller.name", "business_name") if role == "seller" else "{{ buyer.name | default('-') }}"
if receipt:
return f'<div class="rt-buyer"><strong>{title}:</strong> {expr}</div>'
return f'<div class="rt-card"><div class="rt-party"><h4>{title}</h4><div>{expr}</div></div></div>'
def _detail_lines(props: dict[str, Any]) -> str:
items_var = str(props.get("items_var") or "lines")
columns = v2._visible_columns(list(props.get("columns") or []))
if not columns:
return ""
striped = "striped" if props.get("striped", True) else ""
headers = "".join(
v2._wrap_if_flag(
v2._column_display_flag(column),
f"<th style='width:{v2._esc(column.get('width') or 'auto')};'>{v2._esc(column.get('title') or column.get('key') or '')}</th>",
)
for column in columns
)
cells = "".join(
v2._wrap_if_flag(v2._column_display_flag(column), f"<td class='num'>{v2._cell_expr(column)}</td>")
for column in columns
)
return f"""
<div class="rt-card table-card">
<table class="rt-table {striped}">
<thead><tr>{headers}</tr></thead>
<tbody>{{% for row in {items_var} %}}<tr>{cells}</tr>{{% endfor %}}</tbody>
</table>
</div>
""".strip()
def _receipt_cell(column: dict[str, Any], *, show_unit_price: bool) -> str:
key = str(column.get("key") or "").strip()
if key == "product_name":
result = (
"<div class='rt-item-name'>"
"{% if row.product_code is defined and row.product_code %}{{ row.product_code }} — {% endif %}"
"{{ row.product_name | default('-') }}</div>"
"{% if row.description is defined and row.description %}<div class='rt-item-meta'>{{ row.description }}</div>{% endif %}"
)
if show_unit_price:
result += (
"{% if row.unit_price is defined and row.unit_price %}<div class='rt-item-meta'>{{ row.unit_price | money }}"
"{% if row.unit_display is defined and row.unit_display %} / {{ row.unit_display }}{% endif %}</div>{% endif %}"
)
return result
if key in ("quantity", "quantity_display"):
return "{{ row.quantity_display | default(row.quantity, true) }}"
return v2._cell_expr(column)
def _receipt_lines(props: dict[str, Any]) -> str:
items_var = str(props.get("items_var") or "lines")
columns = v2._visible_columns(list(props.get("columns") or []))
if not columns:
return ""
headers = "".join(
v2._wrap_if_flag(
v2._column_display_flag(column),
f"<th style='width:{v2._esc(column.get('width') or 'auto')};'>{v2._esc(column.get('title') or column.get('key') or '')}</th>",
)
for column in columns
)
cells = "".join(
v2._wrap_if_flag(
v2._column_display_flag(column),
f"<td>{_receipt_cell(column, show_unit_price=props.get('show_unit_price', True) is not False)}</td>",
)
for column in columns
)
return f"""
<table class="rt-receipt-items">
<thead><tr>{headers}</tr></thead>
<tbody>{{% for row in {items_var} %}}<tr>{cells}</tr>{{% endfor %}}</tbody>
</table>
""".strip()
def _totals_block(props: dict[str, Any], *, receipt: bool) -> str:
rows = [
row
for row in (props.get("rows") or [])
if isinstance(row, dict) and row.get("visible", True) is not False
]
if not rows:
return ""
rows_html: list[str] = []
for row in rows:
emphasis = " class='emphasis'" if row.get("emphasis") else ""
title = v2._esc(row.get("title") or "")
value = v2._total_expr(row)
value_style = " style='text-align:end;font-weight:700;'" if receipt else ""
row_html = f"<tr{emphasis}><td>{title}</td><td{value_style}>{value}</td></tr>"
rows_html.append(v2._wrap_if_flag(v2._total_display_flag(row), row_html))
table = f"<table class='rt-totals'><tbody>{''.join(rows_html)}</tbody></table>"
return f"<hr class='rt-rule-solid' />{table}" if receipt else f"<div class='rt-card'>{table}</div>"
def _payments_block(*, receipt: bool) -> str:
if receipt:
return """
{% if payments is defined and payments %}<hr class="rt-rule" />
{% for p in payments %}<div class="rt-receipt-meta">{{ p.method_name | default('-') }} — {{ p.amount | money }}</div>{% endfor %}{% endif %}
""".strip()
return """
{% if payments is defined and payments %}<div class="rt-card"><h4 style="margin:0 0 6px 0;color:var(--rt-primary);">پرداخت‌ها</h4>
<ul style="margin:0;padding-inline-start:18px;">{% for p in payments %}<li>{{ p.method_name | default('-') }} — {{ p.amount | money }}</li>{% endfor %}</ul></div>{% endif %}
""".strip()
def _compile_block_content(design: dict[str, Any], block: dict[str, Any], *, receipt: bool) -> str:
block_type = str(block.get("type") or "")
props = block.get("props") or {}
if block_type == "brand_header":
return _header_block(design, receipt=receipt)
if block_type == "party_info":
return _party_block(props, receipt=receipt)
if block_type == "invoice_lines":
return _receipt_lines(props) if receipt else _detail_lines(props)
if block_type == "invoice_totals":
return _totals_block(props, receipt=receipt)
if block_type == "payments":
return _payments_block(receipt=receipt)
if block_type == "note":
css_class = "rt-receipt-meta" if receipt else "rt-footer-note"
prefix = '<hr class="rt-rule" />' if receipt else ""
return f"{{% if invoice_footer_note is defined and invoice_footer_note %}}{prefix}<div class='{css_class}'>{{{{ invoice_footer_note }}}}</div>{{% endif %}}"
if block_type == "signatures":
parts: list[str] = []
if props.get("show_seller", True):
parts.append('<div style="flex:1;"><div class="rt-sig-box"></div><div class="rt-sig-label">امضای فروشنده</div></div>')
if props.get("show_buyer", True):
parts.append('<div style="flex:1;"><div class="rt-sig-box"></div><div class="rt-sig-label">امضای خریدار</div></div>')
return f'<div class="rt-signatures">{"".join(parts)}</div>' if parts else ""
if block_type == "qr":
size = 64 if receipt else 120
return f"""
{{% if show_invoice_verify_qr is defined and show_invoice_verify_qr and invoice_verify_qr_data_uri is defined and invoice_verify_qr_data_uri %}}
<div class="rt-qr-wrap"><img src="{{{{ invoice_verify_qr_data_uri }}}}" width="{size}" height="{size}" alt="QR" /></div>{{% endif %}}
""".strip()
if block_type == "footer_meta":
bits: list[str] = []
if props.get("show_print_time", True):
bits.append("{{ generated_at | default('') }}")
if props.get("show_preparer", True):
bits.append("{{ issuer_name | default('') }}")
return f'<div class="rt-studio-footer-meta">{" — ".join(bits)}</div>' if bits else ""
if block_type == "custom_text":
return f'<div class="rt-custom-text">{v2._esc(props.get("text") or "")}</div>'
if block_type == "divider":
style = "dashed" if str(props.get("style") or "") == "dashed" else "solid"
return f'<hr style="border:0;border-top:1px {style} #94a3b8;margin:8px 0;" />'
if block_type == "spacer":
try:
height = max(4, min(80, int(props.get("height") or 12)))
except Exception:
height = 12
return f'<div style="height:{height}px;"></div>'
return ""
def _compile_block(design: dict[str, Any], block: dict[str, Any], *, receipt: bool) -> str:
content = _compile_block_content(design, block, receipt=receipt)
if not content:
return ""
style = block.get("style") or {}
align = str(style.get("text_align") or "").strip().lower()
if not align and str(block.get("type") or "") == "custom_text":
align = str((block.get("props") or {}).get("align") or "").strip().lower()
if align in ("right", "center", "left"):
return f'<div class="rt-block rt-block-align-{align}">{content}</div>'
return content
def compile_v3_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, str, str]:
if not is_v3_design(design):
raise ValueError("Not a v3 design schema")
family_id = str(design.get("family_id") or "")
family = get_family(family_id)
if not family:
raise ValueError(f"Unknown template family: {family_id}")
if family.layout not in ("invoice_detail", "invoice_receipt"):
raise ValueError(f"Studio v3 does not support layout: {family.layout}")
receipt = family.layout == "invoice_receipt"
theme = design.get("theme") or {}
direction = str(theme.get("direction") or "rtl").strip().lower()
if direction not in ("rtl", "ltr"):
direction = "rtl"
projection = _v2_projection(design)
if receipt:
_, css, _, _ = v2._compile_invoice_receipt(projection)
else:
css = v2._theme_css(design, family_id)
css += """
.rt-studio-footer-meta { font-size: 10px; color: #64748b; text-align: center; margin-top: 8px; }
.rt-custom-text { white-space: pre-wrap; margin: 6px 0; }
.rt-block-align-right, .rt-block-align-right * { text-align: right !important; }
.rt-block-align-center, .rt-block-align-center * { text-align: center !important; }
.rt-block-align-left, .rt-block-align-left * { text-align: left !important; }
"""
header_html = "".join(_compile_block(design, block, receipt=receipt) for block in _blocks(design, "header"))
body = "".join(_compile_block(design, block, receipt=receipt) for block in _blocks(design, "body"))
footer_html = "".join(_compile_block(design, block, receipt=receipt) for block in _blocks(design, "footer"))
body_html = f'<div class="rt-layout">{body}</div>'
html_doc = f'<!doctype html><html dir="{direction}"><head></head><body>{body_html}</body></html>'
return html_doc, css.strip(), header_html, footer_html
def compile_template_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, str, str]:
if is_v3_design(design):
return compile_v3_design_to_jinja_html(design)
return v2.compile_v2_design_to_jinja_html(design)

View file

@ -1,12 +1,17 @@
from __future__ import annotations from __future__ import annotations
import pytest from jinja2 import BaseLoader, StrictUndefined
from app.services.report_template_v2_service import migrate_builder_design_to_v2, validate_v2_design
from app.services.report_template_gallery import default_design_for_family, list_gallery_items
from app.services.template_design_v2_compiler import compile_v2_design_to_jinja_html
from jinja2.sandbox import SandboxedEnvironment from jinja2.sandbox import SandboxedEnvironment
from jinja2 import BaseLoader
from app.services.report_template_gallery import default_design_for_family, list_gallery_items
from app.services.report_template_v2_service import migrate_builder_design_to_v2, validate_v2_design
from app.services.report_template_v3_service import (
migrate_v2_design_to_v3,
studio_block_catalog,
validate_v3_design,
)
from app.services.template_design_v2_compiler import compile_v2_design_to_jinja_html
from app.services.template_design_v3_compiler import compile_v3_design_to_jinja_html
def _sample_invoice_context() -> dict: def _sample_invoice_context() -> dict:
@ -67,7 +72,7 @@ def test_compile_and_render_invoice_classic():
html, css, header, footer = compile_v2_design_to_jinja_html(design) html, css, header, footer = compile_v2_design_to_jinja_html(design)
assert "<table" in html assert "<table" in html
assert "lines" in html assert "lines" in html
env = SandboxedEnvironment(loader=BaseLoader(), autoescape=True) env = SandboxedEnvironment(loader=BaseLoader(), autoescape=True, undefined=StrictUndefined)
env.filters["money"] = lambda value, *args, **kwargs: str(value if value is not None else "") env.filters["money"] = lambda value, *args, **kwargs: str(value if value is not None else "")
env.filters["date"] = lambda value, *args, **kwargs: str(value if value is not None else "") env.filters["date"] = lambda value, *args, **kwargs: str(value if value is not None else "")
full = f"<style>{css}</style>{header}{html}{footer}" full = f"<style>{css}</style>{header}{html}{footer}"
@ -76,6 +81,30 @@ def test_compile_and_render_invoice_classic():
assert "A" in rendered assert "A" in rendered
def test_compile_and_render_invoice_classic_without_optional_display_flags():
design = default_design_for_family("invoice_classic")
assert design is not None
html, css, header, footer = compile_v2_design_to_jinja_html(design)
context = _sample_invoice_context()
for key in (
"show_line_discount_column",
"show_line_tax_column",
"show_line_amount_before_discount_column",
"show_line_amount_before_tax_column",
"show_summary_discount",
"show_summary_tax",
"show_summary_amount_without_tax",
):
context.pop(key)
env = SandboxedEnvironment(loader=BaseLoader(), autoescape=True, undefined=StrictUndefined)
env.filters["money"] = lambda value, *args, **kwargs: str(value if value is not None else "")
env.filters["date"] = lambda value, *args, **kwargs: str(value if value is not None else "")
full = f"<style>{css}</style>{header}{html}{footer}"
rendered = env.from_string(full).render(**context)
assert "INV-1" in rendered
assert "تخفیف" in rendered
def test_compile_and_render_invoice_receipt(): def test_compile_and_render_invoice_receipt():
design = default_design_for_family("invoice_receipt_simple") design = default_design_for_family("invoice_receipt_simple")
assert design is not None assert design is not None
@ -84,7 +113,7 @@ def test_compile_and_render_invoice_receipt():
html, css, header, footer = compile_v2_design_to_jinja_html(design) html, css, header, footer = compile_v2_design_to_jinja_html(design)
assert "rt-receipt-items" in html assert "rt-receipt-items" in html
assert "lines" in html assert "lines" in html
env = SandboxedEnvironment(loader=BaseLoader(), autoescape=True) env = SandboxedEnvironment(loader=BaseLoader(), autoescape=True, undefined=StrictUndefined)
env.filters["money"] = lambda value, *args, **kwargs: str(value if value is not None else "") env.filters["money"] = lambda value, *args, **kwargs: str(value if value is not None else "")
env.filters["date"] = lambda value, *args, **kwargs: str(value if value is not None else "") env.filters["date"] = lambda value, *args, **kwargs: str(value if value is not None else "")
full = f"<style>{css}</style>{header}{html}{footer}" full = f"<style>{css}</style>{header}{html}{footer}"
@ -131,3 +160,95 @@ def test_compile_postal_label():
html, css, header, footer = compile_v2_design_to_jinja_html(design) html, css, header, footer = compile_v2_design_to_jinja_html(design)
assert "sender" in html assert "sender" in html
assert "receiver" in html assert "receiver" in html
def test_migrate_invoice_design_to_v3_and_render_strict():
design_v2 = default_design_for_family("invoice_classic")
assert design_v2 is not None
design = migrate_v2_design_to_v3(design_v2)
assert design["schema_version"] == 3
assert design["theme"]["direction"] == "rtl"
assert [block["type"] for block in design["regions"]["body"]][:3] == [
"party_info",
"party_info",
"invoice_lines",
]
validation = validate_v3_design("invoices", "detail", design)
assert validation["errors"] == []
html, css, header, footer = compile_v3_design_to_jinja_html(design)
env = SandboxedEnvironment(loader=BaseLoader(), autoescape=True, undefined=StrictUndefined)
env.filters["money"] = lambda value, *args, **kwargs: str(value if value is not None else "")
env.filters["date"] = lambda value, *args, **kwargs: str(value if value is not None else "")
rendered = env.from_string(f"<style>{css}</style>{header}{html}{footer}").render(**_sample_invoice_context())
assert "INV-1" in rendered
assert "A" in rendered
def test_v3_compiler_preserves_dragged_block_order():
design_v2 = default_design_for_family("invoice_classic")
assert design_v2 is not None
design = migrate_v2_design_to_v3(design_v2)
body = design["regions"]["body"]
body.insert(0, {"id": "custom-first", "type": "custom_text", "visible": True, "props": {"text": "ابتدای بدنه"}, "style": {}})
html, _, _, _ = compile_v3_design_to_jinja_html(design)
assert html.index("ابتدای بدنه") < html.index("rt-party")
def test_v3_compiler_applies_ltr_direction_and_block_text_alignment():
design_v2 = default_design_for_family("invoice_classic")
assert design_v2 is not None
design = migrate_v2_design_to_v3(design_v2)
design["theme"]["direction"] = "ltr"
design["regions"]["body"].insert(
0,
{
"id": "centered-text",
"type": "custom_text",
"visible": True,
"props": {"text": "Centered"},
"style": {"text_align": "center"},
},
)
validation = validate_v3_design("invoices", "detail", design)
assert validation["errors"] == []
html, css, _, _ = compile_v3_design_to_jinja_html(design)
assert '<html dir="ltr">' in html
assert "direction: ltr;" in css
assert 'class="rt-block rt-block-align-center"' in html
def test_v3_validation_rejects_invalid_direction_and_alignment():
design_v2 = default_design_for_family("invoice_classic")
assert design_v2 is not None
design = migrate_v2_design_to_v3(design_v2)
design["theme"]["direction"] = "diagonal"
design["regions"]["body"][0]["style"] = {"text_align": "wide"}
validation = validate_v3_design("invoices", "detail", design)
assert "Invalid theme.direction" in validation["errors"]
assert any("Invalid text alignment" in error for error in validation["errors"])
def test_v3_catalog_and_required_invoice_lines_validation():
catalog = studio_block_catalog("invoices", "detail")
assert any(item["type"] == "invoice_lines" and item.get("required") for item in catalog)
design_v2 = default_design_for_family("invoice_classic")
assert design_v2 is not None
design = migrate_v2_design_to_v3(design_v2)
design["regions"]["body"] = [block for block in design["regions"]["body"] if block["type"] != "invoice_lines"]
validation = validate_v3_design("invoices", "detail", design)
assert any("invoice_lines" in error for error in validation["errors"])
def test_migrate_and_render_invoice_receipt_v3():
design_v2 = default_design_for_family("invoice_receipt_simple")
assert design_v2 is not None
design = migrate_v2_design_to_v3(design_v2)
validation = validate_v3_design("invoices", "receipt", design)
assert validation["errors"] == []
html, css, header, footer = compile_v3_design_to_jinja_html(design)
env = SandboxedEnvironment(loader=BaseLoader(), autoescape=True, undefined=StrictUndefined)
env.filters["money"] = lambda value, *args, **kwargs: str(value if value is not None else "")
env.filters["date"] = lambda value, *args, **kwargs: str(value if value is not None else "")
rendered = env.from_string(f"<style>{css}</style>{header}{html}{footer}").render(**_sample_invoice_context())
assert "INV-1" in rendered
assert "rt-receipt-items" in rendered

View file

@ -382,17 +382,23 @@ class _ReportTemplateHtmlEditorPageState extends State<ReportTemplateHtmlEditorP
if (!mounted) return; if (!mounted) return;
await showDialog<void>( await showDialog<void>(
context: context, context: context,
builder: (ctx) => AlertDialog( builder: (ctx) {
title: Text(t.reportTemplatePreview), final viewport = MediaQuery.sizeOf(ctx);
content: SizedBox( final availableWidth = viewport.width > 64 ? viewport.width - 64 : viewport.width;
width: 720, final availableHeight = viewport.height > 180 ? viewport.height - 180 : viewport.height;
height: 520, return AlertDialog(
child: ReportTemplateEmbeddedPdf(bytes: Uint8List.fromList(pdfBytes)), insetPadding: const EdgeInsets.all(16),
), title: Text(t.reportTemplatePreview),
actions: [ content: SizedBox(
TextButton(onPressed: () => Navigator.pop(ctx), child: Text(t.close)), width: availableWidth > 720 ? 720 : availableWidth,
], height: availableHeight > 520 ? 520 : availableHeight,
), child: ReportTemplateEmbeddedPdf(bytes: Uint8List.fromList(pdfBytes)),
),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx), child: Text(t.close)),
],
);
},
); );
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {

View file

@ -17,11 +17,14 @@ import '../../widgets/permission/permission_widgets.dart';
import '../../widgets/report_template/studio/report_template_studio_customize_panel.dart'; import '../../widgets/report_template/studio/report_template_studio_customize_panel.dart';
import '../../widgets/report_template/studio/report_template_studio_gallery.dart'; import '../../widgets/report_template/studio/report_template_studio_gallery.dart';
import '../../widgets/report_template/studio/report_template_studio_preview_panel.dart'; import '../../widgets/report_template/studio/report_template_studio_preview_panel.dart';
import '../../widgets/report_template/studio/report_template_studio_v3_builder.dart';
import '../../core/hesabix_back.dart'; import '../../core/hesabix_back.dart';
import 'report_template_html_editor_page.dart'; import 'report_template_html_editor_page.dart';
enum _StudioStep { gallery, customize } enum _StudioStep { gallery, customize }
enum _StudioToolbarAction { changeTemplate, advancedHtml, pageSettings }
class ReportTemplateStudioPage extends StatefulWidget { class ReportTemplateStudioPage extends StatefulWidget {
final int businessId; final int businessId;
final AuthStore authStore; final AuthStore authStore;
@ -43,7 +46,8 @@ class ReportTemplateStudioPage extends StatefulWidget {
bool get isNew => template == null && templateId == null; bool get isNew => template == null && templateId == null;
@override @override
State<ReportTemplateStudioPage> createState() => _ReportTemplateStudioPageState(); State<ReportTemplateStudioPage> createState() =>
_ReportTemplateStudioPageState();
} }
class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> { class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
@ -69,14 +73,18 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
List<Map<String, dynamic>> _galleryItems = const []; List<Map<String, dynamic>> _galleryItems = const [];
List<Map<String, dynamic>> _scopeCatalog = const []; List<Map<String, dynamic>> _scopeCatalog = const [];
List<Map<String, dynamic>> _blockCatalog = const [];
Map<String, dynamic>? _design; Map<String, dynamic>? _design;
Map<String, dynamic> _assets = {'images': <String, String>{}}; Map<String, dynamic> _assets = {'images': <String, String>{}};
Map<String, dynamic> _sampleContext = const {}; Map<String, dynamic> _sampleContext = const {};
String? _paperSize = 'A4'; String? _paperSize = 'A4';
String? _orientation = 'portrait'; String? _orientation = 'portrait';
String? _previewHtml;
Uint8List? _previewPdfBytes; Uint8List? _previewPdfBytes;
bool _showPdfPreview = false;
int _previewRevision = 0; int _previewRevision = 0;
int _previewRequestId = 0;
List<String> _validationErrors = const []; List<String> _validationErrors = const [];
List<String> _validationWarnings = const []; List<String> _validationWarnings = const [];
@ -109,25 +117,30 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
} }
String _fingerprint() => jsonEncode({ String _fingerprint() => jsonEncode({
'name': _nameCtrl.text.trim(), 'name': _nameCtrl.text.trim(),
'desc': _descCtrl.text.trim(), 'desc': _descCtrl.text.trim(),
'module': _moduleKey, 'module': _moduleKey,
'subtype': _subtype, 'subtype': _subtype,
'design': _design, 'design': _design,
'paperSize': _paperSize, 'paperSize': _paperSize,
'orientation': _orientation, 'orientation': _orientation,
'margins': { 'margins': {
'top': _marginTopCtrl.text.trim(), 'top': _marginTopCtrl.text.trim(),
'right': _marginRightCtrl.text.trim(), 'right': _marginRightCtrl.text.trim(),
'bottom': _marginBottomCtrl.text.trim(), 'bottom': _marginBottomCtrl.text.trim(),
'left': _marginLeftCtrl.text.trim(), 'left': _marginLeftCtrl.text.trim(),
}, },
}); });
Future<void> _bootstrap() async { Future<void> _bootstrap() async {
setState(() => _loading = true); setState(() => _loading = true);
try { try {
await Future.wait([_loadScopeCatalog(), _loadGallery(), _loadSampleContext()]); await Future.wait([
_loadScopeCatalog(),
_loadGallery(),
_loadSampleContext(),
_loadBlockCatalog(),
]);
if (widget.template != null) { if (widget.template != null) {
await _loadExistingTemplate(); await _loadExistingTemplate();
} else if (widget.templateId != null) { } else if (widget.templateId != null) {
@ -137,9 +150,15 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
_step = _StudioStep.customize; _step = _StudioStep.customize;
_schedulePreview(); _schedulePreview();
} }
if (_lastSavedFingerprint.isEmpty) {
_lastSavedFingerprint = _fingerprint();
}
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); SnackBarHelper.showError(
context,
message: ErrorExtractor.forContext(e, context),
);
} }
} finally { } finally {
if (mounted) setState(() => _loading = false); if (mounted) setState(() => _loading = false);
@ -170,8 +189,20 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
if (mounted) setState(() => _sampleContext = sample ?? const {}); if (mounted) setState(() => _sampleContext = sample ?? const {});
} }
Future<void> _loadBlockCatalog() async {
final items = await _service.studioBlocks(
businessId: widget.businessId,
moduleKey: _moduleKey ?? 'invoices',
subtype: _subtype,
);
if (mounted) setState(() => _blockCatalog = items);
}
Future<void> _loadExistingTemplateById(int templateId) async { Future<void> _loadExistingTemplateById(int templateId) async {
final full = await _service.getTemplate(businessId: widget.businessId, templateId: templateId); final full = await _service.getTemplate(
businessId: widget.businessId,
templateId: templateId,
);
_templateId = templateId; _templateId = templateId;
await _applyLoadedTemplate(full); await _applyLoadedTemplate(full);
} }
@ -179,7 +210,10 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
Future<void> _loadExistingTemplate() async { Future<void> _loadExistingTemplate() async {
final tid = (widget.template!['id'] as num?)?.toInt(); final tid = (widget.template!['id'] as num?)?.toInt();
if (tid == null) return; if (tid == null) return;
final full = await _service.getTemplate(businessId: widget.businessId, templateId: tid); final full = await _service.getTemplate(
businessId: widget.businessId,
templateId: tid,
);
_templateId = tid; _templateId = tid;
await _applyLoadedTemplate(full); await _applyLoadedTemplate(full);
} }
@ -191,10 +225,13 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
_descCtrl.text = (full['description'] ?? '').toString(); _descCtrl.text = (full['description'] ?? '').toString();
_paperSize = (full['paper_size'] ?? _paperSize)?.toString(); _paperSize = (full['paper_size'] ?? _paperSize)?.toString();
_orientation = (full['orientation'] ?? _orientation)?.toString(); _orientation = (full['orientation'] ?? _orientation)?.toString();
final margins = (full['margins'] as Map?)?.cast<String, dynamic>() ?? const {}; final margins =
(full['margins'] as Map?)?.cast<String, dynamic>() ?? const {};
_marginTopCtrl.text = margins['top']?.toString() ?? _marginTopCtrl.text; _marginTopCtrl.text = margins['top']?.toString() ?? _marginTopCtrl.text;
_marginRightCtrl.text = margins['right']?.toString() ?? _marginRightCtrl.text; _marginRightCtrl.text =
_marginBottomCtrl.text = margins['bottom']?.toString() ?? _marginBottomCtrl.text; margins['right']?.toString() ?? _marginRightCtrl.text;
_marginBottomCtrl.text =
margins['bottom']?.toString() ?? _marginBottomCtrl.text;
_marginLeftCtrl.text = margins['left']?.toString() ?? _marginLeftCtrl.text; _marginLeftCtrl.text = margins['left']?.toString() ?? _marginLeftCtrl.text;
final engine = (full['engine'] ?? '').toString().toLowerCase(); final engine = (full['engine'] ?? '').toString().toLowerCase();
@ -204,7 +241,9 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
if (engine == 'template_v2') { if (engine == 'template_v2') {
_design = (assets['template_design'] as Map?)?.cast<String, dynamic>(); _design = (assets['template_design'] as Map?)?.cast<String, dynamic>();
} else if (engine == 'builder') { } else if (engine == 'builder') {
final builderDesign = (assets['builder_design'] as Map?)?.cast<String, dynamic>() ?? const {}; final builderDesign =
(assets['builder_design'] as Map?)?.cast<String, dynamic>() ??
const {};
if (mounted && builderDesign.isNotEmpty) { if (mounted && builderDesign.isNotEmpty) {
final migrate = await showDialog<bool>( final migrate = await showDialog<bool>(
context: context, context: context,
@ -215,8 +254,14 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
'برخی جزئیات ممکن است نیاز به بازبینی داشته باشند.', 'برخی جزئیات ممکن است نیاز به بازبینی داشته باشند.',
), ),
actions: [ actions: [
TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('انصراف')), TextButton(
FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('انتقال')), onPressed: () => Navigator.pop(ctx, false),
child: const Text('انصراف'),
),
FilledButton(
onPressed: () => Navigator.pop(ctx, true),
child: const Text('انتقال'),
),
], ],
), ),
); );
@ -234,10 +279,26 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
} }
} }
await _loadGallery(); await _upgradeDesignToV3IfSupported();
await Future.wait([_loadGallery(), _loadBlockCatalog()]);
_lastSavedFingerprint = _fingerprint(); _lastSavedFingerprint = _fingerprint();
} }
Future<void> _upgradeDesignToV3IfSupported() async {
final design = _design;
if (design == null || (design['schema_version'] as num?)?.toInt() != 2)
return;
if (_moduleKey != 'invoices' ||
!const {'detail', 'receipt'}.contains(_subtype))
return;
final out = await _service.migrateV2ToV3(
businessId: widget.businessId,
design: design,
);
_design = (out['design'] as Map?)?.cast<String, dynamic>() ?? design;
}
void _onScopeChanged(String? scopeId) { void _onScopeChanged(String? scopeId) {
if (scopeId == null) return; if (scopeId == null) return;
final idx = scopeId.indexOf(':'); final idx = scopeId.indexOf(':');
@ -247,7 +308,12 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
_subtype = scopeId.substring(idx + 1); _subtype = scopeId.substring(idx + 1);
_step = _StudioStep.gallery; _step = _StudioStep.gallery;
_design = null; _design = null;
_previewHtml = null;
_previewPdfBytes = null; _previewPdfBytes = null;
_showPdfPreview = false;
_previewLoading = false;
_previewRequestId++;
_blockCatalog = const [];
if (_moduleKey == 'invoices' && _subtype == 'receipt') { if (_moduleKey == 'invoices' && _subtype == 'receipt') {
_applyReceiptPageDefaultsIfNeeded(); _applyReceiptPageDefaultsIfNeeded();
} else if (kInvoiceReceiptPaperSizeOptions.contains(_paperSize)) { } else if (kInvoiceReceiptPaperSizeOptions.contains(_paperSize)) {
@ -259,77 +325,99 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
_marginLeftCtrl.text = '10'; _marginLeftCtrl.text = '10';
} }
}); });
Future.wait([_loadGallery(), _loadSampleContext()]); Future.wait([_loadGallery(), _loadSampleContext(), _loadBlockCatalog()]);
} }
void _selectGalleryItem(Map<String, dynamic> item) { void _selectGalleryItem(Map<String, dynamic> item) {
final design = (item['default_design'] as Map?)?.cast<String, dynamic>(); final design = ((item['studio_design'] ?? item['default_design']) as Map?)
?.cast<String, dynamic>();
if (design == null) return; if (design == null) return;
setState(() { setState(() {
_design = Map<String, dynamic>.from(design); _design = Map<String, dynamic>.from(design);
_step = _StudioStep.customize; _step = _StudioStep.customize;
_previewHtml = null;
_previewPdfBytes = null;
_showPdfPreview = false;
_applyReceiptPageDefaultsIfNeeded(); _applyReceiptPageDefaultsIfNeeded();
}); });
_schedulePreview(); _schedulePreview();
} }
void _onDesignChanged(Map<String, dynamic> design) { void _onDesignChanged(Map<String, dynamic> design) {
setState(() => _design = design); setState(() {
_design = design;
_previewPdfBytes = null;
_showPdfPreview = false;
});
_schedulePreview(); _schedulePreview();
} }
void _schedulePreview() { void _schedulePreview() {
if (mounted && (_showPdfPreview || _previewPdfBytes != null)) {
setState(() {
_showPdfPreview = false;
_previewPdfBytes = null;
});
}
_previewDebouncer.schedule(_refreshPreview); _previewDebouncer.schedule(_refreshPreview);
} }
Future<void> _refreshPreview() async { Future<void> _refreshPreview() async {
if (_design == null || !mounted) return; final design = _design;
if (design == null || !mounted) return;
final requestId = ++_previewRequestId;
setState(() { setState(() {
_previewLoading = true; _previewLoading = true;
_validationErrors = const []; _validationErrors = const [];
_validationWarnings = const []; _validationWarnings = const [];
}); });
try { try {
final validation = await _service.validateV2Design( final validation = await _service.validateStudioDesign(
businessId: widget.businessId, businessId: widget.businessId,
moduleKey: _moduleKey ?? 'invoices', moduleKey: _moduleKey ?? 'invoices',
subtype: _subtype, subtype: _subtype,
design: _design!, design: design,
); );
final errors = ((validation['errors'] as List?) ?? const []).map((e) => e.toString()).toList(); final errors = ((validation['errors'] as List?) ?? const [])
final warnings = ((validation['warnings'] as List?) ?? const []).map((e) => e.toString()).toList(); .map((e) => e.toString())
.toList();
final warnings = ((validation['warnings'] as List?) ?? const [])
.map((e) => e.toString())
.toList();
if (!mounted || requestId != _previewRequestId) return;
if (errors.isNotEmpty) { if (errors.isNotEmpty) {
if (mounted) { if (mounted) {
setState(() { setState(() {
_validationErrors = errors; _validationErrors = errors;
_validationWarnings = warnings; _validationWarnings = warnings;
_previewLoading = false; _previewLoading = false;
_previewHtml = null;
_previewPdfBytes = null; _previewPdfBytes = null;
}); });
} }
return; return;
} }
final pdfBytes = await _service.previewPdf( final html = await _service.previewHtml(
businessId: widget.businessId, businessId: widget.businessId,
engine: 'template_v2', engine: 'template_v2',
design: _design, design: design,
assets: {'template_design': _design, ..._assets}, assets: {..._assets, 'template_design': design},
context: _sampleContext, context: _sampleContext,
paperSize: _effectivePaperSize(), paperSize: _effectivePaperSize(),
orientation: _orientation, orientation: _orientation,
margins: _parseMargins(), margins: _parseMargins(),
); );
if (mounted) { if (mounted && requestId == _previewRequestId) {
setState(() { setState(() {
_previewPdfBytes = Uint8List.fromList(pdfBytes); _previewHtml = html;
_previewRevision++; _previewRevision++;
_validationWarnings = warnings; _validationWarnings = warnings;
_previewLoading = false; _previewLoading = false;
}); });
} }
} catch (e) { } catch (e) {
if (mounted) { if (mounted && requestId == _previewRequestId) {
setState(() { setState(() {
_previewLoading = false; _previewLoading = false;
_validationErrors = [ErrorExtractor.forContext(e, context)]; _validationErrors = [ErrorExtractor.forContext(e, context)];
@ -338,6 +426,37 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
} }
} }
Future<void> _refreshPdfPreview() async {
if (_design == null || !mounted) return;
final requestId = ++_previewRequestId;
setState(() => _previewLoading = true);
try {
final pdfBytes = await _service.previewPdf(
businessId: widget.businessId,
engine: 'template_v2',
design: _design,
assets: {..._assets, 'template_design': _design},
context: _sampleContext,
paperSize: _effectivePaperSize(),
orientation: _orientation,
margins: _parseMargins(),
);
if (!mounted || requestId != _previewRequestId) return;
setState(() {
_previewPdfBytes = Uint8List.fromList(pdfBytes);
_previewRevision++;
_showPdfPreview = true;
_previewLoading = false;
});
} catch (e) {
if (!mounted || requestId != _previewRequestId) return;
setState(() {
_previewLoading = false;
_validationErrors = [ErrorExtractor.forContext(e, context)];
});
}
}
Map<String, dynamic>? _parseMargins() { Map<String, dynamic>? _parseMargins() {
double? parse(String s) { double? parse(String s) {
try { try {
@ -392,13 +511,15 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
setState(() => _saving = true); setState(() => _saving = true);
try { try {
final validation = await _service.validateV2Design( final validation = await _service.validateStudioDesign(
businessId: widget.businessId, businessId: widget.businessId,
moduleKey: _moduleKey ?? 'invoices', moduleKey: _moduleKey ?? 'invoices',
subtype: _subtype, subtype: _subtype,
design: _design!, design: _design!,
); );
final errors = ((validation['errors'] as List?) ?? const []).map((e) => e.toString()).toList(); final errors = ((validation['errors'] as List?) ?? const [])
.map((e) => e.toString())
.toList();
if (errors.isNotEmpty) { if (errors.isNotEmpty) {
SnackBarHelper.showError(context, message: errors.join(' | ')); SnackBarHelper.showError(context, message: errors.join(' | '));
return; return;
@ -416,7 +537,9 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
moduleKey: _moduleKey ?? 'invoices', moduleKey: _moduleKey ?? 'invoices',
subtype: _subtype, subtype: _subtype,
name: name, name: name,
description: _descCtrl.text.trim().isEmpty ? null : _descCtrl.text.trim(), description: _descCtrl.text.trim().isEmpty
? null
: _descCtrl.text.trim(),
contentHtml: '<html><body></body></html>', contentHtml: '<html><body></body></html>',
paperSize: _effectivePaperSize(), paperSize: _effectivePaperSize(),
orientation: _orientation, orientation: _orientation,
@ -431,7 +554,9 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
templateId: _templateId!, templateId: _templateId!,
changes: { changes: {
'name': name, 'name': name,
'description': _descCtrl.text.trim().isEmpty ? null : _descCtrl.text.trim(), 'description': _descCtrl.text.trim().isEmpty
? null
: _descCtrl.text.trim(),
'module_key': _moduleKey, 'module_key': _moduleKey,
'subtype': _subtype, 'subtype': _subtype,
'engine': 'template_v2', 'engine': 'template_v2',
@ -450,7 +575,10 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
} }
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); SnackBarHelper.showError(
context,
message: ErrorExtractor.forContext(e, context),
);
} }
} finally { } finally {
if (mounted) setState(() => _saving = false); if (mounted) setState(() => _saving = false);
@ -465,8 +593,14 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
title: const Text('خروج بدون ذخیره؟'), title: const Text('خروج بدون ذخیره؟'),
content: const Text('تغییرات ذخیره نشده از بین می‌رود.'), content: const Text('تغییرات ذخیره نشده از بین می‌رود.'),
actions: [ actions: [
TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('ماندن')), TextButton(
FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('خروج')), onPressed: () => Navigator.pop(ctx, false),
child: const Text('ماندن'),
),
FilledButton(
onPressed: () => Navigator.pop(ctx, true),
child: const Text('خروج'),
),
], ],
), ),
); );
@ -484,15 +618,21 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
'می‌توانید کد را در ادیتور پیشرفته ویرایش کنید.', 'می‌توانید کد را در ادیتور پیشرفته ویرایش کنید.',
), ),
actions: [ actions: [
TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('انصراف')), TextButton(
FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('ادامه')), onPressed: () => Navigator.pop(ctx, false),
child: const Text('انصراف'),
),
FilledButton(
onPressed: () => Navigator.pop(ctx, true),
child: const Text('ادامه'),
),
], ],
), ),
); );
if (ok != true || !mounted) return; if (ok != true || !mounted) return;
try { try {
final fragments = await _service.compileV2Design( final fragments = await _service.compileStudioDesign(
businessId: widget.businessId, businessId: widget.businessId,
design: _design!, design: _design!,
); );
@ -500,7 +640,9 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
final seed = ReportTemplateHtmlEditorSeed( final seed = ReportTemplateHtmlEditorSeed(
name: _nameCtrl.text.trim(), name: _nameCtrl.text.trim(),
description: _descCtrl.text.trim().isEmpty ? null : _descCtrl.text.trim(), description: _descCtrl.text.trim().isEmpty
? null
: _descCtrl.text.trim(),
moduleKey: _moduleKey, moduleKey: _moduleKey,
subtype: _subtype, subtype: _subtype,
contentHtml: fragments['content_html']?.toString(), contentHtml: fragments['content_html']?.toString(),
@ -536,7 +678,10 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
if (mounted) context.pop(true); if (mounted) context.pop(true);
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); SnackBarHelper.showError(
context,
message: ErrorExtractor.forContext(e, context),
);
} }
} }
} }
@ -569,7 +714,8 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
String _scopeLabel() { String _scopeLabel() {
for (final s in _scopeCatalog) { for (final s in _scopeCatalog) {
final id = '${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}'; final id =
'${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}';
if (id == _currentScopeId()) return (s['label_fa'] ?? id).toString(); if (id == _currentScopeId()) return (s['label_fa'] ?? id).toString();
} }
return _currentScopeId(); return _currentScopeId();
@ -586,14 +732,23 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
DropdownButtonFormField<String>( DropdownButtonFormField<String>(
value: _paperChoices.contains(_paperSize) ? _paperSize : _paperChoices.first, value: _paperChoices.contains(_paperSize)
? _paperSize
: _paperChoices.first,
decoration: InputDecoration( decoration: InputDecoration(
labelText: 'سایز کاغذ', labelText: 'سایز کاغذ',
border: const OutlineInputBorder(), border: const OutlineInputBorder(),
helperText: _isReceiptScope ? 'عرض فیش؛ ارتفاع هر صفحه ۲۹۷ میلی‌متر است' : null, helperText: _isReceiptScope
? 'عرض فیش؛ ارتفاع هر صفحه ۲۹۷ میلی‌متر است'
: null,
), ),
items: _paperChoices items: _paperChoices
.map((e) => DropdownMenuItem(value: e, child: Text(reportTemplatePaperSizeLabel(e)))) .map(
(e) => DropdownMenuItem(
value: e,
child: Text(reportTemplatePaperSizeLabel(e)),
),
)
.toList(), .toList(),
onChanged: (v) => setState(() { onChanged: (v) => setState(() {
_paperSize = v; _paperSize = v;
@ -606,13 +761,17 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
decoration: InputDecoration( decoration: InputDecoration(
labelText: 'جهت', labelText: 'جهت',
border: const OutlineInputBorder(), border: const OutlineInputBorder(),
helperText: _isReceiptScope ? 'فیش پرینتر همیشه عمودی است' : null, helperText: _isReceiptScope
? 'فیش پرینتر همیشه عمودی است'
: null,
), ),
items: const [ items: const [
DropdownMenuItem(value: 'portrait', child: Text('عمودی')), DropdownMenuItem(value: 'portrait', child: Text('عمودی')),
DropdownMenuItem(value: 'landscape', child: Text('افقی')), DropdownMenuItem(value: 'landscape', child: Text('افقی')),
], ],
onChanged: _isReceiptScope ? null : (v) => setState(() => _orientation = v), onChanged: _isReceiptScope
? null
: (v) => setState(() => _orientation = v),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
Row( Row(
@ -634,7 +793,10 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
), ),
), ),
actions: [ actions: [
TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('بستن')), TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('بستن'),
),
FilledButton( FilledButton(
onPressed: () { onPressed: () {
Navigator.pop(ctx); Navigator.pop(ctx);
@ -650,63 +812,153 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
Widget _marginField(String label, TextEditingController ctrl) { Widget _marginField(String label, TextEditingController ctrl) {
return TextField( return TextField(
controller: ctrl, controller: ctrl,
decoration: InputDecoration(labelText: label, border: const OutlineInputBorder(), isDense: true), decoration: InputDecoration(
labelText: label,
border: const OutlineInputBorder(),
isDense: true,
),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
inputFormatters: [EnglishDigitsFormatter()], inputFormatters: [EnglishDigitsFormatter()],
); );
} }
Future<void> _handleToolbarAction(_StudioToolbarAction action) async {
switch (action) {
case _StudioToolbarAction.changeTemplate:
setState(() => _step = _StudioStep.gallery);
return;
case _StudioToolbarAction.advancedHtml:
await _openAdvancedHtml();
return;
case _StudioToolbarAction.pageSettings:
await _showPageSettings();
return;
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (!widget.authStore.hasBusinessPermission('report_templates', 'write')) { if (!widget.authStore.hasBusinessPermission('report_templates', 'write')) {
return const AccessDeniedPage(message: 'شما دسترسی لازم برای ویرایش قالب‌ها را ندارید'); return const AccessDeniedPage(
message: 'شما دسترسی لازم برای ویرایش قالب‌ها را ندارید',
);
} }
final isNew = widget.isNew; final isNew = widget.isNew;
final title = isNew ? 'استودیو قالب — جدید' : 'استودیو قالب — ویرایش'; final title = isNew ? 'استودیو قالب — جدید' : 'استودیو قالب — ویرایش';
final compactToolbar = MediaQuery.sizeOf(context).width < 900;
return HesabixBackInterceptor( return HesabixBackInterceptor(
onWillPop: _confirmDiscard, onWillPop: _confirmDiscard,
child: Scaffold( child: Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(title), title: Text(title),
leading: hesabixBackAppBarLeading(context, businessId: widget.businessId), leading: hesabixBackAppBarLeading(
context,
businessId: widget.businessId,
),
actions: [ actions: [
if (_step == _StudioStep.customize && isNew) if (!compactToolbar && _step == _StudioStep.customize && isNew)
TextButton.icon( TextButton.icon(
onPressed: () => setState(() => _step = _StudioStep.gallery), onPressed: () => setState(() => _step = _StudioStep.gallery),
icon: const Icon(Icons.grid_view), icon: const Icon(Icons.grid_view),
label: const Text('تغییر قالب'), label: const Text('تغییر قالب'),
), ),
if (_step == _StudioStep.customize && _design != null) if (!compactToolbar &&
_step == _StudioStep.customize &&
_design != null)
TextButton.icon( TextButton.icon(
onPressed: _openAdvancedHtml, onPressed: _openAdvancedHtml,
icon: const Icon(Icons.code), icon: const Icon(Icons.code),
label: const Text('حالت پیشرفته'), label: const Text('حالت پیشرفته'),
), ),
IconButton(icon: const Icon(Icons.settings), tooltip: 'تنظیمات صفحه', onPressed: _showPageSettings), if (!compactToolbar)
if (_hasUnsavedChanges) IconButton(
icon: const Icon(Icons.settings),
tooltip: 'تنظیمات صفحه',
onPressed: _showPageSettings,
),
if (compactToolbar)
PopupMenuButton<_StudioToolbarAction>(
tooltip: 'گزینه‌های استودیو',
onSelected: _handleToolbarAction,
itemBuilder: (context) => [
if (_step == _StudioStep.customize && isNew)
const PopupMenuItem(
value: _StudioToolbarAction.changeTemplate,
child: ListTile(
leading: Icon(Icons.grid_view),
title: Text('تغییر قالب'),
contentPadding: EdgeInsets.zero,
),
),
if (_step == _StudioStep.customize && _design != null)
const PopupMenuItem(
value: _StudioToolbarAction.advancedHtml,
child: ListTile(
leading: Icon(Icons.code),
title: Text('حالت پیشرفته'),
contentPadding: EdgeInsets.zero,
),
),
const PopupMenuItem(
value: _StudioToolbarAction.pageSettings,
child: ListTile(
leading: Icon(Icons.settings),
title: Text('تنظیمات صفحه'),
contentPadding: EdgeInsets.zero,
),
),
],
),
if (_hasUnsavedChanges && !compactToolbar)
const Padding( const Padding(
padding: EdgeInsets.symmetric(horizontal: 8), padding: EdgeInsets.symmetric(horizontal: 8),
child: Chip(label: Text('ذخیره نشده'), visualDensity: VisualDensity.compact), child: Chip(
label: Text('ذخیره نشده'),
visualDensity: VisualDensity.compact,
),
), ),
Padding( Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), padding: EdgeInsets.symmetric(
child: FilledButton.icon( horizontal: compactToolbar ? 2 : 8,
onPressed: _saving || _loading || _design == null ? null : _save, vertical: 8,
icon: _saving
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.save),
label: Text(_saving ? 'در حال ذخیره...' : 'ذخیره'),
), ),
child: compactToolbar
? IconButton(
tooltip: _saving ? 'در حال ذخیره...' : 'ذخیره',
onPressed: _saving || _loading || _design == null
? null
: _save,
icon: _saving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.save),
)
: FilledButton.icon(
onPressed: _saving || _loading || _design == null
? null
: _save,
icon: _saving
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.save),
label: Text(_saving ? 'در حال ذخیره...' : 'ذخیره'),
),
), ),
], ],
), ),
body: _loading body: _loading
? const Center(child: LoadingIndicator()) ? const Center(child: LoadingIndicator())
: _step == _StudioStep.gallery : _step == _StudioStep.gallery
? _buildGalleryStep(context) ? _buildGalleryStep(context)
: _buildCustomizeStep(context), : _buildCustomizeStep(context),
), ),
); );
} }
@ -720,20 +972,30 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text('انتخاب قالب', style: Theme.of(context).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold)), Text(
'انتخاب قالب',
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4), const SizedBox(height: 4),
Text( Text(
'یک قالب حرفه‌ای انتخاب کنید؛ سپس آن را سفارشی کنید.', 'یک قالب حرفه‌ای انتخاب کنید؛ سپس آن را سفارشی کنید.',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant), style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
Row( Row(
children: [ children: [
Expanded( Expanded(
child: DropdownButtonFormField<String>( child: DropdownButtonFormField<String>(
value: _scopeCatalog.any((s) => value:
'${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}' == _scopeCatalog.any(
_currentScopeId()) (s) =>
'${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}' ==
_currentScopeId(),
)
? _currentScopeId() ? _currentScopeId()
: null, : null,
decoration: const InputDecoration( decoration: const InputDecoration(
@ -744,7 +1006,8 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
items: _scopeCatalog items: _scopeCatalog
.map( .map(
(s) => DropdownMenuItem<String>( (s) => DropdownMenuItem<String>(
value: '${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}', value:
'${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}',
child: Text((s['label_fa'] ?? '').toString()), child: Text((s['label_fa'] ?? '').toString()),
), ),
) )
@ -777,62 +1040,121 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
return const Center(child: Text('قالبی انتخاب نشده است.')); return const Center(child: Text('قالبی انتخاب نشده است.'));
} }
return Row( if ((design['schema_version'] as num?)?.toInt() == 3) {
children: [ return ReportTemplateStudioV3Builder(
SizedBox( design: design,
width: 360, blockCatalog: _blockCatalog,
onDesignChanged: _onDesignChanged,
editorHeader: _buildTemplateIdentityFields(),
previewPane: _buildPreviewPane(),
);
}
final settingsPane = _buildCustomizeSettings(design);
final previewPane = _buildPreviewPane();
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth >= 900) {
return Row(
children: [
SizedBox(width: 520, child: settingsPane),
VerticalDivider(width: 1, color: Theme.of(context).dividerColor),
Expanded(flex: 3, child: previewPane),
],
);
}
return DefaultTabController(
length: 2,
child: Column( child: Column(
children: [ children: [
Padding( const Material(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), child: TabBar(
child: Column( tabs: [
children: [ Tab(icon: Icon(Icons.tune), text: 'تنظیمات'),
TextField( Tab(
controller: _nameCtrl, icon: Icon(Icons.picture_as_pdf_outlined),
decoration: const InputDecoration( text: 'پیش‌نمایش',
labelText: 'نام قالب',
border: OutlineInputBorder(),
isDense: true,
),
),
const SizedBox(height: 8),
TextField(
controller: _descCtrl,
decoration: const InputDecoration(
labelText: 'توضیحات (اختیاری)',
border: OutlineInputBorder(),
isDense: true,
),
maxLines: 2,
), ),
], ],
), ),
), ),
const Divider(height: 16),
Expanded( Expanded(
child: ReportTemplateStudioCustomizePanel( child: TabBarView(children: [settingsPane, previewPane]),
design: design,
moduleKey: _moduleKey ?? 'invoices',
subtype: _subtype,
onDesignChanged: _onDesignChanged,
),
), ),
], ],
), ),
), );
VerticalDivider(width: 1, color: Theme.of(context).dividerColor), },
);
}
Widget _buildCustomizeSettings(Map<String, dynamic> design) {
return Column(
children: [
_buildTemplateIdentityFields(),
const Divider(height: 16),
Expanded( Expanded(
flex: 3, child: ReportTemplateStudioCustomizePanel(
child: ReportTemplateStudioPreviewPanel( design: design,
loading: _previewLoading, moduleKey: _moduleKey ?? 'invoices',
pdfBytes: _previewPdfBytes, subtype: _subtype,
previewRevision: _previewRevision, blockCatalog: _blockCatalog,
errors: _validationErrors, onDesignChanged: _onDesignChanged,
warnings: _validationWarnings,
onRefresh: _refreshPreview,
), ),
), ),
], ],
); );
} }
Widget _buildTemplateIdentityFields() {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Column(
children: [
TextField(
controller: _nameCtrl,
decoration: const InputDecoration(
labelText: 'نام قالب',
border: OutlineInputBorder(),
isDense: true,
),
),
const SizedBox(height: 8),
TextField(
controller: _descCtrl,
decoration: const InputDecoration(
labelText: 'توضیحات (اختیاری)',
border: OutlineInputBorder(),
isDense: true,
),
maxLines: 2,
),
],
),
);
}
Widget _buildPreviewPane() {
return ReportTemplateStudioPreviewPanel(
loading: _previewLoading,
pdfBytes: _previewPdfBytes,
html: _previewHtml,
previewRevision: _previewRevision,
paperSize: _effectivePaperSize(),
orientation: _orientation,
errors: _validationErrors,
warnings: _validationWarnings,
onRefresh: _refreshPreview,
onGeneratePdf: () {
if (_previewPdfBytes != null && _previewPdfBytes!.isNotEmpty) {
setState(() => _showPdfPreview = true);
} else {
_refreshPdfPreview();
}
},
onShowHtml: () => setState(() => _showPdfPreview = false),
showPdf: _showPdfPreview,
);
}
} }

View file

@ -29,6 +29,7 @@ class ReportTemplatesPage extends StatefulWidget {
State<ReportTemplatesPage> createState() => _ReportTemplatesPageState(); State<ReportTemplatesPage> createState() => _ReportTemplatesPageState();
} }
class _ReportTemplatesPageState extends State<ReportTemplatesPage> { class _ReportTemplatesPageState extends State<ReportTemplatesPage> {
late final ReportTemplateService _service; late final ReportTemplateService _service;
final _moduleCtrl = TextEditingController(text: 'invoices'); final _moduleCtrl = TextEditingController(text: 'invoices');
@ -1260,43 +1261,68 @@ class _ReportTemplatesPageState extends State<ReportTemplatesPage> {
await showDialog<void>( await showDialog<void>(
context: context, context: context,
builder: (ctx) { builder: (ctx) {
return DefaultTabController( final viewport = MediaQuery.sizeOf(ctx);
length: 2, final availableWidth = viewport.width > 32 ? viewport.width - 32 : viewport.width;
child: AlertDialog( final availableHeight = viewport.height > 32 ? viewport.height - 32 : viewport.height;
title: Text(t.reportTemplatePreviewTitle), final dialogWidth = availableWidth > 900 ? 900.0 : availableWidth;
content: SizedBox( final dialogHeight = availableHeight > 720 ? 720.0 : availableHeight;
width: 720, return SafeArea(
height: 480, child: Dialog(
child: Column( insetPadding: const EdgeInsets.all(16),
crossAxisAlignment: CrossAxisAlignment.stretch, clipBehavior: Clip.antiAlias,
children: [ child: SizedBox(
TabBar( width: dialogWidth,
tabs: [ height: dialogHeight,
Tab(text: t.reportTemplatePreviewHtmlTab), child: DefaultTabController(
Tab(text: t.reportTemplatePreviewPdfTab), length: 2,
], child: Column(
), crossAxisAlignment: CrossAxisAlignment.stretch,
Expanded( children: [
child: TabBarView( Padding(
children: [ padding: const EdgeInsetsDirectional.fromSTEB(20, 12, 8, 4),
SingleChildScrollView( child: Row(
child: SelectableText(html.isEmpty ? '—' : html), children: [
), Expanded(
_listPreviewPdfPane( child: Text(
t, t.reportTemplatePreviewTitle,
pdfBytes, style: Theme.of(ctx).textTheme.titleLarge,
lenFromPreview, ),
pdfFetchFailed, ),
), IconButton(
tooltip: t.close,
onPressed: () => Navigator.pop(ctx),
icon: const Icon(Icons.close),
),
],
),
),
TabBar(
tabs: [
Tab(text: t.reportTemplatePreviewHtmlTab),
Tab(text: t.reportTemplatePreviewPdfTab),
], ],
), ),
), const Divider(height: 1),
], Expanded(
child: TabBarView(
children: [
SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: SelectableText(html.isEmpty ? '—' : html),
),
_listPreviewPdfPane(
t,
pdfBytes,
lenFromPreview,
pdfFetchFailed,
),
],
),
),
],
),
), ),
), ),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx), child: Text(t.close)),
],
), ),
); );
}, },
@ -1978,4 +2004,3 @@ class _ReportTemplatesPageState extends State<ReportTemplatesPage> {
} }
} }

View file

@ -175,6 +175,31 @@ class ReportTemplateService {
return res.data ?? const <String, dynamic>{}; return res.data ?? const <String, dynamic>{};
} }
Future<String> previewHtml({
required int businessId,
required String engine,
required Map<String, dynamic> design,
required Map<String, dynamic> assets,
required Map<String, dynamic> context,
String? paperSize,
String? orientation,
Map<String, dynamic>? margins,
}) async {
final res = await _api.post<Map<String, dynamic>>(
'/report-templates/business/$businessId/preview-html',
data: {
'engine': engine,
'design': design,
'assets': assets,
'context': context,
if (paperSize != null) 'paper_size': paperSize,
if (orientation != null) 'orientation': orientation,
if (margins != null) 'margins': margins,
},
);
return (res.data?['html'] ?? '').toString();
}
Future<Map<String, dynamic>> schema({ Future<Map<String, dynamic>> schema({
required int businessId, required int businessId,
required String moduleKey, required String moduleKey,
@ -267,6 +292,61 @@ class ReportTemplateService {
return items.cast<Map<String, dynamic>>(); return items.cast<Map<String, dynamic>>();
} }
Future<List<Map<String, dynamic>>> studioBlocks({
required int businessId,
required String moduleKey,
String? subtype,
}) async {
final res = await _api.get<Map<String, dynamic>>(
'/report-templates/business/$businessId/studio-blocks',
query: {
'module_key': moduleKey,
if (subtype != null && subtype.isNotEmpty) 'subtype': subtype,
},
);
final items = (res.data?['items'] as List?) ?? const [];
return items.cast<Map<String, dynamic>>();
}
Future<Map<String, dynamic>> validateStudioDesign({
required int businessId,
required String moduleKey,
String? subtype,
required Map<String, dynamic> design,
}) async {
final res = await _api.post<Map<String, dynamic>>(
'/report-templates/business/$businessId/validate-studio-design',
data: {
'module_key': moduleKey,
if (subtype != null) 'subtype': subtype,
'design': design,
},
);
return res.data ?? const <String, dynamic>{};
}
Future<Map<String, dynamic>> compileStudioDesign({
required int businessId,
required Map<String, dynamic> design,
}) async {
final res = await _api.post<Map<String, dynamic>>(
'/report-templates/business/$businessId/compile-studio-design',
data: {'design': design},
);
return res.data ?? const <String, dynamic>{};
}
Future<Map<String, dynamic>> migrateV2ToV3({
required int businessId,
required Map<String, dynamic> design,
}) async {
final res = await _api.post<Map<String, dynamic>>(
'/report-templates/business/$businessId/migrate-v2-to-v3',
data: {'design': design},
);
return res.data ?? const <String, dynamic>{};
}
Future<Map<String, dynamic>> validateV2Design({ Future<Map<String, dynamic>> validateV2Design({
required int businessId, required int businessId,
required String moduleKey, required String moduleKey,
@ -339,5 +419,3 @@ class ReportTemplateService {
return res.data ?? const <String, dynamic>{}; return res.data ?? const <String, dynamic>{};
} }
} }

View file

@ -0,0 +1,2 @@
export 'embedded_html_iframe_stub.dart'
if (dart.library.js_interop) 'embedded_html_iframe_web.dart';

View file

@ -0,0 +1,14 @@
import 'package:flutter/material.dart';
class ReportTemplateEmbeddedHtml extends StatelessWidget {
final String html;
const ReportTemplateEmbeddedHtml({super.key, required this.html});
@override
Widget build(BuildContext context) {
return const Center(
child: Text('پیش‌نمایش HTML فقط در نسخه وب در دسترس است.'),
);
}
}

View file

@ -0,0 +1,67 @@
import 'dart:js_interop';
import 'dart:ui_web' as ui_web;
import 'package:flutter/material.dart';
import 'package:web/web.dart' as web;
class ReportTemplateEmbeddedHtml extends StatefulWidget {
final String html;
const ReportTemplateEmbeddedHtml({super.key, required this.html});
@override
State<ReportTemplateEmbeddedHtml> createState() =>
_ReportTemplateEmbeddedHtmlState();
}
class _ReportTemplateEmbeddedHtmlState
extends State<ReportTemplateEmbeddedHtml> {
static int _sequence = 0;
late final String _viewType;
web.HTMLIFrameElement? _iframe;
@override
void initState() {
super.initState();
_viewType = 'report-html-${++_sequence}';
ui_web.platformViewRegistry.registerViewFactory(_viewType, _createView);
}
@override
void didUpdateWidget(covariant ReportTemplateEmbeddedHtml oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.html != widget.html) _applyHtml();
}
web.Element _createView(int viewId) {
final iframe = web.document.createElement('iframe') as web.HTMLIFrameElement
..title = 'HTML preview'
..style.border = 'none'
..style.width = '100%'
..style.height = '100%'
..style.display = 'block'
..style.backgroundColor = '#ffffff';
iframe.setAttribute('sandbox', 'allow-same-origin');
_iframe = iframe;
_applyHtml();
return iframe;
}
void _applyHtml() {
final iframe = _iframe;
if (iframe == null) return;
iframe.srcdoc = widget.html.toJS;
}
@override
void dispose() {
_iframe = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
return SizedBox.expand(child: HtmlElementView(viewType: _viewType));
}
}

View file

@ -1,4 +1,3 @@
import 'dart:typed_data';
import 'dart:ui_web' as ui_web; import 'dart:ui_web' as ui_web;
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
@ -16,20 +15,24 @@ bool _isPdfBytes(Uint8List bytes) {
} }
/// نمایش PDF داخل صفحه (وب) با platform view و blob URL. /// نمایش PDF داخل صفحه (وب) با platform view و blob URL.
///
/// استفاده از embed به جای iframe مهم است: برخی مرورگرها نمایشگر PDF را برای
/// blob داخل iframe سفید رندر می‌کنند، در حالی که همان URL در تب جدید سالم است.
class ReportTemplateEmbeddedPdf extends StatefulWidget { class ReportTemplateEmbeddedPdf extends StatefulWidget {
final Uint8List bytes; final Uint8List bytes;
const ReportTemplateEmbeddedPdf({super.key, required this.bytes}); const ReportTemplateEmbeddedPdf({super.key, required this.bytes});
@override @override
State<ReportTemplateEmbeddedPdf> createState() => _ReportTemplateEmbeddedPdfState(); State<ReportTemplateEmbeddedPdf> createState() =>
_ReportTemplateEmbeddedPdfState();
} }
class _ReportTemplateEmbeddedPdfState extends State<ReportTemplateEmbeddedPdf> { class _ReportTemplateEmbeddedPdfState extends State<ReportTemplateEmbeddedPdf> {
static int _factorySeq = 0; static int _factorySeq = 0;
late final String _viewType; late final String _viewType;
web.HTMLIFrameElement? _iframe; web.HTMLEmbedElement? _embed;
String? _objectUrl; String? _objectUrl;
String? _error; String? _error;
bool _viewMounted = false; bool _viewMounted = false;
@ -55,36 +58,25 @@ class _ReportTemplateEmbeddedPdfState extends State<ReportTemplateEmbeddedPdf> {
} }
web.Element _createView(int viewId) { web.Element _createView(int viewId) {
final root = web.document.createElement('div') as web.HTMLDivElement final embed = web.document.createElement('embed') as web.HTMLEmbedElement
..type = 'application/pdf'
..style.border = 'none'
..style.width = '100%' ..style.width = '100%'
..style.height = '100%' ..style.height = '100%'
..style.minHeight = '320px'
..style.position = 'relative'
..style.overflow = 'hidden'
..style.display = 'block' ..style.display = 'block'
..style.backgroundColor = '#ffffff'; ..style.backgroundColor = '#ffffff';
final iframe = web.document.createElement('iframe') as web.HTMLIFrameElement embed.setAttribute('aria-label', 'PDF preview');
..title = 'PDF preview' _embed = embed;
..style.border = 'none'
..style.position = 'absolute'
..style.left = '0'
..style.top = '0'
..style.width = '100%'
..style.height = '100%'
..style.display = 'block';
root.append(iframe);
_iframe = iframe;
_viewMounted = true; _viewMounted = true;
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _applyBytes(); if (mounted) _applyBytes();
}); });
return root; return embed;
} }
void _applyBytes() { void _applyBytes() {
if (!_viewMounted || _iframe == null) return; if (!_viewMounted || _embed == null) return;
if (widget.bytes.isEmpty) { if (widget.bytes.isEmpty) {
setState(() => _error = 'فایل PDF خالی است'); setState(() => _error = 'فایل PDF خالی است');
@ -101,7 +93,7 @@ class _ReportTemplateEmbeddedPdfState extends State<ReportTemplateEmbeddedPdf> {
widget.bytes, widget.bytes,
mimeType: 'application/pdf', mimeType: 'application/pdf',
); );
_iframe!.src = url; _embed!.src = url;
_objectUrl = url; _objectUrl = url;
if (previousUrl != null && previousUrl != url) { if (previousUrl != null && previousUrl != url) {
_scheduleRevoke(previousUrl); _scheduleRevoke(previousUrl);
@ -123,7 +115,8 @@ class _ReportTemplateEmbeddedPdfState extends State<ReportTemplateEmbeddedPdf> {
void dispose() { void dispose() {
final url = _objectUrl; final url = _objectUrl;
_objectUrl = null; _objectUrl = null;
_iframe = null; _embed = null;
_viewMounted = false;
super.dispose(); super.dispose();
if (url != null) { if (url != null) {
_scheduleRevoke(url); _scheduleRevoke(url);
@ -140,8 +133,8 @@ class _ReportTemplateEmbeddedPdfState extends State<ReportTemplateEmbeddedPdf> {
_error!, _error!,
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium?.copyWith( style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.error, color: Theme.of(context).colorScheme.error,
), ),
), ),
), ),
); );
@ -152,8 +145,8 @@ class _ReportTemplateEmbeddedPdfState extends State<ReportTemplateEmbeddedPdf> {
child: Text( child: Text(
'فایل PDF خالی است', 'فایل PDF خالی است',
style: Theme.of(context).textTheme.bodyMedium?.copyWith( style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant, color: Theme.of(context).colorScheme.onSurfaceVariant,
), ),
), ),
); );
} }
@ -163,10 +156,12 @@ class _ReportTemplateEmbeddedPdfState extends State<ReportTemplateEmbeddedPdf> {
var width = constraints.maxWidth; var width = constraints.maxWidth;
var height = constraints.maxHeight; var height = constraints.maxHeight;
if (!width.isFinite || width <= 0) { if (!width.isFinite || width <= 0) {
width = MediaQuery.sizeOf(context).width; final screenWidth = MediaQuery.sizeOf(context).width;
width = screenWidth > 720 ? 720 : screenWidth;
} }
if (!height.isFinite || height <= 0) { if (!height.isFinite || height <= 0) {
height = MediaQuery.sizeOf(context).height * 0.55; final screenHeight = MediaQuery.sizeOf(context).height;
height = screenHeight > 520 ? 520 : screenHeight;
} }
return SizedBox( return SizedBox(
width: width, width: width,

View file

@ -3,10 +3,13 @@ import 'dart:convert';
import 'package:file_picker/file_picker.dart'; import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'report_template_studio_v3_builder.dart';
class ReportTemplateStudioCustomizePanel extends StatelessWidget { class ReportTemplateStudioCustomizePanel extends StatelessWidget {
final Map<String, dynamic> design; final Map<String, dynamic> design;
final String moduleKey; final String moduleKey;
final String? subtype; final String? subtype;
final List<Map<String, dynamic>> blockCatalog;
final ValueChanged<Map<String, dynamic>> onDesignChanged; final ValueChanged<Map<String, dynamic>> onDesignChanged;
const ReportTemplateStudioCustomizePanel({ const ReportTemplateStudioCustomizePanel({
@ -14,6 +17,7 @@ class ReportTemplateStudioCustomizePanel extends StatelessWidget {
required this.design, required this.design,
required this.moduleKey, required this.moduleKey,
required this.subtype, required this.subtype,
this.blockCatalog = const [],
required this.onDesignChanged, required this.onDesignChanged,
}); });
@ -69,6 +73,13 @@ class ReportTemplateStudioCustomizePanel extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if ((design['schema_version'] as num?)?.toInt() == 3) {
return ReportTemplateStudioV3Builder(
design: design,
blockCatalog: blockCatalog,
onDesignChanged: onDesignChanged,
);
}
final theme = _theme(); final theme = _theme();
final sections = _sections(); final sections = _sections();
final branding = _branding(); final branding = _branding();

View file

@ -5,27 +5,95 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../utils/web/web_utils.dart' as web_utils; import '../../../utils/web/web_utils.dart' as web_utils;
import '../embedded_html_iframe.dart';
import '../embedded_pdf_iframe.dart'; import '../embedded_pdf_iframe.dart';
import 'package:hesabix_ui/theme/semantic_color_resolver.dart'; import 'package:hesabix_ui/theme/semantic_color_resolver.dart';
class ReportTemplateStudioPreviewPanel extends StatelessWidget { class ReportTemplateStudioPreviewPanel extends StatelessWidget {
final bool loading; final bool loading;
final Uint8List? pdfBytes; final Uint8List? pdfBytes;
final String? html;
final int previewRevision; final int previewRevision;
final String? paperSize;
final String? orientation;
final List<String> errors; final List<String> errors;
final List<String> warnings; final List<String> warnings;
final VoidCallback? onRefresh; final VoidCallback? onRefresh;
final VoidCallback? onGeneratePdf;
final VoidCallback? onShowHtml;
final bool showPdf;
const ReportTemplateStudioPreviewPanel({ const ReportTemplateStudioPreviewPanel({
super.key, super.key,
required this.loading, required this.loading,
required this.pdfBytes, required this.pdfBytes,
this.html,
this.previewRevision = 0, this.previewRevision = 0,
this.paperSize,
this.orientation,
this.errors = const [], this.errors = const [],
this.warnings = const [], this.warnings = const [],
this.onRefresh, this.onRefresh,
this.onGeneratePdf,
this.onShowHtml,
this.showPdf = false,
}); });
double get _viewportAspectRatio {
final paper = (paperSize ?? '').trim().toLowerCase();
var portraitRatio = switch (paper) {
'letter' => 8.5 / 11,
'legal' => 8.5 / 14,
'60mm' || '80mm' || '100mm' => 0.55,
_ => 1 / 1.414,
};
if ((orientation ?? '').toLowerCase() == 'landscape') {
portraitRatio = 1 / portraitRatio;
}
return portraitRatio;
}
Widget _pagePreview(BuildContext context, Widget child) {
return LayoutBuilder(
builder: (context, constraints) {
final fallbackSize = MediaQuery.sizeOf(context);
final availableWidth = constraints.maxWidth.isFinite ? constraints.maxWidth : fallbackSize.width;
final availableHeight = constraints.maxHeight.isFinite ? constraints.maxHeight : fallbackSize.height * 0.7;
final maxWidth = availableWidth > 24 ? availableWidth - 24 : availableWidth;
final maxHeight = availableHeight > 24 ? availableHeight - 24 : availableHeight;
var width = maxWidth;
var height = width / _viewportAspectRatio;
if (height > maxHeight) {
height = maxHeight;
width = height * _viewportAspectRatio;
}
return ColoredBox(
color: Colors.grey.shade200,
child: Center(
child: SizedBox(
width: width,
height: height,
child: DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.12),
blurRadius: 12,
offset: const Offset(0, 4),
),
],
),
child: child,
),
),
),
);
},
);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Column( return Column(
@ -49,7 +117,21 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget {
tooltip: 'بروزرسانی پیش‌نمایش', tooltip: 'بروزرسانی پیش‌نمایش',
onPressed: loading ? null : onRefresh, onPressed: loading ? null : onRefresh,
), ),
if (kIsWeb && pdfBytes != null && pdfBytes!.isNotEmpty) if (html != null && html!.isNotEmpty)
IconButton(
icon: const Icon(Icons.code_outlined, size: 20),
color: !showPdf ? Theme.of(context).colorScheme.primary : null,
tooltip: 'پیش‌نمایش سریع',
onPressed: onShowHtml,
),
if (onGeneratePdf != null)
IconButton(
icon: const Icon(Icons.picture_as_pdf, size: 20),
color: showPdf ? Theme.of(context).colorScheme.primary : null,
tooltip: pdfBytes == null ? 'ساخت پیش‌نمایش چاپ' : 'پیش‌نمایش چاپ',
onPressed: loading ? null : onGeneratePdf,
),
if (showPdf && kIsWeb && pdfBytes != null && pdfBytes!.isNotEmpty)
IconButton( IconButton(
icon: const Icon(Icons.open_in_new, size: 20), icon: const Icon(Icons.open_in_new, size: 20),
tooltip: 'باز کردن در تب جدید', tooltip: 'باز کردن در تب جدید',
@ -82,29 +164,20 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget {
child: Stack( child: Stack(
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
if (pdfBytes != null && pdfBytes!.isNotEmpty) if (showPdf && pdfBytes != null && pdfBytes!.isNotEmpty)
ColoredBox( _pagePreview(
color: Colors.grey.shade200, context,
child: Padding( ReportTemplateEmbeddedPdf(
padding: const EdgeInsets.all(12), key: ValueKey('pdf-preview-$previewRevision'),
child: DecoratedBox( bytes: pdfBytes!,
decoration: BoxDecoration( ),
color: Colors.white, )
boxShadow: [ else if (html != null && html!.isNotEmpty)
BoxShadow( _pagePreview(
color: Colors.black.withValues(alpha: 0.12), context,
blurRadius: 12, ReportTemplateEmbeddedHtml(
offset: const Offset(0, 4), key: ValueKey('html-preview-$previewRevision'),
), html: html!,
],
),
child: SizedBox.expand(
child: ReportTemplateEmbeddedPdf(
key: ValueKey('preview-$previewRevision'),
bytes: pdfBytes!,
),
),
),
), ),
) )
else if (!loading) else if (!loading)

View file

@ -0,0 +1,190 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hesabix_ui/widgets/report_template/studio/report_template_studio_v3_builder.dart';
void main() {
testWidgets('adds a palette block and supports undo', (tester) async {
var design = <String, dynamic>{
'schema_version': 3,
'family_id': 'invoice_classic',
'layout': 'invoice_detail',
'theme': <String, dynamic>{
'primary_color': '#1e3a5f',
'font_size_base': 11,
},
'branding': <String, dynamic>{
'show_logo': true,
'show_business_name': true,
},
'regions': <String, dynamic>{
'header': <Map<String, dynamic>>[],
'body': <Map<String, dynamic>>[
<String, dynamic>{
'id': 'invoice-lines',
'type': 'invoice_lines',
'visible': true,
'props': <String, dynamic>{
'columns': <Map<String, dynamic>>[
<String, dynamic>{
'key': 'product_name',
'title': 'شرح',
'visible': true,
'width': 'auto',
},
],
},
'style': <String, dynamic>{},
},
],
'footer': <Map<String, dynamic>>[],
},
};
const catalog = <Map<String, dynamic>>[
<String, dynamic>{
'type': 'invoice_lines',
'label_fa': 'جدول اقلام',
'allowed_regions': <String>['body'],
'max_instances': 1,
'required': true,
'default_props': <String, dynamic>{},
},
<String, dynamic>{
'type': 'custom_text',
'label_fa': 'متن دلخواه',
'allowed_regions': <String>['header', 'body', 'footer'],
'default_props': <String, dynamic>{
'text': 'متن دلخواه',
'align': 'right',
},
},
];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) {
return SizedBox(
width: 600,
height: 900,
child: ReportTemplateStudioV3Builder(
design: design,
blockCatalog: catalog,
onDesignChanged: (next) => setState(() => design = next),
),
);
},
),
),
),
);
await tester.tap(find.text('ظاهر، برندینگ و جهت نوشتار'));
await tester.pumpAndSettle();
await tester.tap(find.text('چپ‌به‌راست'));
await tester.pump();
expect((design['theme'] as Map)['direction'], 'ltr');
await tester.tap(find.text('متن دلخواه').first);
await tester.pump();
final body = ((design['regions'] as Map)['body'] as List)
.cast<Map<String, dynamic>>();
expect(body.map((block) => block['type']), contains('custom_text'));
await tester.tap(find.byIcon(Icons.undo));
await tester.pump();
final restoredBody = ((design['regions'] as Map)['body'] as List)
.cast<Map<String, dynamic>>();
expect(
restoredBody.map((block) => block['type']),
isNot(contains('custom_text')),
);
});
testWidgets('shows block settings in the left workspace column', (
tester,
) async {
tester.view.physicalSize = const Size(1100, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
var design = <String, dynamic>{
'schema_version': 3,
'family_id': 'invoice_classic',
'layout': 'invoice_detail',
'theme': <String, dynamic>{},
'branding': <String, dynamic>{},
'regions': <String, dynamic>{
'header': <Map<String, dynamic>>[],
'body': <Map<String, dynamic>>[
<String, dynamic>{
'id': 'invoice-lines',
'type': 'invoice_lines',
'visible': true,
'props': <String, dynamic>{'columns': <Map<String, dynamic>>[]},
'style': <String, dynamic>{},
},
],
'footer': <Map<String, dynamic>>[],
},
};
const catalog = <Map<String, dynamic>>[
<String, dynamic>{
'type': 'invoice_lines',
'label_fa': 'جدول اقلام',
'allowed_regions': <String>['body'],
'max_instances': 1,
'required': true,
'default_props': <String, dynamic>{},
},
];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => ReportTemplateStudioV3Builder(
design: design,
blockCatalog: catalog,
onDesignChanged: (next) => setState(() => design = next),
editorHeader: const Text('مشخصات قالب'),
previewPane: const Center(child: Text('پیش‌نمایش آزمایشی')),
),
),
),
),
);
expect(
find.text(
'یک بلوک را انتخاب کنید تا تنظیمات آن در این ستون نمایش داده شود.',
),
findsOneWidget,
);
await tester.tap(find.text('جدول اقلام').last);
await tester.pump();
final inspector = find.text('تنظیمات جدول اقلام');
final preview = find.text('پیش‌نمایش آزمایشی');
final designer = find.text('طراح بلوکی');
expect(inspector, findsOneWidget);
expect(
tester.getCenter(inspector).dx,
lessThan(tester.getCenter(preview).dx),
);
expect(
tester.getCenter(preview).dx,
lessThan(tester.getCenter(designer).dx),
);
await tester.tap(find.text('وسط'));
await tester.pump();
final body = ((design['regions'] as Map)['body'] as List)
.cast<Map<String, dynamic>>();
expect((body.first['style'] as Map)['text_align'], 'center');
});
}