feat(report-templates): add interactive multi-size invoice canvas #24

Merged
morrning merged 1 commit from Seyyed/Seyyed_arc:feature/report-template-studio into master 2026-10-20 17:25:38 +03:30
17 changed files with 1924 additions and 199 deletions

View file

@ -40,6 +40,18 @@ def _preview_assets(body: Dict[str, Any], engine: str) -> Optional[Dict[str, Any
return None
def _preview_context(body: Dict[str, Any], *, include_farsi_fonts: bool) -> Dict[str, Any]:
context = dict((body or {}).get("context") or {})
if not include_farsi_fonts or context.get("is_fa", True) is False:
return context
from app.services.pdf.template_renderer import load_farsi_font_data_uris
regular, bold = load_farsi_font_data_uris()
context.setdefault("fa_font_url_regular", regular or "")
context.setdefault("fa_font_url_bold", bold or "")
return context
def _validate_design_for_publish(entity) -> None:
engine = (entity.engine or "").lower()
if engine not in ("builder", "template_v2"):
@ -571,7 +583,7 @@ async def preview_report_template(
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 ""
context = (body or {}).get("context") or {}
context = _preview_context(body or {}, include_farsi_fonts=True)
# محدودیت ساده روی اندازه ورودی‌ها
max_len = 1_000_000 # 1MB
if len(content_html) > max_len or len(content_css) > max_len:
@ -636,7 +648,10 @@ async def preview_report_template_html(
"assets": _preview_assets(body or {}, engine),
})()
try:
rendered = ReportTemplateService.render_with_template(temp, (body or {}).get("context") or {})
rendered = ReportTemplateService.render_with_template(
temp,
_preview_context(body or {}, include_farsi_fonts=False),
)
except ApiError:
raise
except Exception as ex:
@ -665,7 +680,7 @@ async def preview_report_template_pdf(
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 ""
context = (body or {}).get("context") or {}
context = _preview_context(body or {}, include_farsi_fonts=True)
# محدودیت ساده روی اندازه ورودی‌ها
max_len = 1_000_000 # 1MB
if len(content_html) > max_len or len(content_css) > max_len:

View file

@ -5,6 +5,7 @@
"""
from __future__ import annotations
import re
from typing import Any, Dict, Optional
RECEIPT_PAGE_HEIGHT = "297mm"
@ -13,6 +14,7 @@ RECEIPT_SUBTYPE = "receipt"
# توکن UI/API → عرض استاندارد
_RECEIPT_WIDTH_ALIASES: Dict[str, str] = {
"58mm": "58mm",
"60mm": "60mm",
"80mm": "80mm",
"100mm": "100mm",
@ -23,6 +25,8 @@ _RECEIPT_WIDTH_ALIASES: Dict[str, str] = {
RECEIPT_PAPER_SIZES = frozenset(_RECEIPT_WIDTH_ALIASES.keys())
_SINGLE_MM_RE = re.compile(r"^(?P<width>[0-9]+(?:\.[0-9]+)?)mm$", re.IGNORECASE)
RECEIPT_DEFAULT_MARGINS_MM: Dict[str, float] = {
"top": 3,
"right": 2,
@ -36,7 +40,7 @@ def _norm_token(value: Optional[str]) -> str:
def canonical_receipt_width(paper_size: Optional[str]) -> Optional[str]:
"""اگر سایز فیش باشد عرض استاندارد (مثلاً ``80mm``) برمی‌گرداند."""
"""اگر سایز رول باشد عرض آن (مثلاً ``80mm`` یا ``72.5mm``) را برمی‌گرداند."""
ps = (paper_size or "").strip()
if not ps:
return None
@ -51,6 +55,13 @@ def canonical_receipt_width(paper_size: Optional[str]) -> Optional[str]:
rest = compact[len(_norm_token(mapped)) :]
if rest in ("", "297mm", "x297mm"):
return mapped
# یک اندازهٔ mm به‌تنهایی یعنی عرض رول. دو اندازه (مثلاً
# ``105mm 148mm``) همچنان کاغذ سفارشی صفحه‌ای محسوب می‌شود.
match = _SINGLE_MM_RE.fullmatch(compact)
if match:
width = float(match.group("width"))
if 20 <= width <= 500:
return f"{width:g}mm"
return None

View file

@ -801,7 +801,10 @@ class ReportTemplateService:
pass
# درج CSS سفارشی در <style>
css = (template.content_css or "").strip()
css = _render_jinja_fragment(
getattr(template, "content_css", None) or "",
fragment="CSS قالب",
)
if css:
# ساده: تزریق داخل head اگر وجود دارد
if "</head>" in html:
@ -895,4 +898,3 @@ class ReportTemplateService:
except Exception as e:
errors.append(f"خطای رندر: {str(e)}")
return errors

View file

@ -13,6 +13,82 @@ _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_]*$")
def default_media(*, receipt: bool = False) -> dict[str, Any]:
if receipt:
return {
"type": "roll",
"preset": "80mm",
"width_mm": 80,
"height_mode": "auto",
"orientation": "portrait",
"margins_mm": {"top": 3, "right": 2, "bottom": 4, "left": 2},
}
return {
"type": "sheet",
"preset": "A4",
"width_mm": 210,
"height_mm": 297,
"orientation": "portrait",
"margins_mm": {"top": 10, "right": 10, "bottom": 10, "left": 10},
}
def _validate_media(media: Any) -> list[str]:
if media is None:
return []
if not isinstance(media, dict):
return ["media must be an object"]
errors: list[str] = []
media_type = str(media.get("type") or "sheet").strip().lower()
if media_type not in ("sheet", "roll"):
errors.append("Invalid media.type")
return errors
def number(key: str, *, minimum: float, maximum: float, required: bool = True) -> float | None:
raw = media.get(key)
if raw in (None, ""):
if required:
errors.append(f"media.{key} is required")
return None
try:
value = float(raw)
except (TypeError, ValueError):
errors.append(f"media.{key} must be a number")
return None
if value < minimum or value > maximum:
errors.append(f"media.{key} must be between {minimum:g} and {maximum:g} mm")
return value
width = number("width_mm", minimum=20, maximum=500)
height = None
if media_type == "sheet":
height = number("height_mm", minimum=40, maximum=2000)
orientation = str(media.get("orientation") or "portrait").strip().lower()
if orientation not in ("portrait", "landscape"):
errors.append("Invalid media.orientation")
elif str(media.get("height_mode") or "auto").strip().lower() != "auto":
errors.append("Roll media.height_mode must be auto")
margins = media.get("margins_mm") or {}
if not isinstance(margins, dict):
errors.append("media.margins_mm must be an object")
return errors
parsed_margins: dict[str, float] = {}
for side in ("top", "right", "bottom", "left"):
raw = margins.get(side, 0)
try:
value = float(raw)
except (TypeError, ValueError):
errors.append(f"media.margins_mm.{side} must be a number")
continue
if value < 0 or value > 100:
errors.append(f"media.margins_mm.{side} must be between 0 and 100 mm")
parsed_margins[side] = value
if width is not None and parsed_margins.get("left", 0) + parsed_margins.get("right", 0) >= width:
errors.append("Horizontal margins leave no printable width")
if height is not None and parsed_margins.get("top", 0) + parsed_margins.get("bottom", 0) >= height:
errors.append("Vertical margins leave no printable height")
return errors
_BLOCKS: dict[str, dict[str, Any]] = {
"brand_header": {
@ -110,7 +186,7 @@ def _block(block_id: str, block_type: str, props: dict[str, Any] | None = None)
"type": block_type,
"visible": True,
"props": deepcopy(props or {}),
"style": {},
"style": {"width_mode": "full"},
}
@ -178,6 +254,7 @@ def migrate_v2_design_to_v3(design: dict[str, Any]) -> dict[str, Any]:
"theme": theme,
"branding": deepcopy(design.get("branding") or {}),
"custom_css": str(design.get("custom_css") or ""),
"media": deepcopy(design.get("media") or default_media(receipt=family.layout == "invoice_receipt")),
"regions": {"header": header, "body": body, "footer": footer},
}
@ -200,6 +277,7 @@ def validate_v3_design(
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")
errors.extend(_validate_media(design.get("media")))
theme = design.get("theme") or {}
direction = str(theme.get("direction") or "rtl").strip().lower()
@ -251,6 +329,18 @@ def validate_v3_design(
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}'")
width_mode = str(style.get("width_mode") or "full").strip().lower()
if width_mode not in ("full", "percentage", "fixed", "content"):
errors.append(f"Invalid width mode in block '{block_id}'")
if width_mode in ("percentage", "fixed"):
try:
width_value = float(style.get("width_value"))
except (TypeError, ValueError):
errors.append(f"Width value is required in block '{block_id}'")
else:
limit = 100 if width_mode == "percentage" else 500
if width_value < 10 or width_value > limit:
errors.append(f"Invalid width value 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):

View file

@ -121,6 +121,11 @@ def _theme_css(design: Dict[str, Any], family_id: str) -> str:
if direction not in ("rtl", "ltr"):
direction = "rtl"
default_align = "right" if direction == "rtl" else "left"
font_family = (
"'YekanBakhFaNum', 'Vazirmatn', Tahoma, Arial, sans-serif"
if direction == "rtl"
else "Roboto, Arial, sans-serif"
)
primary = _color(theme.get("primary_color"), "#1e3a5f")
accent = _color(theme.get("accent_color"), "#366092")
text = _color(theme.get("text_color"), "#212529")
@ -136,10 +141,24 @@ def _theme_css(design: Dict[str, Any], family_id: str) -> str:
--rt-base: {base_font}px;
--rt-table: {table_font}px;
}}
@font-face {{
font-family: 'YekanBakhFaNum';
src: url("{{{{ fa_font_url_regular | default('') }}}}") format('truetype');
font-weight: 400;
font-style: normal;
}}
@font-face {{
font-family: 'YekanBakhFaNum';
src: url("{{{{ fa_font_url_bold | default('') }}}}") format('truetype');
font-weight: 700;
font-style: normal;
}}
html, body {{
direction: {direction};
text-align: {default_align};
font-family: {font_family};
}}
body * {{ font-family: inherit; }}
.rt-layout {{
font-size: var(--rt-base);
color: var(--rt-text);

View file

@ -253,12 +253,27 @@ def _compile_block(design: dict[str, Any], block: dict[str, Any], *, receipt: bo
if not content:
return ""
style = block.get("style") or {}
classes = ["rt-block"]
align = str(style.get("text_align") or "").strip().lower()
if not align and str(block.get("type") or "") == "custom_text":
align = str((block.get("props") or {}).get("align") or "").strip().lower()
if align in ("right", "center", "left"):
return f'<div class="rt-block rt-block-align-{align}">{content}</div>'
return content
classes.append(f"rt-block-align-{align}")
width_mode = str(style.get("width_mode") or "full").strip().lower()
width_css = "width:100%;"
if width_mode == "percentage":
try:
width_css = f"width:{max(10, min(100, float(style.get('width_value') or 100))):g}%;"
except (TypeError, ValueError):
pass
elif width_mode == "fixed":
try:
width_css = f"width:{max(10, min(500, float(style.get('width_value') or 100))):g}mm;"
except (TypeError, ValueError):
pass
elif width_mode == "content":
width_css = "width:max-content;"
return f'<div class="{" ".join(classes)}" style="{width_css}">{content}</div>'
def compile_v3_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, str, str]:
@ -282,6 +297,11 @@ def compile_v3_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, s
else:
css = v2._theme_css(design, family_id)
css += """
.rt-layout, .rt-layout * { box-sizing: border-box; }
.rt-layout { width: 100%; max-width: 100%; overflow-wrap: anywhere; }
.rt-layout table { width: 100%; table-layout: auto; }
.rt-layout img { max-width: 100%; height: auto; }
.rt-block { max-width: 100%; }
.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; }

View file

@ -35,6 +35,10 @@ def test_build_page_size_css_custom_mm_pair():
assert build_page_size_css("105mm 148mm", "landscape") == "105mm 148mm"
def test_build_page_size_css_custom_roll_width():
assert build_page_size_css("72.5mm", "landscape") == "72.5mm 297mm"
def test_is_receipt_paper():
assert is_receipt_paper("80mm") is True
assert is_receipt_paper("A5") is False

View file

@ -4,6 +4,7 @@ from jinja2 import BaseLoader, StrictUndefined
from jinja2.sandbox import SandboxedEnvironment
from app.services.report_template_gallery import default_design_for_family, list_gallery_items
from app.services.report_template_service import ReportTemplateService
from app.services.report_template_v2_service import migrate_builder_design_to_v2, validate_v2_design
from app.services.report_template_v3_service import (
migrate_v2_design_to_v3,
@ -168,6 +169,8 @@ def test_migrate_invoice_design_to_v3_and_render_strict():
design = migrate_v2_design_to_v3(design_v2)
assert design["schema_version"] == 3
assert design["theme"]["direction"] == "rtl"
assert design["media"]["preset"] == "A4"
assert design["media"]["width_mm"] == 210
assert [block["type"] for block in design["regions"]["body"]][:3] == [
"party_info",
"party_info",
@ -209,12 +212,44 @@ def test_v3_compiler_applies_ltr_direction_and_block_text_alignment():
"style": {"text_align": "center"},
},
)
design["regions"]["body"][0]["style"]["width_mode"] = "percentage"
design["regions"]["body"][0]["style"]["width_value"] = 60
validation = validate_v3_design("invoices", "detail", design)
assert validation["errors"] == []
html, css, _, _ = compile_v3_design_to_jinja_html(design)
assert '<html dir="ltr">' in html
assert "direction: ltr;" in css
assert 'class="rt-block rt-block-align-center"' in html
assert 'style="width:60%;"' in html
def test_v3_render_uses_hesabix_persian_font_in_css():
design_v2 = default_design_for_family("invoice_classic")
assert design_v2 is not None
design = migrate_v2_design_to_v3(design_v2)
template = type(
"Template",
(),
{
"engine": "template_v2",
"assets": {"template_design": design},
"content_html": "",
"content_css": "",
"header_html": "",
"footer_html": "",
"paper_size": "A4",
"orientation": "portrait",
"margins": None,
},
)()
context = _sample_invoice_context()
context["fa_font_url_regular"] = "data:font/ttf;base64,UkVHVUxBUg=="
context["fa_font_url_bold"] = "data:font/ttf;base64,Qk9MRA=="
rendered = ReportTemplateService.render_with_template(template, context)
assert "font-family: 'YekanBakhFaNum'" in rendered
assert "data:font/ttf;base64,UkVHVUxBUg==" in rendered
assert "data:font/ttf;base64,Qk9MRA==" in rendered
assert "{{ fa_font_url" not in rendered
def test_v3_validation_rejects_invalid_direction_and_alignment():
@ -228,6 +263,27 @@ def test_v3_validation_rejects_invalid_direction_and_alignment():
assert any("Invalid text alignment" in error for error in validation["errors"])
def test_v3_validation_accepts_custom_roll_and_rejects_impossible_margins():
design_v2 = default_design_for_family("invoice_receipt_simple")
assert design_v2 is not None
design = migrate_v2_design_to_v3(design_v2)
assert design["media"]["type"] == "roll"
design["media"] = {
"type": "roll",
"preset": "custom",
"width_mm": 72.5,
"height_mode": "auto",
"orientation": "portrait",
"margins_mm": {"top": 3, "right": 2, "bottom": 4, "left": 2},
}
assert validate_v3_design("invoices", "receipt", design)["errors"] == []
design["media"]["margins_mm"]["right"] = 40
design["media"]["margins_mm"]["left"] = 40
assert "Horizontal margins leave no printable width" in validate_v3_design(
"invoices", "receipt", design
)["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)

View file

@ -7,11 +7,13 @@ const List<String> kReportTemplatePaperSizeOptions = [
'Letter',
'A3',
'A5',
'A6',
'Legal',
];
/// سایزهای فیش پرینتر برای قالب فاکتور (عرض ثابت، ارتفاع تکه‌تکه).
const List<String> kInvoiceReceiptPaperSizeOptions = [
'58mm',
'60mm',
'80mm',
'100mm',
@ -19,6 +21,8 @@ const List<String> kInvoiceReceiptPaperSizeOptions = [
String reportTemplatePaperSizeLabel(String value) {
switch (value) {
case '58mm':
return '۵۸ میلی‌متر (فیش)';
case '60mm':
return '۶ سانتی‌متر (فیش)';
case '80mm':

View file

@ -1,5 +1,3 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
@ -81,7 +79,9 @@ class _ReportTemplateHtmlEditorPageState extends State<ReportTemplateHtmlEditorP
final _htmlCtrl = TextEditingController(
text: '<html><head></head><body><h3>{{ title_text }}</h3></body></html>',
);
final _cssCtrl = TextEditingController(text: 'body { font-family: Tahoma, Arial; }');
final _cssCtrl = TextEditingController(
text: "body { font-family: 'YekanBakhFaNum', 'Vazirmatn', Tahoma, Arial, sans-serif; }",
);
final _headerCtrl = TextEditingController();
final _footerCtrl = TextEditingController();
final _marginTopCtrl = TextEditingController(text: '10');

View file

@ -10,12 +10,12 @@ import '../../core/auth_store.dart';
import '../../core/business_named_route_locations.dart';
import '../../services/report_template_service.dart';
import '../../utils/error_extractor.dart';
import '../../utils/number_normalizer.dart';
import '../../utils/snackbar_helper.dart';
import '../../widgets/loading_indicator.dart';
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_media_settings.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';
@ -279,7 +279,15 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
}
}
final hadStoredMedia = _design?['media'] is Map;
await _upgradeDesignToV3IfSupported();
if (hadStoredMedia) {
_applyMediaToLegacyFields(
normalizedReportTemplateMedia(_design!, preferRoll: _isReceiptScope),
);
} else {
_syncDesignMediaFromLegacy();
}
await Future.wait([_loadGallery(), _loadBlockCatalog()]);
_lastSavedFingerprint = _fingerprint();
@ -332,8 +340,16 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
final design = ((item['studio_design'] ?? item['default_design']) as Map?)
?.cast<String, dynamic>();
if (design == null) return;
final nextDesign = Map<String, dynamic>.from(design);
nextDesign['media'] = normalizedReportTemplateMedia(
nextDesign,
preferRoll: _isReceiptScope,
);
_applyMediaToLegacyFields(
(nextDesign['media'] as Map).cast<String, dynamic>(),
);
setState(() {
_design = Map<String, dynamic>.from(design);
_design = nextDesign;
_step = _StudioStep.customize;
_previewHtml = null;
_previewPdfBytes = null;
@ -344,6 +360,12 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
}
void _onDesignChanged(Map<String, dynamic> design) {
final media = normalizedReportTemplateMedia(
design,
preferRoll: _isReceiptScope,
);
design['media'] = media;
_applyMediaToLegacyFields(media);
setState(() {
_design = design;
_previewPdfBytes = null;
@ -458,6 +480,15 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
}
Map<String, dynamic>? _parseMargins() {
final design = _design;
if (design != null && design['media'] is Map) {
final media = normalizedReportTemplateMedia(
design,
preferRoll: _isReceiptScope,
);
final margins = (media['margins_mm'] as Map?)?.cast<String, dynamic>();
if (margins != null) return Map<String, dynamic>.from(margins);
}
double? parse(String s) {
try {
if (s.trim().isEmpty) return null;
@ -481,6 +512,12 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
}
String _effectivePaperSize() {
final design = _design;
if (design != null && design['media'] is Map) {
return reportTemplatePaperSizeFromMedia(
normalizedReportTemplateMedia(design, preferRoll: _isReceiptScope),
);
}
final c = _paperCustomCtrl.text.trim();
if (c.isEmpty) return _paperSize ?? 'A4';
return c.length > kReportTemplatePaperSizeMaxLength
@ -488,6 +525,59 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
: c;
}
void _syncDesignMediaFromLegacy() {
final design = _design;
if (design == null) return;
final media = reportTemplateMediaFromLegacy(
paperSize: _paperSize,
orientation: _orientation,
margins: _parseLegacyMargins(),
preferRoll: _isReceiptScope,
);
_design = Map<String, dynamic>.from(design)..['media'] = media;
_applyMediaToLegacyFields(media);
}
Map<String, dynamic>? _parseLegacyMargins() {
double? parse(String value) => double.tryParse(value.trim());
final values = <String, dynamic>{
if (parse(_marginTopCtrl.text) != null) 'top': parse(_marginTopCtrl.text),
if (parse(_marginRightCtrl.text) != null)
'right': parse(_marginRightCtrl.text),
if (parse(_marginBottomCtrl.text) != null)
'bottom': parse(_marginBottomCtrl.text),
if (parse(_marginLeftCtrl.text) != null)
'left': parse(_marginLeftCtrl.text),
};
return values.isEmpty ? null : values;
}
void _applyMediaToLegacyFields(Map<String, dynamic> media) {
_paperSize = reportTemplatePaperSizeFromMedia(media);
_paperCustomCtrl.clear();
_orientation = media['type'] == 'roll'
? 'portrait'
: (media['orientation'] == 'landscape' ? 'landscape' : 'portrait');
final margins =
(media['margins_mm'] as Map?)?.cast<String, dynamic>() ?? const {};
String textFor(String side, String fallback) {
final value = margins[side];
if (value == null) return fallback;
final number = value is num
? value.toDouble()
: double.tryParse('$value');
if (number == null) return fallback;
return number == number.roundToDouble()
? number.toInt().toString()
: number.toString();
}
_marginTopCtrl.text = textFor('top', _marginTopCtrl.text);
_marginRightCtrl.text = textFor('right', _marginRightCtrl.text);
_marginBottomCtrl.text = textFor('bottom', _marginBottomCtrl.text);
_marginLeftCtrl.text = textFor('left', _marginLeftCtrl.text);
}
void _navigateBackAfterSave() {
if (!mounted) return;
if (context.canPop()) {
@ -722,106 +812,56 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
}
Future<void> _showPageSettings() async {
final design = _design;
var media = design == null
? reportTemplateMediaFromLegacy(
paperSize: _paperSize,
orientation: _orientation,
margins: _parseLegacyMargins(),
preferRoll: _isReceiptScope,
)
: normalizedReportTemplateMedia(design, preferRoll: _isReceiptScope);
await showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('تنظیمات صفحه'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
DropdownButtonFormField<String>(
value: _paperChoices.contains(_paperSize)
? _paperSize
: _paperChoices.first,
decoration: InputDecoration(
labelText: 'سایز کاغذ',
border: const OutlineInputBorder(),
helperText: _isReceiptScope
? 'عرض فیش؛ ارتفاع هر صفحه ۲۹۷ میلی‌متر است'
: null,
),
items: _paperChoices
.map(
(e) => DropdownMenuItem(
value: e,
child: Text(reportTemplatePaperSizeLabel(e)),
),
)
.toList(),
onChanged: (v) => setState(() {
_paperSize = v;
if (_isReceiptScope) _orientation = 'portrait';
}),
builder: (ctx) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog(
title: const Text('صفحه و چاپ'),
content: SizedBox(
width: 520,
child: SingleChildScrollView(
child: ReportTemplateMediaSettings(
media: media,
onChanged: (next) => setDialogState(() => media = next),
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
value: _orientation,
decoration: InputDecoration(
labelText: 'جهت',
border: const OutlineInputBorder(),
helperText: _isReceiptScope
? 'فیش پرینتر همیشه عمودی است'
: null,
),
items: const [
DropdownMenuItem(value: 'portrait', child: Text('عمودی')),
DropdownMenuItem(value: 'landscape', child: Text('افقی')),
],
onChanged: _isReceiptScope
? null
: (v) => setState(() => _orientation = v),
),
const SizedBox(height: 12),
Row(
children: [
Expanded(child: _marginField('بالا', _marginTopCtrl)),
const SizedBox(width: 8),
Expanded(child: _marginField('راست', _marginRightCtrl)),
],
),
const SizedBox(height: 8),
Row(
children: [
Expanded(child: _marginField('پایین', _marginBottomCtrl)),
const SizedBox(width: 8),
Expanded(child: _marginField('چپ', _marginLeftCtrl)),
],
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('انصراف'),
),
FilledButton(
onPressed: () {
FocusScope.of(context).unfocus();
Navigator.pop(ctx);
if (design != null) {
_onDesignChanged(
Map<String, dynamic>.from(design)..['media'] = media,
);
} else {
_applyMediaToLegacyFields(media);
setState(() {});
_schedulePreview();
}
},
child: const Text('اعمال'),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('بستن'),
),
FilledButton(
onPressed: () {
Navigator.pop(ctx);
_schedulePreview();
},
child: const Text('اعمال'),
),
],
),
);
}
Widget _marginField(String label, TextEditingController ctrl) {
return TextField(
controller: ctrl,
decoration: InputDecoration(
labelText: label,
border: const OutlineInputBorder(),
isDense: true,
),
keyboardType: TextInputType.number,
inputFormatters: [EnglishDigitsFormatter()],
);
}
Future<void> _handleToolbarAction(_StudioToolbarAction action) async {
switch (action) {
case _StudioToolbarAction.changeTemplate:
@ -1143,6 +1183,12 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
previewRevision: _previewRevision,
paperSize: _effectivePaperSize(),
orientation: _orientation,
media: _design == null
? null
: normalizedReportTemplateMedia(
_design!,
preferRoll: _isReceiptScope,
),
errors: _validationErrors,
warnings: _validationWarnings,
onRefresh: _refreshPreview,

View file

@ -2,8 +2,13 @@ import 'package:flutter/material.dart';
class ReportTemplateEmbeddedHtml extends StatelessWidget {
final String html;
final Map<String, dynamic>? previewMarginsMm;
const ReportTemplateEmbeddedHtml({super.key, required this.html});
const ReportTemplateEmbeddedHtml({
super.key,
required this.html,
this.previewMarginsMm,
});
@override
Widget build(BuildContext context) {

View file

@ -1,13 +1,20 @@
import 'dart:js_interop';
import 'dart:convert';
import 'dart:ui_web' as ui_web;
import 'package:flutter/material.dart';
import 'package:web/web.dart' as web;
import '../../utils/web/web_utils.dart' as web_utils;
class ReportTemplateEmbeddedHtml extends StatefulWidget {
final String html;
final Map<String, dynamic>? previewMarginsMm;
const ReportTemplateEmbeddedHtml({super.key, required this.html});
const ReportTemplateEmbeddedHtml({
super.key,
required this.html,
this.previewMarginsMm,
});
@override
State<ReportTemplateEmbeddedHtml> createState() =>
@ -20,6 +27,7 @@ class _ReportTemplateEmbeddedHtmlState
late final String _viewType;
web.HTMLIFrameElement? _iframe;
String? _objectUrl;
@override
void initState() {
@ -31,7 +39,12 @@ class _ReportTemplateEmbeddedHtmlState
@override
void didUpdateWidget(covariant ReportTemplateEmbeddedHtml oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.html != widget.html) _applyHtml();
if (oldWidget.html != widget.html ||
oldWidget.previewMarginsMm != widget.previewMarginsMm) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _applyHtml();
});
}
}
web.Element _createView(int viewId) {
@ -44,20 +57,97 @@ class _ReportTemplateEmbeddedHtmlState
..style.backgroundColor = '#ffffff';
iframe.setAttribute('sandbox', 'allow-same-origin');
_iframe = iframe;
_applyHtml();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _applyHtml();
});
return iframe;
}
void _applyHtml() {
final iframe = _iframe;
if (iframe == null) return;
iframe.srcdoc = widget.html.toJS;
final previousUrl = _objectUrl;
final url = web_utils.createObjectUrlFromBytes(
utf8.encode(_htmlWithWebFonts(widget.html)),
mimeType: 'text/html;charset=utf-8',
);
iframe.removeAttribute('srcdoc');
iframe.src = url;
_objectUrl = url;
if (previousUrl != null && previousUrl != url) {
_scheduleRevoke(previousUrl);
}
}
String _htmlWithWebFonts(String source) {
final baseUri = Uri.parse(web.document.baseURI);
String fontUrl(String name) => baseUri.resolve('fonts/$name').toString();
String margin(String side) {
final value = widget.previewMarginsMm?[side];
final number = value is num
? value.toDouble()
: double.tryParse((value ?? '').toString());
return '${number ?? 0}mm';
}
final head =
'''
<base href="${baseUri.toString()}">
<style id="hesabix-preview-fonts">
@font-face {
font-family: 'YekanBakhFaNum';
src: url('${fontUrl('YekanBakhFaNum-Regular.woff2')}') format('woff2');
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'YekanBakhFaNum';
src: url('${fontUrl('YekanBakhFaNum-SemiBold.woff2')}') format('woff2');
font-weight: 600;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'YekanBakhFaNum';
src: url('${fontUrl('YekanBakhFaNum-Bold.woff2')}') format('woff2');
font-weight: 700;
font-style: normal;
font-display: swap;
}
html[dir='rtl'] body, html[dir='rtl'] body * {
font-family: 'YekanBakhFaNum', 'Vazirmatn', Tahoma, Arial, sans-serif !important;
}
html, body {
box-sizing: border-box;
margin: 0;
min-height: 100%;
}
body {
padding: ${margin('top')} ${margin('right')} ${margin('bottom')} ${margin('left')};
overflow-wrap: anywhere;
}
</style>
''';
if (source.contains('<head>')) {
return source.replaceFirst('<head>', '<head>$head');
}
return '<!doctype html><html dir="rtl"><head>$head</head><body>$source</body></html>';
}
void _scheduleRevoke(String url) {
Future<void>.delayed(const Duration(seconds: 30), () {
web_utils.revokeBlobUrl(url);
});
}
@override
void dispose() {
final url = _objectUrl;
_objectUrl = null;
_iframe = null;
super.dispose();
if (url != null) _scheduleRevoke(url);
}
@override

View file

@ -0,0 +1,418 @@
import 'package:flutter/material.dart';
import '../../../utils/number_normalizer.dart';
const Map<String, Size> reportTemplateSheetPresetsMm = {
'A3': Size(297, 420),
'A4': Size(210, 297),
'A5': Size(148, 210),
'A6': Size(105, 148),
'Letter': Size(215.9, 279.4),
'Legal': Size(215.9, 355.6),
};
Map<String, dynamic> defaultReportTemplateMedia({bool roll = false}) {
if (roll) {
return <String, dynamic>{
'type': 'roll',
'preset': '80mm',
'width_mm': 80,
'height_mode': 'auto',
'orientation': 'portrait',
'margins_mm': <String, dynamic>{
'top': 3,
'right': 2,
'bottom': 4,
'left': 2,
},
};
}
return <String, dynamic>{
'type': 'sheet',
'preset': 'A4',
'width_mm': 210,
'height_mm': 297,
'orientation': 'portrait',
'margins_mm': <String, dynamic>{
'top': 10,
'right': 10,
'bottom': 10,
'left': 10,
},
};
}
double? _number(dynamic value) {
if (value is num) return value.toDouble();
return double.tryParse((value ?? '').toString().trim());
}
String _compactNumber(double value) {
return value == value.roundToDouble()
? value.toInt().toString()
: value.toStringAsFixed(1).replaceFirst(RegExp(r'\.0$'), '');
}
Map<String, dynamic> reportTemplateMediaFromLegacy({
String? paperSize,
String? orientation,
Map<String, dynamic>? margins,
bool preferRoll = false,
}) {
final token = (paperSize ?? '').trim();
MapEntry<String, Size>? preset;
for (final entry in reportTemplateSheetPresetsMm.entries) {
if (entry.key.toLowerCase() == token.toLowerCase()) {
preset = entry;
break;
}
}
Map<String, dynamic> media;
if (preset != null) {
media = defaultReportTemplateMedia()
..['preset'] = preset.key
..['width_mm'] = preset.value.width
..['height_mm'] = preset.value.height;
} else {
final parts = RegExp(
r'([0-9]+(?:\.[0-9]+)?)\s*mm',
caseSensitive: false,
).allMatches(token).toList();
if (parts.length >= 2) {
media = defaultReportTemplateMedia()
..['preset'] = 'custom'
..['width_mm'] = double.parse(parts[0].group(1)!)
..['height_mm'] = double.parse(parts[1].group(1)!);
} else if (parts.length == 1 || preferRoll) {
final width = parts.isEmpty ? 80.0 : double.parse(parts.first.group(1)!);
media = defaultReportTemplateMedia(roll: true)
..['preset'] = '${_compactNumber(width)}mm'
..['width_mm'] = width;
} else {
media = defaultReportTemplateMedia();
}
}
media['orientation'] = orientation == 'landscape' ? 'landscape' : 'portrait';
if (margins != null && margins.isNotEmpty) {
media['margins_mm'] = <String, dynamic>{
for (final side in const ['top', 'right', 'bottom', 'left'])
side:
_number(margins[side]) ??
((media['margins_mm'] as Map)[side] as num).toDouble(),
};
}
return media;
}
Map<String, dynamic> normalizedReportTemplateMedia(
Map<String, dynamic> design, {
bool preferRoll = false,
}) {
final raw = design['media'];
if (raw is! Map) return defaultReportTemplateMedia(roll: preferRoll);
final type = raw['type'] == 'roll' ? 'roll' : 'sheet';
final fallback = defaultReportTemplateMedia(roll: type == 'roll');
final media = <String, dynamic>{...fallback, ...raw.cast<String, dynamic>()};
final fallbackMargins = (fallback['margins_mm'] as Map)
.cast<String, dynamic>();
final rawMargins = raw['margins_mm'];
media['margins_mm'] = <String, dynamic>{
...fallbackMargins,
if (rawMargins is Map) ...rawMargins.cast<String, dynamic>(),
};
return media;
}
String reportTemplatePaperSizeFromMedia(Map<String, dynamic> media) {
if (media['type'] == 'roll') {
return '${_compactNumber(_number(media['width_mm']) ?? 80)}mm';
}
final preset = (media['preset'] ?? '').toString();
if (reportTemplateSheetPresetsMm.containsKey(preset)) return preset;
final width = _number(media['width_mm']) ?? 210;
final height = _number(media['height_mm']) ?? 297;
return '${_compactNumber(width)}mm ${_compactNumber(height)}mm';
}
Size reportTemplateMediaSizeMm(Map<String, dynamic> media) {
var width = _number(media['width_mm']) ?? 210;
var height = media['type'] == 'roll'
? width * 3.4
: (_number(media['height_mm']) ?? 297);
if (media['type'] != 'roll' && media['orientation'] == 'landscape') {
final swap = width;
width = height;
height = swap;
}
return Size(width, height);
}
class ReportTemplateMediaSettings extends StatelessWidget {
final Map<String, dynamic> media;
final ValueChanged<Map<String, dynamic>> onChanged;
final bool compact;
const ReportTemplateMediaSettings({
super.key,
required this.media,
required this.onChanged,
this.compact = false,
});
Map<String, dynamic> _copy() {
final margins = (media['margins_mm'] as Map?)?.cast<String, dynamic>();
return <String, dynamic>{
...media,
'margins_mm': <String, dynamic>{...?margins},
};
}
void _patch(String key, dynamic value) {
onChanged(_copy()..[key] = value);
}
void _setPreset(String preset) {
if (media['type'] == 'roll') {
final width = double.tryParse(preset.replaceAll('mm', ''));
final next = _copy()..['preset'] = preset;
if (width != null) next['width_mm'] = width;
onChanged(next);
return;
}
final size = reportTemplateSheetPresetsMm[preset];
final next = _copy()..['preset'] = preset;
if (size != null) {
next['width_mm'] = size.width;
next['height_mm'] = size.height;
}
onChanged(next);
}
void _setDimension(String key, String raw) {
final value = double.tryParse(raw.trim());
if (value == null || value < 20 || value > 2000) return;
final next = _copy()
..['preset'] = 'custom'
..[key] = value;
onChanged(next);
}
void _setMargin(String side, String raw) {
final value = double.tryParse(raw.trim());
if (value == null || value < 0 || value > 100) return;
final next = _copy();
(next['margins_mm'] as Map<String, dynamic>)[side] = value;
onChanged(next);
}
@override
Widget build(BuildContext context) {
final isRoll = media['type'] == 'roll';
final preset = (media['preset'] ?? (isRoll ? '80mm' : 'A4')).toString();
final sheetItems = <String>[...reportTemplateSheetPresetsMm.keys, 'custom'];
const rollItems = ['58mm', '60mm', '80mm', '100mm', 'custom'];
final items = isRoll ? rollItems : sheetItems;
final selectedPreset = items.contains(preset) ? preset : 'custom';
final margins =
(media['margins_mm'] as Map?)?.cast<String, dynamic>() ?? const {};
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SegmentedButton<String>(
segments: const [
ButtonSegment(
value: 'sheet',
icon: Icon(Icons.description_outlined),
label: Text('کاغذ صفحه‌ای'),
),
ButtonSegment(
value: 'roll',
icon: Icon(Icons.receipt_long_outlined),
label: Text('رول'),
),
],
selected: {isRoll ? 'roll' : 'sheet'},
onSelectionChanged: (selection) => onChanged(
defaultReportTemplateMedia(roll: selection.first == 'roll'),
),
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
key: ValueKey('media-preset-$isRoll-$selectedPreset'),
initialValue: selectedPreset,
decoration: const InputDecoration(
labelText: 'اندازه کاغذ',
border: OutlineInputBorder(),
isDense: true,
),
items: items
.map(
(value) => DropdownMenuItem(
value: value,
child: Text(value == 'custom' ? 'اندازه سفارشی' : value),
),
)
.toList(),
onChanged: (value) {
if (value != null) _setPreset(value);
},
),
if (selectedPreset == 'custom') ...[
const SizedBox(height: 10),
Row(
children: [
Expanded(
child: _numberField(
keyName: 'media-width',
label: 'عرض (mm)',
value: media['width_mm'],
onSubmitted: (value) => _setDimension('width_mm', value),
),
),
if (!isRoll) ...[
const SizedBox(width: 8),
Expanded(
child: _numberField(
keyName: 'media-height',
label: 'ارتفاع (mm)',
value: media['height_mm'],
onSubmitted: (value) => _setDimension('height_mm', value),
),
),
],
],
),
],
if (!isRoll) ...[
const SizedBox(height: 12),
SegmentedButton<String>(
segments: const [
ButtonSegment(value: 'portrait', label: Text('عمودی')),
ButtonSegment(value: 'landscape', label: Text('افقی')),
],
selected: {
media['orientation'] == 'landscape' ? 'landscape' : 'portrait',
},
onSelectionChanged: (selection) =>
_patch('orientation', selection.first),
),
],
const SizedBox(height: 14),
Text(
'حاشیه چاپ (میلی‌متر)',
style: Theme.of(context).textTheme.labelLarge,
),
const SizedBox(height: 8),
Row(
children: [
for (final entry in const [
('top', 'بالا'),
('right', 'راست'),
('bottom', 'پایین'),
('left', 'چپ'),
]) ...[
Expanded(
child: _numberField(
keyName: 'media-margin-${entry.$1}',
label: entry.$2,
value: margins[entry.$1] ?? 0,
onSubmitted: (value) => _setMargin(entry.$1, value),
),
),
if (entry.$1 != 'left') const SizedBox(width: 6),
],
],
),
if (isRoll) ...[
const SizedBox(height: 8),
Text(
'ارتفاع رول با محتوای فاکتور افزایش می‌یابد؛ PDFهای بسیار بلند در چند برش تولید می‌شوند.',
style: Theme.of(context).textTheme.bodySmall,
),
],
],
);
}
Widget _numberField({
required String keyName,
required String label,
required dynamic value,
required ValueChanged<String> onSubmitted,
}) {
return _ReportTemplateNumberField(
key: ValueKey(keyName),
label: label,
value: _compactNumber(_number(value) ?? 0),
onCommitted: onSubmitted,
);
}
}
class _ReportTemplateNumberField extends StatefulWidget {
final String label;
final String value;
final ValueChanged<String> onCommitted;
const _ReportTemplateNumberField({
super.key,
required this.label,
required this.value,
required this.onCommitted,
});
@override
State<_ReportTemplateNumberField> createState() =>
_ReportTemplateNumberFieldState();
}
class _ReportTemplateNumberFieldState
extends State<_ReportTemplateNumberField> {
late final TextEditingController _controller;
late final FocusNode _focusNode;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.value);
_focusNode = FocusNode()..addListener(_handleFocus);
}
@override
void didUpdateWidget(covariant _ReportTemplateNumberField oldWidget) {
super.didUpdateWidget(oldWidget);
if (!_focusNode.hasFocus && widget.value != _controller.text) {
_controller.text = widget.value;
}
}
void _handleFocus() {
if (!_focusNode.hasFocus) widget.onCommitted(_controller.text);
}
@override
void dispose() {
_focusNode
..removeListener(_handleFocus)
..dispose();
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
focusNode: _focusNode,
decoration: InputDecoration(
labelText: widget.label,
border: const OutlineInputBorder(),
isDense: true,
),
keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: const [EnglishDigitsFormatter()],
onSubmitted: widget.onCommitted,
);
}
}

View file

@ -1,5 +1,4 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
@ -8,6 +7,7 @@ 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';
import 'report_template_media_settings.dart';
class ReportTemplateStudioPreviewPanel extends StatelessWidget {
final bool loading;
@ -16,6 +16,7 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget {
final int previewRevision;
final String? paperSize;
final String? orientation;
final Map<String, dynamic>? media;
final List<String> errors;
final List<String> warnings;
final VoidCallback? onRefresh;
@ -31,6 +32,7 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget {
this.previewRevision = 0,
this.paperSize,
this.orientation,
this.media,
this.errors = const [],
this.warnings = const [],
this.onRefresh,
@ -39,33 +41,44 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget {
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;
Map<String, dynamic> get _effectiveMedia {
if (media != null) return Map<String, dynamic>.from(media!);
return reportTemplateMediaFromLegacy(
paperSize: paperSize,
orientation: orientation,
preferRoll: RegExp(
r'^\s*[0-9.]+\s*mm\s*$',
caseSensitive: false,
).hasMatch(paperSize ?? ''),
);
}
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) {
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;
final effectiveMedia = _effectiveMedia;
final isRoll = effectiveMedia['type'] == 'roll';
final mediaSize = reportTemplateMediaSizeMm(effectiveMedia);
var width = isRoll ? maxWidth.clamp(180.0, 430.0).toDouble() : maxWidth;
var height = isRoll
? maxHeight
: width * mediaSize.height / mediaSize.width;
if (!isRoll && height > maxHeight) {
height = maxHeight;
width = height * _viewportAspectRatio;
width = height * mediaSize.width / mediaSize.height;
}
return ColoredBox(
@ -77,6 +90,11 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget {
child: DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
border: isRoll
? Border.symmetric(
vertical: BorderSide(color: Colors.grey.shade400),
)
: null,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.12),
@ -103,68 +121,157 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
border: Border(bottom: BorderSide(color: Theme.of(context).dividerColor)),
border: Border(
bottom: BorderSide(color: Theme.of(context).dividerColor),
),
),
child: Row(
children: [
const Icon(Icons.picture_as_pdf_outlined, size: 20),
const SizedBox(width: 8),
Text('پیش‌نمایش زنده', style: Theme.of(context).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold)),
const Spacer(),
if (onRefresh != null)
IconButton(
icon: const Icon(Icons.refresh, size: 20),
tooltip: 'بروزرسانی پیش‌نمایش',
onPressed: loading ? null : onRefresh,
),
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: 'باز کردن در تب جدید',
onPressed: () {
final url = web_utils.createObjectUrlFromBytes(
pdfBytes!,
mimeType: 'application/pdf',
);
web_utils.openUrlInNewTabWeb(url);
},
),
],
child: LayoutBuilder(
builder: (context, constraints) {
final compact = constraints.maxWidth < 520;
final effectiveMedia = _effectiveMedia;
final paperLabel = effectiveMedia['type'] == 'roll'
? reportTemplatePaperSizeFromMedia(effectiveMedia)
: (effectiveMedia['preset'] ??
reportTemplatePaperSizeFromMedia(effectiveMedia))
.toString();
IconButton button({
required IconData icon,
required String tooltip,
required VoidCallback? onPressed,
Color? color,
}) {
return IconButton(
icon: Icon(icon, size: 20),
tooltip: tooltip,
onPressed: onPressed,
color: color,
visualDensity: compact
? VisualDensity.compact
: VisualDensity.standard,
constraints: compact
? const BoxConstraints.tightFor(width: 34, height: 36)
: null,
padding: compact ? EdgeInsets.zero : null,
);
}
return Row(
children: [
const Icon(Icons.picture_as_pdf_outlined, size: 20),
const SizedBox(width: 8),
Flexible(
child: Text(
compact ? 'پیش‌نمایش · $paperLabel' : 'پیش‌نمایش زنده',
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
if (!compact) ...[
const SizedBox(width: 8),
Flexible(
child: Text(
effectiveMedia['type'] == 'roll'
? '$paperLabel · ارتفاع خودکار'
: '$paperLabel · ${effectiveMedia['orientation'] == 'landscape' ? 'افقی' : 'عمودی'}',
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.labelSmall,
),
),
],
const Spacer(),
if (onRefresh != null)
button(
icon: Icons.refresh,
tooltip: 'بروزرسانی پیش‌نمایش',
onPressed: loading ? null : onRefresh,
),
if (html != null && html!.isNotEmpty)
button(
icon: Icons.code_outlined,
tooltip: 'پیش‌نمایش سریع',
onPressed: onShowHtml,
color: !showPdf
? Theme.of(context).colorScheme.primary
: null,
),
if (onGeneratePdf != null)
button(
icon: Icons.picture_as_pdf,
tooltip: pdfBytes == null
? 'ساخت پیش‌نمایش چاپ'
: 'پیش‌نمایش چاپ',
onPressed: loading ? null : onGeneratePdf,
color: showPdf
? Theme.of(context).colorScheme.primary
: null,
),
if (showPdf &&
kIsWeb &&
pdfBytes != null &&
pdfBytes!.isNotEmpty)
button(
icon: Icons.open_in_new,
tooltip: 'باز کردن در تب جدید',
onPressed: () {
final url = web_utils.createObjectUrlFromBytes(
pdfBytes!,
mimeType: 'application/pdf',
);
web_utils.openUrlInNewTabWeb(url);
},
),
],
);
},
),
),
if (errors.isNotEmpty)
Container(
width: double.infinity,
color: SemanticColorResolver.negative(context).withValues(alpha: 0.12),
color: SemanticColorResolver.negative(
context,
).withValues(alpha: 0.12),
padding: const EdgeInsets.all(8),
child: Text(errors.join('\n'), style: TextStyle(color: SemanticColorResolver.negative(context), fontSize: 12)),
child: Text(
errors.join('\n'),
style: TextStyle(
color: SemanticColorResolver.negative(context),
fontSize: 12,
),
),
),
if (warnings.isNotEmpty)
Container(
width: double.infinity,
color: SemanticColorResolver.warning(context).withValues(alpha: 0.12),
color: SemanticColorResolver.warning(
context,
).withValues(alpha: 0.12),
padding: const EdgeInsets.all(8),
child: Text(warnings.join('\n'), style: TextStyle(color: SemanticColorResolver.warning(context), fontSize: 12)),
child: Text(
warnings.join('\n'),
style: TextStyle(
color: SemanticColorResolver.warning(context),
fontSize: 12,
),
),
),
Expanded(
child: Stack(
fit: StackFit.expand,
children: [
if (showPdf && pdfBytes != null && pdfBytes!.isNotEmpty)
if (html != null && html!.isNotEmpty)
_pagePreview(
context,
ReportTemplateEmbeddedHtml(
key: ValueKey('html-preview-$previewRevision'),
html: html!,
previewMarginsMm: (_effectiveMedia['margins_mm'] as Map?)
?.cast<String, dynamic>(),
),
)
else if (pdfBytes != null && pdfBytes!.isNotEmpty)
_pagePreview(
context,
ReportTemplateEmbeddedPdf(
@ -172,21 +279,13 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget {
bytes: pdfBytes!,
),
)
else if (html != null && html!.isNotEmpty)
_pagePreview(
context,
ReportTemplateEmbeddedHtml(
key: ValueKey('html-preview-$previewRevision'),
html: html!,
),
)
else if (!loading)
Center(
child: Text(
'پیش‌نمایش آماده می‌شود…',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
if (loading)
@ -206,7 +305,10 @@ class ReportTemplateStudioPreviewPanel extends StatelessWidget {
class ReportTemplatePreviewDebouncer {
Timer? _timer;
void schedule(VoidCallback action, {Duration delay = const Duration(milliseconds: 600)}) {
void schedule(
VoidCallback action, {
Duration delay = const Duration(milliseconds: 600),
}) {
_timer?.cancel();
_timer = Timer(delay, action);
}

View file

@ -3,6 +3,8 @@ import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'report_template_media_settings.dart';
class ReportTemplateStudioV3Builder extends StatefulWidget {
final Map<String, dynamic> design;
final List<Map<String, dynamic>> blockCatalog;
@ -38,6 +40,7 @@ class _ReportTemplateStudioV3BuilderState
int _historyIndex = -1;
int _idSequence = 0;
String? _selectedBlockId;
bool _showLivePreview = false;
@override
void initState() {
@ -159,7 +162,7 @@ class _ReportTemplateStudioV3BuilderState
'type': type,
'visible': true,
'props': _cloneMap(definition['default_props']),
'style': <String, dynamic>{},
'style': <String, dynamic>{'width_mode': 'full'},
};
blocks.insert(index.clamp(0, blocks.length), block);
regions[region] = blocks;
@ -231,6 +234,10 @@ class _ReportTemplateStudioV3BuilderState
}
}
void _selectBlock(String id) {
setState(() => _selectedBlockId = id);
}
void _removeBlock(String id) {
final found = _findBlock(id);
if (found == null) return;
@ -343,7 +350,7 @@ class _ReportTemplateStudioV3BuilderState
children: [
SizedBox(width: spacious ? 420 : 380, child: designerPane),
VerticalDivider(width: 1, color: Theme.of(context).dividerColor),
Expanded(child: widget.previewPane!),
Expanded(child: _workspacePane(context)),
VerticalDivider(width: 1, color: Theme.of(context).dividerColor),
SizedBox(
width: spacious ? 350 : 320,
@ -361,8 +368,8 @@ class _ReportTemplateStudioV3BuilderState
child: TabBar(
tabs: [
Tab(icon: Icon(Icons.dashboard_customize), text: 'طراحی'),
Tab(icon: Icon(Icons.preview_outlined), text: 'پیش‌نمایش'),
Tab(icon: Icon(Icons.tune), text: 'تنظیمات بلوک'),
Tab(icon: Icon(Icons.edit_note_outlined), text: 'صفحه'),
Tab(icon: Icon(Icons.tune), text: 'تنظیمات'),
],
),
),
@ -370,7 +377,7 @@ class _ReportTemplateStudioV3BuilderState
child: TabBarView(
children: [
designerPane,
widget.previewPane!,
_workspacePane(context),
_inspectorPane(context, selected?.block),
],
),
@ -382,6 +389,573 @@ class _ReportTemplateStudioV3BuilderState
);
}
Widget _workspacePane(BuildContext context) {
return Column(
children: [
Material(
color: Theme.of(context).colorScheme.surfaceContainerLow,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
child: Row(
children: [
const Icon(Icons.dashboard_customize_outlined, size: 20),
const SizedBox(width: 8),
Expanded(
child: Text(
_showLivePreview
? 'پیش‌نمایش واقعی خروجی'
: 'بوم طراحی تعاملی',
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
SegmentedButton<bool>(
showSelectedIcon: false,
segments: const [
ButtonSegment(
value: false,
icon: Icon(Icons.touch_app_outlined, size: 18),
label: Text('طراحی'),
),
ButtonSegment(
value: true,
icon: Icon(Icons.visibility_outlined, size: 18),
label: Text('خروجی'),
),
],
selected: {_showLivePreview},
onSelectionChanged: (value) => setState(() {
_showLivePreview = value.first;
}),
),
],
),
),
),
const Divider(height: 1),
Expanded(
child: _showLivePreview
? widget.previewPane!
: _visualCanvas(context),
),
],
);
}
Widget _visualCanvas(BuildContext context) {
final media = normalizedReportTemplateMedia(
widget.design,
preferRoll: widget.design['layout'] == 'invoice_receipt',
);
final mediaSize = reportTemplateMediaSizeMm(media);
final isRoll = media['type'] == 'roll';
final margins =
(media['margins_mm'] as Map?)?.cast<String, dynamic>() ?? const {};
final direction = ((widget.design['theme'] as Map?)?['direction'] == 'ltr')
? TextDirection.ltr
: TextDirection.rtl;
return LayoutBuilder(
builder: (context, constraints) {
final availableWidth = constraints.maxWidth.isFinite
? constraints.maxWidth
: 800.0;
final pageWidth = (availableWidth - 48).clamp(280.0, 760.0).toDouble();
final pageHeight = isRoll
? 760.0
: pageWidth * mediaSize.height / mediaSize.width;
double pageMargin(String side, double fallback) {
final raw = margins[side];
final mm = raw is num ? raw.toDouble() : double.tryParse('$raw');
final reference = side == 'top' || side == 'bottom'
? mediaSize.height
: mediaSize.width;
return (((mm ?? fallback) / reference) * pageWidth).clamp(6.0, 64.0);
}
return ColoredBox(
color: const Color(0xffe5e7eb),
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Center(
child: Container(
key: const ValueKey('interactive-invoice-canvas'),
width: pageWidth,
constraints: BoxConstraints(minHeight: pageHeight),
padding: EdgeInsets.fromLTRB(
pageMargin('left', isRoll ? 2 : 10),
pageMargin('top', isRoll ? 3 : 10),
pageMargin('right', isRoll ? 2 : 10),
pageMargin('bottom', isRoll ? 4 : 10),
),
decoration: BoxDecoration(
color: Colors.white,
border: isRoll
? Border.symmetric(
vertical: BorderSide(color: Colors.grey.shade400),
)
: null,
boxShadow: const [
BoxShadow(
color: Color(0x26000000),
blurRadius: 18,
offset: Offset(0, 6),
),
],
),
child: Directionality(
textDirection: direction,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_canvasRegion(context, 'header', 'سربرگ'),
_canvasRegion(context, 'body', 'بدنه فاکتور'),
_canvasRegion(context, 'footer', 'پاورقی'),
if (isRoll)
Padding(
padding: const EdgeInsets.only(top: 16),
child: Row(
children: [
Expanded(
child: Divider(color: Colors.grey.shade400),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8,
),
child: Text(
'ادامه رول',
style: Theme.of(context).textTheme.labelSmall
?.copyWith(color: Colors.grey.shade600),
),
),
Expanded(
child: Divider(color: Colors.grey.shade400),
),
],
),
),
],
),
),
),
),
),
);
},
);
}
Widget _canvasRegion(BuildContext context, String region, String title) {
final blocks = _regionBlocks(widget.design, region);
return DragTarget<_BlockDragData>(
onWillAcceptWithDetails: (details) =>
_canDropOnRegion(details.data, region),
onAcceptWithDetails: (details) =>
_handleDrop(details.data, region, blocks.length),
builder: (context, candidates, rejected) {
final active = candidates.isNotEmpty;
return AnimatedContainer(
duration: const Duration(milliseconds: 120),
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: active
? Theme.of(
context,
).colorScheme.primaryContainer.withValues(alpha: 0.45)
: Colors.transparent,
borderRadius: BorderRadius.circular(8),
border: active
? Border.all(color: Theme.of(context).colorScheme.primary)
: null,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (blocks.isEmpty)
_canvasEmptyRegion(context, region, title)
else
for (var index = 0; index < blocks.length; index++) ...[
_canvasDropLine(region, index),
_canvasBlock(context, blocks[index]),
],
_canvasDropLine(region, blocks.length, expanded: active),
],
),
);
},
);
}
bool _canDropOnRegion(_BlockDragData data, String region) {
final type =
data.blockType ??
_findBlock(data.blockId ?? '')?.block['type']?.toString();
final allowed = List<String>.from(
(_definition(type ?? '')?['allowed_regions'] as List?) ?? const [],
);
return allowed.contains(region);
}
Widget _canvasEmptyRegion(BuildContext context, String region, String title) {
return DragTarget<_BlockDragData>(
onWillAcceptWithDetails: (details) =>
_canDropOnRegion(details.data, region),
onAcceptWithDetails: (details) => _handleDrop(details.data, region, 0),
builder: (context, candidates, rejected) => Container(
height: 48,
alignment: Alignment.center,
decoration: BoxDecoration(
color: candidates.isNotEmpty
? Theme.of(context).colorScheme.primaryContainer
: Colors.grey.shade50,
borderRadius: BorderRadius.circular(6),
border: Border.all(
color: candidates.isNotEmpty
? Theme.of(context).colorScheme.primary
: Colors.grey.shade300,
style: BorderStyle.solid,
),
),
child: Text(
'$title — بلوک را اینجا رها کنید',
style: Theme.of(
context,
).textTheme.labelSmall?.copyWith(color: Colors.grey.shade600),
),
),
);
}
Widget _canvasDropLine(String region, int index, {bool expanded = false}) {
return DragTarget<_BlockDragData>(
onWillAcceptWithDetails: (details) =>
_canDropOnRegion(details.data, region),
onAcceptWithDetails: (details) =>
_handleDrop(details.data, region, index),
builder: (context, candidates, rejected) {
final active = candidates.isNotEmpty;
return AnimatedContainer(
duration: const Duration(milliseconds: 100),
height: active || expanded ? 24 : 6,
margin: const EdgeInsets.symmetric(vertical: 2),
decoration: BoxDecoration(
color: active
? Theme.of(context).colorScheme.primary.withValues(alpha: 0.18)
: Colors.transparent,
borderRadius: BorderRadius.circular(4),
border: active
? Border.all(color: Theme.of(context).colorScheme.primary)
: null,
),
alignment: Alignment.center,
child: active
? Icon(
Icons.add,
size: 16,
color: Theme.of(context).colorScheme.primary,
)
: null,
);
},
);
}
Widget _canvasBlock(BuildContext context, Map<String, dynamic> block) {
final id = block['id'].toString();
final type = block['type'].toString();
final selected = id == _selectedBlockId;
final style = (block['style'] as Map?)?.cast<String, dynamic>() ?? const {};
final widthMode = (style['width_mode'] ?? 'full').toString();
final media = normalizedReportTemplateMedia(widget.design);
final pageWidthMm = (media['width_mm'] as num?)?.toDouble() ?? 210;
final widthValue = (style['width_value'] as num?)?.toDouble();
final widthFactor = switch (widthMode) {
'percentage' => ((widthValue ?? 100) / 100).clamp(0.1, 1.0),
'fixed' => ((widthValue ?? 80) / pageWidthMm).clamp(0.1, 1.0),
'content' => 0.62,
_ => 1.0,
}.toDouble();
final alignment = switch (style['text_align']) {
'left' => Alignment.centerLeft,
'center' => Alignment.center,
_ => Alignment.centerRight,
};
final blockCard = GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => _selectBlock(id),
child: AnimatedContainer(
duration: const Duration(milliseconds: 120),
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: selected
? Theme.of(
context,
).colorScheme.primaryContainer.withValues(alpha: 0.35)
: Colors.transparent,
borderRadius: BorderRadius.circular(6),
border: Border.all(
color: selected
? Theme.of(context).colorScheme.primary
: Colors.transparent,
width: selected ? 2 : 1,
),
),
child: Stack(
clipBehavior: Clip.none,
children: [
Align(
alignment: alignment,
child: _canvasBlockContent(context, block),
),
if (selected)
PositionedDirectional(
top: -20,
end: -4,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(10),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.drag_indicator,
size: 13,
color: Colors.white,
),
const SizedBox(width: 2),
Text(
_labelForType(type),
style: const TextStyle(
color: Colors.white,
fontSize: 10,
),
),
],
),
),
),
],
),
),
);
return Align(
alignment: alignment,
child: FractionallySizedBox(
widthFactor: widthFactor,
child: Opacity(
opacity: block['visible'] == false ? 0.42 : 1,
child: Draggable<_BlockDragData>(
data: _BlockDragData.existing(id),
onDragStarted: () => _selectBlock(id),
feedback: Material(
elevation: 8,
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: 280,
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
Icon(_iconForType(type), size: 18),
const SizedBox(width: 8),
Text(_labelForType(type)),
],
),
),
),
),
childWhenDragging: Opacity(opacity: 0.25, child: blockCard),
child: MouseRegion(
cursor: SystemMouseCursors.grab,
child: blockCard,
),
),
),
),
);
}
Widget _canvasBlockContent(BuildContext context, Map<String, dynamic> block) {
final type = block['type'].toString();
final props = (block['props'] as Map?)?.cast<String, dynamic>() ?? const {};
final theme =
(widget.design['theme'] as Map?)?.cast<String, dynamic>() ?? const {};
final primary = _colorFromHex(
(theme['primary_color'] ?? '#1e3a5f').toString(),
);
final small = Theme.of(context).textTheme.bodySmall;
switch (type) {
case 'brand_header':
return Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'فاکتور فروش',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: primary,
fontWeight: FontWeight.bold,
),
),
Text('شماره: ۱۰۰۱ • تاریخ: ۱۴۰۵/۰۷/۲۷', style: small),
],
),
),
Icon(Icons.business, color: primary, size: 34),
],
);
case 'party_info':
return Container(
width: double.infinity,
padding: const EdgeInsets.all(9),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade300),
borderRadius: BorderRadius.circular(6),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
(props['title'] ?? 'طرف حساب').toString(),
style: small?.copyWith(
color: primary,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
const Text('نام و مشخصات طرف حساب'),
],
),
);
case 'invoice_lines':
final columns = ((props['columns'] as List?) ?? const [])
.whereType<Map>()
.where((column) => column['visible'] != false)
.take(4)
.toList();
final titles = columns.isEmpty
? const ['شرح', 'تعداد', 'مبلغ']
: columns
.map(
(column) => (column['title'] ?? column['key']).toString(),
)
.toList();
return Table(
border: TableBorder.all(color: Colors.grey.shade300),
children: [
TableRow(
decoration: BoxDecoration(color: primary),
children: [
for (final title in titles)
Padding(
padding: const EdgeInsets.all(5),
child: Text(
title,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white, fontSize: 10),
),
),
],
),
for (var row = 0; row < 3; row++)
TableRow(
children: [
for (var column = 0; column < titles.length; column++)
Padding(
padding: const EdgeInsets.all(5),
child: Text(
column == 0
? 'نمونه کالا ${row + 1}'
: '${row + column + 1}',
style: const TextStyle(fontSize: 9),
),
),
],
),
],
);
case 'invoice_totals':
return Column(
children: const [
_CanvasTotalRow(label: 'جمع اقلام', value: '۱٬۲۰۰٬۰۰۰'),
_CanvasTotalRow(label: 'تخفیف', value: '۵۰٬۰۰۰'),
_CanvasTotalRow(
label: 'قابل پرداخت',
value: '۱٬۱۵۰٬۰۰۰',
bold: true,
),
],
);
case 'payments':
return const ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
leading: Icon(Icons.payments_outlined),
title: Text('پرداخت‌ها'),
subtitle: Text('کارت‌خوان — ۱٬۱۵۰٬۰۰۰'),
);
case 'note':
return Container(
width: double.infinity,
padding: const EdgeInsets.all(8),
color: const Color(0xfffffbeb),
child: const Text('یادداشت فاکتور در این قسمت نمایش داده می‌شود.'),
);
case 'signatures':
return const Row(
children: [
Expanded(child: _CanvasSignature(label: 'امضای فروشنده')),
SizedBox(width: 12),
Expanded(child: _CanvasSignature(label: 'امضای خریدار')),
],
);
case 'qr':
return const Center(child: Icon(Icons.qr_code_2, size: 72));
case 'footer_meta':
return Text(
'زمان چاپ • تهیه‌کننده سند',
textAlign: TextAlign.center,
style: small?.copyWith(color: Colors.grey.shade600),
);
case 'custom_text':
return Text((props['text'] ?? 'متن دلخواه').toString());
case 'divider':
return Divider(color: Colors.grey.shade500);
case 'spacer':
return SizedBox(
height: ((props['height'] as num?)?.toDouble() ?? 12)
.clamp(4, 80)
.toDouble(),
);
default:
return Row(
children: [
Icon(_iconForType(type), size: 18),
const SizedBox(width: 8),
Text(_labelForType(type)),
],
);
}
}
Color _colorFromHex(String value) {
final hex = value.replaceFirst('#', '');
final parsed = int.tryParse(hex.length == 6 ? 'ff$hex' : hex, radix: 16);
return Color(parsed ?? 0xff1e3a5f);
}
Widget _designerPane(BuildContext context, {Map<String, dynamic>? selected}) {
return ListView(
padding: const EdgeInsets.all(12),
@ -450,6 +1024,28 @@ class _ReportTemplateStudioV3BuilderState
return ListView(
padding: const EdgeInsets.all(12),
children: [
ExpansionTile(
key: ValueKey('studio-media-settings-${selected == null}'),
initiallyExpanded: selected == null,
tilePadding: EdgeInsets.zero,
leading: const Icon(Icons.straighten_outlined),
title: const Text('صفحه و چاپ'),
subtitle: Text(_mediaSummary()),
children: [
ReportTemplateMediaSettings(
media: normalizedReportTemplateMedia(
widget.design,
preferRoll: widget.design['layout'] == 'invoice_receipt',
),
compact: true,
onChanged: (media) => _patchRoot((design) {
design['media'] = media;
}),
),
const SizedBox(height: 12),
],
),
const Divider(),
if (selected == null)
Card(
margin: EdgeInsets.zero,
@ -464,7 +1060,7 @@ class _ReportTemplateStudioV3BuilderState
),
const SizedBox(height: 12),
const Text(
'یک بلوک را انتخاب کنید تا تنظیمات آن در این ستون نمایش داده شود.',
'یک بلوک را انتخاب کنید تا تنظیمات آن زیر تنظیمات صفحه نمایش داده شود.',
textAlign: TextAlign.center,
),
],
@ -477,6 +1073,19 @@ class _ReportTemplateStudioV3BuilderState
);
}
String _mediaSummary() {
final media = normalizedReportTemplateMedia(
widget.design,
preferRoll: widget.design['layout'] == 'invoice_receipt',
);
if (media['type'] == 'roll') {
return 'رول ${reportTemplatePaperSizeFromMedia(media)} با ارتفاع خودکار';
}
final orientation = media['orientation'] == 'landscape' ? 'افقی' : 'عمودی';
final preset = (media['preset'] ?? 'A4').toString();
return '${preset == 'custom' ? reportTemplatePaperSizeFromMedia(media) : preset}، $orientation';
}
Widget _buildAppearance(BuildContext context) {
final theme =
(widget.design['theme'] as Map?)?.cast<String, dynamic>() ?? const {};
@ -783,7 +1392,7 @@ class _ReportTemplateStudioV3BuilderState
margin: const EdgeInsets.symmetric(vertical: 2),
child: ListTile(
dense: true,
onTap: () => setState(() => _selectedBlockId = id),
onTap: () => _selectBlock(id),
leading: Draggable<_BlockDragData>(
data: _BlockDragData.existing(id),
feedback: Material(
@ -854,6 +1463,19 @@ class _ReportTemplateStudioV3BuilderState
(type == 'custom_text' ? props['align'] : null) ??
defaultAlignment)
.toString();
final widthMode =
const {
'full',
'percentage',
'fixed',
'content',
}.contains(style['width_mode'])
? style['width_mode'].toString()
: 'full';
final widthValue =
((style['width_value'] as num?)?.toDouble() ??
(widthMode == 'percentage' ? 100 : 80))
.clamp(10.0, widthMode == 'percentage' ? 100.0 : 500.0);
const alignableTypes = {
'brand_header',
'party_info',
@ -916,6 +1538,60 @@ class _ReportTemplateStudioV3BuilderState
),
const SizedBox(height: 12),
],
const Text('عرض بلوک'),
const SizedBox(height: 6),
DropdownButtonFormField<String>(
key: ValueKey('$id-width-mode-$widthMode'),
isExpanded: true,
initialValue: widthMode,
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: true,
),
items: const [
DropdownMenuItem(value: 'full', child: Text('تمام عرض')),
DropdownMenuItem(
value: 'percentage',
child: Text('درصدی از صفحه'),
),
DropdownMenuItem(
value: 'fixed',
child: Text('عرض ثابت (میلی‌متر)'),
),
DropdownMenuItem(
value: 'content',
child: Text('متناسب با محتوا'),
),
],
onChanged: (value) {
if (value == null) return;
_patchBlockStyle(id, {
'width_mode': value,
if (value == 'percentage') 'width_value': 100,
if (value == 'fixed') 'width_value': 80,
});
},
),
if (widthMode == 'percentage' || widthMode == 'fixed') ...[
const SizedBox(height: 8),
Text(
widthMode == 'percentage'
? 'عرض: ${widthValue.round()}٪'
: 'عرض: ${widthValue.toStringAsFixed(0)} میلی‌متر',
),
Slider(
min: 10,
max: widthMode == 'percentage' ? 100 : 300,
divisions: widthMode == 'percentage' ? 18 : 29,
value: widthValue.clamp(
10.0,
widthMode == 'percentage' ? 100.0 : 300.0,
),
onChanged: (value) =>
_patchBlockStyle(id, {'width_value': value.round()}),
),
],
const SizedBox(height: 12),
if (type == 'custom_text')
TextFormField(
key: ValueKey('$id-custom-text'),
@ -1189,3 +1865,55 @@ class _ReportTemplateStudioV3BuilderState
);
}
}
class _CanvasTotalRow extends StatelessWidget {
final String label;
final String value;
final bool bold;
const _CanvasTotalRow({
required this.label,
required this.value,
this.bold = false,
});
@override
Widget build(BuildContext context) {
final style = TextStyle(
fontSize: 10,
fontWeight: bold ? FontWeight.bold : FontWeight.normal,
);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Row(
children: [
Expanded(child: Text(label, style: style)),
Text(value, style: style),
],
),
);
}
}
class _CanvasSignature extends StatelessWidget {
final String label;
const _CanvasSignature({required this.label});
@override
Widget build(BuildContext context) {
return Column(
children: [
Container(
height: 54,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(4),
),
),
const SizedBox(height: 4),
Text(label, style: Theme.of(context).textTheme.labelSmall),
],
);
}
}

