diff --git a/hesabixAPI/adapters/api/v1/report_templates.py b/hesabixAPI/adapters/api/v1/report_templates.py index 6963d8e2..bbd02f22 100755 --- a/hesabixAPI/adapters/api/v1/report_templates.py +++ b/hesabixAPI/adapters/api/v1/report_templates.py @@ -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: diff --git a/hesabixAPI/app/services/pdf/page_size.py b/hesabixAPI/app/services/pdf/page_size.py index d808ec1f..4c81c7a1 100644 --- a/hesabixAPI/app/services/pdf/page_size.py +++ b/hesabixAPI/app/services/pdf/page_size.py @@ -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[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 diff --git a/hesabixAPI/app/services/report_template_service.py b/hesabixAPI/app/services/report_template_service.py index 2cec0b33..f32ecced 100755 --- a/hesabixAPI/app/services/report_template_service.py +++ b/hesabixAPI/app/services/report_template_service.py @@ -801,7 +801,10 @@ class ReportTemplateService: pass # درج CSS سفارشی در +'''; + if (source.contains('')) { + return source.replaceFirst('', '$head'); + } + return '$head$source'; + } + + void _scheduleRevoke(String url) { + Future.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 diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_media_settings.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_media_settings.dart new file mode 100644 index 00000000..1b7906c4 --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_media_settings.dart @@ -0,0 +1,418 @@ +import 'package:flutter/material.dart'; + +import '../../../utils/number_normalizer.dart'; + +const Map 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 defaultReportTemplateMedia({bool roll = false}) { + if (roll) { + 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, + }, + }; +} + +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 reportTemplateMediaFromLegacy({ + String? paperSize, + String? orientation, + Map? margins, + bool preferRoll = false, +}) { + final token = (paperSize ?? '').trim(); + MapEntry? preset; + for (final entry in reportTemplateSheetPresetsMm.entries) { + if (entry.key.toLowerCase() == token.toLowerCase()) { + preset = entry; + break; + } + } + Map 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'] = { + 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 normalizedReportTemplateMedia( + Map 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 = {...fallback, ...raw.cast()}; + final fallbackMargins = (fallback['margins_mm'] as Map) + .cast(); + final rawMargins = raw['margins_mm']; + media['margins_mm'] = { + ...fallbackMargins, + if (rawMargins is Map) ...rawMargins.cast(), + }; + return media; +} + +String reportTemplatePaperSizeFromMedia(Map 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 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 media; + final ValueChanged> onChanged; + final bool compact; + + const ReportTemplateMediaSettings({ + super.key, + required this.media, + required this.onChanged, + this.compact = false, + }); + + Map _copy() { + final margins = (media['margins_mm'] as Map?)?.cast(); + return { + ...media, + 'margins_mm': {...?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)[side] = value; + onChanged(next); + } + + @override + Widget build(BuildContext context) { + final isRoll = media['type'] == 'roll'; + final preset = (media['preset'] ?? (isRoll ? '80mm' : 'A4')).toString(); + final sheetItems = [...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() ?? const {}; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SegmentedButton( + 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( + 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( + 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 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 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, + ); + } +} 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 512f17f1..7bc69f10 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 @@ -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? media; final List errors; final List 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 get _effectiveMedia { + if (media != null) return Map.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(), + ), + ) + 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); } 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 index a44b88e1..dde707ef 100644 --- 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 @@ -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 design; final List> 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': {}, + 'style': {'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( + 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() ?? 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.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 block) { + final id = block['id'].toString(); + final type = block['type'].toString(); + final selected = id == _selectedBlockId; + final style = (block['style'] as Map?)?.cast() ?? 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 block) { + final type = block['type'].toString(); + final props = (block['props'] as Map?)?.cast() ?? const {}; + final theme = + (widget.design['theme'] as Map?)?.cast() ?? 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() + .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? 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() ?? 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( + 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), + ], + ); + } +} 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 index d6ad881d..bcb4f1b5 100644 --- 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 @@ -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 = { 'schema_version': 3, @@ -140,6 +160,12 @@ void main() { 'required': true, 'default_props': {}, }, + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': {'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>(); + 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>(); 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: 'preview', + 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: 'preview', + 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); }); }