diff --git a/hesabixAPI/adapters/api/v1/report_templates.py b/hesabixAPI/adapters/api/v1/report_templates.py index b70c7004..6963d8e2 100755 --- a/hesabixAPI/adapters/api/v1/report_templates.py +++ b/hesabixAPI/adapters/api/v1/report_templates.py @@ -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_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=["قالب‌های گزارش", "گزارش‌ها"]) @@ -599,6 +604,46 @@ async def preview_report_template( 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( "/business/{business_id}/preview-pdf", summary="پیش‌نمایش PDF قالب (فقط سازندگان)", @@ -715,6 +760,13 @@ async def report_template_schema( {"name": "business_logo_data_uri", "desc": "لوگوی کسب‌وکار"}, {"name": "invoice_footer_note", "desc": "یادداشت پاورقی"}, {"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( { @@ -727,6 +779,8 @@ async def report_template_schema( "issue_date": "1403/10/01", "subtotal": 1000000, "discount_total": 50000, + "discount_summary_display": "۵٪ (50,000)", + "amount_without_tax": 950000, "tax_total": 85500, "payable_total": 1035500, }, @@ -738,7 +792,12 @@ async def report_template_schema( "quantity_display": "2", "unit_display": "عدد", "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": "کالای نمونه ۲", @@ -747,7 +806,12 @@ async def report_template_schema( "quantity_display": "1", "unit_display": "عدد", "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": "مشتری نمونه"}, @@ -755,6 +819,15 @@ async def report_template_schema( "payments": [{"method_name": "نقد", "amount": 500000}], "invoice_footer_note": "این یک پیش‌نمایش نمونه است.", "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", "issuer_name": "کاربر نمونه", "is_fa": True, @@ -1015,7 +1088,30 @@ async def report_template_gallery( ctx: AuthContext = Depends(get_current_user), 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( @@ -1060,10 +1156,8 @@ async def compile_v2_design_endpoint( design = (body or {}).get("design") or {} if not isinstance(design, dict): 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: - 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: raise ApiError("COMPILE_ERROR", str(ex), http_status=400) 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( "/business/{business_id}/migrate-builder-to-v2", summary="تبدیل طراحی Builder قدیمی به Studio v2", @@ -1101,5 +1271,3 @@ async def migrate_builder_to_v2( raise ApiError("MIGRATION_ERROR", str(ex), http_status=400) validation = ReportTemplateService.validate_template_v2_design_scope(module_key, subtype, design) return {"design": design, **validation} - - diff --git a/hesabixAPI/app/services/report_template_service.py b/hesabixAPI/app/services/report_template_service.py index ab5e0a58..2cec0b33 100755 --- a/hesabixAPI/app/services/report_template_service.py +++ b/hesabixAPI/app/services/report_template_service.py @@ -16,9 +16,10 @@ from adapters.db.models.report_template import ReportTemplate from adapters.db.models.report_template_status_event import ReportTemplateStatusEvent from app.core.responses import ApiError 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_v2_service import validate_v2_design +from app.services.report_template_v3_service import is_v3_design, validate_v3_design logger = logging.getLogger(__name__) @@ -219,6 +220,8 @@ class ReportTemplateService: subtype: Optional[str], design: Dict[str, Any], ) -> 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) @staticmethod @@ -527,7 +530,7 @@ class ReportTemplateService: assets = getattr(template, "assets", None) or {} if engine_name == "template_v2": 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: design = assets.get("builder_design") or assets.get("design") or {} html, css, header_html, footer_html = compile_design_to_jinja_html(design) @@ -893,4 +896,3 @@ class ReportTemplateService: errors.append(f"خطای رندر: {str(e)}") return errors - diff --git a/hesabixAPI/app/services/report_template_v3_service.py b/hesabixAPI/app/services/report_template_v3_service.py new file mode 100644 index 00000000..15135a5f --- /dev/null +++ b/hesabixAPI/app/services/report_template_v3_service.py @@ -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} diff --git a/hesabixAPI/app/services/template_design_v2_compiler.py b/hesabixAPI/app/services/template_design_v2_compiler.py index 4caa9883..5c65d614 100644 --- a/hesabixAPI/app/services/template_design_v2_compiler.py +++ b/hesabixAPI/app/services/template_design_v2_compiler.py @@ -69,7 +69,11 @@ def _total_display_flag(row: Dict[str, Any]) -> str | None: def _wrap_if_flag(flag: str | None, inner: str) -> str: if not flag: 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: @@ -113,6 +117,10 @@ def _total_expr(row: Dict[str, Any]) -> str: def _theme_css(design: Dict[str, Any], family_id: str) -> str: 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") accent = _color(theme.get("accent_color"), "#366092") 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-table: {table_font}px; }} +html, body {{ + direction: {direction}; + text-align: {default_align}; +}} .rt-layout {{ font-size: var(--rt-base); 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": inner = ( "
" - "{% 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('-') }}" "
" - "{% if row.description %}
{{ row.description }}
{% endif %}" + "{% if row.description is defined and row.description %}" + "
{{ row.description }}
{% endif %}" ) if sections.get("show_unit_price", True): inner += ( - "{% if row.unit_price %}
{{ row.unit_price | money }}" - "{% if row.unit_display %} / {{ row.unit_display }}{% endif %}
{% endif %}" + "{% if row.unit_price is defined and row.unit_price %}" + "
{{ row.unit_price | money }}" + "{% if row.unit_display is defined and row.unit_display %}" + " / {{ row.unit_display }}{% endif %}
{% endif %}" ) return inner if key in ("quantity", "quantity_display"): diff --git a/hesabixAPI/app/services/template_design_v3_compiler.py b/hesabixAPI/app/services/template_design_v3_compiler.py new file mode 100644 index 00000000..68cdde84 --- /dev/null +++ b/hesabixAPI/app/services/template_design_v3_compiler.py @@ -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""" +
+ {logo_html} + {f'
{business_name}
' if business_name else ''} +
{{{{ title_text | default('فاکتور') }}}}
+
{{{{ invoice.code | default('-') }}}} — {v2._jinja_first_of("invoice.issue_date", "invoice_date_jalali")}
+
+
+""".strip() + if family_id == "invoice_modern": + return f""" +
+
+
+

{{{{ title_text | default('فاکتور') }}}}

+
{{{{ invoice.code | default('-') }}}} — {v2._jinja_first_of("invoice.issue_date", "invoice_date_jalali")}
+
+ {logo_html} +
+
+""".strip() + name_html = f"
{business_name}
" if business_name else "" + return f""" +
+
+

{{{{ title_text | default('فاکتور') }}}}

{name_html}
+ {logo_html} +
+
+
کد: {{{{ invoice.code | default('-') }}}}
+
تاریخ: {v2._jinja_first_of("invoice.issue_date", "invoice_date_jalali")}
+
+
+""".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'
{title}: {expr}
' + return f'

{title}

{expr}
' + + +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"{v2._esc(column.get('title') or column.get('key') or '')}", + ) + for column in columns + ) + cells = "".join( + v2._wrap_if_flag(v2._column_display_flag(column), f"{v2._cell_expr(column)}") + for column in columns + ) + return f""" +
+ + {headers} + {{% for row in {items_var} %}}{cells}{{% endfor %}} +
+
+""".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 = ( + "
" + "{% if row.product_code is defined and row.product_code %}{{ row.product_code }} — {% endif %}" + "{{ row.product_name | default('-') }}
" + "{% if row.description is defined and row.description %}
{{ row.description }}
{% endif %}" + ) + if show_unit_price: + result += ( + "{% if row.unit_price is defined and row.unit_price %}
{{ row.unit_price | money }}" + "{% if row.unit_display is defined and row.unit_display %} / {{ row.unit_display }}{% endif %}
{% 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"{v2._esc(column.get('title') or column.get('key') or '')}", + ) + for column in columns + ) + cells = "".join( + v2._wrap_if_flag( + v2._column_display_flag(column), + f"{_receipt_cell(column, show_unit_price=props.get('show_unit_price', True) is not False)}", + ) + for column in columns + ) + return f""" + + {headers} + {{% for row in {items_var} %}}{cells}{{% endfor %}} +
+""".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"{title}{value}" + rows_html.append(v2._wrap_if_flag(v2._total_display_flag(row), row_html)) + table = f"{''.join(rows_html)}
" + return f"
{table}" if receipt else f"
{table}
" + + +def _payments_block(*, receipt: bool) -> str: + if receipt: + return """ +{% if payments is defined and payments %}
+{% for p in payments %}
{{ p.method_name | default('-') }} — {{ p.amount | money }}
{% endfor %}{% endif %} +""".strip() + return """ +{% if payments is defined and payments %}

پرداخت‌ها

+
    {% for p in payments %}
  • {{ p.method_name | default('-') }} — {{ p.amount | money }}
  • {% endfor %}
{% 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 = '
' if receipt else "" + return f"{{% if invoice_footer_note is defined and invoice_footer_note %}}{prefix}
{{{{ invoice_footer_note }}}}
{{% endif %}}" + if block_type == "signatures": + parts: list[str] = [] + if props.get("show_seller", True): + parts.append('
امضای فروشنده
') + if props.get("show_buyer", True): + parts.append('
امضای خریدار
') + return f'
{"".join(parts)}
' 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 %}} +
QR
{{% 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'' if bits else "" + if block_type == "custom_text": + return f'
{v2._esc(props.get("text") or "")}
' + if block_type == "divider": + style = "dashed" if str(props.get("style") or "") == "dashed" else "solid" + return f'
' + if block_type == "spacer": + try: + height = max(4, min(80, int(props.get("height") or 12))) + except Exception: + height = 12 + return f'
' + 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'
{content}
' + 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'
{body}
' + html_doc = f'{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) diff --git a/hesabixAPI/tests/test_template_design_v2_compiler.py b/hesabixAPI/tests/test_template_design_v2_compiler.py index e63774fc..1c9bcef1 100644 --- a/hesabixAPI/tests/test_template_design_v2_compiler.py +++ b/hesabixAPI/tests/test_template_design_v2_compiler.py @@ -1,12 +1,17 @@ from __future__ import annotations -import pytest - -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 import BaseLoader, StrictUndefined 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: @@ -67,7 +72,7 @@ def test_compile_and_render_invoice_classic(): html, css, header, footer = compile_v2_design_to_jinja_html(design) assert "{css}{header}{html}{footer}" @@ -76,6 +81,30 @@ def test_compile_and_render_invoice_classic(): 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"{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(): design = default_design_for_family("invoice_receipt_simple") 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) assert "rt-receipt-items" 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["date"] = lambda value, *args, **kwargs: str(value if value is not None else "") full = f"{header}{html}{footer}" @@ -131,3 +160,95 @@ def test_compile_postal_label(): html, css, header, footer = compile_v2_design_to_jinja_html(design) assert "sender" 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"{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 '' 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"{header}{html}{footer}").render(**_sample_invoice_context()) + assert "INV-1" in rendered + assert "rt-receipt-items" in rendered diff --git a/hesabixUI/hesabix_ui/lib/pages/business/report_template_html_editor_page.dart b/hesabixUI/hesabix_ui/lib/pages/business/report_template_html_editor_page.dart index a19045e5..caa037e9 100644 --- a/hesabixUI/hesabix_ui/lib/pages/business/report_template_html_editor_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/report_template_html_editor_page.dart @@ -382,17 +382,23 @@ class _ReportTemplateHtmlEditorPageState extends State( context: context, - builder: (ctx) => AlertDialog( - title: Text(t.reportTemplatePreview), - content: SizedBox( - width: 720, - height: 520, - child: ReportTemplateEmbeddedPdf(bytes: Uint8List.fromList(pdfBytes)), - ), - actions: [ - TextButton(onPressed: () => Navigator.pop(ctx), child: Text(t.close)), - ], - ), + builder: (ctx) { + final viewport = MediaQuery.sizeOf(ctx); + final availableWidth = viewport.width > 64 ? viewport.width - 64 : viewport.width; + final availableHeight = viewport.height > 180 ? viewport.height - 180 : viewport.height; + return AlertDialog( + insetPadding: const EdgeInsets.all(16), + title: Text(t.reportTemplatePreview), + content: SizedBox( + 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) { if (mounted) { diff --git a/hesabixUI/hesabix_ui/lib/pages/business/report_template_studio_page.dart b/hesabixUI/hesabix_ui/lib/pages/business/report_template_studio_page.dart index 61872646..1917dd3c 100644 --- a/hesabixUI/hesabix_ui/lib/pages/business/report_template_studio_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/report_template_studio_page.dart @@ -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_gallery.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 'report_template_html_editor_page.dart'; enum _StudioStep { gallery, customize } +enum _StudioToolbarAction { changeTemplate, advancedHtml, pageSettings } + class ReportTemplateStudioPage extends StatefulWidget { final int businessId; final AuthStore authStore; @@ -43,7 +46,8 @@ class ReportTemplateStudioPage extends StatefulWidget { bool get isNew => template == null && templateId == null; @override - State createState() => _ReportTemplateStudioPageState(); + State createState() => + _ReportTemplateStudioPageState(); } class _ReportTemplateStudioPageState extends State { @@ -69,14 +73,18 @@ class _ReportTemplateStudioPageState extends State { List> _galleryItems = const []; List> _scopeCatalog = const []; + List> _blockCatalog = const []; Map? _design; Map _assets = {'images': {}}; Map _sampleContext = const {}; String? _paperSize = 'A4'; String? _orientation = 'portrait'; + String? _previewHtml; Uint8List? _previewPdfBytes; + bool _showPdfPreview = false; int _previewRevision = 0; + int _previewRequestId = 0; List _validationErrors = const []; List _validationWarnings = const []; @@ -109,25 +117,30 @@ class _ReportTemplateStudioPageState extends State { } String _fingerprint() => jsonEncode({ - 'name': _nameCtrl.text.trim(), - 'desc': _descCtrl.text.trim(), - 'module': _moduleKey, - 'subtype': _subtype, - 'design': _design, - 'paperSize': _paperSize, - 'orientation': _orientation, - 'margins': { - 'top': _marginTopCtrl.text.trim(), - 'right': _marginRightCtrl.text.trim(), - 'bottom': _marginBottomCtrl.text.trim(), - 'left': _marginLeftCtrl.text.trim(), - }, - }); + 'name': _nameCtrl.text.trim(), + 'desc': _descCtrl.text.trim(), + 'module': _moduleKey, + 'subtype': _subtype, + 'design': _design, + 'paperSize': _paperSize, + 'orientation': _orientation, + 'margins': { + 'top': _marginTopCtrl.text.trim(), + 'right': _marginRightCtrl.text.trim(), + 'bottom': _marginBottomCtrl.text.trim(), + 'left': _marginLeftCtrl.text.trim(), + }, + }); Future _bootstrap() async { setState(() => _loading = true); try { - await Future.wait([_loadScopeCatalog(), _loadGallery(), _loadSampleContext()]); + await Future.wait([ + _loadScopeCatalog(), + _loadGallery(), + _loadSampleContext(), + _loadBlockCatalog(), + ]); if (widget.template != null) { await _loadExistingTemplate(); } else if (widget.templateId != null) { @@ -137,9 +150,15 @@ class _ReportTemplateStudioPageState extends State { _step = _StudioStep.customize; _schedulePreview(); } + if (_lastSavedFingerprint.isEmpty) { + _lastSavedFingerprint = _fingerprint(); + } } catch (e) { if (mounted) { - SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); + SnackBarHelper.showError( + context, + message: ErrorExtractor.forContext(e, context), + ); } } finally { if (mounted) setState(() => _loading = false); @@ -170,8 +189,20 @@ class _ReportTemplateStudioPageState extends State { if (mounted) setState(() => _sampleContext = sample ?? const {}); } + Future _loadBlockCatalog() async { + final items = await _service.studioBlocks( + businessId: widget.businessId, + moduleKey: _moduleKey ?? 'invoices', + subtype: _subtype, + ); + if (mounted) setState(() => _blockCatalog = items); + } + Future _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; await _applyLoadedTemplate(full); } @@ -179,7 +210,10 @@ class _ReportTemplateStudioPageState extends State { Future _loadExistingTemplate() async { final tid = (widget.template!['id'] as num?)?.toInt(); 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; await _applyLoadedTemplate(full); } @@ -191,10 +225,13 @@ class _ReportTemplateStudioPageState extends State { _descCtrl.text = (full['description'] ?? '').toString(); _paperSize = (full['paper_size'] ?? _paperSize)?.toString(); _orientation = (full['orientation'] ?? _orientation)?.toString(); - final margins = (full['margins'] as Map?)?.cast() ?? const {}; + final margins = + (full['margins'] as Map?)?.cast() ?? const {}; _marginTopCtrl.text = margins['top']?.toString() ?? _marginTopCtrl.text; - _marginRightCtrl.text = margins['right']?.toString() ?? _marginRightCtrl.text; - _marginBottomCtrl.text = margins['bottom']?.toString() ?? _marginBottomCtrl.text; + _marginRightCtrl.text = + margins['right']?.toString() ?? _marginRightCtrl.text; + _marginBottomCtrl.text = + margins['bottom']?.toString() ?? _marginBottomCtrl.text; _marginLeftCtrl.text = margins['left']?.toString() ?? _marginLeftCtrl.text; final engine = (full['engine'] ?? '').toString().toLowerCase(); @@ -204,7 +241,9 @@ class _ReportTemplateStudioPageState extends State { if (engine == 'template_v2') { _design = (assets['template_design'] as Map?)?.cast(); } else if (engine == 'builder') { - final builderDesign = (assets['builder_design'] as Map?)?.cast() ?? const {}; + final builderDesign = + (assets['builder_design'] as Map?)?.cast() ?? + const {}; if (mounted && builderDesign.isNotEmpty) { final migrate = await showDialog( context: context, @@ -215,8 +254,14 @@ class _ReportTemplateStudioPageState extends State { 'برخی جزئیات ممکن است نیاز به بازبینی داشته باشند.', ), actions: [ - TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('انصراف')), - FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('انتقال')), + TextButton( + 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 { } } - await _loadGallery(); + await _upgradeDesignToV3IfSupported(); + + await Future.wait([_loadGallery(), _loadBlockCatalog()]); _lastSavedFingerprint = _fingerprint(); } + Future _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() ?? design; + } + void _onScopeChanged(String? scopeId) { if (scopeId == null) return; final idx = scopeId.indexOf(':'); @@ -247,7 +308,12 @@ class _ReportTemplateStudioPageState extends State { _subtype = scopeId.substring(idx + 1); _step = _StudioStep.gallery; _design = null; + _previewHtml = null; _previewPdfBytes = null; + _showPdfPreview = false; + _previewLoading = false; + _previewRequestId++; + _blockCatalog = const []; if (_moduleKey == 'invoices' && _subtype == 'receipt') { _applyReceiptPageDefaultsIfNeeded(); } else if (kInvoiceReceiptPaperSizeOptions.contains(_paperSize)) { @@ -259,77 +325,99 @@ class _ReportTemplateStudioPageState extends State { _marginLeftCtrl.text = '10'; } }); - Future.wait([_loadGallery(), _loadSampleContext()]); + Future.wait([_loadGallery(), _loadSampleContext(), _loadBlockCatalog()]); } void _selectGalleryItem(Map item) { - final design = (item['default_design'] as Map?)?.cast(); + final design = ((item['studio_design'] ?? item['default_design']) as Map?) + ?.cast(); if (design == null) return; setState(() { _design = Map.from(design); _step = _StudioStep.customize; + _previewHtml = null; + _previewPdfBytes = null; + _showPdfPreview = false; _applyReceiptPageDefaultsIfNeeded(); }); _schedulePreview(); } void _onDesignChanged(Map design) { - setState(() => _design = design); + setState(() { + _design = design; + _previewPdfBytes = null; + _showPdfPreview = false; + }); _schedulePreview(); } void _schedulePreview() { + if (mounted && (_showPdfPreview || _previewPdfBytes != null)) { + setState(() { + _showPdfPreview = false; + _previewPdfBytes = null; + }); + } _previewDebouncer.schedule(_refreshPreview); } Future _refreshPreview() async { - if (_design == null || !mounted) return; + final design = _design; + if (design == null || !mounted) return; + final requestId = ++_previewRequestId; setState(() { _previewLoading = true; _validationErrors = const []; _validationWarnings = const []; }); try { - final validation = await _service.validateV2Design( + final validation = await _service.validateStudioDesign( businessId: widget.businessId, moduleKey: _moduleKey ?? 'invoices', subtype: _subtype, - design: _design!, + design: design, ); - final errors = ((validation['errors'] as List?) ?? const []).map((e) => e.toString()).toList(); - final warnings = ((validation['warnings'] as List?) ?? const []).map((e) => e.toString()).toList(); + final errors = ((validation['errors'] as List?) ?? const []) + .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 (mounted) { setState(() { _validationErrors = errors; _validationWarnings = warnings; _previewLoading = false; + _previewHtml = null; _previewPdfBytes = null; }); } return; } - final pdfBytes = await _service.previewPdf( + final html = await _service.previewHtml( businessId: widget.businessId, engine: 'template_v2', - design: _design, - assets: {'template_design': _design, ..._assets}, + design: design, + assets: {..._assets, 'template_design': design}, context: _sampleContext, paperSize: _effectivePaperSize(), orientation: _orientation, margins: _parseMargins(), ); - if (mounted) { + if (mounted && requestId == _previewRequestId) { setState(() { - _previewPdfBytes = Uint8List.fromList(pdfBytes); + _previewHtml = html; _previewRevision++; _validationWarnings = warnings; _previewLoading = false; }); } } catch (e) { - if (mounted) { + if (mounted && requestId == _previewRequestId) { setState(() { _previewLoading = false; _validationErrors = [ErrorExtractor.forContext(e, context)]; @@ -338,6 +426,37 @@ class _ReportTemplateStudioPageState extends State { } } + Future _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? _parseMargins() { double? parse(String s) { try { @@ -392,13 +511,15 @@ class _ReportTemplateStudioPageState extends State { setState(() => _saving = true); try { - final validation = await _service.validateV2Design( + final validation = await _service.validateStudioDesign( businessId: widget.businessId, moduleKey: _moduleKey ?? 'invoices', subtype: _subtype, 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) { SnackBarHelper.showError(context, message: errors.join(' | ')); return; @@ -416,7 +537,9 @@ class _ReportTemplateStudioPageState extends State { moduleKey: _moduleKey ?? 'invoices', subtype: _subtype, name: name, - description: _descCtrl.text.trim().isEmpty ? null : _descCtrl.text.trim(), + description: _descCtrl.text.trim().isEmpty + ? null + : _descCtrl.text.trim(), contentHtml: '', paperSize: _effectivePaperSize(), orientation: _orientation, @@ -431,7 +554,9 @@ class _ReportTemplateStudioPageState extends State { templateId: _templateId!, changes: { 'name': name, - 'description': _descCtrl.text.trim().isEmpty ? null : _descCtrl.text.trim(), + 'description': _descCtrl.text.trim().isEmpty + ? null + : _descCtrl.text.trim(), 'module_key': _moduleKey, 'subtype': _subtype, 'engine': 'template_v2', @@ -450,7 +575,10 @@ class _ReportTemplateStudioPageState extends State { } } catch (e) { if (mounted) { - SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); + SnackBarHelper.showError( + context, + message: ErrorExtractor.forContext(e, context), + ); } } finally { if (mounted) setState(() => _saving = false); @@ -465,8 +593,14 @@ class _ReportTemplateStudioPageState extends State { title: const Text('خروج بدون ذخیره؟'), content: const Text('تغییرات ذخیره نشده از بین می‌رود.'), actions: [ - TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('ماندن')), - FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('خروج')), + TextButton( + 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 { 'می‌توانید کد را در ادیتور پیشرفته ویرایش کنید.', ), actions: [ - TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('انصراف')), - FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('ادامه')), + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('انصراف'), + ), + FilledButton( + onPressed: () => Navigator.pop(ctx, true), + child: const Text('ادامه'), + ), ], ), ); if (ok != true || !mounted) return; try { - final fragments = await _service.compileV2Design( + final fragments = await _service.compileStudioDesign( businessId: widget.businessId, design: _design!, ); @@ -500,7 +640,9 @@ class _ReportTemplateStudioPageState extends State { final seed = ReportTemplateHtmlEditorSeed( name: _nameCtrl.text.trim(), - description: _descCtrl.text.trim().isEmpty ? null : _descCtrl.text.trim(), + description: _descCtrl.text.trim().isEmpty + ? null + : _descCtrl.text.trim(), moduleKey: _moduleKey, subtype: _subtype, contentHtml: fragments['content_html']?.toString(), @@ -536,7 +678,10 @@ class _ReportTemplateStudioPageState extends State { if (mounted) context.pop(true); } catch (e) { 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 { String _scopeLabel() { 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(); } return _currentScopeId(); @@ -586,14 +732,23 @@ class _ReportTemplateStudioPageState extends State { mainAxisSize: MainAxisSize.min, children: [ DropdownButtonFormField( - value: _paperChoices.contains(_paperSize) ? _paperSize : _paperChoices.first, + value: _paperChoices.contains(_paperSize) + ? _paperSize + : _paperChoices.first, decoration: InputDecoration( labelText: 'سایز کاغذ', border: const OutlineInputBorder(), - helperText: _isReceiptScope ? 'عرض فیش؛ ارتفاع هر صفحه ۲۹۷ میلی‌متر است' : null, + helperText: _isReceiptScope + ? 'عرض فیش؛ ارتفاع هر صفحه ۲۹۷ میلی‌متر است' + : null, ), items: _paperChoices - .map((e) => DropdownMenuItem(value: e, child: Text(reportTemplatePaperSizeLabel(e)))) + .map( + (e) => DropdownMenuItem( + value: e, + child: Text(reportTemplatePaperSizeLabel(e)), + ), + ) .toList(), onChanged: (v) => setState(() { _paperSize = v; @@ -606,13 +761,17 @@ class _ReportTemplateStudioPageState extends State { decoration: InputDecoration( labelText: 'جهت', border: const OutlineInputBorder(), - helperText: _isReceiptScope ? 'فیش پرینتر همیشه عمودی است' : null, + helperText: _isReceiptScope + ? 'فیش پرینتر همیشه عمودی است' + : null, ), items: const [ DropdownMenuItem(value: 'portrait', 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), Row( @@ -634,7 +793,10 @@ class _ReportTemplateStudioPageState extends State { ), ), actions: [ - TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('بستن')), + TextButton( + onPressed: () => Navigator.pop(ctx), + child: const Text('بستن'), + ), FilledButton( onPressed: () { Navigator.pop(ctx); @@ -650,63 +812,153 @@ class _ReportTemplateStudioPageState extends State { Widget _marginField(String label, TextEditingController ctrl) { return TextField( controller: ctrl, - decoration: InputDecoration(labelText: label, border: const OutlineInputBorder(), isDense: true), + decoration: InputDecoration( + labelText: label, + border: const OutlineInputBorder(), + isDense: true, + ), keyboardType: TextInputType.number, inputFormatters: [EnglishDigitsFormatter()], ); } + Future _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 Widget build(BuildContext context) { if (!widget.authStore.hasBusinessPermission('report_templates', 'write')) { - return const AccessDeniedPage(message: 'شما دسترسی لازم برای ویرایش قالب‌ها را ندارید'); + return const AccessDeniedPage( + message: 'شما دسترسی لازم برای ویرایش قالب‌ها را ندارید', + ); } final isNew = widget.isNew; final title = isNew ? 'استودیو قالب — جدید' : 'استودیو قالب — ویرایش'; + final compactToolbar = MediaQuery.sizeOf(context).width < 900; return HesabixBackInterceptor( onWillPop: _confirmDiscard, child: Scaffold( appBar: AppBar( title: Text(title), - leading: hesabixBackAppBarLeading(context, businessId: widget.businessId), + leading: hesabixBackAppBarLeading( + context, + businessId: widget.businessId, + ), actions: [ - if (_step == _StudioStep.customize && isNew) + if (!compactToolbar && _step == _StudioStep.customize && isNew) TextButton.icon( onPressed: () => setState(() => _step = _StudioStep.gallery), icon: const Icon(Icons.grid_view), label: const Text('تغییر قالب'), ), - if (_step == _StudioStep.customize && _design != null) + if (!compactToolbar && + _step == _StudioStep.customize && + _design != null) TextButton.icon( onPressed: _openAdvancedHtml, icon: const Icon(Icons.code), label: const Text('حالت پیشرفته'), ), - IconButton(icon: const Icon(Icons.settings), tooltip: 'تنظیمات صفحه', onPressed: _showPageSettings), - if (_hasUnsavedChanges) + if (!compactToolbar) + 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( padding: EdgeInsets.symmetric(horizontal: 8), - child: Chip(label: Text('ذخیره نشده'), visualDensity: VisualDensity.compact), + child: Chip( + label: Text('ذخیره نشده'), + visualDensity: VisualDensity.compact, + ), ), Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), - child: 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 ? 'در حال ذخیره...' : 'ذخیره'), + padding: EdgeInsets.symmetric( + horizontal: compactToolbar ? 2 : 8, + vertical: 8, ), + 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 ? const Center(child: LoadingIndicator()) : _step == _StudioStep.gallery - ? _buildGalleryStep(context) - : _buildCustomizeStep(context), + ? _buildGalleryStep(context) + : _buildCustomizeStep(context), ), ); } @@ -720,20 +972,30 @@ class _ReportTemplateStudioPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, 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), 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), Row( children: [ Expanded( child: DropdownButtonFormField( - value: _scopeCatalog.any((s) => - '${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}' == - _currentScopeId()) + value: + _scopeCatalog.any( + (s) => + '${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}' == + _currentScopeId(), + ) ? _currentScopeId() : null, decoration: const InputDecoration( @@ -744,7 +1006,8 @@ class _ReportTemplateStudioPageState extends State { items: _scopeCatalog .map( (s) => DropdownMenuItem( - value: '${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}', + value: + '${(s['module_key'] ?? '').toString()}:${(s['subtype'] ?? '').toString()}', child: Text((s['label_fa'] ?? '').toString()), ), ) @@ -777,62 +1040,121 @@ class _ReportTemplateStudioPageState extends State { return const Center(child: Text('قالبی انتخاب نشده است.')); } - return Row( - children: [ - SizedBox( - width: 360, + if ((design['schema_version'] as num?)?.toInt() == 3) { + return ReportTemplateStudioV3Builder( + design: design, + 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( children: [ - 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, + const Material( + child: TabBar( + tabs: [ + Tab(icon: Icon(Icons.tune), text: 'تنظیمات'), + Tab( + icon: Icon(Icons.picture_as_pdf_outlined), + text: 'پیش‌نمایش', ), ], ), ), - const Divider(height: 16), Expanded( - child: ReportTemplateStudioCustomizePanel( - design: design, - moduleKey: _moduleKey ?? 'invoices', - subtype: _subtype, - onDesignChanged: _onDesignChanged, - ), + child: TabBarView(children: [settingsPane, previewPane]), ), ], ), - ), - VerticalDivider(width: 1, color: Theme.of(context).dividerColor), + ); + }, + ); + } + + Widget _buildCustomizeSettings(Map design) { + return Column( + children: [ + _buildTemplateIdentityFields(), + const Divider(height: 16), Expanded( - flex: 3, - child: ReportTemplateStudioPreviewPanel( - loading: _previewLoading, - pdfBytes: _previewPdfBytes, - previewRevision: _previewRevision, - errors: _validationErrors, - warnings: _validationWarnings, - onRefresh: _refreshPreview, + child: ReportTemplateStudioCustomizePanel( + design: design, + moduleKey: _moduleKey ?? 'invoices', + subtype: _subtype, + blockCatalog: _blockCatalog, + onDesignChanged: _onDesignChanged, ), ), ], ); } + + 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, + ); + } } diff --git a/hesabixUI/hesabix_ui/lib/pages/business/report_templates_page.dart b/hesabixUI/hesabix_ui/lib/pages/business/report_templates_page.dart index c01784f5..4321bd28 100755 --- a/hesabixUI/hesabix_ui/lib/pages/business/report_templates_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/report_templates_page.dart @@ -29,6 +29,7 @@ class ReportTemplatesPage extends StatefulWidget { State createState() => _ReportTemplatesPageState(); } + class _ReportTemplatesPageState extends State { late final ReportTemplateService _service; final _moduleCtrl = TextEditingController(text: 'invoices'); @@ -1260,43 +1261,68 @@ class _ReportTemplatesPageState extends State { await showDialog( context: context, builder: (ctx) { - return DefaultTabController( - length: 2, - child: AlertDialog( - title: Text(t.reportTemplatePreviewTitle), - content: SizedBox( - width: 720, - height: 480, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - TabBar( - tabs: [ - Tab(text: t.reportTemplatePreviewHtmlTab), - Tab(text: t.reportTemplatePreviewPdfTab), - ], - ), - Expanded( - child: TabBarView( - children: [ - SingleChildScrollView( - child: SelectableText(html.isEmpty ? '—' : html), - ), - _listPreviewPdfPane( - t, - pdfBytes, - lenFromPreview, - pdfFetchFailed, - ), + final viewport = MediaQuery.sizeOf(ctx); + final availableWidth = viewport.width > 32 ? viewport.width - 32 : viewport.width; + final availableHeight = viewport.height > 32 ? viewport.height - 32 : viewport.height; + final dialogWidth = availableWidth > 900 ? 900.0 : availableWidth; + final dialogHeight = availableHeight > 720 ? 720.0 : availableHeight; + return SafeArea( + child: Dialog( + insetPadding: const EdgeInsets.all(16), + clipBehavior: Clip.antiAlias, + child: SizedBox( + width: dialogWidth, + height: dialogHeight, + child: DefaultTabController( + length: 2, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(20, 12, 8, 4), + child: Row( + children: [ + Expanded( + child: Text( + t.reportTemplatePreviewTitle, + style: Theme.of(ctx).textTheme.titleLarge, + ), + ), + 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 { } } - diff --git a/hesabixUI/hesabix_ui/lib/services/report_template_service.dart b/hesabixUI/hesabix_ui/lib/services/report_template_service.dart index 875f42e3..50ba92cc 100755 --- a/hesabixUI/hesabix_ui/lib/services/report_template_service.dart +++ b/hesabixUI/hesabix_ui/lib/services/report_template_service.dart @@ -175,6 +175,31 @@ class ReportTemplateService { return res.data ?? const {}; } + Future previewHtml({ + required int businessId, + required String engine, + required Map design, + required Map assets, + required Map context, + String? paperSize, + String? orientation, + Map? margins, + }) async { + final res = await _api.post>( + '/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> schema({ required int businessId, required String moduleKey, @@ -267,6 +292,61 @@ class ReportTemplateService { return items.cast>(); } + Future>> studioBlocks({ + required int businessId, + required String moduleKey, + String? subtype, + }) async { + final res = await _api.get>( + '/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>(); + } + + Future> validateStudioDesign({ + required int businessId, + required String moduleKey, + String? subtype, + required Map design, + }) async { + final res = await _api.post>( + '/report-templates/business/$businessId/validate-studio-design', + data: { + 'module_key': moduleKey, + if (subtype != null) 'subtype': subtype, + 'design': design, + }, + ); + return res.data ?? const {}; + } + + Future> compileStudioDesign({ + required int businessId, + required Map design, + }) async { + final res = await _api.post>( + '/report-templates/business/$businessId/compile-studio-design', + data: {'design': design}, + ); + return res.data ?? const {}; + } + + Future> migrateV2ToV3({ + required int businessId, + required Map design, + }) async { + final res = await _api.post>( + '/report-templates/business/$businessId/migrate-v2-to-v3', + data: {'design': design}, + ); + return res.data ?? const {}; + } + Future> validateV2Design({ required int businessId, required String moduleKey, @@ -339,5 +419,3 @@ class ReportTemplateService { return res.data ?? const {}; } } - - diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_html_iframe.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_html_iframe.dart new file mode 100644 index 00000000..7491c2fc --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_html_iframe.dart @@ -0,0 +1,2 @@ +export 'embedded_html_iframe_stub.dart' + if (dart.library.js_interop) 'embedded_html_iframe_web.dart'; diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_html_iframe_stub.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_html_iframe_stub.dart new file mode 100644 index 00000000..f5e7f05b --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_html_iframe_stub.dart @@ -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 فقط در نسخه وب در دسترس است.'), + ); + } +} diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_html_iframe_web.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_html_iframe_web.dart new file mode 100644 index 00000000..a3cbd6f4 --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_html_iframe_web.dart @@ -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 createState() => + _ReportTemplateEmbeddedHtmlState(); +} + +class _ReportTemplateEmbeddedHtmlState + extends State { + 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)); + } +} diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_pdf_iframe_web.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_pdf_iframe_web.dart index f6f9d04b..bab80951 100755 --- a/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_pdf_iframe_web.dart +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/embedded_pdf_iframe_web.dart @@ -1,4 +1,3 @@ -import 'dart:typed_data'; import 'dart:ui_web' as ui_web; import 'package:flutter/foundation.dart'; @@ -16,20 +15,24 @@ bool _isPdfBytes(Uint8List bytes) { } /// نمایش PDF داخل صفحه (وب) با platform view و blob URL. +/// +/// استفاده از embed به جای iframe مهم است: برخی مرورگرها نمایشگر PDF را برای +/// blob داخل iframe سفید رندر می‌کنند، در حالی که همان URL در تب جدید سالم است. class ReportTemplateEmbeddedPdf extends StatefulWidget { final Uint8List bytes; const ReportTemplateEmbeddedPdf({super.key, required this.bytes}); @override - State createState() => _ReportTemplateEmbeddedPdfState(); + State createState() => + _ReportTemplateEmbeddedPdfState(); } class _ReportTemplateEmbeddedPdfState extends State { static int _factorySeq = 0; late final String _viewType; - web.HTMLIFrameElement? _iframe; + web.HTMLEmbedElement? _embed; String? _objectUrl; String? _error; bool _viewMounted = false; @@ -55,36 +58,25 @@ class _ReportTemplateEmbeddedPdfState extends State { } 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.height = '100%' - ..style.minHeight = '320px' - ..style.position = 'relative' - ..style.overflow = 'hidden' ..style.display = 'block' ..style.backgroundColor = '#ffffff'; - final iframe = web.document.createElement('iframe') as web.HTMLIFrameElement - ..title = 'PDF preview' - ..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; + embed.setAttribute('aria-label', 'PDF preview'); + _embed = embed; _viewMounted = true; WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) _applyBytes(); }); - return root; + return embed; } void _applyBytes() { - if (!_viewMounted || _iframe == null) return; + if (!_viewMounted || _embed == null) return; if (widget.bytes.isEmpty) { setState(() => _error = 'فایل PDF خالی است'); @@ -101,7 +93,7 @@ class _ReportTemplateEmbeddedPdfState extends State { widget.bytes, mimeType: 'application/pdf', ); - _iframe!.src = url; + _embed!.src = url; _objectUrl = url; if (previousUrl != null && previousUrl != url) { _scheduleRevoke(previousUrl); @@ -123,7 +115,8 @@ class _ReportTemplateEmbeddedPdfState extends State { void dispose() { final url = _objectUrl; _objectUrl = null; - _iframe = null; + _embed = null; + _viewMounted = false; super.dispose(); if (url != null) { _scheduleRevoke(url); @@ -140,8 +133,8 @@ class _ReportTemplateEmbeddedPdfState extends State { _error!, textAlign: TextAlign.center, 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 { child: Text( 'فایل PDF خالی است', 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 { var width = constraints.maxWidth; var height = constraints.maxHeight; 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) { - height = MediaQuery.sizeOf(context).height * 0.55; + final screenHeight = MediaQuery.sizeOf(context).height; + height = screenHeight > 520 ? 520 : screenHeight; } return SizedBox( width: width, diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_customize_panel.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_customize_panel.dart index d67aaa7a..0fecd3eb 100644 --- a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_customize_panel.dart +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_customize_panel.dart @@ -3,10 +3,13 @@ import 'dart:convert'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; +import 'report_template_studio_v3_builder.dart'; + class ReportTemplateStudioCustomizePanel extends StatelessWidget { final Map design; final String moduleKey; final String? subtype; + final List> blockCatalog; final ValueChanged> onDesignChanged; const ReportTemplateStudioCustomizePanel({ @@ -14,6 +17,7 @@ class ReportTemplateStudioCustomizePanel extends StatelessWidget { required this.design, required this.moduleKey, required this.subtype, + this.blockCatalog = const [], required this.onDesignChanged, }); @@ -69,6 +73,13 @@ class ReportTemplateStudioCustomizePanel extends StatelessWidget { @override Widget build(BuildContext context) { + if ((design['schema_version'] as num?)?.toInt() == 3) { + return ReportTemplateStudioV3Builder( + design: design, + blockCatalog: blockCatalog, + onDesignChanged: onDesignChanged, + ); + } final theme = _theme(); final sections = _sections(); final branding = _branding(); diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_preview_panel.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_preview_panel.dart index fd351c43..512f17f1 100644 --- a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_preview_panel.dart +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_preview_panel.dart @@ -5,27 +5,95 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import '../../../utils/web/web_utils.dart' as web_utils; +import '../embedded_html_iframe.dart'; import '../embedded_pdf_iframe.dart'; import 'package:hesabix_ui/theme/semantic_color_resolver.dart'; class ReportTemplateStudioPreviewPanel extends StatelessWidget { final bool loading; final Uint8List? pdfBytes; + final String? html; final int previewRevision; + final String? paperSize; + final String? orientation; final List errors; final List warnings; final VoidCallback? onRefresh; + final VoidCallback? onGeneratePdf; + final VoidCallback? onShowHtml; + final bool showPdf; const ReportTemplateStudioPreviewPanel({ super.key, required this.loading, required this.pdfBytes, + this.html, this.previewRevision = 0, + this.paperSize, + this.orientation, this.errors = const [], this.warnings = const [], 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 Widget build(BuildContext context) { return Column( @@ -49,7 +117,21 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget { tooltip: 'بروزرسانی پیش‌نمایش', 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( icon: const Icon(Icons.open_in_new, size: 20), tooltip: 'باز کردن در تب جدید', @@ -82,29 +164,20 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget { child: Stack( fit: StackFit.expand, children: [ - if (pdfBytes != null && pdfBytes!.isNotEmpty) - ColoredBox( - color: Colors.grey.shade200, - child: Padding( - padding: const EdgeInsets.all(12), - child: DecoratedBox( - decoration: BoxDecoration( - color: Colors.white, - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.12), - blurRadius: 12, - offset: const Offset(0, 4), - ), - ], - ), - child: SizedBox.expand( - child: ReportTemplateEmbeddedPdf( - key: ValueKey('preview-$previewRevision'), - bytes: pdfBytes!, - ), - ), - ), + if (showPdf && pdfBytes != null && pdfBytes!.isNotEmpty) + _pagePreview( + context, + ReportTemplateEmbeddedPdf( + key: ValueKey('pdf-preview-$previewRevision'), + bytes: pdfBytes!, + ), + ) + else if (html != null && html!.isNotEmpty) + _pagePreview( + context, + ReportTemplateEmbeddedHtml( + key: ValueKey('html-preview-$previewRevision'), + html: html!, ), ) else if (!loading) diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v3_builder.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v3_builder.dart new file mode 100644 index 00000000..a44b88e1 --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v3_builder.dart @@ -0,0 +1,1191 @@ +import 'dart:convert'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; + +class ReportTemplateStudioV3Builder extends StatefulWidget { + final Map design; + final List> blockCatalog; + final ValueChanged> onDesignChanged; + final Widget? editorHeader; + final Widget? previewPane; + + const ReportTemplateStudioV3Builder({ + super.key, + required this.design, + required this.blockCatalog, + required this.onDesignChanged, + this.editorHeader, + this.previewPane, + }); + + @override + State createState() => + _ReportTemplateStudioV3BuilderState(); +} + +class _BlockDragData { + final String? blockId; + final String? blockType; + + const _BlockDragData.existing(this.blockId) : blockType = null; + const _BlockDragData.palette(this.blockType) : blockId = null; +} + +class _ReportTemplateStudioV3BuilderState + extends State { + final List> _history = []; + int _historyIndex = -1; + int _idSequence = 0; + String? _selectedBlockId; + + @override + void initState() { + super.initState(); + _resetHistory(widget.design); + } + + @override + void didUpdateWidget(covariant ReportTemplateStudioV3Builder oldWidget) { + super.didUpdateWidget(oldWidget); + if (_historyIndex < 0 || + _encoded(_history[_historyIndex]) != _encoded(widget.design)) { + _resetHistory(widget.design); + } + } + + String _encoded(Map value) => jsonEncode(value); + + Map _clone(Map value) { + return (jsonDecode(jsonEncode(value)) as Map).cast(); + } + + void _resetHistory(Map design) { + _history + ..clear() + ..add(_clone(design)); + _historyIndex = 0; + } + + void _commit(Map design) { + final copy = _clone(design); + if (_historyIndex >= 0 && + _encoded(_history[_historyIndex]) == _encoded(copy)) { + return; + } + if (_historyIndex + 1 < _history.length) { + _history.removeRange(_historyIndex + 1, _history.length); + } + _history.add(copy); + if (_history.length > 50) _history.removeAt(0); + _historyIndex = _history.length - 1; + widget.onDesignChanged(copy); + setState(() {}); + } + + void _undo() { + if (_historyIndex <= 0) return; + _historyIndex--; + widget.onDesignChanged(_clone(_history[_historyIndex])); + setState(() {}); + } + + void _redo() { + if (_historyIndex + 1 >= _history.length) return; + _historyIndex++; + widget.onDesignChanged(_clone(_history[_historyIndex])); + setState(() {}); + } + + Map _regions(Map design) { + return (design['regions'] as Map?)?.cast() ?? + {}; + } + + List> _regionBlocks( + Map design, + String region, + ) { + final regions = _regions(design); + return List>.from( + (regions[region] as List?) ?? const [], + ); + } + + Map? _definition(String type) { + for (final definition in widget.blockCatalog) { + if (definition['type']?.toString() == type) return definition; + } + return null; + } + + int _typeCount(String type) { + var count = 0; + for (final region in const ['header', 'body', 'footer']) { + count += _regionBlocks( + widget.design, + region, + ).where((block) => block['type'] == type).length; + } + return count; + } + + bool _canAdd(Map definition) { + final max = (definition['max_instances'] as num?)?.toInt(); + return max == null || _typeCount(definition['type'].toString()) < max; + } + + String _newId(String type) { + _idSequence++; + return '${type}_${DateTime.now().microsecondsSinceEpoch}_$_idSequence'; + } + + void _addBlock(String type, String region, int index) { + final definition = _definition(type); + if (definition == null || !_canAdd(definition)) return; + final allowed = List.from( + (definition['allowed_regions'] as List?) ?? const [], + ); + if (!allowed.contains(region)) { + region = allowed.isEmpty ? 'body' : allowed.first; + } + final design = _clone(widget.design); + final regions = _regions(design); + final blocks = List>.from( + (regions[region] as List?) ?? const [], + ); + final block = { + 'id': _newId(type), + 'type': type, + 'visible': true, + 'props': _cloneMap(definition['default_props']), + 'style': {}, + }; + blocks.insert(index.clamp(0, blocks.length), block); + regions[region] = blocks; + design['regions'] = regions; + _selectedBlockId = block['id'].toString(); + _commit(design); + } + + Map _cloneMap(dynamic value) { + if (value is! Map) return {}; + return (jsonDecode(jsonEncode(value)) as Map).cast(); + } + + ({String region, int index, Map block})? _findBlock( + String id, + ) { + for (final region in const ['header', 'body', 'footer']) { + final blocks = _regionBlocks(widget.design, region); + final index = blocks.indexWhere((block) => block['id']?.toString() == id); + if (index >= 0) { + return (region: region, index: index, block: blocks[index]); + } + } + return null; + } + + void _moveBlock(String id, String targetRegion, int targetIndex) { + final design = _clone(widget.design); + final regions = _regions(design); + Map? moving; + String? sourceRegion; + int sourceIndex = -1; + for (final region in const ['header', 'body', 'footer']) { + final blocks = List>.from( + (regions[region] as List?) ?? const [], + ); + final index = blocks.indexWhere((block) => block['id']?.toString() == id); + if (index >= 0) { + moving = blocks.removeAt(index); + sourceRegion = region; + sourceIndex = index; + regions[region] = blocks; + break; + } + } + if (moving == null) return; + final definition = _definition(moving['type'].toString()); + final allowed = List.from( + (definition?['allowed_regions'] as List?) ?? const [], + ); + if (!allowed.contains(targetRegion)) return; + final target = List>.from( + (regions[targetRegion] as List?) ?? const [], + ); + if (sourceRegion == targetRegion && sourceIndex < targetIndex) { + targetIndex--; + } + target.insert(targetIndex.clamp(0, target.length), moving); + regions[targetRegion] = target; + design['regions'] = regions; + _commit(design); + } + + void _handleDrop(_BlockDragData data, String region, int index) { + if (data.blockType != null) { + _addBlock(data.blockType!, region, index); + } else if (data.blockId != null) { + _moveBlock(data.blockId!, region, index); + } + } + + void _removeBlock(String id) { + final found = _findBlock(id); + if (found == null) return; + final definition = _definition(found.block['type'].toString()); + if (definition?['required'] == true) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('این بخش برای فاکتور الزامی است.')), + ); + return; + } + final design = _clone(widget.design); + final regions = _regions(design); + final blocks = List>.from( + (regions[found.region] as List?) ?? const [], + ); + blocks.removeAt(found.index); + regions[found.region] = blocks; + design['regions'] = regions; + if (_selectedBlockId == id) _selectedBlockId = null; + _commit(design); + } + + void _duplicateBlock(String id) { + final found = _findBlock(id); + if (found == null) return; + final type = found.block['type'].toString(); + final definition = _definition(type); + if (definition == null || !_canAdd(definition)) return; + final design = _clone(widget.design); + final regions = _regions(design); + final blocks = List>.from( + (regions[found.region] as List?) ?? const [], + ); + final copy = _clone(found.block)..['id'] = _newId(type); + blocks.insert(found.index + 1, copy); + regions[found.region] = blocks; + design['regions'] = regions; + _selectedBlockId = copy['id'].toString(); + _commit(design); + } + + void _patchBlock( + String id, + void Function(Map block) mutate, + ) { + final design = _clone(widget.design); + final regions = _regions(design); + for (final region in const ['header', 'body', 'footer']) { + final blocks = List>.from( + (regions[region] as List?) ?? const [], + ); + final index = blocks.indexWhere((block) => block['id']?.toString() == id); + if (index >= 0) { + final block = Map.from(blocks[index]); + mutate(block); + blocks[index] = block; + regions[region] = blocks; + design['regions'] = regions; + _commit(design); + return; + } + } + } + + void _patchRoot(void Function(Map design) mutate) { + final design = _clone(widget.design); + mutate(design); + _commit(design); + } + + String _labelForType(String type) { + return (_definition(type)?['label_fa'] ?? type).toString(); + } + + IconData _iconForType(String type) { + return switch (type) { + 'brand_header' => Icons.branding_watermark_outlined, + 'party_info' => Icons.person_outline, + 'invoice_lines' => Icons.table_chart_outlined, + 'invoice_totals' => Icons.calculate_outlined, + 'payments' => Icons.payments_outlined, + 'note' => Icons.notes, + 'signatures' => Icons.draw_outlined, + 'qr' => Icons.qr_code, + 'footer_meta' => Icons.schedule, + 'custom_text' => Icons.text_fields, + 'divider' => Icons.horizontal_rule, + 'spacer' => Icons.height, + _ => Icons.widgets_outlined, + }; + } + + @override + Widget build(BuildContext context) { + final selected = _selectedBlockId == null + ? null + : _findBlock(_selectedBlockId!); + final designerPane = _designerPane(context); + + if (widget.previewPane == null) { + return _designerPane(context, selected: selected?.block); + } + + return LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth >= 1024) { + final spacious = constraints.maxWidth >= 1400; + return Row( + textDirection: TextDirection.rtl, + children: [ + SizedBox(width: spacious ? 420 : 380, child: designerPane), + VerticalDivider(width: 1, color: Theme.of(context).dividerColor), + Expanded(child: widget.previewPane!), + VerticalDivider(width: 1, color: Theme.of(context).dividerColor), + SizedBox( + width: spacious ? 350 : 320, + child: _inspectorPane(context, selected?.block), + ), + ], + ); + } + + return DefaultTabController( + length: 3, + child: Column( + children: [ + const Material( + child: TabBar( + tabs: [ + Tab(icon: Icon(Icons.dashboard_customize), text: 'طراحی'), + Tab(icon: Icon(Icons.preview_outlined), text: 'پیش‌نمایش'), + Tab(icon: Icon(Icons.tune), text: 'تنظیمات بلوک'), + ], + ), + ), + Expanded( + child: TabBarView( + children: [ + designerPane, + widget.previewPane!, + _inspectorPane(context, selected?.block), + ], + ), + ), + ], + ), + ); + }, + ); + } + + Widget _designerPane(BuildContext context, {Map? selected}) { + return ListView( + padding: const EdgeInsets.all(12), + children: [ + if (widget.editorHeader != null) ...[ + widget.editorHeader!, + const Divider(height: 24), + ], + Row( + children: [ + Text( + 'طراح بلوکی', + style: Theme.of( + context, + ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), + ), + const Spacer(), + IconButton( + onPressed: _historyIndex > 0 ? _undo : null, + icon: const Icon(Icons.undo), + tooltip: 'بازگشت', + ), + IconButton( + onPressed: _historyIndex + 1 < _history.length ? _redo : null, + icon: const Icon(Icons.redo), + tooltip: 'انجام دوباره', + ), + ], + ), + Text( + 'قطعه را بکشید و در محل دلخواه رها کنید؛ برای موبایل می‌توانید روی قطعه بزنید.', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 12), + _buildAppearance(context), + const SizedBox(height: 12), + Text( + 'قطعات', + style: Theme.of( + context, + ).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Wrap( + spacing: 6, + runSpacing: 6, + children: widget.blockCatalog + .map((definition) => _paletteItem(context, definition)) + .toList(), + ), + const SizedBox(height: 16), + _region(context, 'header', 'سربرگ'), + const SizedBox(height: 10), + _region(context, 'body', 'بدنه فاکتور'), + const SizedBox(height: 10), + _region(context, 'footer', 'پاورقی'), + if (selected != null) ...[ + const SizedBox(height: 16), + _inspector(context, selected), + ], + ], + ); + } + + Widget _inspectorPane(BuildContext context, Map? selected) { + return ListView( + padding: const EdgeInsets.all(12), + children: [ + if (selected == null) + Card( + margin: EdgeInsets.zero, + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + children: [ + Icon( + Icons.touch_app_outlined, + size: 40, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + const SizedBox(height: 12), + const Text( + 'یک بلوک را انتخاب کنید تا تنظیمات آن در این ستون نمایش داده شود.', + textAlign: TextAlign.center, + ), + ], + ), + ), + ) + else + _inspector(context, selected), + ], + ); + } + + Widget _buildAppearance(BuildContext context) { + final theme = + (widget.design['theme'] as Map?)?.cast() ?? const {}; + final branding = + (widget.design['branding'] as Map?)?.cast() ?? + const {}; + const colors = [ + '#1e3a5f', + '#2563eb', + '#0f766e', + '#7c3aed', + '#b45309', + '#be123c', + ]; + final logoSource = (branding['logo_source'] ?? 'business').toString(); + final direction = theme['direction'] == 'ltr' ? 'ltr' : 'rtl'; + return ExpansionTile( + tilePadding: EdgeInsets.zero, + title: const Text('ظاهر، برندینگ و جهت نوشتار'), + children: [ + const Align( + alignment: Alignment.centerRight, + child: Text('جهت کلی فاکتور'), + ), + const SizedBox(height: 6), + SegmentedButton( + segments: const [ + ButtonSegment( + value: 'rtl', + icon: Icon(Icons.format_textdirection_r_to_l), + label: Text('راست‌به‌چپ'), + ), + ButtonSegment( + value: 'ltr', + icon: Icon(Icons.format_textdirection_l_to_r), + label: Text('چپ‌به‌راست'), + ), + ], + selected: {direction}, + onSelectionChanged: (values) => _patchRoot((design) { + final next = + (design['theme'] as Map?)?.cast() ?? + {}; + design['theme'] = {...next, 'direction': values.first}; + }), + ), + const SizedBox(height: 16), + Wrap( + spacing: 8, + children: colors.map((hex) { + final color = Color( + int.parse(hex.substring(1), radix: 16) + 0xFF000000, + ); + final selected = + theme['primary_color']?.toString().toLowerCase() == hex; + return InkWell( + onTap: () => _patchRoot((design) { + final next = + (design['theme'] as Map?)?.cast() ?? + {}; + design['theme'] = { + ...next, + 'primary_color': hex, + 'accent_color': hex, + }; + }), + child: Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: selected + ? Theme.of(context).colorScheme.onSurface + : Colors.transparent, + width: 2, + ), + ), + child: selected + ? const Icon(Icons.check, color: Colors.white, size: 18) + : null, + ), + ); + }).toList(), + ), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('نمایش لوگو'), + value: branding['show_logo'] != false, + onChanged: (value) => _patchRoot((design) { + final next = + (design['branding'] as Map?)?.cast() ?? + {}; + design['branding'] = {...next, 'show_logo': value}; + }), + ), + if (branding['show_logo'] != false) ...[ + SegmentedButton( + segments: const [ + ButtonSegment(value: 'business', label: Text('کسب‌وکار')), + ButtonSegment(value: 'custom', label: Text('سفارشی')), + ButtonSegment(value: 'none', label: Text('بدون لوگو')), + ], + selected: {logoSource}, + onSelectionChanged: (values) => _patchRoot((design) { + final next = + (design['branding'] as Map?)?.cast() ?? + {}; + design['branding'] = {...next, 'logo_source': values.first}; + }), + ), + if (logoSource == 'custom') + Align( + alignment: Alignment.centerRight, + child: OutlinedButton.icon( + onPressed: _pickLogo, + icon: const Icon(Icons.upload_file), + label: Text( + (branding['custom_logo_data_uri'] ?? '').toString().isEmpty + ? 'بارگذاری لوگو' + : 'تغییر لوگو', + ), + ), + ), + ], + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('نمایش نام کسب‌وکار'), + value: branding['show_business_name'] != false, + onChanged: (value) => _patchRoot((design) { + final next = + (design['branding'] as Map?)?.cast() ?? + {}; + design['branding'] = {...next, 'show_business_name': value}; + }), + ), + Text( + 'اندازه فونت: ${((theme['font_size_base'] as num?) ?? 11).round()}', + ), + Slider( + min: 8, + max: 16, + divisions: 8, + value: ((theme['font_size_base'] as num?)?.toDouble() ?? 11).clamp( + 8.0, + 16.0, + ), + onChanged: (value) => _patchRoot((design) { + final next = + (design['theme'] as Map?)?.cast() ?? + {}; + design['theme'] = {...next, 'font_size_base': value.round()}; + }), + ), + ], + ); + } + + Future _pickLogo() async { + final result = await FilePicker.platform.pickFiles( + type: FileType.image, + withData: true, + ); + if (result == null || + result.files.isEmpty || + result.files.first.bytes == null) { + return; + } + final file = result.files.first; + final lower = file.name.toLowerCase(); + final mime = lower.endsWith('.jpg') || lower.endsWith('.jpeg') + ? 'image/jpeg' + : lower.endsWith('.webp') + ? 'image/webp' + : lower.endsWith('.gif') + ? 'image/gif' + : 'image/png'; + final dataUri = 'data:$mime;base64,${base64Encode(file.bytes!)}'; + _patchRoot((design) { + final next = + (design['branding'] as Map?)?.cast() ?? + {}; + design['branding'] = { + ...next, + 'show_logo': true, + 'logo_source': 'custom', + 'custom_logo_data_uri': dataUri, + }; + }); + } + + Widget _paletteItem(BuildContext context, Map definition) { + final type = definition['type'].toString(); + final enabled = _canAdd(definition); + final allowed = List.from( + (definition['allowed_regions'] as List?) ?? const ['body'], + ); + final defaultRegion = allowed.contains('body') ? 'body' : allowed.first; + final chip = ActionChip( + avatar: Icon(_iconForType(type), size: 17), + label: Text((definition['label_fa'] ?? type).toString()), + onPressed: enabled + ? () => _addBlock( + type, + defaultRegion, + _regionBlocks(widget.design, defaultRegion).length, + ) + : null, + ); + if (!enabled) return Opacity(opacity: 0.45, child: chip); + return Draggable<_BlockDragData>( + data: _BlockDragData.palette(type), + feedback: Material( + elevation: 6, + borderRadius: BorderRadius.circular(20), + child: chip, + ), + childWhenDragging: Opacity(opacity: 0.35, child: chip), + child: chip, + ); + } + + Widget _region(BuildContext context, String region, String title) { + final blocks = _regionBlocks(widget.design, region); + return Card( + margin: EdgeInsets.zero, + clipBehavior: Clip.antiAlias, + child: Padding( + padding: const EdgeInsets.all(8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + title, + style: Theme.of( + context, + ).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold), + ), + const SizedBox(height: 4), + _dropZone(region, 0, expanded: blocks.isEmpty), + for (var index = 0; index < blocks.length; index++) ...[ + _blockTile(context, region, index, blocks[index]), + _dropZone(region, index + 1), + ], + ], + ), + ), + ); + } + + Widget _dropZone(String region, int index, {bool expanded = false}) { + return DragTarget<_BlockDragData>( + onWillAcceptWithDetails: (details) { + final type = + details.data.blockType ?? + _findBlock(details.data.blockId ?? '')?.block['type']?.toString(); + final allowed = List.from( + (_definition(type ?? '')?['allowed_regions'] as List?) ?? const [], + ); + return allowed.contains(region); + }, + onAcceptWithDetails: (details) => + _handleDrop(details.data, region, index), + builder: (context, candidates, rejected) { + final active = candidates.isNotEmpty; + return AnimatedContainer( + duration: const Duration(milliseconds: 120), + height: expanded ? 48 : (active ? 28 : 12), + margin: const EdgeInsets.symmetric(vertical: 2), + decoration: BoxDecoration( + color: active + ? Theme.of(context).colorScheme.primaryContainer + : Colors.transparent, + borderRadius: BorderRadius.circular(6), + border: expanded || active + ? Border.all( + color: Theme.of(context).colorScheme.primary.withValues( + alpha: active ? 0.8 : 0.25, + ), + ) + : null, + ), + alignment: Alignment.center, + child: expanded + ? Text(active ? 'اینجا رها کنید' : 'قطعه‌ای به این بخش بکشید') + : null, + ); + }, + ); + } + + Widget _blockTile( + BuildContext context, + String region, + int index, + Map block, + ) { + final id = block['id'].toString(); + final type = block['type'].toString(); + final selected = id == _selectedBlockId; + return Card( + color: selected ? Theme.of(context).colorScheme.secondaryContainer : null, + margin: const EdgeInsets.symmetric(vertical: 2), + child: ListTile( + dense: true, + onTap: () => setState(() => _selectedBlockId = id), + leading: Draggable<_BlockDragData>( + data: _BlockDragData.existing(id), + feedback: Material( + elevation: 6, + child: Padding( + padding: const EdgeInsets.all(10), + child: Text(_labelForType(type)), + ), + ), + child: const MouseRegion( + cursor: SystemMouseCursors.grab, + child: Icon(Icons.drag_handle), + ), + ), + title: Text(_labelForType(type)), + subtitle: type == 'party_info' + ? Text(((block['props'] as Map?)?['title'] ?? '').toString()) + : null, + trailing: Wrap( + spacing: 0, + children: [ + IconButton( + visualDensity: VisualDensity.compact, + tooltip: 'بالا', + onPressed: index > 0 + ? () => _moveBlock(id, region, index - 1) + : null, + icon: const Icon(Icons.keyboard_arrow_up, size: 19), + ), + IconButton( + visualDensity: VisualDensity.compact, + tooltip: 'پایین', + onPressed: index + 1 < _regionBlocks(widget.design, region).length + ? () => _moveBlock(id, region, index + 2) + : null, + icon: const Icon(Icons.keyboard_arrow_down, size: 19), + ), + IconButton( + visualDensity: VisualDensity.compact, + tooltip: 'کپی', + onPressed: _canAdd(_definition(type) ?? const {}) + ? () => _duplicateBlock(id) + : null, + icon: const Icon(Icons.copy_outlined, size: 18), + ), + IconButton( + visualDensity: VisualDensity.compact, + tooltip: 'حذف', + onPressed: () => _removeBlock(id), + icon: const Icon(Icons.delete_outline, size: 19), + ), + ], + ), + ), + ); + } + + Widget _inspector(BuildContext context, Map block) { + final id = block['id'].toString(); + final type = block['type'].toString(); + final props = (block['props'] as Map?)?.cast() ?? const {}; + final style = (block['style'] as Map?)?.cast() ?? const {}; + final theme = + (widget.design['theme'] as Map?)?.cast() ?? const {}; + final defaultAlignment = theme['direction'] == 'ltr' ? 'left' : 'right'; + final textAlignment = + (style['text_align'] ?? + (type == 'custom_text' ? props['align'] : null) ?? + defaultAlignment) + .toString(); + const alignableTypes = { + 'brand_header', + 'party_info', + 'invoice_lines', + 'invoice_totals', + 'payments', + 'note', + 'signatures', + 'footer_meta', + 'custom_text', + }; + return Card( + margin: EdgeInsets.zero, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + 'تنظیمات ${_labelForType(type)}', + style: Theme.of( + context, + ).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold), + ), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('نمایش این بخش'), + value: block['visible'] != false, + onChanged: (value) => + _patchBlock(id, (next) => next['visible'] = value), + ), + if (alignableTypes.contains(type)) ...[ + const Text('تراز متن این بلوک'), + const SizedBox(height: 6), + SegmentedButton( + segments: const [ + ButtonSegment( + value: 'right', + icon: Icon(Icons.format_align_right), + label: Text('راست'), + ), + ButtonSegment( + value: 'center', + icon: Icon(Icons.format_align_center), + label: Text('وسط'), + ), + ButtonSegment( + value: 'left', + icon: Icon(Icons.format_align_left), + label: Text('چپ'), + ), + ], + selected: { + const {'right', 'center', 'left'}.contains(textAlignment) + ? textAlignment + : defaultAlignment, + }, + onSelectionChanged: (values) => + _patchBlockStyle(id, {'text_align': values.first}), + ), + const SizedBox(height: 12), + ], + if (type == 'custom_text') + TextFormField( + key: ValueKey('$id-custom-text'), + initialValue: (props['text'] ?? '').toString(), + maxLines: 3, + decoration: const InputDecoration( + labelText: 'متن', + border: OutlineInputBorder(), + ), + onChanged: (value) => _patchProps(id, {'text': value}), + ), + if (type == 'party_info') + TextFormField( + key: ValueKey('$id-party-title'), + initialValue: (props['title'] ?? '').toString(), + decoration: const InputDecoration( + labelText: 'عنوان بخش', + border: OutlineInputBorder(), + ), + onChanged: (value) => _patchProps(id, {'title': value}), + ), + if (type == 'signatures') ...[ + _propertySwitch(id, props, 'show_seller', 'امضای فروشنده'), + _propertySwitch(id, props, 'show_buyer', 'امضای خریدار'), + ], + if (type == 'footer_meta') ...[ + _propertySwitch(id, props, 'show_print_time', 'زمان چاپ'), + _propertySwitch(id, props, 'show_preparer', 'نام صادرکننده'), + ], + if (type == 'divider') + DropdownButtonFormField( + initialValue: (props['style'] ?? 'solid').toString(), + decoration: const InputDecoration(labelText: 'نوع خط'), + items: const [ + DropdownMenuItem(value: 'solid', child: Text('پیوسته')), + DropdownMenuItem(value: 'dashed', child: Text('خط‌چین')), + ], + onChanged: (value) => _patchProps(id, {'style': value}), + ), + if (type == 'spacer') + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'ارتفاع فاصله: ${(props['height'] as num?)?.round() ?? 12}px', + ), + Slider( + min: 4, + max: 80, + divisions: 19, + value: ((props['height'] as num?)?.toDouble() ?? 12).clamp( + 4.0, + 80.0, + ), + onChanged: (value) => + _patchProps(id, {'height': value.round()}), + ), + ], + ), + if (type == 'invoice_lines') _columnsEditor(id, props), + if (type == 'invoice_totals') _totalsEditor(id, props), + ], + ), + ), + ); + } + + Widget _propertySwitch( + String id, + Map props, + String key, + String label, + ) { + return SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text(label), + value: props[key] != false, + onChanged: (value) => _patchProps(id, {key: value}), + ); + } + + void _patchProps(String id, Map changes) { + _patchBlock(id, (block) { + final props = + (block['props'] as Map?)?.cast() ?? + {}; + block['props'] = {...props, ...changes}; + }); + } + + void _patchBlockStyle(String id, Map changes) { + _patchBlock(id, (block) { + final style = + (block['style'] as Map?)?.cast() ?? + {}; + block['style'] = {...style, ...changes}; + }); + } + + Widget _columnsEditor(String id, Map props) { + final columns = List>.from( + (props['columns'] as List?) ?? const [], + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Divider(), + const Text('ستون‌های جدول'), + ReorderableListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: columns.length, + onReorder: (oldIndex, newIndex) { + if (newIndex > oldIndex) newIndex--; + final next = List>.from(columns); + final item = next.removeAt(oldIndex); + next.insert(newIndex, item); + _patchProps(id, {'columns': next}); + }, + itemBuilder: (context, index) { + final column = columns[index]; + return Card( + key: ValueKey('$id-column-${column['key']}'), + child: Column( + children: [ + SwitchListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 8), + secondary: const Icon(Icons.drag_handle), + title: Text((column['title'] ?? column['key']).toString()), + subtitle: Text((column['key'] ?? '').toString()), + value: column['visible'] != false, + onChanged: (value) => _updateColumn(id, columns, index, { + ...column, + 'visible': value, + }), + ), + if (column['visible'] != false) + Padding( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 8), + child: Row( + children: [ + Expanded( + child: TextFormField( + key: ValueKey( + '$id-column-title-${column['key']}', + ), + initialValue: (column['title'] ?? '').toString(), + decoration: const InputDecoration( + labelText: 'عنوان', + isDense: true, + ), + onChanged: (value) => _updateColumn( + id, + columns, + index, + {...column, 'title': value}, + ), + ), + ), + const SizedBox(width: 8), + SizedBox( + width: 100, + child: DropdownButtonFormField( + initialValue: + const [ + 'auto', + '8%', + '10%', + '12%', + '16%', + '20%', + '24%', + '30%', + '40%', + '50%', + ].contains(column['width']) + ? column['width'].toString() + : 'auto', + decoration: const InputDecoration( + labelText: 'عرض', + isDense: true, + ), + items: + const [ + 'auto', + '8%', + '10%', + '12%', + '16%', + '20%', + '24%', + '30%', + '40%', + '50%', + ] + .map( + (value) => DropdownMenuItem( + value: value, + child: Text(value), + ), + ) + .toList(), + onChanged: (value) => _updateColumn( + id, + columns, + index, + {...column, 'width': value}, + ), + ), + ), + ], + ), + ), + ], + ), + ); + }, + ), + ], + ); + } + + void _updateColumn( + String id, + List> columns, + int index, + Map column, + ) { + final next = List>.from(columns); + next[index] = column; + _patchProps(id, {'columns': next}); + } + + Widget _totalsEditor(String id, Map props) { + final rows = List>.from( + (props['rows'] as List?) ?? const [], + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Divider(), + const Text('ردیف‌های جمع‌بندی'), + ReorderableListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: rows.length, + onReorder: (oldIndex, newIndex) { + if (newIndex > oldIndex) newIndex--; + final next = List>.from(rows); + final item = next.removeAt(oldIndex); + next.insert(newIndex, item); + _patchProps(id, {'rows': next}); + }, + itemBuilder: (context, index) { + final row = rows[index]; + return SwitchListTile( + key: ValueKey('$id-total-${row['key']}'), + contentPadding: EdgeInsets.zero, + secondary: const Icon(Icons.drag_handle), + title: Text((row['title'] ?? row['key']).toString()), + value: row['visible'] != false, + onChanged: (value) { + final next = List>.from(rows); + next[index] = {...row, 'visible': value}; + _patchProps(id, {'rows': next}); + }, + ); + }, + ), + ], + ); + } +} diff --git a/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v3_builder_test.dart b/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v3_builder_test.dart new file mode 100644 index 00000000..d6ad881d --- /dev/null +++ b/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v3_builder_test.dart @@ -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 = { + 'schema_version': 3, + 'family_id': 'invoice_classic', + 'layout': 'invoice_detail', + 'theme': { + 'primary_color': '#1e3a5f', + 'font_size_base': 11, + }, + 'branding': { + 'show_logo': true, + 'show_business_name': true, + }, + 'regions': { + 'header': >[], + 'body': >[ + { + 'id': 'invoice-lines', + 'type': 'invoice_lines', + 'visible': true, + 'props': { + 'columns': >[ + { + 'key': 'product_name', + 'title': 'شرح', + 'visible': true, + 'width': 'auto', + }, + ], + }, + 'style': {}, + }, + ], + 'footer': >[], + }, + }; + const catalog = >[ + { + 'type': 'invoice_lines', + 'label_fa': 'جدول اقلام', + 'allowed_regions': ['body'], + 'max_instances': 1, + 'required': true, + 'default_props': {}, + }, + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': { + '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>(); + 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>(); + 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 = { + 'schema_version': 3, + 'family_id': 'invoice_classic', + 'layout': 'invoice_detail', + 'theme': {}, + 'branding': {}, + 'regions': { + 'header': >[], + 'body': >[ + { + 'id': 'invoice-lines', + 'type': 'invoice_lines', + 'visible': true, + 'props': {'columns': >[]}, + 'style': {}, + }, + ], + 'footer': >[], + }, + }; + const catalog = >[ + { + 'type': 'invoice_lines', + 'label_fa': 'جدول اقلام', + 'allowed_regions': ['body'], + 'max_instances': 1, + 'required': true, + 'default_props': {}, + }, + ]; + + 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>(); + expect((body.first['style'] as Map)['text_align'], 'center'); + }); +}