View file

@ -1,8 +1,28 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hesabix_ui/widgets/report_template/studio/report_template_media_settings.dart';
import 'package:hesabix_ui/widgets/report_template/studio/report_template_studio_preview_panel.dart';
import 'package:hesabix_ui/widgets/report_template/studio/report_template_studio_v3_builder.dart';
void main() {
test('maps legacy paper sizes to sheet and custom roll media', () {
final sheet = reportTemplateMediaFromLegacy(
paperSize: 'A5',
orientation: 'landscape',
);
expect(sheet['type'], 'sheet');
expect(sheet['width_mm'], 148);
expect(sheet['height_mm'], 210);
expect(reportTemplatePaperSizeFromMedia(sheet), 'A5');
final roll = reportTemplateMediaFromLegacy(paperSize: '72.5mm');
expect(roll['type'], 'roll');
expect(roll['width_mm'], 72.5);
expect(reportTemplatePaperSizeFromMedia(roll), '72.5mm');
});
testWidgets('adds a palette block and supports undo', (tester) async {
var design = <String, dynamic>{
'schema_version': 3,
@ -140,6 +160,12 @@ void main() {
'required': true,
'default_props': <String, dynamic>{},
},
<String, dynamic>{
'type': 'custom_text',
'label_fa': 'متن دلخواه',
'allowed_regions': <String>['header', 'body', 'footer'],
'default_props': <String, dynamic>{'text': 'متن دلخواه'},
},
];
await tester.pumpWidget(
@ -160,24 +186,51 @@ void main() {
expect(
find.text(
'یک بلوک را انتخاب کنید تا تنظیمات آن در این ستون نمایش داده شود.',
'یک بلوک را انتخاب کنید تا تنظیمات آن زیر تنظیمات صفحه نمایش داده شود.',
),
findsOneWidget,
);
await tester.tap(find.text('جدول اقلام').last);
expect(find.text('صفحه و چاپ'), findsOneWidget);
await tester.tap(find.text('رول'));
await tester.pump();
expect((design['media'] as Map)['type'], 'roll');
expect((design['media'] as Map)['width_mm'], 80);
expect(
find.byKey(const ValueKey('interactive-invoice-canvas')),
findsOneWidget,
);
expect(find.text('نمونه کالا 1'), findsOneWidget);
final paletteText = find.text('متن دلخواه').first;
final footerDropTarget = find.textContaining(
'پاورقی — بلوک را اینجا رها کنید',
);
await tester.dragFrom(
tester.getCenter(paletteText),
tester.getCenter(footerDropTarget) - tester.getCenter(paletteText),
);
await tester.pumpAndSettle();
final footer = ((design['regions'] as Map)['footer'] as List)
.cast<Map<String, dynamic>>();
expect(footer.map((block) => block['type']), contains('custom_text'));
await tester.tap(find.text('نمونه کالا 1'));
await tester.pump();
final inspector = find.text('تنظیمات جدول اقلام');
final preview = find.text('پیش‌نمایش آزمایشی');
final canvas = find.byKey(const ValueKey('interactive-invoice-canvas'));
final designer = find.text('طراح بلوکی');
expect(inspector, findsOneWidget);
expect(find.text('عرض بلوک'), findsOneWidget);
expect(find.text('تمام عرض'), findsOneWidget);
expect(
tester.getCenter(inspector).dx,
lessThan(tester.getCenter(preview).dx),
lessThan(tester.getCenter(canvas).dx),
);
expect(
tester.getCenter(preview).dx,
tester.getCenter(canvas).dx,
lessThan(tester.getCenter(designer).dx),
);
@ -186,5 +239,67 @@ void main() {
final body = ((design['regions'] as Map)['body'] as List)
.cast<Map<String, dynamic>>();
expect((body.first['style'] as Map)['text_align'], 'center');
await tester.tap(find.text('خروجی'));
await tester.pump();
expect(find.text('پیش‌نمایش آزمایشی'), findsOneWidget);
});
testWidgets('keeps live HTML visible after print PDF is generated', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 700,
height: 800,
child: ReportTemplateStudioPreviewPanel(
loading: false,
html: '<!doctype html><html><body>preview</body></html>',
pdfBytes: Uint8List.fromList('%PDF-1.7'.codeUnits),
showPdf: true,
previewRevision: 1,
),
),
),
),
);
expect(
find.text('پیش‌نمایش HTML فقط در نسخه وب در دسترس است.'),
findsOneWidget,
);
expect(find.textContaining('برای مشاهدهٔ PDF در دسکتاپ'), findsNothing);
});
testWidgets('preview toolbar remains usable on a narrow screen', (
tester,
) async {
tester.view.physicalSize = const Size(360, 640);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ReportTemplateStudioPreviewPanel(
loading: false,
html: '<html><body>preview</body></html>',
pdfBytes: Uint8List.fromList('%PDF-1.7'.codeUnits),
showPdf: true,
media: defaultReportTemplateMedia(roll: true),
onRefresh: () {},
onGeneratePdf: () {},
onShowHtml: () {},
),
),
),
);
await tester.pump();
expect(tester.takeException(), isNull);
expect(find.textContaining('80mm'), findsOneWidget);
});
}