diff --git a/docs/INVOICE_TEMPLATE_STUDIO_ARCHITECTURE.md b/docs/INVOICE_TEMPLATE_STUDIO_ARCHITECTURE.md new file mode 100644 index 00000000..935685ac --- /dev/null +++ b/docs/INVOICE_TEMPLATE_STUDIO_ARCHITECTURE.md @@ -0,0 +1,462 @@ +# معماری آینده‌نگر استودیوی طراحی فاکتور + +> وضعیت: فاز ۰ و فاز ۱ پیاده‌سازی شده؛ آماده بازبینی تیم حسابیکس +> تاریخ: ۱۴۰۵/۰۷/۲۹ (2026-10-21) +> دامنه: استودیوی قالب فاکتور، خروجی HTML/CSS، PDF و آمادگی برای اتصال AI/MCP + +## ۱. تصمیم اصلی + +استودیوی فاکتور باید یک **Design Document ساختاریافته و نسخه‌بندی‌شده** را ویرایش کند. این سند توسط compiler رسمی حسابیکس به HTML/CSS تبدیل می‌شود و همان HTML/CSS منبع تولید PDF و چاپ فیزیکی است. + +```text +کاربر، UI یا AI + ↓ +Design Document با گرید تمام‌صفحه + ↓ +Validator + Normalizer + ↓ +Deterministic HTML/CSS Compiler + ↓ +HTML نهایی + ↓ +PDF Renderer موجود + ↓ +پرینتر فیزیکی +``` + +اصول غیرقابل نقض: + +1. خروجی رسمی فاکتور فقط HTML/CSS است. +2. موتور مستقل برای تولید PDF فاکتور ساخته نمی‌شود. +3. PDF فقط از HTML/CSS تولیدشده توسط compiler رسمی ساخته می‌شود. +4. ویرایشگر بصری، موتور خروجی محسوب نمی‌شود و نباید خروجی چاپی مستقلی تولید کند. +5. کاربر و AI هر دو یک Design Document مشترک را تغییر می‌دهند. +6. AI یا MCP اجازه تولید JavaScript، Jinja یا CSS دلخواه برای استودیوی ساختاریافته ندارد. +7. حالت پیشرفته HTML/CSS از استودیوی ساختاریافته و مسیر AI جدا باقی می‌ماند. + +## ۲. تفاوت منبع طراحی و خروجی + +ذخیره مستقیم HTML/CSS به‌عنوان تنها منبع طراحی برای drag-and-drop، migration، responsive layout و AI مناسب نیست. در عوض: + +- **منبع طراحی:** JSON معنایی، محدود و نسخه‌بندی‌شده؛ +- **خروجی کامپایل‌شده:** HTML/CSS؛ +- **خروجی چاپی:** PDF حاصل از همان HTML/CSS. + +این تفکیک باعث می‌شود UI، REST API و MCP قواعد یکسانی داشته باشند، بدون آنکه موتور چاپ جدیدی ایجاد شود. + +## ۳. وضعیت فعلی + +استودیوی فعلی این قابلیت‌ها را دارد: + +- schema نسخه ۳ و نواحی `header`، `body` و `footer`؛ +- بلوک‌های معنایی فاکتور و کاتالوگ bindingهای کنترل‌شده؛ +- انتخاب A3، A4، A5، A6، Letter، Legal و رول سفارشی؛ +- RTL/LTR و تراز متن؛ +- گرید میلی‌متری یکپارچه روی کل سطح قابل چاپ؛ +- حرکت و تغییر اندازهٔ همهٔ بلوک‌ها در دو محور؛ +- HTML preview و PDF بر پایه compiler موجود؛ +- سازگاری با قالب‌های قبلی. + +مواردی که هنوز پایه معماری پایدار ندارند: + +- containerهای تو‌در‌تو؛ +- freeform layout محدود و امن؛ +- Snap هوشمند به عناصر، حاشیه و guideها؛ +- variant مستقل برای A4، A5 و رول؛ +- عملیات patch اتمیک و revision-based؛ +- API دامنه‌ای مناسب برای اتصال MCP؛ +- audit منشأ تغییرات کاربر یا AI. + +## ۴. مدل مفهومی نسخه بعدی + +نام کاری نسخه بعدی در این سند `schema_version: 4` است. شماره نهایی باید هنگام تصویب تیم تثبیت شود. + +Design Document باید یک درخت از container و component باشد: + +```json +{ + "schema_version": 4, + "document": { + "direction": "rtl", + "default_media_profile": "a4_portrait" + }, + "root": { + "id": "invoice-root", + "kind": "container", + "layout": { + "type": "page_grid", + "grid_mm": 1, + "snap": true, + "width_mm": 190, + "height_mm": 277 + }, + "children": [] + }, + "variants": { + "base": {}, + "a4_portrait": {}, + "a5_portrait": {}, + "roll_80": {} + } +} +``` + +### ۴.۱. انواع container + +| نوع | کاربرد | نمونه | +|---|---|---| +| `page_grid` | چیدمان اصلی و قابل‌مشاهدهٔ کل صفحه | تمام اجزای فاکتور | +| `flow` | گروه‌بندی معنایی داخلی و سازگاری با قالب قدیمی؛ در UI حالت طراحی نیست | ناحیه‌های داده‌ای قدیمی | +| `grid` | چیدمان ستونی و responsive | فروشنده و خریدار کنار هم | +| `freeform` | موقعیت آزاد در محدوده کنترل‌شده | لوگو، QR، مهر و متن ثابت | +| `stack` | قرارگیری لایه‌ای | واترمارک و عناصر پس‌زمینه | + +هر node باید `id` پایدار داشته باشد. این شناسه نباید با reorder، تغییر عنوان یا migration بی‌دلیل عوض شود. + +### ۴.۲. نمونه grid + +```json +{ + "id": "buyer-info", + "kind": "component", + "component": "invoice.party_info", + "placement": { + "column_start": 31, + "column_span": 30, + "min_height_mm": 22 + }, + "content": { + "role": "buyer", + "title": "خریدار" + } +} +``` + +### ۴.۳. نمونه جای‌گذاری روی گرید صفحه + +```json +{ + "id": "invoice-qr", + "kind": "component", + "component": "invoice.qr", + "placement": { + "x_mm": 160, + "y_mm": 5, + "width_mm": 25, + "height_mm": 25 + }, + "content": { + "binding": "invoice.public_url" + } +} +``` + +مختصات هر component نسبت به سطح قابل چاپ صفحه تعریف می‌شوند، نه نسبت به viewport مرورگر. جهت متن RTL/LTR نباید معنای هندسه فیزیکی را مبهم کند. + +## ۵. محدودیت مهم محتوای پویا + +همه اجزای فاکتور، از جمله جدول اقلام، روی گرید تمام‌صفحه جای‌گذاری می‌شوند. component پویا درون خانهٔ گرید می‌تواند از حداقل ارتفاع طراحی‌شده بزرگ‌تر شود و موتور HTML/CSS باید ردیف‌های بعدی را جابه‌جا کند. + +قواعد پیشنهادی: + +- جدول اقلام یک component پویا روی `page_grid` است و ارتفاع تنظیم‌شده برای آن حداقل ارتفاع محسوب می‌شود. +- جمع‌بندی، توضیحات و امضا در خانه‌های بعدی گرید قرار می‌گیرند و با رشد جدول توسط CSS Grid جابه‌جا می‌شوند. +- header و footer تکرارشونده توسط compiler و CSS چاپ مدیریت شوند. +- ردیف جدول تا حد امکان با `break-inside: avoid` نصف نشود. +- عنوان ستون‌ها در صفحه بعد تکرار شود. +- حالت row-level freeform در UI وجود ندارد؛ کل صفحه بوم واحد است. + +این مرز جلوی هم‌پوشانی داده پویا با جمع‌بندی و پاورقی را می‌گیرد. + +## ۶. responsive layout برای چاپ + +ریسپانسیو بودن فاکتور باید براساس **پروفایل رسانه چاپی** باشد، نه عرض viewport مرورگر. + +پروفایل‌های پایه: + +- `a3_portrait` و `a3_landscape` +- `a4_portrait` +- `a4_landscape` +- `a5_portrait` +- `a5_landscape` +- `a6_portrait` و `a6_landscape` +- `letter_portrait` و `letter_landscape` +- `legal_portrait` و `legal_landscape` +- `roll_80` +- `roll_58` +- `roll_60` و `roll_100` +- `custom_sheet_portrait` و `custom_sheet_landscape` +- `custom_roll` + +هر variant فقط override هندسی nodeها را نگه می‌دارد و محتوا در درخت canonical باقی می‌ماند. همه پروفایل‌های پشتیبانی‌شده override صریح دارند؛ برای مثال اطلاعات فروشنده و خریدار در A4 می‌توانند دو ستون باشند و روی رول تمام عرض شوند. + +انتخاب variant باید پیش از compile انجام شود. تکیه کامل بر media query مرورگر یا قابلیت‌های غیرقطعی PDF Renderer مجاز نیست. + +## ۷. معماری ویرایشگر + +ویرایشگر می‌تواند برای تعامل سریع، هندسه nodeها را در Flutter نمایش دهد؛ اما این صحنه نباید خروجی چاپی تولید کند. + +چرخه صحیح ویرایش: + +1. UI یک عملیات ساختاریافته روی Design Document اعمال می‌کند. +2. تغییر در history محلی ثبت می‌شود. +3. Design Document اعتبارسنجی می‌شود. +4. compiler رسمی HTML/CSS پیش‌نمایش را تولید می‌کند. +5. PDF backend مرجع نهایی تطبیق چاپ است. + +در صورت پایداری فنی، می‌توان در آینده interaction را مستقیماً روی DOM خروجی انجام داد؛ اما این انتخاب نباید شرط schema یا compiler باشد. + +دو سطح پیش‌نمایش لازم است: + +- **HTML Preview:** سریع و مناسب ویرایش روزمره؛ +- **PDF Preview:** معتبر برای کنترل نهایی صفحه‌بندی و چاپ. + +مرورگر و PDF Renderer ممکن است یک CSS مشترک را با تفاوت‌های جزئی نمایش دهند؛ بنابراین HTML preview نباید تنها مرجع صحت چاپ باشد. + +## ۸. Snap هوشمند + +Snap باید در فضای مختصات container و فقط میان siblingهای قابل مقایسه انجام شود. + +### ۸.۱. نامزدهای Snap + +- لبه ابتدا و انتهای عنصر؛ +- مرکز افقی و عمودی؛ +- baseline متن در فاز بعدی؛ +- حاشیه امن container؛ +- guideهای دستی؛ +- گرید ۱، ۳ یا ۵ میلی‌متری؛ +- فاصله مساوی میان عناصر در فاز بعدی. + +### ۸.۲. قواعد تعامل + +- حرکت حین drag باید روان و بدون پرش باشد. +- Snap به‌صورت زنده همراه خط راهنما نمایش داده شود. +- آستانه Snap در screen pixel تعریف و با Zoom به میلی‌متر تبدیل شود. +- محور X و Y جداگانه resolve شوند. +- برای جلوگیری از لرزش روی مرز، hysteresis وجود داشته باشد. +- کاربر بتواند Snap را موقتاً با کلید modifier غیرفعال کند. +- در پایان drag فقط یک history entry ایجاد شود. +- مختصات و اندازه نهایی داخل محدوده container clamp شوند. + +اولویت پیشنهادی: + +```text +Guide دستی +→ لبه یا مرکز siblingها +→ حاشیه امن +→ فاصله مساوی +→ گرید +``` + +در MVP، نتیجه Snap به مختصات عددی تبدیل می‌شود. برای آینده یک فیلد اختیاری `constraints` در schema رزرو می‌شود، ولی constraint solver در MVP ساخته نمی‌شود. + +## ۹. compiler رسمی HTML/CSS + +compiler باید: + +- قطعی و نسخه‌بندی‌شده باشد؛ +- فقط CSS پشتیبانی‌شده توسط PDF Renderer پروژه تولید کند؛ +- برای تمام nodeها markup پایدار و قابل ردیابی تولید کند؛ +- واحدهای چاپی را با `mm` یا `pt` تولید کند؛ +- فونت فارسی حسابیکس را embed کند؛ +- RTL/LTR را مستقل از هندسه مدیریت کند؛ +- CSS و Jinja دلخواه را از schema ساختاریافته قبول نکند؛ +- diagnostics قابل استفاده توسط UI و AI برگرداند. + +نمونه markup قابل ردیابی: + +```html +
+ ... +
+``` + +برای بازتولید خروجی منتشرشده بهتر است snapshot انتشار شامل این موارد باشد: + +- Design Document؛ +- `schema_version`؛ +- `compiler_version`؛ +- HTML/CSS کامپایل‌شده؛ +- assetها و فونت‌های مؤثر؛ +- زمان و کاربر منتشرکننده. + +## ۱۰. آمادگی برای AI و MCP + +MCP نباید مستقیماً به دیتابیس یا compiler داخلی دسترسی داشته باشد. ابتدا باید domain serviceهای پایدار ایجاد شوند: + +- Draft Service +- Validation Service +- Patch Service +- Compilation Service +- Preview Service +- Publication Service + +سپس UI، REST API و MCP همگی از همان serviceها استفاده می‌کنند: + +```text +Flutter UI ─┐ +REST API ───┼→ Template Domain Services +MCP Server ─┘ +``` + +### ۱۰.۱. عملیات patch + +AI و UI باید عملیات کوچک و معنایی ارسال کنند، نه HTML کامل: + +```json +{ + "template_id": 42, + "base_revision": 17, + "operation_id": "uuid", + "operations": [ + { + "op": "move_node", + "node_id": "business-logo", + "x_mm": 8, + "y_mm": 5 + } + ] +} +``` + +عملیات باید: + +- اتمیک؛ +- idempotent؛ +- revision-based؛ +- قابل audit؛ +- قابل Undo؛ +- محدود به draft؛ +- دارای validation قبل از commit + +باشند. + +انتشار از طریق AI باید همیشه نیازمند تأیید صریح کاربر و permission مناسب باشد. + +### ۱۰.۲. ساخت قالب از روی عکس + +جریان آینده: + +1. کاربر تصویر نمونه فاکتور را به AI می‌دهد. +2. AI schema و کاتالوگ componentها و bindingها را دریافت می‌کند. +3. ساختار تصویر را به componentهای حسابیکس نگاشت می‌کند. +4. موارد نامطمئن را همراه confidence اعلام می‌کند. +5. یک draft ایجاد می‌کند. +6. حسابیکس draft را validate و compile می‌کند. +7. AI یا کاربر preview را بررسی و patchهای اصلاحی اعمال می‌کنند. +8. انتشار فقط پس از تأیید کاربر انجام می‌شود. + +AI نباید عبارت دیده‌شده در تصویر را بدون کنترل به متغیر Jinja تبدیل کند. نگاشت باید فقط به binding catalog رسمی انجام شود. + +## ۱۱. امنیت + +مسیر استودیوی ساختاریافته و MCP نباید این موارد را بپذیرد: + +- JavaScript؛ +- Jinja expression آزاد؛ +- CSS دلخواه؛ +- URL خارجی تأییدنشده؛ +- فونت یا asset ثبت‌نشده؛ +- نام binding خارج از catalog؛ +- component ناشناخته؛ +- مختصات یا اندازه خارج از محدوده؛ +- انتشار بدون permission و تأیید کاربر. + +styleها باید از propertyهای whitelist‌شده و design tokenهای حسابیکس ساخته شوند. + +## ۱۲. نسخه‌بندی، migration و هم‌زمانی + +- schema باید migration یک‌طرفه و تست‌شده داشته باشد. +- مهاجرت قالب v3 به نسخه بعدی نباید قالب قبلی را overwrite کند. +- هنگام بازکردن قالب قدیمی، migration در حافظه یا روی draft جدید انجام شود. +- هر draft باید `revision` داشته باشد. +- patch با `base_revision` قدیمی باید conflict برگرداند. +- منشأ تغییر باید `user`، `migration`، `api` یا `ai` ثبت شود. +- قالب منتشرشده immutable باشد و ویرایش بعدی draft جدید بسازد. + +## ۱۳. محدوده پیشنهادی اجرای فعلی + +پیشنهاد این سند این است که اجرای فعلی در پایان **فاز ۱** متوقف و برای تست واقعی کاربران تحویل شود. + +### فاز ۰ — قرارداد معماری و schema + +این فاز باید قبل از توسعه بیشتر UI انجام شود: + +- [ ] تصویب نهایی اصول این سند توسط تیم؛ +- [x] تعریف schema نسخه بعدی و JSON Schema رسمی؛ +- [x] تعریف container tree و component node؛ +- [x] تعریف component catalog و binding catalog؛ +- [x] تعریف media profile و variant inheritance؛ +- [x] تثبیت قرارداد compiler با خروجی انحصاری HTML/CSS؛ +- [x] تعریف migration از v3 به‌صورت copy-on-write و بدون overwrite؛ +- [x] تعریف diagnostics استاندارد validator/compiler. + +### فاز ۱ — MVP ویرایشگر آینده‌نگر + +- [x] پشتیبانی compiler از schema جدید؛ +- [x] تبدیل سطح طراحی v4 به گرید تمام‌صفحه؛ +- [x] حفظ grouping معنایی header/body/footer بدون شکستن بوم به سه Flow قابل‌مشاهده؛ +- [x] پشتیبانی از componentهای ثابت و پویا روی همان گرید؛ +- [x] drag و resize میلی‌متری همهٔ عناصر؛ +- [x] انتخاب گرید ۱، ۳ و ۵ میلی‌متری؛ +- [x] Snap به گرید، حاشیه، لبه و مرکز siblingها؛ +- [x] نمایش guide هنگام Snap؛ +- [x] clamp کامل حرکت و resize داخل container؛ +- [x] Undo/Redo با یک entry برای هر gesture؛ +- [x] پنل عددی X/Y/W/H؛ +- [x] تولید HTML preview از compiler رسمی؛ +- [x] کنترل نهایی با PDF preview موجود؛ +- [x] variant مستقل برای تمام کاغذهای صفحه‌ای، رول و سفارشی؛ +- [x] تست migration، validation، compiler، A4، رول ۸۰ و تعامل ویرایشگر. + +### موارد خارج از اجرای فعلی + +این موارد باید پس از دریافت بازخورد فاز ۱ انجام شوند: + +- multi-select و group؛ +- equal-spacing و baseline snapping؛ +- constraint solver؛ +- collaboration هم‌زمان؛ +- patch API عمومی؛ +- revision conflict و audit کامل AI؛ +- MCP server؛ +- تحلیل تصویر و تولید قالب توسط vision AI؛ +- انتشار قالب توسط AI؛ +- marketplace برای componentهای شخص ثالث. + +## ۱۴. معیار پذیرش فاز ۱ + +فاز ۱ زمانی کامل است که: + +1. قالب v3 بدون از دست رفتن محتوا به draft جدید مهاجرت کند. +2. خروجی رسمی همچنان فقط HTML/CSS باشد. +3. HTML و PDF از یک Design Document و compiler واحد تولید شوند. +4. جدول با تعداد اقلام متغیر باعث هم‌پوشانی جمع‌بندی نشود. +5. عنصر ثابت با ماوس حرکت و resize شود. +6. Snap گرید و Snap لبه/مرکز قابل مشاهده و قابل غیرفعال‌کردن باشند. +7. موقعیت و اندازه خارج از محدوده ذخیره نشود. +8. RTL/LTR هندسه فیزیکی را تغییر ناخواسته ندهد. +9. هر gesture فقط یک مرحله Undo بسازد. +10. A4 و رول ۸۰ میلی‌متری با PDF واقعی آزمایش شوند. +11. قالب‌های قدیمی بدون overwrite باقی بمانند. +12. schema و compiler تست‌های deterministic داشته باشند. + +## ۱۵. تصمیم پیشنهادی برای اکنون + +در حال حاضر نباید MCP یا تولید قالب از روی عکس پیاده‌سازی شود. اقدام درست این است که ابتدا فاز ۰ و فاز ۱ تکمیل شوند؛ زیرا MCP بدون schema پایدار و patch service معتبر، فقط بدهی فنی را از UI به AI منتقل می‌کند. + +ترتیب پیشنهادی اجرای نزدیک: + +1. تصویب این سند و تثبیت schema؛ +2. نوشتن validator، normalizer و migration؛ +3. تکمیل compiler HTML/CSS؛ +4. ساخت گرید تمام‌صفحه و Snap MVP؛ +5. تست با A4 و رول ۸۰؛ +6. تحویل به کاربران منتخب و دریافت بازخورد؛ +7. تصمیم‌گیری درباره responsive variant و patch API؛ +8. سپس طراحی MCP. + +این مرزبندی باعث می‌شود قابلیت فعلی قابل استفاده باقی بماند و در عین حال پایه‌ای ساخته شود که بعداً بدون بازنویسی کامل، AI و MCP روی آن قرار بگیرند. diff --git a/hesabixAPI/adapters/api/v1/report_templates.py b/hesabixAPI/adapters/api/v1/report_templates.py index bbd02f22..52ba93d4 100755 --- a/hesabixAPI/adapters/api/v1/report_templates.py +++ b/hesabixAPI/adapters/api/v1/report_templates.py @@ -23,6 +23,10 @@ from app.services.report_template_v3_service import ( migrate_v2_design_to_v3, studio_block_catalog, ) +from app.services.report_template_v4_service import ( + migrate_v3_design_to_v4, + studio_v4_contract, +) from app.services.template_design_v3_compiler import compile_template_design_to_jinja_html router = APIRouter(prefix="/report-templates", tags=["قالب‌های گزارش", "گزارش‌ها"]) @@ -1106,7 +1110,9 @@ async def report_template_gallery( items = list_gallery_items(module_key=module_key, subtype=subtype) for item in items: try: - item["studio_design"] = migrate_v2_design_to_v3(item["default_design"]) + item["studio_design"] = migrate_v3_design_to_v4( + migrate_v2_design_to_v3(item["default_design"]) + ) except ValueError: # Scopeهایی که هنوز وارد Studio v3 نشده‌اند، با ویرایشگر v2 باز می‌شوند. pass @@ -1129,6 +1135,22 @@ async def report_template_studio_blocks( return {"items": studio_block_catalog(module_key, subtype)} +@router.get( + "/business/{business_id}/studio-contract", + summary="قرارداد schema، compiler، component و binding استودیو v4", +) +@require_business_access("business_id") +async def report_template_studio_contract( + request: Request, + business_id: int, + module_key: str, + subtype: Optional[str] = None, + ctx: AuthContext = Depends(get_current_user), + db: Session = Depends(get_db), +): + return studio_v4_contract(module_key, subtype) + + @router.post( "/business/{business_id}/validate-v2-design", summary="اعتبارسنجی طراحی Studio v2", @@ -1259,6 +1281,31 @@ async def migrate_v2_to_v3_endpoint( return {"design": migrated} +@router.post( + "/business/{business_id}/migrate-v3-to-v4", + summary="تبدیل غیرمخرب طراحی Studio v3 به v4", + description="فقط یک design جدید برمی‌گرداند و قالب اصلی را تغییر نمی‌دهد.", +) +@require_business_access("business_id") +async def migrate_v3_to_v4_endpoint( + request: Request, + business_id: int, + body: Dict[str, Any] = Body(...), + ctx: AuthContext = Depends(get_current_user), + db: Session = Depends(get_db), +): + if not ctx.can_write_section("report_templates"): + raise ApiError("FORBIDDEN", "Missing permission: report_templates.write", http_status=403) + design = (body or {}).get("design") or {} + if not isinstance(design, dict): + raise ApiError("VALIDATION_ERROR", "design must be an object", http_status=400) + try: + migrated = migrate_v3_design_to_v4(design) + except Exception as ex: + raise ApiError("MIGRATION_ERROR", str(ex), http_status=400) + return {"design": migrated, "source_preserved": True} + + @router.post( "/business/{business_id}/migrate-builder-to-v2", summary="تبدیل طراحی Builder قدیمی به Studio v2", diff --git a/hesabixAPI/app/services/report_template_service.py b/hesabixAPI/app/services/report_template_service.py index f32ecced..378ed8ad 100755 --- a/hesabixAPI/app/services/report_template_service.py +++ b/hesabixAPI/app/services/report_template_service.py @@ -20,6 +20,7 @@ from app.services.template_design_v3_compiler import compile_template_design_to_ from app.services.report_template_scope_registry import get_scope_meta, is_known_scope from app.services.report_template_v2_service import validate_v2_design from app.services.report_template_v3_service import is_v3_design, validate_v3_design +from app.services.report_template_v4_service import is_v4_design, validate_v4_design logger = logging.getLogger(__name__) @@ -220,6 +221,8 @@ class ReportTemplateService: subtype: Optional[str], design: Dict[str, Any], ) -> Dict[str, List[str]]: + if is_v4_design(design): + return validate_v4_design(module_key, subtype, design) if is_v3_design(design): return validate_v3_design(module_key, subtype, design) return validate_v2_design(module_key, subtype, design) diff --git a/hesabixAPI/app/services/report_template_v3_service.py b/hesabixAPI/app/services/report_template_v3_service.py index 1a79a245..0594e4b8 100644 --- a/hesabixAPI/app/services/report_template_v3_service.py +++ b/hesabixAPI/app/services/report_template_v3_service.py @@ -186,7 +186,11 @@ def _block(block_id: str, block_type: str, props: dict[str, Any] | None = None) "type": block_type, "visible": True, "props": deepcopy(props or {}), - "style": {"width_mode": "full"}, + "style": { + "width_mode": "full", + "row_id": f"row-{block_id}", + "grid_span": 60, + }, } @@ -299,6 +303,7 @@ def validate_v3_design( if not isinstance(blocks, list): errors.append(f"regions.{region_name} must be a list") continue + row_spans: dict[str, int] = {} for index, block in enumerate(blocks): if not isinstance(block, dict): errors.append(f"Invalid block in {region_name} at index {index}") @@ -329,6 +334,30 @@ 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}'") + row_id = str(style.get("row_id") or "").strip() + if row_id and not _ID_RE.fullmatch(row_id): + errors.append(f"Invalid row id in block '{block_id}'") + if style.get("grid_span") not in (None, ""): + try: + grid_span = int(style.get("grid_span")) + except (TypeError, ValueError): + errors.append(f"Invalid grid span in block '{block_id}'") + else: + if grid_span < 1 or grid_span > 60: + errors.append(f"Invalid grid span in block '{block_id}'") + elif row_id: + row_spans[row_id] = row_spans.get(row_id, 0) + grid_span + row_height_mode = str(style.get("row_height_mode") or "auto").strip().lower() + if row_height_mode not in ("auto", "minimum", "fixed"): + errors.append(f"Invalid row height mode in block '{block_id}'") + if row_height_mode in ("minimum", "fixed"): + try: + row_height_mm = float(style.get("row_height_mm")) + except (TypeError, ValueError): + errors.append(f"Row height is required in block '{block_id}'") + else: + if row_height_mm < 4 or row_height_mm > 500: + errors.append(f"Invalid row height 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}'") @@ -369,6 +398,11 @@ def validate_v3_design( errors.append(f"Invalid totals expression in row {row_index}: {ex.message}") if block_type == "custom_text" and len(str(props.get("text") or "")) > 2000: errors.append(f"Custom text is too long in block '{block_id}'") + for row_id, span in row_spans.items(): + if span > 60: + errors.append( + f"Grid row '{row_id}' in region '{region_name}' exceeds 60 columns" + ) for block_type, definition in _BLOCKS.items(): count = counts.get(block_type, 0) diff --git a/hesabixAPI/app/services/report_template_v4_service.py b/hesabixAPI/app/services/report_template_v4_service.py new file mode 100644 index 00000000..5e9e8e84 --- /dev/null +++ b/hesabixAPI/app/services/report_template_v4_service.py @@ -0,0 +1,753 @@ +from __future__ import annotations + +from copy import deepcopy +from typing import Any, Iterable + +from app.services.report_template_gallery import get_family +from app.services.report_template_v3_service import ( + _validate_media, + is_v3_design, + studio_block_catalog, + validate_v3_design, +) + +SCHEMA_VERSION = 4 +COMPILER_NAME = "hesabix-template-html-css" +COMPILER_VERSION = 1 +GRID_COLUMNS = 60 + +_SHEET_SIZES: dict[str, tuple[float, float]] = { + "A3": (297, 420), + "A4": (210, 297), + "A5": (148, 210), + "A6": (105, 148), + "Letter": (215.9, 279.4), + "Legal": (215.9, 355.6), +} +_ROLL_WIDTHS = (58, 60, 80, 100) +_REGIONS = ("header", "body", "footer") +_CONTAINER_LAYOUTS = {"flow", "grid", "freeform", "stack", "page_grid"} +_FREEFORM_COMPONENTS = { + "brand_header", + "party_info", + "note", + "signatures", + "qr", + "footer_meta", + "custom_text", + "divider", + "spacer", +} + + +def is_v4_design(design: dict[str, Any]) -> bool: + try: + return int(design.get("schema_version") or 0) == SCHEMA_VERSION + except Exception: + return False + + +def _profile_key(media: dict[str, Any]) -> str: + media_type = str(media.get("type") or "sheet").lower() + if media_type == "roll": + try: + width = float(media.get("width_mm") or 80) + except (TypeError, ValueError): + return "custom_roll" + for preset in _ROLL_WIDTHS: + if abs(width - preset) < 0.01: + return f"roll_{preset}" + return "custom_roll" + preset = str(media.get("preset") or "A4") + orientation = "landscape" if media.get("orientation") == "landscape" else "portrait" + if preset in _SHEET_SIZES: + return f"{preset.lower()}_{orientation}" + return f"custom_sheet_{orientation}" + + +def media_profile_catalog() -> list[dict[str, Any]]: + items: list[dict[str, Any]] = [] + for preset, (width, height) in _SHEET_SIZES.items(): + for orientation in ("portrait", "landscape"): + items.append( + { + "key": f"{preset.lower()}_{orientation}", + "label": f"{preset} {'افقی' if orientation == 'landscape' else 'عمودی'}", + "media": { + "type": "sheet", + "preset": preset, + "width_mm": width, + "height_mm": height, + "orientation": orientation, + "margins_mm": {"top": 10, "right": 10, "bottom": 10, "left": 10}, + }, + } + ) + for width in _ROLL_WIDTHS: + items.append( + { + "key": f"roll_{width}", + "label": f"رول {width} میلی‌متر", + "media": { + "type": "roll", + "preset": f"{width}mm", + "width_mm": width, + "height_mode": "auto", + "orientation": "portrait", + "margins_mm": {"top": 3, "right": 2, "bottom": 4, "left": 2}, + }, + } + ) + items.extend( + [ + {"key": "custom_sheet_portrait", "label": "صفحه سفارشی عمودی", "custom": True}, + {"key": "custom_sheet_landscape", "label": "صفحه سفارشی افقی", "custom": True}, + {"key": "custom_roll", "label": "رول سفارشی", "custom": True}, + ] + ) + return items + + +def component_catalog(module_key: str, subtype: str | None) -> list[dict[str, Any]]: + items = [] + for item in studio_block_catalog(module_key, subtype): + next_item = deepcopy(item) + next_item["component"] = str(next_item.pop("type")) + next_item["allowed_containers"] = ["page_grid"] + items.append(next_item) + return items + + +def binding_catalog(module_key: str, subtype: str | None) -> list[dict[str, Any]]: + if module_key != "invoices" or (subtype or "") not in ("detail", "receipt"): + return [] + return [ + {"key": "title_text", "type": "string", "label_fa": "عنوان فاکتور"}, + {"key": "business_name", "type": "string", "label_fa": "نام کسب‌وکار"}, + {"key": "invoice.code", "type": "string", "label_fa": "شماره فاکتور"}, + {"key": "invoice.issue_date", "type": "date", "label_fa": "تاریخ فاکتور"}, + {"key": "buyer.name", "type": "string", "label_fa": "نام خریدار"}, + {"key": "seller.name", "type": "string", "label_fa": "نام فروشنده"}, + {"key": "lines", "type": "collection", "label_fa": "اقلام فاکتور"}, + {"key": "payments", "type": "collection", "label_fa": "پرداخت‌ها"}, + {"key": "invoice_footer_note", "type": "string", "label_fa": "یادداشت فاکتور"}, + {"key": "invoice_verify_qr_data_uri", "type": "asset", "label_fa": "QR اعتبارسنجی"}, + {"key": "generated_at", "type": "datetime", "label_fa": "زمان تولید"}, + {"key": "issuer_name", "type": "string", "label_fa": "تنظیم‌کننده"}, + ] + + +def studio_v4_contract(module_key: str, subtype: str | None) -> dict[str, Any]: + return { + "schema_version": SCHEMA_VERSION, + "compiler": {"name": COMPILER_NAME, "version": COMPILER_VERSION, "output": "html_css"}, + "grid_columns": GRID_COLUMNS, + "container_types": sorted(_CONTAINER_LAYOUTS), + "freeform": { + "legacy": True, + "grid_sizes_mm": [1, 3, 5], + "snap_targets": ["grid", "safe_margin", "sibling_edge", "sibling_center"], + "position_unit": "mm", + "dynamic_components_allowed": False, + }, + "page_grid": { + "grid_sizes_mm": [1, 3, 5], + "snap_targets": ["grid", "safe_margin", "sibling_edge", "sibling_center"], + "position_unit": "mm", + "dynamic_components_allowed": True, + }, + "components": component_catalog(module_key, subtype), + "bindings": binding_catalog(module_key, subtype), + "media_profiles": media_profile_catalog(), + "json_schema": _json_schema(), + } + + +def _json_schema() -> dict[str, Any]: + return { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hesabix.ir/schemas/report-template-studio-v4.json", + "title": "Hesabix report template design v4", + "type": "object", + "required": ["schema_version", "compiler_contract", "root", "variants", "media"], + "properties": { + "schema_version": {"const": SCHEMA_VERSION}, + "compiler_contract": { + "type": "object", + "required": ["name", "version", "output"], + "properties": { + "name": {"const": COMPILER_NAME}, + "version": {"const": COMPILER_VERSION}, + "output": {"const": "html_css"}, + }, + }, + "root": {"$ref": "#/$defs/node"}, + "variants": {"type": "object", "additionalProperties": {"$ref": "#/$defs/variant"}}, + "media": {"type": "object"}, + }, + "$defs": { + "node": { + "type": "object", + "required": ["id", "kind"], + "properties": { + "id": {"type": "string", "pattern": "^[a-zA-Z0-9_-]{1,80}$"}, + "kind": {"enum": ["container", "component"]}, + "children": {"type": "array", "items": {"$ref": "#/$defs/node"}}, + "component": {"type": "string"}, + "layout": {"type": "object"}, + "placement": {"type": "object"}, + }, + }, + "variant": { + "type": "object", + "required": ["media", "node_overrides"], + "properties": {"media": {"type": "object"}, "node_overrides": {"type": "object"}}, + }, + }, + } + + +def _iter_nodes(node: dict[str, Any]) -> Iterable[dict[str, Any]]: + yield node + for child in node.get("children") or []: + if isinstance(child, dict): + yield from _iter_nodes(child) + + +def _row_layout_from_v3(block: dict[str, Any]) -> dict[str, Any]: + style = block.get("style") or {} + height_mode = str(style.get("row_height_mode") or "auto") + layout: dict[str, Any] = {"type": "grid", "columns": GRID_COLUMNS, "gap_mm": 0} + if height_mode in ("minimum", "fixed"): + layout["height_mode"] = height_mode + layout["height_mm"] = float(style.get("row_height_mm") or 20) + return layout + + +def _component_from_v3(block: dict[str, Any]) -> dict[str, Any]: + style = deepcopy(block.get("style") or {}) + span = int(style.pop("grid_span", GRID_COLUMNS) or GRID_COLUMNS) + style.pop("row_id", None) + style.pop("row_height_mode", None) + style.pop("row_height_mm", None) + return { + "id": str(block.get("id") or "component"), + "kind": "component", + "component": str(block.get("type") or ""), + "visible": block.get("visible", True) is not False, + "props": deepcopy(block.get("props") or {}), + "style": style, + "placement": {"column_span": max(1, min(GRID_COLUMNS, span))}, + } + + +def _printable_size(media: dict[str, Any]) -> tuple[float, float]: + try: + width = float(media.get("width_mm") or 210) + except (TypeError, ValueError): + width = 210 + try: + height = float(media.get("height_mm") or (300 if media.get("type") == "roll" else 297)) + except (TypeError, ValueError): + height = 300 if media.get("type") == "roll" else 297 + if media.get("type") != "roll" and media.get("orientation") == "landscape": + width, height = height, width + margins = media.get("margins_mm") or {} + try: + width -= float(margins.get("left") or 0) + float(margins.get("right") or 0) + height -= float(margins.get("top") or 0) + float(margins.get("bottom") or 0) + except (TypeError, ValueError): + pass + return max(10, width), max(20, height) + + +def _default_component_height(component: str) -> float: + return { + "brand_header": 30, + "party_info": 24, + "invoice_lines": 72, + "invoice_totals": 38, + "payments": 24, + "note": 22, + "signatures": 38, + "qr": 34, + "footer_meta": 14, + "custom_text": 18, + "divider": 4, + "spacer": 10, + }.get(component, 20) + + +def _base_root_from_v3(design: dict[str, Any]) -> dict[str, Any]: + printable_width, printable_height = _printable_size(design.get("media") or {}) + region_nodes: list[dict[str, Any]] = [] + cursor_y = 0.0 + regions = design.get("regions") or {} + for region_name in _REGIONS: + rows: list[dict[str, Any]] = [] + for block in regions.get(region_name) or []: + if not isinstance(block, dict): + continue + style = block.get("style") or {} + row_id = str(style.get("row_id") or f"row-{block.get('id')}") + if not rows or rows[-1]["id"] != row_id: + rows.append( + { + "id": row_id, + "kind": "container", + "layout": _row_layout_from_v3(block), + "children": [], + } + ) + component = _component_from_v3(block) + rows[-1]["children"].append(component) + for row in rows: + children = row.get("children") or [] + row_height = max( + [_default_component_height(str(child.get("component") or "")) for child in children] or [20] + ) + layout = row.get("layout") or {} + if layout.get("height_mode") in ("minimum", "fixed"): + try: + row_height = max(row_height, float(layout.get("height_mm") or row_height)) + except (TypeError, ValueError): + pass + cursor_x = 0.0 + for child in children: + placement = child.get("placement") or {} + span = max(1, min(GRID_COLUMNS, int(placement.get("column_span") or GRID_COLUMNS))) + width = printable_width * span / GRID_COLUMNS + child["placement"] = { + **placement, + "x_mm": round(cursor_x, 3), + "y_mm": round(cursor_y, 3), + "width_mm": round(width, 3), + "height_mm": round(row_height, 3), + } + cursor_x += width + cursor_y += row_height + 3 + region_nodes.append( + { + "id": f"region-{region_name}", + "kind": "container", + "region": region_name, + "layout": {"type": "flow", "gap_mm": 2}, + "children": rows, + } + ) + if (design.get("media") or {}).get("type") != "roll" and cursor_y > printable_height: + vertical_ratio = printable_height / cursor_y + for region_node in region_nodes: + for node in _iter_nodes(region_node): + if node.get("kind") != "component": + continue + placement = node.get("placement") or {} + placement["y_mm"] = round(float(placement.get("y_mm") or 0) * vertical_ratio, 3) + placement["height_mm"] = round(max(4, float(placement.get("height_mm") or 20) * vertical_ratio), 3) + cursor_y = printable_height + return { + "id": "invoice-root", + "kind": "container", + "layout": { + "type": "page_grid", + "grid_mm": 1, + "snap": True, + "width_mm": round(printable_width, 3), + "height_mm": round(max(printable_height, cursor_y), 3), + }, + "children": region_nodes, + } + + +def _full_overrides( + root: dict[str, Any], + *, + media: dict[str, Any], + base_width: float, + base_height: float, + narrow: bool, +) -> dict[str, dict[str, Any]]: + overrides: dict[str, dict[str, Any]] = {} + printable_width, printable_height = _printable_size(media) + stack_y = 0.0 + content_bottom = 0.0 + for node in _iter_nodes(root): + node_id = str(node.get("id") or "") + if not node_id: + continue + if node.get("kind") == "container": + layout = deepcopy(node.get("layout") or {}) + if node_id == str(root.get("id") or ""): + layout.update( + { + "type": "page_grid", + "width_mm": round(printable_width, 3), + "height_mm": round(max(printable_height, stack_y), 3), + } + ) + overrides[node_id] = {"layout": layout} + else: + placement = deepcopy(node.get("placement") or {}) + if narrow: + placement["column_span"] = GRID_COLUMNS + height = float(placement.get("height_mm") or _default_component_height(str(node.get("component") or ""))) + placement.update( + { + "x_mm": 0, + "y_mm": round(stack_y, 3), + "width_mm": round(printable_width, 3), + "height_mm": round(height, 3), + } + ) + stack_y += height + 3 + else: + ratio = printable_width / max(1, base_width) + vertical_ratio = printable_height / max(1, base_height) + placement.update( + { + "x_mm": round(float(placement.get("x_mm") or 0) * ratio, 3), + "y_mm": round(float(placement.get("y_mm") or 0) * vertical_ratio, 3), + "width_mm": round(float(placement.get("width_mm") or base_width) * ratio, 3), + "height_mm": round(max(4, float(placement.get("height_mm") or 20) * vertical_ratio), 3), + } + ) + content_bottom = max( + content_bottom, + float(placement.get("y_mm") or 0) + float(placement.get("height_mm") or 0), + ) + overrides[node_id] = {"placement": placement} + root_id = str(root.get("id") or "") + if root_id and root_id in overrides: + overrides[root_id]["layout"]["height_mm"] = round( + max(printable_height, stack_y if narrow else content_bottom), + 3, + ) + return overrides + + +def migrate_v3_design_to_v4(design: dict[str, Any]) -> dict[str, Any]: + if is_v4_design(design): + return deepcopy(design) + if not is_v3_design(design): + raise ValueError("Only template design v3 can be migrated to v4") + root = _base_root_from_v3(design) + base_width = float((root.get("layout") or {}).get("width_mm") or 190) + base_height = float((root.get("layout") or {}).get("height_mm") or 277) + variants: dict[str, Any] = {} + for profile in media_profile_catalog(): + key = str(profile["key"]) + media = deepcopy(profile.get("media") or design.get("media") or {}) + variants[key] = { + "media": media, + "node_overrides": _full_overrides( + root, + media=media, + base_width=base_width, + base_height=base_height, + narrow=key.startswith("roll_") or key == "custom_roll", + ), + } + active = _profile_key(design.get("media") or {}) + if active in variants: + variants[active]["media"] = deepcopy(design.get("media") or variants[active]["media"]) + return { + "schema_version": SCHEMA_VERSION, + "family_id": design.get("family_id"), + "layout": design.get("layout"), + "theme": deepcopy(design.get("theme") or {}), + "branding": deepcopy(design.get("branding") or {}), + "custom_css": str(design.get("custom_css") or ""), + "media": deepcopy(design.get("media") or {}), + "active_variant": active, + "compiler_contract": {"name": COMPILER_NAME, "version": COMPILER_VERSION, "output": "html_css"}, + "root": root, + "variants": variants, + "migration": {"from_schema_version": 3, "mode": "copy_on_write"}, + } + + +def active_variant_key(design: dict[str, Any]) -> str: + computed = _profile_key(design.get("media") or {}) + variants = design.get("variants") or {} + if computed in variants: + return computed + configured = str(design.get("active_variant") or "") + return configured if configured in variants else computed + + +def resolved_root(design: dict[str, Any]) -> dict[str, Any]: + root = deepcopy(design.get("root") or {}) + variant = (design.get("variants") or {}).get(active_variant_key(design)) or {} + overrides = variant.get("node_overrides") or {} + for node in _iter_nodes(root): + override = overrides.get(str(node.get("id") or "")) or {} + for key in ("layout", "placement", "style"): + if isinstance(override.get(key), dict): + node[key] = {**(node.get(key) or {}), **deepcopy(override[key])} + return root + + +def v4_to_v3_projection(design: dict[str, Any]) -> dict[str, Any]: + root = resolved_root(design) + regions: dict[str, list[dict[str, Any]]] = {key: [] for key in _REGIONS} + for region_node in root.get("children") or []: + if not isinstance(region_node, dict): + continue + region_name = str(region_node.get("region") or "") + if region_name not in regions: + continue + for row in region_node.get("children") or []: + if not isinstance(row, dict): + continue + layout = row.get("layout") or {} + for component in row.get("children") or []: + if not isinstance(component, dict) or component.get("kind") != "component": + continue + placement = component.get("placement") or {} + style = deepcopy(component.get("style") or {}) + style.update( + { + # The v3 projection is used for component/property validation and + # theme CSS only. A responsive v4 grid is allowed to wrap (for + # example two 60-column cells on roll media), while v3 rows were + # required to total at most 60 columns. + "row_id": f"{row.get('id')}-{component.get('id')}", + "layout_type": layout.get("type", "grid"), + "grid_span": placement.get("column_span", GRID_COLUMNS), + } + ) + if layout.get("height_mode"): + style["row_height_mode"] = layout.get("height_mode") + style["row_height_mm"] = layout.get("height_mm") + if layout.get("type") == "freeform": + style.update( + { + "freeform_grid_mm": layout.get("grid_mm", 1), + "freeform_snap": layout.get("snap", True), + "freeform_height_mm": layout.get("height_mm", 40), + "x_mm": placement.get("x_mm", 0), + "y_mm": placement.get("y_mm", 0), + "width_mm": placement.get("width_mm", 30), + "height_mm": placement.get("height_mm", 15), + } + ) + regions[region_name].append( + { + "id": component.get("id"), + "type": component.get("component"), + "visible": component.get("visible", True), + "props": deepcopy(component.get("props") or {}), + "style": style, + } + ) + return { + "schema_version": 3, + "family_id": design.get("family_id"), + "layout": design.get("layout"), + "theme": deepcopy(design.get("theme") or {}), + "branding": deepcopy(design.get("branding") or {}), + "custom_css": str(design.get("custom_css") or ""), + "media": deepcopy(design.get("media") or {}), + "regions": regions, + } + + +def validate_v4_design(module_key: str, subtype: str | None, design: dict[str, Any]) -> dict[str, list[str]]: + errors: list[str] = [] + warnings: list[str] = [] + if not isinstance(design, dict) or not is_v4_design(design): + return {"errors": ["schema_version must be 4"], "warnings": []} + contract = design.get("compiler_contract") or {} + if contract != {"name": COMPILER_NAME, "version": COMPILER_VERSION, "output": "html_css"}: + errors.append("Unsupported compiler_contract") + errors.extend(_validate_media(design.get("media"))) + root = design.get("root") + if not isinstance(root, dict) or root.get("kind") != "container": + return {"errors": errors + ["root must be a container"], "warnings": warnings} + definitions = {item["component"]: item for item in component_catalog(module_key, subtype)} + seen: set[str] = set() + component_counts: dict[str, int] = {} + for node in _iter_nodes(root): + node_id = str(node.get("id") or "") + if not node_id or len(node_id) > 80 or not all(ch.isalnum() or ch in "_-" for ch in node_id): + errors.append(f"Invalid node id: {node_id}") + elif node_id in seen: + errors.append(f"Duplicate node id: {node_id}") + seen.add(node_id) + kind = node.get("kind") + if kind == "container": + if not isinstance(node.get("children"), list): + errors.append(f"Container '{node_id}' children must be a list") + layout = node.get("layout") or {} + if not isinstance(layout, dict): + errors.append(f"Container '{node_id}' layout must be an object") + continue + layout_type = str(layout.get("type") or "") + if layout_type not in _CONTAINER_LAYOUTS: + errors.append(f"Invalid layout type in '{node_id}'") + if layout_type == "grid": + try: + columns = int(layout.get("columns") or GRID_COLUMNS) + except (TypeError, ValueError): + columns = 0 + if columns != GRID_COLUMNS: + errors.append(f"Grid container '{node_id}' must have 60 columns") + if layout_type == "freeform": + try: + height_mm = float(layout.get("height_mm") or 0) + except (TypeError, ValueError): + height_mm = 0 + try: + grid_mm = int(layout.get("grid_mm") or 1) + except (TypeError, ValueError): + grid_mm = 0 + if height_mm < 4: + errors.append(f"Freeform container '{node_id}' needs a fixed height") + if grid_mm not in (1, 3, 5): + errors.append(f"Invalid freeform grid in '{node_id}'") + for child in node.get("children") or []: + if isinstance(child, dict) and child.get("component") not in _FREEFORM_COMPONENTS: + errors.append(f"{child.get('component')} cannot be placed in a freeform container") + if layout_type == "page_grid": + try: + grid_mm = int(layout.get("grid_mm") or 1) + except (TypeError, ValueError): + grid_mm = 0 + if node is not root: + errors.append("page_grid is only allowed on the document root") + if grid_mm not in (1, 3, 5): + errors.append("Page grid size must be 1, 3 or 5 millimeters") + elif kind == "component": + component = str(node.get("component") or "") + for field in ("props", "style", "placement"): + if node.get(field) is not None and not isinstance(node.get(field), dict): + errors.append(f"Component '{node_id}' {field} must be an object") + definition = definitions.get(component) + if not definition: + errors.append(f"Unknown component: {component}") + else: + component_counts[component] = component_counts.get(component, 0) + 1 + else: + errors.append(f"Invalid node kind in '{node_id}'") + variants = design.get("variants") + if not isinstance(variants, dict): + errors.append("variants must be an object") + else: + required_profiles = {str(item["key"]) for item in media_profile_catalog()} + missing = required_profiles.difference(variants) + if missing: + errors.append("Missing responsive variants: " + ", ".join(sorted(missing))) + for profile_key, variant in variants.items(): + if not isinstance(variant, dict): + errors.append(f"Invalid variant: {profile_key}") + continue + overrides = variant.get("node_overrides") or {} + if not isinstance(overrides, dict): + errors.append(f"Variant '{profile_key}' node_overrides must be an object") + continue + unknown = set(overrides).difference(seen) + if unknown: + errors.append(f"Variant '{profile_key}' refers to unknown nodes") + missing_overrides = seen.difference(overrides) + if missing_overrides: + errors.append(f"Variant '{profile_key}' is missing explicit node overrides") + for node_id, override in overrides.items(): + if not isinstance(override, dict): + errors.append(f"Invalid override for '{node_id}' in '{profile_key}'") + continue + placement = (override or {}).get("placement") or {} + if "column_span" in placement: + try: + span = int(placement.get("column_span") or 0) + except (TypeError, ValueError): + span = 0 + if span < 1 or span > GRID_COLUMNS: + errors.append(f"Invalid column span for '{node_id}' in '{profile_key}'") + for key in ("x_mm", "y_mm", "width_mm", "height_mm"): + if key in placement: + try: + value = float(placement[key]) + except (TypeError, ValueError): + value = -1 + if value < 0: + errors.append(f"Invalid {key} for '{node_id}' in '{profile_key}'") + variant_media = ( + design.get("media") or {} + if profile_key == active_variant_key(design) + else variant.get("media") if isinstance(variant.get("media"), dict) else design.get("media") or {} + ) + try: + printable_width, printable_height = _printable_size(variant_media) + except (TypeError, ValueError): + printable_width = printable_height = 0 + root_layout = { + **(root.get("layout") or {}), + **((overrides.get(str(root.get("id") or "")) or {}).get("layout") or {}), + } + if root_layout.get("type") == "page_grid": + try: + canvas_width = float(root_layout.get("width_mm") or printable_width) + canvas_height = float(root_layout.get("height_mm") or printable_height) + except (TypeError, ValueError): + canvas_width = canvas_height = 0 + if canvas_width <= 0 or canvas_height <= 0: + errors.append(f"Invalid page grid dimensions in '{profile_key}'") + for component_node in _iter_nodes(root): + if component_node.get("kind") != "component": + continue + component_id = str(component_node.get("id") or "") + placement = { + **(component_node.get("placement") or {}), + **((overrides.get(component_id) or {}).get("placement") or {}), + } + try: + x = float(placement.get("x_mm")) + y = float(placement.get("y_mm")) + width = float(placement.get("width_mm")) + height = float(placement.get("height_mm")) + except (TypeError, ValueError): + errors.append(f"Missing page grid geometry for '{component_id}' in '{profile_key}'") + continue + if x < 0 or y < 0 or width < 1 or height < 1: + errors.append(f"Invalid page grid geometry for '{component_id}' in '{profile_key}'") + elif x + width > canvas_width + 0.001 or y + height > canvas_height + 0.001: + errors.append(f"Page grid item '{component_id}' exceeds its canvas in '{profile_key}'") + for node in _iter_nodes(root): + if node.get("kind") != "container": + continue + node_id = str(node.get("id") or "") + layout = {**(node.get("layout") or {}), **((overrides.get(node_id) or {}).get("layout") or {})} + if layout.get("type") != "freeform": + continue + try: + height = float(layout.get("height_mm") or 0) + except (TypeError, ValueError): + height = 0 + for child in node.get("children") or []: + if not isinstance(child, dict): + continue + child_id = str(child.get("id") or "") + placement = { + **(child.get("placement") or {}), + **((overrides.get(child_id) or {}).get("placement") or {}), + } + try: + x = float(placement.get("x_mm") or 0) + y = float(placement.get("y_mm") or 0) + width = float(placement.get("width_mm") or 0) + child_height = float(placement.get("height_mm") or 0) + except (TypeError, ValueError): + errors.append(f"Invalid freeform geometry for '{child_id}' in '{profile_key}'") + continue + if width < 1 or child_height < 1: + errors.append(f"Freeform item '{child_id}' has no usable size in '{profile_key}'") + if x + width > printable_width + 0.001 or y + child_height > height + 0.001: + errors.append(f"Freeform item '{child_id}' exceeds its container in '{profile_key}'") + # Reuse the mature component/property validation through a lossless projection. + try: + projection_result = validate_v3_design(module_key, subtype, v4_to_v3_projection(design)) + errors.extend(projection_result["errors"]) + warnings.extend(projection_result["warnings"]) + except Exception as ex: + errors.append(f"Invalid v4 structure: {ex}") + return {"errors": list(dict.fromkeys(errors)), "warnings": list(dict.fromkeys(warnings))} diff --git a/hesabixAPI/app/services/template_design_v3_compiler.py b/hesabixAPI/app/services/template_design_v3_compiler.py index 0e086568..754cb034 100644 --- a/hesabixAPI/app/services/template_design_v3_compiler.py +++ b/hesabixAPI/app/services/template_design_v3_compiler.py @@ -259,9 +259,16 @@ def _compile_block(design: dict[str, Any], block: dict[str, Any], *, receipt: bo align = str((block.get("props") or {}).get("align") or "").strip().lower() if align in ("right", "center", "left"): classes.append(f"rt-block-align-{align}") + grid_span = style.get("grid_span") + try: + grid_span = max(1, min(60, int(grid_span))) if grid_span not in (None, "") else None + except (TypeError, ValueError): + grid_span = None width_mode = str(style.get("width_mode") or "full").strip().lower() width_css = "width:100%;" - if width_mode == "percentage": + if grid_span is not None: + width_css += f"grid-column:span {grid_span};" + elif width_mode == "percentage": try: width_css = f"width:{max(10, min(100, float(style.get('width_value') or 100))):g}%;" except (TypeError, ValueError): @@ -276,6 +283,42 @@ def _compile_block(design: dict[str, Any], block: dict[str, Any], *, receipt: bo return f'
{content}
' +def _row_id(block: dict[str, Any]) -> str: + style = block.get("style") or {} + return str(style.get("row_id") or f"legacy-{block.get('id') or id(block)}") + + +def _compile_region(design: dict[str, Any], region: str, *, receipt: bool) -> str: + rows: list[list[dict[str, Any]]] = [] + for block in _blocks(design, region): + row_id = _row_id(block) + if not rows or _row_id(rows[-1][0]) != row_id: + rows.append([block]) + else: + rows[-1].append(block) + + compiled_rows: list[str] = [] + for blocks in rows: + style = blocks[0].get("style") or {} + has_grid = any( + (block.get("style") or {}).get("grid_span") not in (None, "") + for block in blocks + ) + row_class = "rt-grid-row" if has_grid else "rt-legacy-row" + height_mode = str(style.get("row_height_mode") or "auto").strip().lower() + height_css = "" + if height_mode in ("minimum", "fixed"): + try: + height = max(4, min(500, float(style.get("row_height_mm") or 4))) + except (TypeError, ValueError): + height = 4 + property_name = "height" if height_mode == "fixed" else "min-height" + height_css = f"{property_name}:{height:g}mm;" + content = "".join(_compile_block(design, block, receipt=receipt) for block in blocks) + compiled_rows.append(f'
{content}
') + return "".join(compiled_rows) + + def compile_v3_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, str, str]: if not is_v3_design(design): raise ValueError("Not a v3 design schema") @@ -302,21 +345,30 @@ def compile_v3_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, s .rt-layout table { width: 100%; table-layout: auto; } .rt-layout img { max-width: 100%; height: auto; } .rt-block { max-width: 100%; } +.rt-grid-row { display:grid;grid-template-columns:repeat(60,minmax(0,1fr));align-items:start;width:100%; } +.rt-grid-row > .rt-block { min-width:0; } +.rt-legacy-row { 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; } .rt-block-align-center, .rt-block-align-center * { text-align: center !important; } .rt-block-align-left, .rt-block-align-left * { text-align: left !important; } """ - header_html = "".join(_compile_block(design, block, receipt=receipt) for block in _blocks(design, "header")) - body = "".join(_compile_block(design, block, receipt=receipt) for block in _blocks(design, "body")) - footer_html = "".join(_compile_block(design, block, receipt=receipt) for block in _blocks(design, "footer")) + header_html = _compile_region(design, "header", receipt=receipt) + body = _compile_region(design, "body", receipt=receipt) + footer_html = _compile_region(design, "footer", receipt=receipt) body_html = f'
{body}
' html_doc = f'{body_html}' return html_doc, css.strip(), header_html, footer_html def compile_template_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, str, str]: + from app.services.report_template_v4_service import is_v4_design + + if is_v4_design(design): + from app.services.template_design_v4_compiler import compile_v4_design_to_jinja_html + + return compile_v4_design_to_jinja_html(design) if is_v3_design(design): return compile_v3_design_to_jinja_html(design) return v2.compile_v2_design_to_jinja_html(design) diff --git a/hesabixAPI/app/services/template_design_v4_compiler.py b/hesabixAPI/app/services/template_design_v4_compiler.py new file mode 100644 index 00000000..825a43d5 --- /dev/null +++ b/hesabixAPI/app/services/template_design_v4_compiler.py @@ -0,0 +1,238 @@ +from __future__ import annotations + +from html import escape +import math +from typing import Any + +from app.services.report_template_gallery import get_family +from app.services.report_template_v4_service import ( + COMPILER_NAME, + COMPILER_VERSION, + active_variant_key, + is_v4_design, + resolved_root, + v4_to_v3_projection, +) +from app.services.template_design_v3_compiler import ( + _compile_block_content, + compile_v3_design_to_jinja_html, +) + + +def _number(value: Any, default: float, minimum: float, maximum: float) -> float: + try: + return max(minimum, min(maximum, float(value))) + except (TypeError, ValueError): + return default + + +def _component_html(design: dict[str, Any], node: dict[str, Any], *, receipt: bool) -> str: + if node.get("visible", True) is False: + return "" + component = str(node.get("component") or "") + block = { + "id": node.get("id"), + "type": component, + "visible": node.get("visible", True), + "props": node.get("props") or {}, + "style": node.get("style") or {}, + } + content = _compile_block_content(design, block, receipt=receipt) + if not content: + return "" + style = node.get("style") or {} + align = str(style.get("text_align") or "").lower() + if not align and component == "custom_text": + align = str((node.get("props") or {}).get("align") or "").lower() + classes = ["rt-node", "rt-component", f"rt-component-{component.replace('_', '-')}"] + if align in ("right", "center", "left"): + classes.append(f"rt-block-align-{align}") + return ( + f'
{content}
' + ) + + +def _grid_container(design: dict[str, Any], node: dict[str, Any], *, receipt: bool) -> str: + layout = node.get("layout") or {} + gap = _number(layout.get("gap_mm"), 0, 0, 50) + height_mode = str(layout.get("height_mode") or "auto") + height_css = "" + if height_mode in ("minimum", "fixed"): + height = _number(layout.get("height_mm"), 20, 4, 500) + height_css = f"{'height' if height_mode == 'fixed' else 'min-height'}:{height:g}mm;" + children: list[str] = [] + for child in node.get("children") or []: + if not isinstance(child, dict) or child.get("kind") != "component": + continue + placement = child.get("placement") or {} + span = int(_number(placement.get("column_span"), 60, 1, 60)) + child_html = _component_html(design, child, receipt=receipt) + if child_html: + children.append(f'
{child_html}
') + return ( + f'
{"".join(children)}
' + ) + + +def _freeform_container(design: dict[str, Any], node: dict[str, Any], *, receipt: bool) -> str: + layout = node.get("layout") or {} + height = _number(layout.get("height_mm"), 40, 4, 500) + children: list[str] = [] + for child in node.get("children") or []: + if not isinstance(child, dict) or child.get("kind") != "component": + continue + if child.get("component") in ("invoice_lines", "invoice_totals", "payments"): + raise ValueError(f"Dynamic component '{child.get('component')}' cannot be compiled in freeform") + placement = child.get("placement") or {} + x = _number(placement.get("x_mm"), 0, 0, 500) + y = _number(placement.get("y_mm"), 0, 0, height) + width = _number(placement.get("width_mm"), 30, 1, 500) + child_height = _number(placement.get("height_mm"), 15, 1, height) + child_html = _component_html(design, child, receipt=receipt) + if child_html: + children.append( + f'
{child_html}
' + ) + return ( + f'
{"".join(children)}
' + ) + + +def _flow_or_stack_container(design: dict[str, Any], node: dict[str, Any], *, receipt: bool) -> str: + layout = node.get("layout") or {} + layout_type = str(layout.get("type") or "flow") + gap = _number(layout.get("gap_mm"), 0, 0, 50) + children = "".join(_node_html(design, child, receipt=receipt) for child in node.get("children") or [] if isinstance(child, dict)) + return ( + f'
{children}
' + ) + + +def _node_html(design: dict[str, Any], node: dict[str, Any], *, receipt: bool) -> str: + if node.get("kind") == "component": + return _component_html(design, node, receipt=receipt) + layout_type = str((node.get("layout") or {}).get("type") or "flow") + if layout_type == "grid": + return _grid_container(design, node, receipt=receipt) + if layout_type == "freeform": + return _freeform_container(design, node, receipt=receipt) + return _flow_or_stack_container(design, node, receipt=receipt) + + +def _page_grid_components( + node: dict[str, Any], + *, + region: str = "body", +) -> list[tuple[str, dict[str, Any]]]: + if node.get("kind") == "component": + return [(region, node)] + next_region = str(node.get("region") or region) + items: list[tuple[str, dict[str, Any]]] = [] + for child in node.get("children") or []: + if isinstance(child, dict): + items.extend(_page_grid_components(child, region=next_region)) + return items + + +def _page_grid_container(design: dict[str, Any], root: dict[str, Any], *, receipt: bool) -> str: + layout = root.get("layout") or {} + grid_mm = int(_number(layout.get("grid_mm"), 1, 1, 5)) + width_mm = _number(layout.get("width_mm"), 190, 10, 1000) + height_mm = _number(layout.get("height_mm"), 277, 20, 5000) + columns = max(1, math.ceil(width_mm / grid_mm)) + rows = max(1, math.ceil(height_mm / grid_mm)) + items: list[str] = [] + for region, component in _page_grid_components(root): + if component.get("visible", True) is False: + continue + placement = component.get("placement") or {} + x = _number(placement.get("x_mm"), 0, 0, width_mm) + y = _number(placement.get("y_mm"), 0, 0, height_mm) + width = _number(placement.get("width_mm"), 30, 1, width_mm) + height = _number(placement.get("height_mm"), 15, 1, height_mm) + column_start = max(1, min(columns, math.floor(x / grid_mm) + 1)) + row_start = max(1, min(rows, math.floor(y / grid_mm) + 1)) + column_span = max(1, min(columns - column_start + 1, math.ceil(width / grid_mm))) + row_span = max(1, min(rows - row_start + 1, math.ceil(height / grid_mm))) + component_html = _component_html(design, component, receipt=receipt) + if not component_html: + continue + component_type = str(component.get("component") or "") + dynamic_class = " rt-page-grid-item-dynamic" if component_type in ("invoice_lines", "invoice_totals", "payments", "note") else "" + items.append( + f'
{component_html}
' + ) + return ( + f'
' + f'{"".join(items)}
' + ) + + +def _region_html(design: dict[str, Any], root: dict[str, Any], region: str, *, receipt: bool) -> str: + for node in root.get("children") or []: + if isinstance(node, dict) and node.get("region") == region: + return _node_html(design, node, receipt=receipt) + return "" + + +def compile_v4_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, str, str]: + if not is_v4_design(design): + raise ValueError("Not a v4 design schema") + contract = design.get("compiler_contract") or {} + if contract.get("name") != COMPILER_NAME or int(contract.get("version") or 0) != COMPILER_VERSION: + raise ValueError("Unsupported compiler contract") + if contract.get("output") != "html_css": + raise ValueError("Studio v4 compiler output must be html_css") + family = get_family(str(design.get("family_id") or "")) + if not family or family.layout not in ("invoice_detail", "invoice_receipt"): + raise ValueError("Studio v4 supports invoice detail and receipt layouts") + receipt = family.layout == "invoice_receipt" + direction = str((design.get("theme") or {}).get("direction") or "rtl").lower() + if direction not in ("rtl", "ltr"): + direction = "rtl" + # Reuse the established theme/table CSS. Only layout markup is compiled here. + _, base_css, _, _ = compile_v3_design_to_jinja_html(v4_to_v3_projection(design)) + root = resolved_root(design) + page_grid = str((root.get("layout") or {}).get("type") or "") == "page_grid" + if page_grid: + header = "" + body = _page_grid_container(design, root, receipt=receipt) + footer = "" + else: + header = _region_html(design, root, "header", receipt=receipt) + body = _region_html(design, root, "body", receipt=receipt) + footer = _region_html(design, root, "footer", receipt=receipt) + profile = active_variant_key(design) + rendered_body = body if page_grid else f'
{body}
' + html = ( + f'' + f'{rendered_body}' + ) + css = base_css + """ +.rt-layout-v4, .rt-layout-v4 * { box-sizing:border-box; } +.rt-container-flow { display:flex; flex-direction:column; width:100%; } +.rt-container-grid { display:grid; grid-template-columns:repeat(60,minmax(0,1fr)); align-items:start; width:100%; } +.rt-grid-cell, .rt-component { min-width:0; max-width:100%; } +.rt-container-freeform { position:relative; width:100%; overflow:hidden; } +.rt-freeform-item { position:absolute; min-width:0; overflow:hidden; } +.rt-freeform-item > .rt-component { width:100%; height:100%; } +.rt-container-stack { display:grid; width:100%; } +.rt-container-stack > .rt-node { grid-area:1 / 1; } +.rt-page-grid { display:grid; width:100%; min-height:var(--rt-page-grid-height); align-items:stretch; } +.rt-page-grid-item { min-width:0; overflow:visible; align-self:stretch; } +.rt-page-grid-item > .rt-component { width:100%; min-height:100%; } +.rt-page-grid-item-dynamic { height:auto; align-self:start; } +@media screen and (max-width:720px) { + .rt-layout-v4 { max-width:100%; overflow-x:auto; } +} +""" + return html, css.strip(), header, footer diff --git a/hesabixAPI/tests/test_template_design_v2_compiler.py b/hesabixAPI/tests/test_template_design_v2_compiler.py index fbe791cc..e8c0db34 100644 --- a/hesabixAPI/tests/test_template_design_v2_compiler.py +++ b/hesabixAPI/tests/test_template_design_v2_compiler.py @@ -11,8 +11,15 @@ from app.services.report_template_v3_service import ( studio_block_catalog, validate_v3_design, ) +from app.services.report_template_v4_service import ( + active_variant_key, + migrate_v3_design_to_v4, + studio_v4_contract, + validate_v4_design, +) from app.services.template_design_v2_compiler import compile_v2_design_to_jinja_html from app.services.template_design_v3_compiler import compile_v3_design_to_jinja_html +from app.services.template_design_v4_compiler import compile_v4_design_to_jinja_html def _sample_invoice_context() -> dict: @@ -223,6 +230,32 @@ def test_v3_compiler_applies_ltr_direction_and_block_text_alignment(): assert 'style="width:60%;"' in html +def test_v3_compiler_groups_blocks_in_a_sixty_column_resizable_row(): + design_v2 = default_design_for_family("invoice_classic") + assert design_v2 is not None + design = migrate_v2_design_to_v3(design_v2) + first, second = design["regions"]["body"][:2] + for block in (first, second): + block["style"].update( + { + "row_id": "party-row", + "grid_span": 30, + "row_height_mode": "minimum", + "row_height_mm": 24, + } + ) + validation = validate_v3_design("invoices", "detail", design) + assert validation["errors"] == [] + html, css, _, _ = compile_v3_design_to_jinja_html(design) + assert "grid-template-columns:repeat(60" in css + assert html.count('grid-column:span 30;') == 2 + assert html.count('class="rt-grid-row" style="min-height:24mm;"') == 1 + + second["style"]["grid_span"] = 31 + validation = validate_v3_design("invoices", "detail", design) + assert any("exceeds 60 columns" in error for error in validation["errors"]) + + def test_v3_render_uses_hesabix_persian_font_in_css(): design_v2 = default_design_for_family("invoice_classic") assert design_v2 is not None @@ -308,3 +341,151 @@ def test_migrate_and_render_invoice_receipt_v3(): rendered = env.from_string(f"{header}{html}{footer}").render(**_sample_invoice_context()) assert "INV-1" in rendered assert "rt-receipt-items" in rendered + + +def test_v4_migration_is_copy_on_write_and_has_every_responsive_profile(): + design_v2 = default_design_for_family("invoice_classic") + assert design_v2 is not None + design_v3 = migrate_v2_design_to_v3(design_v2) + original = __import__("copy").deepcopy(design_v3) + design = migrate_v3_design_to_v4(design_v3) + assert design_v3 == original + assert design["schema_version"] == 4 + assert design["migration"]["mode"] == "copy_on_write" + contract = studio_v4_contract("invoices", "detail") + profile_keys = {item["key"] for item in contract["media_profiles"]} + assert profile_keys == set(design["variants"]) + assert {"a4_portrait", "a4_landscape", "roll_80", "custom_roll"}.issubset(profile_keys) + assert contract["compiler"]["output"] == "html_css" + assert contract["freeform"]["grid_sizes_mm"] == [1, 3, 5] + assert contract["page_grid"]["grid_sizes_mm"] == [1, 3, 5] + assert contract["page_grid"]["dynamic_components_allowed"] is True + assert design["root"]["layout"]["type"] == "page_grid" + landscape_layout = design["variants"]["a4_landscape"]["node_overrides"]["invoice-root"]["layout"] + assert landscape_layout["width_mm"] == 277 + assert landscape_layout["height_mm"] == 190 + assert validate_v4_design("invoices", "detail", design)["errors"] == [] + + +def test_v4_a4_compiles_to_traceable_html_css_and_existing_renderer(): + design_v2 = default_design_for_family("invoice_classic") + assert design_v2 is not None + design = migrate_v3_design_to_v4(migrate_v2_design_to_v3(design_v2)) + assert active_variant_key(design) == "a4_portrait" + html, css, header, footer = compile_v4_design_to_jinja_html(design) + assert 'data-template-schema="4"' in html + assert 'data-template-variant="a4_portrait"' in html + assert "rt-page-grid" in html + assert "grid-column:" in html + assert ".rt-page-grid { display:grid" in css + template = type( + "Template", + (), + { + "engine": "template_v2", + "assets": {"template_design": design}, + "content_html": "", + "content_css": "", + "header_html": "", + "footer_html": "", + "paper_size": "A4", + "orientation": "portrait", + "margins": {"top": 10, "right": 10, "bottom": 10, "left": 10}, + }, + )() + rendered = ReportTemplateService.render_with_template(template, _sample_invoice_context()) + assert "INV-1" in rendered + assert "@page { size: A4 portrait;" in rendered + assert 'data-template-node-id="invoice-lines"' in rendered + + +def test_v4_roll_80_uses_explicit_full_page_grid_variant(): + design_v2 = default_design_for_family("invoice_receipt_simple") + assert design_v2 is not None + design = migrate_v3_design_to_v4(migrate_v2_design_to_v3(design_v2)) + assert active_variant_key(design) == "roll_80" + assert validate_v4_design("invoices", "receipt", design)["errors"] == [] + html, css, header, footer = compile_v4_design_to_jinja_html(design) + assert 'data-template-variant="roll_80"' in html + assert "rt-receipt-items" in html + assert "rt-page-grid" in html + assert 'data-template-region="body"' in html + assert header == "" + assert footer == "" + env = SandboxedEnvironment(loader=BaseLoader(), autoescape=True, undefined=StrictUndefined) + env.filters["money"] = lambda value, *args, **kwargs: str(value if value is not None else "") + env.filters["date"] = lambda value, *args, **kwargs: str(value if value is not None else "") + rendered = env.from_string(f"{header}{html}{footer}").render(**_sample_invoice_context()) + assert "INV-1" in rendered + + +def test_v4_page_grid_compiles_geometry_and_allows_dynamic_table(): + design_v2 = default_design_for_family("invoice_classic") + assert design_v2 is not None + design = migrate_v3_design_to_v4(migrate_v2_design_to_v3(design_v2)) + assert validate_v4_design("invoices", "detail", design)["errors"] == [] + html, _, _, _ = compile_v4_design_to_jinja_html(design) + assert "rt-page-grid-item-dynamic" in html + assert 'data-template-node-id="invoice-lines"' in html + assert "min-height:" in html + + +def test_v4_a4_and_roll_80_render_with_the_existing_pdf_engine(): + from weasyprint import HTML + + for family_id, paper_size, orientation, expected_width_mm in ( + ("invoice_classic", "A4", "portrait", 210), + ("invoice_receipt_simple", "80mm", "portrait", 80), + ): + design_v2 = default_design_for_family(family_id) + assert design_v2 is not None + design = migrate_v3_design_to_v4(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": paper_size, + "orientation": orientation, + "margins": None, + }, + )() + rendered = ReportTemplateService.render_with_template(template, _sample_invoice_context()) + document = HTML(string=rendered).render() + assert document.pages + page_width_mm = document.pages[0].width * 25.4 / 96 + assert abs(page_width_mm - expected_width_mm) < 0.2 + + +def test_v4_full_page_grid_keeps_long_invoice_on_existing_pdf_pipeline(): + from weasyprint import HTML + + design_v2 = default_design_for_family("invoice_classic") + assert design_v2 is not None + design = migrate_v3_design_to_v4(migrate_v2_design_to_v3(design_v2)) + template = type( + "Template", + (), + { + "engine": "template_v2", + "assets": {"template_design": design}, + "content_html": "", + "content_css": "", + "header_html": "", + "footer_html": "", + "paper_size": "A4", + "orientation": "portrait", + "margins": None, + }, + )() + context = _sample_invoice_context() + base_line = context["lines"][0] + context["lines"] = [{**base_line, "product_name": f"کالای شماره {index}"} for index in range(1, 81)] + rendered = ReportTemplateService.render_with_template(template, context) + document = HTML(string=rendered).render() + assert len(document.pages) >= 2 diff --git a/hesabixUI/hesabix_ui/lib/pages/business/report_template_studio_page.dart b/hesabixUI/hesabix_ui/lib/pages/business/report_template_studio_page.dart index 8edcf7a4..9989c1c0 100644 --- a/hesabixUI/hesabix_ui/lib/pages/business/report_template_studio_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/report_template_studio_page.dart @@ -18,6 +18,7 @@ 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 '../../widgets/report_template/studio/report_template_studio_v4_adapter.dart'; import '../../core/hesabix_back.dart'; import 'report_template_html_editor_page.dart'; @@ -69,6 +70,7 @@ class _ReportTemplateStudioPageState extends State { String? _moduleKey; String? _subtype; int? _templateId; + bool _legacyTemplateCopied = false; String _lastSavedFingerprint = ''; List> _galleryItems = const []; @@ -280,7 +282,7 @@ class _ReportTemplateStudioPageState extends State { } final hadStoredMedia = _design?['media'] is Map; - await _upgradeDesignToV3IfSupported(); + await _upgradeDesignToV4IfSupported(); if (hadStoredMedia) { _applyMediaToLegacyFields( normalizedReportTemplateMedia(_design!, preferRoll: _isReceiptScope), @@ -293,18 +295,38 @@ class _ReportTemplateStudioPageState extends State { _lastSavedFingerprint = _fingerprint(); } - Future _upgradeDesignToV3IfSupported() async { - final design = _design; - if (design == null || (design['schema_version'] as num?)?.toInt() != 2) - return; + Future _upgradeDesignToV4IfSupported() async { + var design = _design; + if (design == null) return; if (_moduleKey != 'invoices' || - !const {'detail', 'receipt'}.contains(_subtype)) + !const {'detail', 'receipt'}.contains(_subtype)) { return; - final out = await _service.migrateV2ToV3( - businessId: widget.businessId, - design: design, - ); - _design = (out['design'] as Map?)?.cast() ?? design; + } + final originalSchema = (design['schema_version'] as num?)?.toInt(); + if (originalSchema == 2) { + final out = await _service.migrateV2ToV3( + businessId: widget.businessId, + design: design, + ); + design = (out['design'] as Map?)?.cast() ?? design; + } + if ((design['schema_version'] as num?)?.toInt() == 3) { + final out = await _service.migrateV3ToV4( + businessId: widget.businessId, + design: design, + ); + design = (out['design'] as Map?)?.cast() ?? design; + } + _design = design; + if (originalSchema != 4 && _templateId != null) { + // Copy-on-write: saving a migrated legacy design must never overwrite v3. + _templateId = null; + _legacyTemplateCopied = true; + final currentName = _nameCtrl.text.trim(); + if (currentName.isNotEmpty && !currentName.endsWith('(نسخه جدید)')) { + _nameCtrl.text = '$currentName (نسخه جدید)'; + } + } } void _onScopeChanged(String? scopeId) { @@ -316,6 +338,7 @@ class _ReportTemplateStudioPageState extends State { _subtype = scopeId.substring(idx + 1); _step = _StudioStep.gallery; _design = null; + _legacyTemplateCopied = false; _previewHtml = null; _previewPdfBytes = null; _showPdfPreview = false; @@ -350,6 +373,7 @@ class _ReportTemplateStudioPageState extends State { ); setState(() { _design = nextDesign; + _legacyTemplateCopied = false; _step = _StudioStep.customize; _previewHtml = null; _previewPdfBytes = null; @@ -535,6 +559,7 @@ class _ReportTemplateStudioPageState extends State { preferRoll: _isReceiptScope, ); _design = Map.from(design)..['media'] = media; + syncReportTemplateV4ActiveMedia(_design!); _applyMediaToLegacyFields(media); } @@ -1080,7 +1105,7 @@ class _ReportTemplateStudioPageState extends State { return const Center(child: Text('قالبی انتخاب نشده است.')); } - if ((design['schema_version'] as num?)?.toInt() == 3) { + if (const {3, 4}.contains((design['schema_version'] as num?)?.toInt())) { return ReportTemplateStudioV3Builder( design: design, blockCatalog: _blockCatalog, @@ -1152,6 +1177,17 @@ class _ReportTemplateStudioPageState extends State { padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), child: Column( children: [ + if (_legacyTemplateCopied) ...[ + MaterialBanner( + padding: const EdgeInsets.all(10), + leading: const Icon(Icons.copy_all_outlined), + content: const Text( + 'این طراحی از قالب قدیمی به v4 منتقل شده است. ذخیره، یک قالب جدید می‌سازد و نسخه قبلی را تغییر نمی‌دهد.', + ), + actions: const [SizedBox.shrink()], + ), + const SizedBox(height: 8), + ], TextField( controller: _nameCtrl, decoration: const InputDecoration( diff --git a/hesabixUI/hesabix_ui/lib/services/report_template_service.dart b/hesabixUI/hesabix_ui/lib/services/report_template_service.dart index 50ba92cc..f27b4c3d 100755 --- a/hesabixUI/hesabix_ui/lib/services/report_template_service.dart +++ b/hesabixUI/hesabix_ui/lib/services/report_template_service.dart @@ -347,6 +347,17 @@ class ReportTemplateService { return res.data ?? const {}; } + Future> migrateV3ToV4({ + required int businessId, + required Map design, + }) async { + final res = await _api.post>( + '/report-templates/business/$businessId/migrate-v3-to-v4', + data: {'design': design}, + ); + return res.data ?? const {}; + } + Future> validateV2Design({ required int businessId, required String moduleKey, @@ -408,8 +419,10 @@ class ReportTemplateService { query: { if (status != null && status.trim().isNotEmpty) 'status': status.trim(), if (actorUserId != null) 'actor_user_id': actorUserId, - if (fromDate != null && fromDate.trim().isNotEmpty) 'from_date': fromDate.trim(), - if (toDate != null && toDate.trim().isNotEmpty) 'to_date': toDate.trim(), + if (fromDate != null && fromDate.trim().isNotEmpty) + 'from_date': fromDate.trim(), + if (toDate != null && toDate.trim().isNotEmpty) + 'to_date': toDate.trim(), 'offset': offset, 'sort_by': sortBy, 'sort_order': sortOrder, diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_snap_engine.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_snap_engine.dart new file mode 100644 index 00000000..c96b2539 --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_snap_engine.dart @@ -0,0 +1,199 @@ +import 'dart:math' as math; + +class StudioMmRect { + final double x; + final double y; + final double width; + final double height; + + const StudioMmRect(this.x, this.y, this.width, this.height); + + double get right => x + width; + double get bottom => y + height; + double get centerX => x + width / 2; + double get centerY => y + height / 2; + + StudioMmRect clampInside(double containerWidth, double containerHeight) { + final nextWidth = width.clamp(1, containerWidth).toDouble(); + final nextHeight = height.clamp(1, containerHeight).toDouble(); + return StudioMmRect( + x.clamp(0, math.max(0, containerWidth - nextWidth)).toDouble(), + y.clamp(0, math.max(0, containerHeight - nextHeight)).toDouble(), + nextWidth, + nextHeight, + ); + } +} + +class StudioSnapGuide { + final bool vertical; + final double positionMm; + final String source; + + const StudioSnapGuide({ + required this.vertical, + required this.positionMm, + required this.source, + }); +} + +class StudioSnapResult { + final StudioMmRect rect; + final List guides; + + const StudioSnapResult(this.rect, this.guides); +} + +class _Candidate { + final double delta; + final double guide; + final int priority; + final String source; + + const _Candidate(this.delta, this.guide, this.priority, this.source); +} + +_Candidate? _best(List<_Candidate> candidates, double thresholdMm) { + final within = + candidates + .where((candidate) => candidate.delta.abs() <= thresholdMm) + .toList() + ..sort((a, b) { + final priority = a.priority.compareTo(b.priority); + return priority != 0 + ? priority + : a.delta.abs().compareTo(b.delta.abs()); + }); + return within.isEmpty ? null : within.first; +} + +StudioSnapResult snapStudioMove({ + required StudioMmRect proposed, + required List siblings, + required double containerWidthMm, + required double containerHeightMm, + required double gridMm, + required double thresholdMm, + bool enabled = true, +}) { + var rect = proposed.clampInside(containerWidthMm, containerHeightMm); + if (!enabled) return StudioSnapResult(rect, const []); + final xCandidates = <_Candidate>[]; + final yCandidates = <_Candidate>[]; + + void addX(double moving, double target, int priority, String source) => + xCandidates.add(_Candidate(target - moving, target, priority, source)); + void addY(double moving, double target, int priority, String source) => + yCandidates.add(_Candidate(target - moving, target, priority, source)); + + for (final sibling in siblings) { + for (final target in [sibling.x, sibling.centerX, sibling.right]) { + addX(rect.x, target, 0, 'sibling'); + addX(rect.centerX, target, 0, 'sibling'); + addX(rect.right, target, 0, 'sibling'); + } + for (final target in [sibling.y, sibling.centerY, sibling.bottom]) { + addY(rect.y, target, 0, 'sibling'); + addY(rect.centerY, target, 0, 'sibling'); + addY(rect.bottom, target, 0, 'sibling'); + } + } + for (final target in [0.0, containerWidthMm / 2, containerWidthMm]) { + addX(rect.x, target, 1, 'margin'); + addX(rect.centerX, target, 1, 'margin'); + addX(rect.right, target, 1, 'margin'); + } + for (final target in [0.0, containerHeightMm / 2, containerHeightMm]) { + addY(rect.y, target, 1, 'margin'); + addY(rect.centerY, target, 1, 'margin'); + addY(rect.bottom, target, 1, 'margin'); + } + if (gridMm > 0) { + final gridX = (rect.x / gridMm).round() * gridMm; + final gridY = (rect.y / gridMm).round() * gridMm; + addX(rect.x, gridX, 2, 'grid'); + addY(rect.y, gridY, 2, 'grid'); + } + + final bestX = _best(xCandidates, thresholdMm); + final bestY = _best(yCandidates, thresholdMm); + rect = StudioMmRect( + rect.x + (bestX?.delta ?? 0), + rect.y + (bestY?.delta ?? 0), + rect.width, + rect.height, + ).clampInside(containerWidthMm, containerHeightMm); + return StudioSnapResult(rect, [ + if (bestX != null) + StudioSnapGuide( + vertical: true, + positionMm: bestX.guide, + source: bestX.source, + ), + if (bestY != null) + StudioSnapGuide( + vertical: false, + positionMm: bestY.guide, + source: bestY.source, + ), + ]); +} + +StudioSnapResult snapStudioResize({ + required StudioMmRect proposed, + required List siblings, + required double containerWidthMm, + required double containerHeightMm, + required double gridMm, + required double thresholdMm, + bool enabled = true, +}) { + var rect = proposed.clampInside(containerWidthMm, containerHeightMm); + if (!enabled) return StudioSnapResult(rect, const []); + final xCandidates = <_Candidate>[]; + final yCandidates = <_Candidate>[]; + for (final sibling in siblings) { + for (final target in [sibling.x, sibling.centerX, sibling.right]) { + xCandidates.add(_Candidate(target - rect.right, target, 0, 'sibling')); + } + for (final target in [sibling.y, sibling.centerY, sibling.bottom]) { + yCandidates.add(_Candidate(target - rect.bottom, target, 0, 'sibling')); + } + } + for (final target in [containerWidthMm / 2, containerWidthMm]) { + xCandidates.add(_Candidate(target - rect.right, target, 1, 'margin')); + } + for (final target in [containerHeightMm / 2, containerHeightMm]) { + yCandidates.add(_Candidate(target - rect.bottom, target, 1, 'margin')); + } + if (gridMm > 0) { + final gridRight = (rect.right / gridMm).round() * gridMm; + final gridBottom = (rect.bottom / gridMm).round() * gridMm; + xCandidates.add(_Candidate(gridRight - rect.right, gridRight, 2, 'grid')); + yCandidates.add( + _Candidate(gridBottom - rect.bottom, gridBottom, 2, 'grid'), + ); + } + final bestX = _best(xCandidates, thresholdMm); + final bestY = _best(yCandidates, thresholdMm); + rect = StudioMmRect( + rect.x, + rect.y, + math.max(1, rect.width + (bestX?.delta ?? 0)), + math.max(1, rect.height + (bestY?.delta ?? 0)), + ).clampInside(containerWidthMm, containerHeightMm); + return StudioSnapResult(rect, [ + if (bestX != null) + StudioSnapGuide( + vertical: true, + positionMm: bestX.guide, + source: bestX.source, + ), + if (bestY != null) + StudioSnapGuide( + vertical: false, + positionMm: bestY.guide, + source: bestY.source, + ), + ]); +} 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 dde707ef..9414ad9c 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 @@ -1,9 +1,12 @@ import 'dart:convert'; +import 'dart:math' as math; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'report_template_media_settings.dart'; +import 'report_template_snap_engine.dart'; +import 'report_template_studio_v4_adapter.dart'; class ReportTemplateStudioV3Builder extends StatefulWidget { final Map design; @@ -34,13 +37,42 @@ class _BlockDragData { const _BlockDragData.palette(this.blockType) : blockId = null; } +class _CanvasRow { + final String id; + final int startIndex; + final List> blocks; + + const _CanvasRow({ + required this.id, + required this.startIndex, + required this.blocks, + }); +} + class _ReportTemplateStudioV3BuilderState extends State { + final GlobalKey _pageGridCanvasKey = GlobalKey(); final List> _history = []; int _historyIndex = -1; int _idSequence = 0; String? _selectedBlockId; bool _showLivePreview = false; + String? _resizingBlockId; + int? _resizeStartSpan; + int? _resizePreviewSpan; + double _resizeHorizontalDelta = 0; + String? _resizingRowId; + double? _resizeStartHeightMm; + double? _resizePreviewHeightMm; + double _resizeVerticalDelta = 0; + String? _freeformGestureId; + StudioMmRect? _freeformStartRect; + StudioMmRect? _freeformPreviewRect; + Offset _freeformDelta = Offset.zero; + List _freeformGuides = const []; + int? _freeformResizePointer; + String? _freeformResizingId; + int? _freeformMovePointer; @override void initState() { @@ -101,10 +133,28 @@ class _ReportTemplateStudioV3BuilderState } Map _regions(Map design) { + if (isReportTemplateV4(design)) { + final projection = reportTemplateV4StudioProjection(design); + return (projection['regions'] as Map?)?.cast() ?? + {}; + } return (design['regions'] as Map?)?.cast() ?? {}; } + void _setRegions(Map design, Map regions) { + if (!isReportTemplateV4(design)) { + design['regions'] = regions; + return; + } + final projection = reportTemplateV4StudioProjection(design) + ..['regions'] = regions; + final updated = applyStudioProjectionToReportTemplateV4(design, projection); + design + ..clear() + ..addAll(updated); + } + List> _regionBlocks( Map design, String region, @@ -143,6 +193,59 @@ class _ReportTemplateStudioV3BuilderState return '${type}_${DateTime.now().microsecondsSinceEpoch}_$_idSequence'; } + String _newRowId() => _newId('row'); + + String _blockRowId(Map block, String region) { + final style = (block['style'] as Map?)?.cast() ?? const {}; + final configured = (style['row_id'] ?? '').toString().trim(); + if (configured.isNotEmpty) return configured; + return 'legacy-$region-${block['id']}'; + } + + int _blockSpan(Map block) { + final style = (block['style'] as Map?)?.cast() ?? const {}; + final configured = (style['grid_span'] as num?)?.round(); + if (configured != null) return configured.clamp(1, 60).toInt(); + final mode = (style['width_mode'] ?? 'full').toString(); + final value = (style['width_value'] as num?)?.toDouble(); + if (mode == 'percentage') { + return ((value ?? 100) * 0.6).round().clamp(1, 60).toInt(); + } + return 60; + } + + List<_CanvasRow> _canvasRows( + List> blocks, + String region, + ) { + final rows = <_CanvasRow>[]; + for (var index = 0; index < blocks.length; index++) { + final block = blocks[index]; + final rowId = _blockRowId(block, region); + if (rows.isEmpty || rows.last.id != rowId) { + rows.add(_CanvasRow(id: rowId, startIndex: index, blocks: [block])); + } else { + rows.last.blocks.add(block); + } + } + return rows; + } + + Map _newBlock(String type, String rowId, int span) { + final definition = _definition(type)!; + return { + 'id': _newId(type), + 'type': type, + 'visible': true, + 'props': _cloneMap(definition['default_props']), + 'style': { + 'width_mode': 'full', + 'row_id': rowId, + 'grid_span': span.clamp(1, 60), + }, + }; + } + void _addBlock(String type, String region, int index) { final definition = _definition(type); if (definition == null || !_canAdd(definition)) return; @@ -157,16 +260,10 @@ class _ReportTemplateStudioV3BuilderState final blocks = List>.from( (regions[region] as List?) ?? const [], ); - final block = { - 'id': _newId(type), - 'type': type, - 'visible': true, - 'props': _cloneMap(definition['default_props']), - 'style': {'width_mode': 'full'}, - }; + final block = _newBlock(type, _newRowId(), 60); blocks.insert(index.clamp(0, blocks.length), block); regions[region] = blocks; - design['regions'] = regions; + _setRegions(design, regions); _selectedBlockId = block['id'].toString(); _commit(design); } @@ -214,6 +311,15 @@ class _ReportTemplateStudioV3BuilderState (definition?['allowed_regions'] as List?) ?? const [], ); if (!allowed.contains(targetRegion)) return; + final movingStyle = + (moving['style'] as Map?)?.cast() ?? + {}; + moving['style'] = { + ...movingStyle, + 'width_mode': 'full', + 'row_id': _newRowId(), + 'grid_span': 60, + }; final target = List>.from( (regions[targetRegion] as List?) ?? const [], ); @@ -222,7 +328,7 @@ class _ReportTemplateStudioV3BuilderState } target.insert(targetIndex.clamp(0, target.length), moving); regions[targetRegion] = target; - design['regions'] = regions; + _setRegions(design, regions); _commit(design); } @@ -234,6 +340,136 @@ class _ReportTemplateStudioV3BuilderState } } + void _handleDropBeside(_BlockDragData data, String region, String rowId) { + final type = + data.blockType ?? + _findBlock(data.blockId ?? '')?.block['type']?.toString(); + final definition = _definition(type ?? ''); + if (definition == null || + !List.from( + (definition['allowed_regions'] as List?) ?? const [], + ).contains(region)) { + return; + } + if (data.blockType != null && !_canAdd(definition)) return; + + final design = _clone(widget.design); + final regions = _regions(design); + Map? moving; + for (final sourceRegion in const ['header', 'body', 'footer']) { + final source = List>.from( + (regions[sourceRegion] as List?) ?? const [], + ); + final index = source.indexWhere( + (block) => block['id']?.toString() == data.blockId, + ); + if (index >= 0) { + moving = source.removeAt(index); + regions[sourceRegion] = source; + break; + } + } + moving ??= _newBlock(type!, rowId, 30); + + final target = List>.from( + (regions[region] as List?) ?? const [], + ); + final rowIndexes = []; + for (var index = 0; index < target.length; index++) { + if (_blockRowId(target[index], region) == rowId) rowIndexes.add(index); + } + if (rowIndexes.isEmpty) { + final style = + (moving['style'] as Map?)?.cast() ?? + {}; + moving['style'] = { + ...style, + 'width_mode': 'full', + 'row_id': _newRowId(), + 'grid_span': 60, + }; + target.add(moving); + } else { + final targetRowStyle = + (target[rowIndexes.first]['style'] as Map?) + ?.cast() ?? + const {}; + for (final index in rowIndexes) { + final block = Map.from(target[index]); + final style = + (block['style'] as Map?)?.cast() ?? + {}; + block['style'] = { + ...style, + 'width_mode': 'full', + 'row_id': rowId, + 'grid_span': _blockSpan(block), + }; + target[index] = block; + } + final occupied = rowIndexes.fold( + 0, + (sum, index) => sum + _blockSpan(target[index]), + ); + final remaining = 60 - occupied; + if (remaining <= 0) { + final count = rowIndexes.length + 1; + final base = 60 ~/ count; + var remainder = 60 % count; + for (final index in rowIndexes) { + final span = base + (remainder-- > 0 ? 1 : 0); + final block = Map.from(target[index]); + final style = + (block['style'] as Map?)?.cast() ?? + {}; + block['style'] = { + ...style, + 'width_mode': 'full', + 'row_id': rowId, + 'grid_span': span, + }; + target[index] = block; + } + final style = + (moving['style'] as Map?)?.cast() ?? + {}; + style.remove('row_height_mode'); + style.remove('row_height_mm'); + moving['style'] = { + ...style, + 'width_mode': 'full', + 'row_id': rowId, + 'grid_span': base + (remainder-- > 0 ? 1 : 0), + if (targetRowStyle['row_height_mode'] != null) + 'row_height_mode': targetRowStyle['row_height_mode'], + if (targetRowStyle['row_height_mm'] != null) + 'row_height_mm': targetRowStyle['row_height_mm'], + }; + } else { + final style = + (moving['style'] as Map?)?.cast() ?? + {}; + style.remove('row_height_mode'); + style.remove('row_height_mm'); + moving['style'] = { + ...style, + 'width_mode': 'full', + 'row_id': rowId, + 'grid_span': remaining.clamp(1, 30), + if (targetRowStyle['row_height_mode'] != null) + 'row_height_mode': targetRowStyle['row_height_mode'], + if (targetRowStyle['row_height_mm'] != null) + 'row_height_mm': targetRowStyle['row_height_mm'], + }; + } + target.insert(rowIndexes.last + 1, moving); + } + regions[region] = target; + _setRegions(design, regions); + _selectedBlockId = moving['id'].toString(); + _commit(design); + } + void _selectBlock(String id) { setState(() => _selectedBlockId = id); } @@ -255,7 +491,7 @@ class _ReportTemplateStudioV3BuilderState ); blocks.removeAt(found.index); regions[found.region] = blocks; - design['regions'] = regions; + _setRegions(design, regions); if (_selectedBlockId == id) _selectedBlockId = null; _commit(design); } @@ -272,9 +508,17 @@ class _ReportTemplateStudioV3BuilderState (regions[found.region] as List?) ?? const [], ); final copy = _clone(found.block)..['id'] = _newId(type); + final style = + (copy['style'] as Map?)?.cast() ?? {}; + copy['style'] = { + ...style, + 'width_mode': 'full', + 'row_id': _newRowId(), + 'grid_span': 60, + }; blocks.insert(found.index + 1, copy); regions[found.region] = blocks; - design['regions'] = regions; + _setRegions(design, regions); _selectedBlockId = copy['id'].toString(); _commit(design); } @@ -295,7 +539,7 @@ class _ReportTemplateStudioV3BuilderState mutate(block); blocks[index] = block; regions[region] = blocks; - design['regions'] = regions; + _setRegions(design, regions); _commit(design); return; } @@ -305,6 +549,31 @@ class _ReportTemplateStudioV3BuilderState void _patchRoot(void Function(Map design) mutate) { final design = _clone(widget.design); mutate(design); + syncReportTemplateV4ActiveMedia(design); + _commit(design); + } + + void _patchRowStyle(String rowId, Map patch) { + final design = _clone(widget.design); + final regions = _regions(design); + for (final region in const ['header', 'body', 'footer']) { + final blocks = List>.from( + (regions[region] as List?) ?? const [], + ); + var changed = false; + for (var index = 0; index < blocks.length; index++) { + if (_blockRowId(blocks[index], region) != rowId) continue; + final block = Map.from(blocks[index]); + final style = + (block['style'] as Map?)?.cast() ?? + {}; + block['style'] = {...style, ...patch, 'row_id': rowId}; + blocks[index] = block; + changed = true; + } + if (changed) regions[region] = blocks; + } + _setRegions(design, regions); _commit(design); } @@ -443,7 +712,363 @@ class _ReportTemplateStudioV3BuilderState ); } + List> _allPageGridBlocks() => [ + for (final region in const ['header', 'body', 'footer']) + ..._regionBlocks(widget.design, region), + ]; + + double _pageGridDefaultWidth(String type, double canvasWidthMm) => + switch (type) { + 'invoice_lines' || 'brand_header' => canvasWidthMm, + 'party_info' => canvasWidthMm * 0.48, + 'invoice_totals' => canvasWidthMm * 0.55, + 'signatures' => canvasWidthMm * 0.65, + 'qr' => 34, + _ => canvasWidthMm * 0.5, + }; + + double _pageGridDefaultHeight(String type) => switch (type) { + 'brand_header' => 30, + 'party_info' => 24, + 'invoice_lines' => 72, + 'invoice_totals' => 38, + 'payments' => 24, + 'note' => 22, + 'signatures' => 38, + 'qr' => 34, + 'footer_meta' => 14, + 'divider' => 4, + 'spacer' => 10, + _ => 20, + }; + + bool _canDropOnPageGrid(_BlockDragData data) { + final type = + data.blockType ?? + _findBlock(data.blockId ?? '')?.block['type']?.toString(); + return type != null && _definition(type) != null; + } + + void _dropOnPageGrid( + _BlockDragData data, + double xMm, + double yMm, + double canvasWidthMm, + double canvasHeightMm, + ) { + final design = _clone(widget.design); + final regions = _regions(design); + Map? block; + String? region; + if (data.blockId != null) { + for (final candidateRegion in const ['header', 'body', 'footer']) { + final blocks = List>.from( + (regions[candidateRegion] as List?) ?? const [], + ); + final index = blocks.indexWhere( + (candidate) => candidate['id']?.toString() == data.blockId, + ); + if (index >= 0) { + block = Map.from(blocks[index]); + region = candidateRegion; + break; + } + } + } else if (data.blockType != null) { + final definition = _definition(data.blockType!); + if (definition == null || !_canAdd(definition)) return; + final allowed = List.from( + (definition['allowed_regions'] as List?) ?? const ['body'], + ); + region = allowed.contains('body') + ? 'body' + : (allowed.isEmpty ? 'body' : allowed.first); + block = _newBlock(data.blockType!, _newRowId(), 60); + final blocks = List>.from( + (regions[region] as List?) ?? const [], + )..add(block); + regions[region] = blocks; + } + if (block == null || region == null) return; + final type = block['type'].toString(); + final oldStyle = + (block['style'] as Map?)?.cast() ?? const {}; + final width = _styleNumber( + oldStyle, + 'width_mm', + _pageGridDefaultWidth(type, canvasWidthMm), + ).clamp(4, canvasWidthMm).toDouble(); + final height = _styleNumber( + oldStyle, + 'height_mm', + _pageGridDefaultHeight(type), + ).clamp(4, canvasHeightMm).toDouble(); + final rect = StudioMmRect( + xMm - width / 2, + yMm - 8, + width, + height, + ).clampInside(canvasWidthMm, canvasHeightMm); + final blocks = List>.from( + (regions[region] as List?) ?? const [], + ); + final index = blocks.indexWhere( + (candidate) => candidate['id']?.toString() == block!['id']?.toString(), + ); + if (index < 0) return; + block['style'] = { + ...oldStyle, + 'layout_type': 'page_grid', + 'x_mm': rect.x, + 'y_mm': rect.y, + 'width_mm': rect.width, + 'height_mm': rect.height, + }; + blocks[index] = block; + regions[region] = blocks; + _setRegions(design, regions); + _selectedBlockId = block['id'].toString(); + _commit(design); + } + + void _patchPageGridSettings(Map patch) { + final design = _clone(widget.design); + final regions = _regions(design); + for (final region in const ['header', 'body', 'footer']) { + final blocks = List>.from( + (regions[region] as List?) ?? const [], + ); + for (var index = 0; index < blocks.length; index++) { + final block = Map.from(blocks[index]); + final style = + (block['style'] as Map?)?.cast() ?? const {}; + block['style'] = { + ...style, + 'layout_type': 'page_grid', + ...patch, + }; + blocks[index] = block; + } + regions[region] = blocks; + } + _setRegions(design, regions); + _commit(design); + } + + Widget _pageGridCanvas(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 {}; + double marginMm(String side, double fallback) => + (margins[side] as num?)?.toDouble() ?? fallback; + final leftMm = marginMm('left', isRoll ? 2 : 10); + final rightMm = marginMm('right', isRoll ? 2 : 10); + final topMm = marginMm('top', isRoll ? 3 : 10); + final bottomMm = marginMm('bottom', isRoll ? 4 : 10); + final canvasWidthMm = (mediaSize.width - leftMm - rightMm) + .clamp(10, 1000) + .toDouble(); + final blocks = _allPageGridBlocks(); + final firstStyle = blocks.isEmpty + ? const {} + : (blocks.first['style'] as Map?)?.cast() ?? const {}; + final gridMm = _styleNumber( + firstStyle, + 'page_grid_mm', + 1, + ).clamp(1, 5).toDouble(); + final snapEnabled = firstStyle['page_snap'] != false; + final requiredBottom = blocks.fold( + 0, + (value, block) => math.max(value, _freeformRect(block).bottom + 10), + ); + final sheetHeight = (mediaSize.height - topMm - bottomMm) + .clamp(20, 5000) + .toDouble(); + final configuredHeight = _styleNumber( + firstStyle, + 'page_height_mm', + sheetHeight, + ); + final double canvasHeightMm = isRoll + ? math.max(120.0, math.max(configuredHeight, requiredBottom)) + : sheetHeight; + 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 pageWidthPx = (availableWidth - 48) + .clamp(280.0, 760.0) + .toDouble(); + final pixelsPerMm = pageWidthPx / mediaSize.width; + final pageHeightPx = (topMm + canvasHeightMm + bottomMm) * pixelsPerMm; + return ColoredBox( + color: const Color(0xffe5e7eb), + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Center( + child: Container( + width: pageWidthPx, + height: pageHeightPx, + padding: EdgeInsets.fromLTRB( + leftMm * pixelsPerMm, + topMm * pixelsPerMm, + rightMm * pixelsPerMm, + bottomMm * pixelsPerMm, + ), + decoration: const BoxDecoration( + color: Colors.white, + boxShadow: [ + BoxShadow( + color: Color(0x26000000), + blurRadius: 18, + offset: Offset(0, 6), + ), + ], + ), + child: Directionality( + textDirection: direction, + child: Builder( + builder: (canvasContext) => DragTarget<_BlockDragData>( + onWillAcceptWithDetails: (details) => + _canDropOnPageGrid(details.data), + onAcceptWithDetails: (details) { + final box = + _pageGridCanvasKey.currentContext + ?.findRenderObject() + as RenderBox?; + if (box == null) return; + final local = box.globalToLocal(details.offset); + _dropOnPageGrid( + details.data, + local.dx / pixelsPerMm, + local.dy / pixelsPerMm, + canvasWidthMm, + canvasHeightMm, + ); + }, + builder: (context, candidates, rejected) => Container( + key: _pageGridCanvasKey, + width: canvasWidthMm * pixelsPerMm, + height: canvasHeightMm * pixelsPerMm, + decoration: BoxDecoration( + border: Border.all( + color: candidates.isNotEmpty + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.outlineVariant, + ), + ), + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: CustomPaint( + painter: _MillimeterGridPainter( + pixelsPerMm: pixelsPerMm, + gridMm: gridMm, + color: Theme.of(context) + .colorScheme + .outlineVariant + .withValues(alpha: 0.5), + ), + ), + ), + for (final block in blocks) + _freeformCanvasBlock( + context, + block, + siblings: blocks + .where( + (candidate) => + candidate['id']?.toString() != + block['id']?.toString(), + ) + .map(_freeformRect) + .toList(), + widthMm: canvasWidthMm, + heightMm: canvasHeightMm, + pixelsPerMm: pixelsPerMm, + gridMm: gridMm, + snapEnabled: snapEnabled, + ), + for (final guide in _freeformGuides) + if (guide.vertical) + Positioned( + left: guide.positionMm * pixelsPerMm, + top: 0, + bottom: 0, + child: Container( + width: 1, + color: Theme.of( + context, + ).colorScheme.tertiary, + ), + ) + else + Positioned( + top: guide.positionMm * pixelsPerMm, + left: 0, + right: 0, + child: Container( + height: 1, + color: Theme.of( + context, + ).colorScheme.tertiary, + ), + ), + PositionedDirectional( + top: 4, + end: 4, + child: DecoratedBox( + decoration: BoxDecoration( + color: Theme.of(context) + .colorScheme + .surfaceContainerHighest + .withValues(alpha: 0.9), + borderRadius: BorderRadius.circular(10), + ), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 3, + ), + child: Text( + 'گرید کل صفحه · ${gridMm.toStringAsFixed(0)}mm${snapEnabled ? ' · Snap' : ''}', + style: Theme.of( + context, + ).textTheme.labelSmall, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ), + ); + }, + ); + } + Widget _visualCanvas(BuildContext context) { + if (isReportTemplateV4(widget.design)) { + return _pageGridCanvas(context); + } final media = normalizedReportTemplateMedia( widget.design, preferRoll: widget.design['layout'] == 'invoice_receipt', @@ -549,6 +1174,7 @@ class _ReportTemplateStudioV3BuilderState Widget _canvasRegion(BuildContext context, String region, String title) { final blocks = _regionBlocks(widget.design, region); + final rows = _canvasRows(blocks, region); return DragTarget<_BlockDragData>( onWillAcceptWithDetails: (details) => _canDropOnRegion(details.data, region), @@ -576,11 +1202,12 @@ class _ReportTemplateStudioV3BuilderState children: [ if (blocks.isEmpty) _canvasEmptyRegion(context, region, title) - else - for (var index = 0; index < blocks.length; index++) ...[ - _canvasDropLine(region, index), - _canvasBlock(context, blocks[index]), + else ...[ + for (final row in rows) ...[ + _canvasDropLine(region, row.startIndex), + _canvasRow(context, region, row), ], + ], _canvasDropLine(region, blocks.length, expanded: active), ], ), @@ -589,6 +1216,555 @@ class _ReportTemplateStudioV3BuilderState ); } + Widget _canvasRow(BuildContext context, String region, _CanvasRow row) { + final firstStyle = + (row.blocks.first['style'] as Map?)?.cast() ?? + const {}; + if (isReportTemplateV4(widget.design) && + firstStyle['layout_type'] == 'freeform') { + return _freeformCanvasRow(context, region, row, firstStyle); + } + final heightMode = (firstStyle['row_height_mode'] ?? 'auto').toString(); + final configuredHeight = + (firstStyle['row_height_mm'] as num?)?.toDouble() ?? 20; + final previewHeight = _resizingRowId == row.id + ? _resizePreviewHeightMm + : null; + final heightMm = previewHeight ?? configuredHeight; + final selectedInRow = row.blocks.any( + (block) => block['id']?.toString() == _selectedBlockId, + ); + + return LayoutBuilder( + builder: (context, constraints) { + final rowWidth = constraints.maxWidth; + final media = normalizedReportTemplateMedia(widget.design); + final mediaWidth = (media['width_mm'] as num?)?.toDouble() ?? 210; + final margins = + (media['margins_mm'] as Map?)?.cast() ?? const {}; + final printableMm = + mediaWidth - + ((margins['left'] as num?)?.toDouble() ?? 0) - + ((margins['right'] as num?)?.toDouble() ?? 0); + final pixelsPerMm = rowWidth / printableMm.clamp(10, 500); + final minHeight = (heightMode != 'auto' || previewHeight != null) + ? heightMm.clamp(4, 500) * pixelsPerMm + : 0.0; + final totalSpan = row.blocks.fold( + 0, + (sum, block) => sum + _blockSpan(block), + ); + + Widget rowContent = Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final block in row.blocks) + SizedBox( + width: + rowWidth * + ((_resizingBlockId == block['id']?.toString() + ? _resizePreviewSpan + : null) ?? + _blockSpan(block)) / + 60, + child: DragTarget<_BlockDragData>( + key: ValueKey('canvas-row-drop-${row.id}-${block['id']}'), + onWillAcceptWithDetails: (details) => + details.data.blockId != block['id']?.toString() && + _canDropOnRegion(details.data, region), + onAcceptWithDetails: (details) => + _handleDropBeside(details.data, region, row.id), + builder: (context, candidates, rejected) => DecoratedBox( + decoration: BoxDecoration( + color: candidates.isNotEmpty + ? Theme.of(context).colorScheme.primaryContainer + .withValues(alpha: 0.45) + : Colors.transparent, + border: candidates.isNotEmpty + ? Border.all( + color: Theme.of(context).colorScheme.primary, + ) + : null, + ), + child: _canvasBlock( + context, + block, + rowWidth: rowWidth, + maxSpan: (60 - (totalSpan - _blockSpan(block))) + .clamp(1, 60) + .toInt(), + ), + ), + ), + ), + if (totalSpan < 60) + Expanded( + child: DragTarget<_BlockDragData>( + onWillAcceptWithDetails: (details) => + _canDropOnRegion(details.data, region), + onAcceptWithDetails: (details) => + _handleDropBeside(details.data, region, row.id), + builder: (context, candidates, rejected) => AnimatedContainer( + duration: const Duration(milliseconds: 100), + constraints: const BoxConstraints(minHeight: 38), + decoration: BoxDecoration( + color: candidates.isNotEmpty + ? Theme.of(context).colorScheme.primaryContainer + .withValues(alpha: 0.45) + : Colors.transparent, + border: candidates.isNotEmpty + ? Border.all( + color: Theme.of(context).colorScheme.primary, + ) + : null, + ), + alignment: Alignment.center, + child: candidates.isNotEmpty + ? const Icon(Icons.add, size: 18) + : null, + ), + ), + ), + ], + ); + if (minHeight > 0) { + rowContent = ConstrainedBox( + constraints: BoxConstraints(minHeight: minHeight), + child: rowContent, + ); + } + return Stack( + clipBehavior: Clip.none, + children: [ + rowContent, + if (selectedInRow) + PositionedDirectional( + start: 0, + end: 0, + bottom: 0, + child: MouseRegion( + cursor: SystemMouseCursors.resizeUpDown, + child: GestureDetector( + key: ValueKey('row-height-handle-${row.id}'), + behavior: HitTestBehavior.opaque, + onDoubleTap: () => _patchRowStyle(row.id, { + 'row_height_mode': 'auto', + 'row_height_mm': null, + }), + onVerticalDragStart: (_) { + _resizingRowId = row.id; + _resizeStartHeightMm = heightMode == 'auto' + ? 20 + : configuredHeight; + _resizePreviewHeightMm = _resizeStartHeightMm; + _resizeVerticalDelta = 0; + setState(() {}); + }, + onVerticalDragUpdate: (details) { + _resizeVerticalDelta += details.delta.dy; + setState(() { + _resizePreviewHeightMm = + ((_resizeStartHeightMm ?? 20) + + _resizeVerticalDelta / pixelsPerMm) + .clamp(4, 500); + }); + }, + onVerticalDragEnd: (_) { + final value = _resizePreviewHeightMm ?? configuredHeight; + _resizingRowId = null; + _resizeStartHeightMm = null; + _resizePreviewHeightMm = null; + _resizeVerticalDelta = 0; + _patchRowStyle(row.id, { + 'row_height_mode': 'minimum', + 'row_height_mm': double.parse(value.toStringAsFixed(1)), + }); + }, + child: Container( + height: 10, + alignment: Alignment.center, + child: Container( + width: 54, + height: 3, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, + borderRadius: BorderRadius.circular(3), + ), + ), + ), + ), + ), + ), + ], + ); + }, + ); + } + + double _styleNumber( + Map style, + String key, + double fallback, + ) => (style[key] as num?)?.toDouble() ?? fallback; + + StudioMmRect _freeformRect(Map block) { + final style = (block['style'] as Map?)?.cast() ?? const {}; + return StudioMmRect( + _styleNumber(style, 'x_mm', 0), + _styleNumber(style, 'y_mm', 0), + _styleNumber(style, 'width_mm', 30), + _styleNumber(style, 'height_mm', 15), + ); + } + + void _finishFreeformGesture(String id) { + final rect = _freeformPreviewRect; + _freeformGestureId = null; + _freeformStartRect = null; + _freeformPreviewRect = null; + _freeformDelta = Offset.zero; + _freeformGuides = const []; + if (rect == null) { + setState(() {}); + return; + } + _patchBlockStyle(id, { + 'x_mm': double.parse(rect.x.toStringAsFixed(2)), + 'y_mm': double.parse(rect.y.toStringAsFixed(2)), + 'width_mm': double.parse(rect.width.toStringAsFixed(2)), + 'height_mm': double.parse(rect.height.toStringAsFixed(2)), + }); + } + + void _patchFreeformGeometryField( + Map block, + String field, + double value, + double containerHeightMm, + ) { + final media = normalizedReportTemplateMedia(widget.design); + final margins = + (media['margins_mm'] as Map?)?.cast() ?? const {}; + final containerWidthMm = + ((media['width_mm'] as num?)?.toDouble() ?? 210) - + ((margins['left'] as num?)?.toDouble() ?? 0) - + ((margins['right'] as num?)?.toDouble() ?? 0); + final current = _freeformRect(block); + final proposed = StudioMmRect( + field == 'x_mm' ? value : current.x, + field == 'y_mm' ? value : current.y, + field == 'width_mm' ? value.clamp(1, containerWidthMm) : current.width, + field == 'height_mm' ? value.clamp(1, containerHeightMm) : current.height, + ).clampInside(containerWidthMm, containerHeightMm); + _patchBlockStyle(block['id'].toString(), { + 'x_mm': proposed.x, + 'y_mm': proposed.y, + 'width_mm': proposed.width, + 'height_mm': proposed.height, + }); + } + + Widget _freeformCanvasRow( + BuildContext context, + String region, + _CanvasRow row, + Map rowStyle, + ) { + return LayoutBuilder( + builder: (context, constraints) { + final media = normalizedReportTemplateMedia(widget.design); + final mediaWidth = (media['width_mm'] as num?)?.toDouble() ?? 210; + final margins = + (media['margins_mm'] as Map?)?.cast() ?? const {}; + final printableWidth = + mediaWidth - + ((margins['left'] as num?)?.toDouble() ?? 0) - + ((margins['right'] as num?)?.toDouble() ?? 0); + final widthMm = printableWidth.clamp(10, 500).toDouble(); + final pixelsPerMm = constraints.maxWidth / widthMm; + final heightMm = _styleNumber( + rowStyle, + 'freeform_height_mm', + 40, + ).clamp(4, 500).toDouble(); + final gridMm = _styleNumber( + rowStyle, + 'freeform_grid_mm', + 1, + ).clamp(1, 5).toDouble(); + final snapEnabled = rowStyle['freeform_snap'] != false; + + return Container( + key: ValueKey('freeform-row-${row.id}'), + height: heightMm * pixelsPerMm, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + border: Border.all( + color: Theme.of(context).colorScheme.outlineVariant, + ), + ), + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: CustomPaint( + painter: _MillimeterGridPainter( + pixelsPerMm: pixelsPerMm, + gridMm: gridMm, + color: Theme.of( + context, + ).colorScheme.outlineVariant.withValues(alpha: 0.45), + ), + ), + ), + for (final block in row.blocks) + _freeformCanvasBlock( + context, + block, + siblings: row.blocks + .where( + (candidate) => + candidate['id']?.toString() != + block['id']?.toString(), + ) + .map(_freeformRect) + .toList(), + widthMm: widthMm, + heightMm: heightMm, + pixelsPerMm: pixelsPerMm, + gridMm: gridMm, + snapEnabled: snapEnabled, + ), + for (final guide in _freeformGuides) + if (guide.vertical) + Positioned( + left: guide.positionMm * pixelsPerMm, + top: 0, + bottom: 0, + child: Container( + key: const ValueKey('freeform-guide-vertical'), + width: 1, + color: Theme.of(context).colorScheme.tertiary, + ), + ) + else + Positioned( + top: guide.positionMm * pixelsPerMm, + left: 0, + right: 0, + child: Container( + key: const ValueKey('freeform-guide-horizontal'), + height: 1, + color: Theme.of(context).colorScheme.tertiary, + ), + ), + PositionedDirectional( + top: 4, + end: 4, + child: DecoratedBox( + decoration: BoxDecoration( + color: Theme.of( + context, + ).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(10), + ), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 7, + vertical: 3, + ), + child: Text( + 'آزاد · شبکه ${gridMm.toStringAsFixed(0)}mm${snapEnabled ? ' · Snap' : ''}', + style: Theme.of(context).textTheme.labelSmall, + ), + ), + ), + ), + ], + ), + ); + }, + ); + } + + Widget _freeformCanvasBlock( + BuildContext context, + Map block, { + required List siblings, + required double widthMm, + required double heightMm, + required double pixelsPerMm, + required double gridMm, + required bool snapEnabled, + }) { + final id = block['id'].toString(); + final selected = id == _selectedBlockId; + final stored = _freeformRect(block); + final rect = _freeformGestureId == id + ? (_freeformPreviewRect ?? stored) + : stored; + return Positioned( + key: ValueKey('freeform-block-$id'), + left: rect.x * pixelsPerMm, + top: rect.y * pixelsPerMm, + width: rect.width * pixelsPerMm, + height: rect.height * pixelsPerMm, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => _selectBlock(id), + // Claim the gesture against the surrounding scroll view. Geometry is + // driven by raw pointer deltas below so both axes remain available. + onPanStart: (_) {}, + onPanUpdate: (_) {}, + child: Listener( + behavior: HitTestBehavior.opaque, + onPointerDown: (event) { + if (_freeformResizingId == id) return; + _freeformMovePointer = event.pointer; + _selectBlock(id); + _freeformGestureId = id; + _freeformStartRect = stored; + _freeformPreviewRect = stored; + _freeformDelta = Offset.zero; + }, + onPointerMove: (event) { + if (_freeformMovePointer != event.pointer || + _freeformResizingId == id) { + return; + } + _freeformDelta += event.delta; + final start = _freeformStartRect ?? stored; + final proposed = StudioMmRect( + start.x + _freeformDelta.dx / pixelsPerMm, + start.y + _freeformDelta.dy / pixelsPerMm, + start.width, + start.height, + ); + final result = snapStudioMove( + proposed: proposed, + siblings: siblings, + containerWidthMm: widthMm, + containerHeightMm: heightMm, + gridMm: gridMm, + thresholdMm: 6 / pixelsPerMm, + enabled: snapEnabled, + ); + setState(() { + _freeformPreviewRect = result.rect; + _freeformGuides = result.guides; + }); + }, + onPointerUp: (event) { + if (_freeformMovePointer != event.pointer) return; + _freeformMovePointer = null; + _finishFreeformGesture(id); + }, + onPointerCancel: (event) { + if (_freeformMovePointer != event.pointer) return; + _freeformMovePointer = null; + _finishFreeformGesture(id); + }, + child: DecoratedBox( + decoration: BoxDecoration( + color: selected + ? Theme.of( + context, + ).colorScheme.primaryContainer.withValues(alpha: 0.65) + : Theme.of( + context, + ).colorScheme.surface.withValues(alpha: 0.92), + border: Border.all( + color: selected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.outlineVariant, + width: selected ? 2 : 1, + ), + ), + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: Padding( + padding: const EdgeInsets.all(5), + child: ClipRect(child: _canvasBlockContent(context, block)), + ), + ), + if (selected) + Positioned( + right: 0, + bottom: 0, + child: MouseRegion( + cursor: SystemMouseCursors.resizeDownRight, + child: Listener( + key: ValueKey('freeform-resize-handle-$id'), + behavior: HitTestBehavior.opaque, + onPointerDown: (event) { + _freeformMovePointer = null; + _freeformResizePointer = event.pointer; + _freeformResizingId = id; + _freeformGestureId = id; + _freeformStartRect = stored; + _freeformPreviewRect = stored; + _freeformDelta = Offset.zero; + }, + onPointerMove: (event) { + if (_freeformResizePointer != event.pointer) return; + _freeformDelta += event.delta; + final start = _freeformStartRect ?? stored; + final proposed = StudioMmRect( + start.x, + start.y, + (start.width + _freeformDelta.dx / pixelsPerMm) + .clamp(4, widthMm), + (start.height + _freeformDelta.dy / pixelsPerMm) + .clamp(4, heightMm), + ); + final result = snapStudioResize( + proposed: proposed, + siblings: siblings, + containerWidthMm: widthMm, + containerHeightMm: heightMm, + gridMm: gridMm, + thresholdMm: 6 / pixelsPerMm, + enabled: snapEnabled, + ); + setState(() { + _freeformPreviewRect = result.rect; + _freeformGuides = result.guides; + }); + }, + onPointerUp: (event) { + if (_freeformResizePointer != event.pointer) return; + _freeformResizePointer = null; + _freeformResizingId = null; + _finishFreeformGesture(id); + }, + onPointerCancel: (event) { + if (_freeformResizePointer != event.pointer) return; + _freeformResizePointer = null; + _freeformResizingId = null; + _finishFreeformGesture(id); + }, + child: Container( + width: 16, + height: 16, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, + border: Border.all(color: Colors.white, width: 2), + borderRadius: BorderRadius.circular(3), + ), + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } + bool _canDropOnRegion(_BlockDragData data, String region) { final type = data.blockType ?? @@ -663,27 +1839,23 @@ class _ReportTemplateStudioV3BuilderState ); } - Widget _canvasBlock(BuildContext context, Map block) { + Widget _canvasBlock( + BuildContext context, + Map block, { + required double rowWidth, + required int maxSpan, + }) { 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( + key: ValueKey('canvas-block-$id'), behavior: HitTestBehavior.opaque, onTap: () => _selectBlock(id), child: AnimatedContainer( @@ -743,44 +1915,93 @@ class _ReportTemplateStudioV3BuilderState ), ), ), + if (selected) + PositionedDirectional( + top: 0, + bottom: 0, + end: -6, + child: MouseRegion( + cursor: SystemMouseCursors.resizeLeftRight, + child: GestureDetector( + key: ValueKey('block-width-handle-$id'), + behavior: HitTestBehavior.opaque, + onHorizontalDragStart: (_) { + _resizingBlockId = id; + _resizeStartSpan = _blockSpan(block); + _resizePreviewSpan = _resizeStartSpan; + _resizeHorizontalDelta = 0; + setState(() {}); + }, + onHorizontalDragUpdate: (details) { + _resizeHorizontalDelta += details.delta.dx; + final rtl = + Directionality.of(context) == TextDirection.rtl; + final deltaColumns = + _resizeHorizontalDelta / + (rowWidth / 60) * + (rtl ? -1 : 1); + setState(() { + _resizePreviewSpan = + ((_resizeStartSpan ?? 60) + deltaColumns.round()) + .clamp(1, maxSpan) + .toInt(); + }); + }, + onHorizontalDragEnd: (_) { + final span = _resizePreviewSpan ?? _blockSpan(block); + _resizingBlockId = null; + _resizeStartSpan = null; + _resizePreviewSpan = null; + _resizeHorizontalDelta = 0; + _patchBlockStyle(id, { + 'width_mode': 'full', + 'grid_span': span, + }); + }, + child: Container( + width: 12, + alignment: Alignment.center, + child: Container( + width: 4, + height: 34, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, + borderRadius: BorderRadius.circular(3), + ), + ), + ), + ), + ), + ), ], ), ), ); - 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)), - ], - ), - ), + return 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, - ), ), ), + childWhenDragging: Opacity(opacity: 0.25, child: blockCard), + child: MouseRegion(cursor: SystemMouseCursors.grab, child: blockCard), ), ); } @@ -967,7 +2188,9 @@ class _ReportTemplateStudioV3BuilderState Row( children: [ Text( - 'طراح بلوکی', + isReportTemplateV4(widget.design) + ? 'طراح گرید تمام‌صفحه' + : 'طراح بلوکی', style: Theme.of( context, ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), @@ -986,7 +2209,9 @@ class _ReportTemplateStudioV3BuilderState ], ), Text( - 'قطعه را بکشید و در محل دلخواه رها کنید؛ برای موبایل می‌توانید روی قطعه بزنید.', + isReportTemplateV4(widget.design) + ? 'قطعه را از فهرست روی هر نقطهٔ صفحه رها کنید؛ سپس آن را آزادانه جابه‌جا یا تغییر اندازه دهید.' + : 'برای ساخت ردیف جدید، قطعه را بین ردیف‌ها رها کنید؛ برای چیدن چند قطعه کنار هم، آن را روی یک قطعهٔ دیگر رها کنید.', style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 12), @@ -1042,6 +2267,20 @@ class _ReportTemplateStudioV3BuilderState design['media'] = media; }), ), + if (isReportTemplateV4(widget.design)) + Card( + margin: const EdgeInsets.only(top: 10), + child: ListTile( + dense: true, + leading: const Icon(Icons.devices_fold_outlined), + title: Text( + 'Variant فعال: ${reportTemplateV4ProfileKey(widget.design)}', + ), + subtitle: const Text( + 'چیدمان هر کاغذ مستقل است؛ با تغییر اندازه کاغذ، variant همان کاغذ ویرایش می‌شود.', + ), + ), + ), const SizedBox(height: 12), ], ), @@ -1463,19 +2702,48 @@ 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); + final found = _findBlock(id); + final rowId = found == null + ? (style['row_id'] ?? '').toString() + : _blockRowId(block, found.region); + final gridSpan = _blockSpan(block); + final rowBlocks = found == null + ? >[block] + : _regionBlocks(widget.design, found.region) + .where( + (candidate) => _blockRowId(candidate, found.region) == rowId, + ) + .toList(); + final otherSpans = rowBlocks + .where((candidate) => candidate['id']?.toString() != id) + .fold(0, (sum, candidate) => sum + _blockSpan(candidate)); + final maxGridSpan = (60 - otherSpans).clamp(1, 60).toInt(); + final rowHeightMode = (style['row_height_mode'] ?? 'auto').toString(); + final rowHeightMm = ((style['row_height_mm'] as num?)?.toDouble() ?? 20) + .clamp(4, 500) + .toDouble(); + final layoutType = (style['layout_type'] ?? 'grid').toString(); + final pageGrid = isReportTemplateV4(widget.design); + final freeformGrid = + ((style[pageGrid ? 'page_grid_mm' : 'freeform_grid_mm'] as num?) + ?.toInt() ?? + 1) + .clamp(1, 5); + final media = normalizedReportTemplateMedia(widget.design); + final mediaSize = reportTemplateMediaSizeMm(media); + final mediaMargins = + (media['margins_mm'] as Map?)?.cast() ?? const {}; + final defaultCanvasHeight = + mediaSize.height - + ((mediaMargins['top'] as num?)?.toDouble() ?? 0) - + ((mediaMargins['bottom'] as num?)?.toDouble() ?? 0); + final freeformHeight = + ((style[pageGrid ? 'page_height_mm' : 'freeform_height_mm'] as num?) + ?.toDouble() ?? + (pageGrid ? defaultCanvasHeight : 40)) + .clamp(10, 5000) + .toDouble(); + final freeformRect = _freeformRect(block); const alignableTypes = { 'brand_header', 'party_info', @@ -1538,57 +2806,204 @@ 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, + if (pageGrid) ...[ + const Text('جای‌گذاری روی گرید کل صفحه'), + Text( + 'همه اجزا روی یک بوم مشترک حرکت و تغییر اندازه می‌دهند.', + style: Theme.of(context).textTheme.bodySmall, ), - items: const [ - DropdownMenuItem(value: 'full', child: Text('تمام عرض')), - DropdownMenuItem( - value: 'percentage', - child: Text('درصدی از صفحه'), + const SizedBox(height: 14), + ], + if (layoutType == 'freeform' || pageGrid) ...[ + Text(pageGrid ? 'شبکه کل صفحه و Snap' : 'شبکه و Snap'), + const SizedBox(height: 6), + SegmentedButton( + segments: const [ + ButtonSegment(value: 1, label: Text('۱ mm')), + ButtonSegment(value: 3, label: Text('۳ mm')), + ButtonSegment(value: 5, label: Text('۵ mm')), + ], + selected: { + const {1, 3, 5}.contains(freeformGrid) ? freeformGrid : 1, + }, + onSelectionChanged: (values) => pageGrid + ? _patchPageGridSettings({'page_grid_mm': values.first}) + : _patchRowStyle(rowId, { + 'freeform_grid_mm': values.first, + 'layout_type': 'freeform', + }), + ), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Snap هوشمند'), + subtitle: const Text('گرید، حاشیه، لبه و مرکز عناصر'), + value: style[pageGrid ? 'page_snap' : 'freeform_snap'] != false, + onChanged: (value) => pageGrid + ? _patchPageGridSettings({'page_snap': value}) + : _patchRowStyle(rowId, { + 'freeform_snap': value, + 'layout_type': 'freeform', + }), + ), + if (!pageGrid || media['type'] == 'roll') ...[ + Text( + '${pageGrid ? 'طول بوم رول' : 'ارتفاع محدوده'}: ${freeformHeight.toStringAsFixed(0)} mm', ), - DropdownMenuItem( - value: 'fixed', - child: Text('عرض ثابت (میلی‌متر)'), - ), - DropdownMenuItem( - value: 'content', - child: Text('متناسب با محتوا'), + Slider( + min: pageGrid ? 120 : 10, + max: pageGrid ? 1500 : 300, + divisions: pageGrid ? 138 : 290, + value: freeformHeight.clamp( + pageGrid ? 120 : 10, + pageGrid ? 1500 : 300, + ), + onChanged: (value) => pageGrid + ? _patchPageGridSettings({ + 'page_height_mm': value.round(), + }) + : _patchRowStyle(rowId, { + 'freeform_height_mm': value.round(), + 'layout_type': 'freeform', + }), ), ], - 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') ...[ + Text( + 'X ${freeformRect.x.toStringAsFixed(1)} · Y ${freeformRect.y.toStringAsFixed(1)} · W ${freeformRect.width.toStringAsFixed(1)} · H ${freeformRect.height.toStringAsFixed(1)} mm', + ), + const SizedBox(height: 6), + Row( + children: [ + for (final field in <(String, String, double)>[ + ('x_mm', 'X', freeformRect.x), + ('y_mm', 'Y', freeformRect.y), + ('width_mm', 'W', freeformRect.width), + ('height_mm', 'H', freeformRect.height), + ]) ...[ + Expanded( + child: TextFormField( + key: ValueKey('$id-${field.$1}-${field.$3}'), + initialValue: field.$3.toStringAsFixed(1), + decoration: InputDecoration( + labelText: field.$2, + suffixText: 'mm', + isDense: true, + border: const OutlineInputBorder(), + ), + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + ), + onFieldSubmitted: (raw) { + final value = double.tryParse(raw); + if (value != null && value >= 0) { + _patchFreeformGeometryField( + block, + field.$1, + value, + freeformHeight, + ); + } + }, + ), + ), + if (field.$1 != 'height_mm') const SizedBox(width: 5), + ], + ], + ), + const SizedBox(height: 6), + Text( + 'عنصر را در کل صفحه بکشید؛ برای تغییر اندازه از دستگیرهٔ گوشه استفاده کنید.', + style: Theme.of(context).textTheme.bodySmall, + ), + ] else ...[ + const Text('عرض بلوک'), + Text( + 'شبکهٔ دقیق ۶۰ ستونه', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 6), + Wrap( + spacing: 6, + runSpacing: 6, + children: + const <(String, int)>[ + ('تمام عرض', 60), + ('نصف', 30), + ('یک‌سوم', 20), + ('یک‌چهارم', 15), + ('یک‌پنجم', 12), + ('یک‌ششم', 10), + ].map((preset) { + return ChoiceChip( + label: Text(preset.$1), + selected: gridSpan == preset.$2, + onSelected: preset.$2 > maxGridSpan + ? null + : (_) => _patchBlockStyle(id, { + 'width_mode': 'full', + 'grid_span': preset.$2, + }), + ); + }).toList(), + ), const SizedBox(height: 8), Text( - widthMode == 'percentage' - ? 'عرض: ${widthValue.round()}٪' - : 'عرض: ${widthValue.toStringAsFixed(0)} میلی‌متر', + '$gridSpan از ۶۰ ستون (${(gridSpan * 100 / 60).toStringAsFixed(1)}٪)', ), Slider( - min: 10, - max: widthMode == 'percentage' ? 100 : 300, - divisions: widthMode == 'percentage' ? 18 : 29, - value: widthValue.clamp( - 10.0, - widthMode == 'percentage' ? 100.0 : 300.0, + min: 1, + max: maxGridSpan.toDouble(), + divisions: maxGridSpan > 1 ? maxGridSpan - 1 : null, + value: gridSpan.clamp(1, maxGridSpan).toDouble(), + onChanged: (value) => _patchBlockStyle(id, { + 'width_mode': 'full', + 'grid_span': value.round(), + }), + ), + Text( + 'دستگیرهٔ عمودی کنار بلوک را هم می‌توانید با ماوس بکشید.', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 16), + const Text('ارتفاع ردیف'), + const SizedBox(height: 6), + SegmentedButton( + segments: const [ + ButtonSegment(value: 'auto', label: Text('خودکار')), + ButtonSegment(value: 'minimum', label: Text('حداقل')), + ButtonSegment(value: 'fixed', label: Text('ثابت')), + ], + selected: { + const {'auto', 'minimum', 'fixed'}.contains(rowHeightMode) + ? rowHeightMode + : 'auto', + }, + onSelectionChanged: rowId.isEmpty + ? null + : (values) => _patchRowStyle(rowId, { + 'row_height_mode': values.first, + if (values.first != 'auto') + 'row_height_mm': rowHeightMm, + }), + ), + if (rowHeightMode != 'auto') ...[ + const SizedBox(height: 8), + Text('ارتفاع: ${rowHeightMm.toStringAsFixed(0)} میلی‌متر'), + Slider( + min: 4, + max: 200, + divisions: 196, + value: rowHeightMm.clamp(4, 200), + onChanged: rowId.isEmpty + ? null + : (value) => _patchRowStyle(rowId, { + 'row_height_mode': rowHeightMode, + 'row_height_mm': value.round(), + }), ), - onChanged: (value) => - _patchBlockStyle(id, {'width_value': value.round()}), + ], + Text( + 'دستگیرهٔ افقی پایین ردیف را بکشید؛ دوبار کلیک، ارتفاع را خودکار می‌کند.', + style: Theme.of(context).textTheme.bodySmall, ), ], const SizedBox(height: 12), @@ -1917,3 +3332,36 @@ class _CanvasSignature extends StatelessWidget { ); } } + +class _MillimeterGridPainter extends CustomPainter { + final double pixelsPerMm; + final double gridMm; + final Color color; + + const _MillimeterGridPainter({ + required this.pixelsPerMm, + required this.gridMm, + required this.color, + }); + + @override + void paint(Canvas canvas, Size size) { + final step = pixelsPerMm * gridMm; + if (step < 2) return; + final paint = Paint() + ..color = color + ..strokeWidth = 0.5; + for (var x = step; x < size.width; x += step) { + canvas.drawLine(Offset(x, 0), Offset(x, size.height), paint); + } + for (var y = step; y < size.height; y += step) { + canvas.drawLine(Offset(0, y), Offset(size.width, y), paint); + } + } + + @override + bool shouldRepaint(covariant _MillimeterGridPainter oldDelegate) => + oldDelegate.pixelsPerMm != pixelsPerMm || + oldDelegate.gridMm != gridMm || + oldDelegate.color != color; +} diff --git a/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v4_adapter.dart b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v4_adapter.dart new file mode 100644 index 00000000..0e8f9bf0 --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/widgets/report_template/studio/report_template_studio_v4_adapter.dart @@ -0,0 +1,482 @@ +import 'dart:convert'; + +Map _cloneMap(Map value) => + (jsonDecode(jsonEncode(value)) as Map).cast(); + +Map _map(dynamic value) => + value is Map ? value.cast() : {}; + +List> _maps(dynamic value) => value is List + ? value + .whereType() + .map((item) => item.cast()) + .toList() + : >[]; + +double _number(dynamic value, double fallback) => + value is num ? value.toDouble() : double.tryParse('$value') ?? fallback; + +double _printableWidth(Map media) { + final margins = _map(media['margins_mm']); + final landscape = + media['type'] != 'roll' && media['orientation'] == 'landscape'; + final width = landscape + ? _number(media['height_mm'], 297) + : _number(media['width_mm'], 210); + return (width - _number(margins['left'], 0) - _number(margins['right'], 0)) + .clamp(10, 1000); +} + +double _printableHeight(Map media) { + final margins = _map(media['margins_mm']); + final landscape = + media['type'] != 'roll' && media['orientation'] == 'landscape'; + final height = landscape + ? _number(media['width_mm'], 210) + : _number(media['height_mm'], media['type'] == 'roll' ? 300 : 297); + return (height - _number(margins['top'], 0) - _number(margins['bottom'], 0)) + .clamp(20, 5000); +} + +double _defaultHeight(String component) => switch (component) { + 'brand_header' => 30, + 'party_info' => 24, + 'invoice_lines' => 72, + 'invoice_totals' => 38, + 'payments' => 24, + 'note' => 22, + 'signatures' => 38, + 'qr' => 34, + 'footer_meta' => 14, + 'divider' => 4, + 'spacer' => 10, + _ => 20, +}; + +bool isReportTemplateV4(Map design) => + (design['schema_version'] as num?)?.toInt() == 4; + +String reportTemplateV4ProfileKey(Map design) { + final media = _map(design['media']); + if (media['type'] == 'roll') { + final width = (media['width_mm'] as num?)?.toDouble() ?? 80; + for (final preset in const [58, 60, 80, 100]) { + if ((width - preset).abs() < 0.01) return 'roll_$preset'; + } + return 'custom_roll'; + } + final preset = (media['preset'] ?? 'A4').toString(); + final orientation = media['orientation'] == 'landscape' + ? 'landscape' + : 'portrait'; + if (const {'A3', 'A4', 'A5', 'A6', 'Letter', 'Legal'}.contains(preset)) { + return '${preset.toLowerCase()}_$orientation'; + } + return 'custom_sheet_$orientation'; +} + +void syncReportTemplateV4ActiveMedia(Map design) { + if (!isReportTemplateV4(design)) return; + final variants = _map(design['variants']); + final key = reportTemplateV4ProfileKey(design); + final variant = _map(variants[key]); + if (variant.isEmpty) return; + variant['media'] = _cloneMap(_map(design['media'])); + variants[key] = variant; + design['variants'] = variants; + design['active_variant'] = key; +} + +Map _activeOverrides(Map design) { + final variants = _map(design['variants']); + final variant = _map(variants[reportTemplateV4ProfileKey(design)]); + return _map(variant['node_overrides']); +} + +Map _mergedNode( + Map node, + Map overrides, +) { + final result = _cloneMap(node); + final override = _map(overrides[(node['id'] ?? '').toString()]); + for (final key in const ['layout', 'placement', 'style']) { + if (override[key] is Map) { + result[key] = { + ..._map(result[key]), + ..._map(override[key]), + }; + } + } + return result; +} + +/// Produces the flat, v3-shaped editing projection. It is never persisted. +Map reportTemplateV4StudioProjection( + Map design, +) { + if (!isReportTemplateV4(design)) return _cloneMap(design); + final overrides = _activeOverrides(design); + final regions = { + 'header': >[], + 'body': >[], + 'footer': >[], + }; + final root = _mergedNode(_map(design['root']), overrides); + final rootLayout = _map(root['layout']); + final sourcePageGrid = rootLayout['type'] == 'page_grid'; + // Every v4 document is edited as one page-wide millimeter grid. This also + // upgrades drafts produced by the short-lived row/freeform v4 prototype. + final media = _map(design['media']); + final pageWidth = _number(rootLayout['width_mm'], _printableWidth(media)); + var fallbackY = 0.0; + for (final rawRegion in _maps(root['children'])) { + final region = _mergedNode(rawRegion, overrides); + final regionName = (region['region'] ?? '').toString(); + if (!regions.containsKey(regionName)) continue; + final blocks = regions[regionName] as List>; + for (final rawRow in _maps(region['children'])) { + final row = _mergedNode(rawRow, overrides); + final layout = _map(row['layout']); + final layoutType = (layout['type'] ?? 'grid').toString(); + final rowChildren = _maps(row['children']); + final fallbackHeight = rowChildren + .map((child) => _defaultHeight((child['component'] ?? '').toString())) + .fold(20, (height, next) => next > height ? next : height); + var fallbackX = 0.0; + for (final rawComponent in rowChildren) { + final component = _mergedNode(rawComponent, overrides); + if (component['kind'] != 'component') continue; + final placement = _map(component['placement']); + final span = _number(placement['column_span'], 60).clamp(1, 60); + final fallbackWidth = pageWidth * span / 60; + final style = { + ..._map(component['style']), + 'row_id': row['id'], + 'layout_type': 'page_grid', + 'grid_span': placement['column_span'] ?? 60, + if (layout['height_mode'] != null) + 'row_height_mode': layout['height_mode'], + if (layout['height_mm'] != null) 'row_height_mm': layout['height_mm'], + if (layoutType == 'freeform') ...{ + 'freeform_grid_mm': layout['grid_mm'] ?? 1, + 'freeform_snap': layout['snap'] != false, + 'freeform_height_mm': layout['height_mm'] ?? 40, + 'x_mm': placement['x_mm'] ?? 0, + 'y_mm': placement['y_mm'] ?? 0, + 'width_mm': placement['width_mm'] ?? 30, + 'height_mm': placement['height_mm'] ?? 15, + }, + 'page_grid_mm': rootLayout['grid_mm'] ?? 1, + 'page_snap': rootLayout['snap'] != false, + 'page_height_mm': rootLayout['height_mm'] ?? _printableHeight(media), + 'x_mm': sourcePageGrid + ? placement['x_mm'] ?? fallbackX + : layoutType == 'freeform' + ? placement['x_mm'] ?? fallbackX + : fallbackX, + 'y_mm': sourcePageGrid + ? placement['y_mm'] ?? fallbackY + : fallbackY + + (layoutType == 'freeform' + ? _number(placement['y_mm'], 0) + : 0), + 'width_mm': sourcePageGrid || layoutType == 'freeform' + ? placement['width_mm'] ?? fallbackWidth + : fallbackWidth, + 'height_mm': sourcePageGrid || layoutType == 'freeform' + ? placement['height_mm'] ?? fallbackHeight + : fallbackHeight, + }; + blocks.add({ + 'id': component['id'], + 'type': component['component'], + 'visible': component['visible'] != false, + 'props': _cloneMap(_map(component['props'])), + 'style': style, + }); + fallbackX += fallbackWidth; + } + fallbackY += fallbackHeight + 3; + } + } + return { + 'schema_version': 3, + 'family_id': design['family_id'], + 'layout': design['layout'], + 'theme': _cloneMap(_map(design['theme'])), + 'branding': _cloneMap(_map(design['branding'])), + 'custom_css': (design['custom_css'] ?? '').toString(), + 'media': _cloneMap(_map(design['media'])), + 'regions': regions, + }; +} + +Map _layoutFromBlocks(List> blocks) { + final style = _map(blocks.first['style']); + final type = (style['layout_type'] ?? 'grid').toString(); + if (type == 'freeform') { + return { + 'type': 'freeform', + 'height_mm': + ((style['freeform_height_mm'] ?? style['row_height_mm']) as num?) + ?.toDouble() ?? + 40, + 'grid_mm': (style['freeform_grid_mm'] as num?)?.toInt() ?? 1, + 'snap': style['freeform_snap'] != false, + }; + } + // page_grid is the document-level layout. Semantic rows remain ordinary + // containers so the component/region catalog stays intact. + return { + 'type': 'grid', + 'columns': 60, + 'gap_mm': 0, + if (style['row_height_mode'] != null) + 'height_mode': style['row_height_mode'], + if (style['row_height_mm'] != null) 'height_mm': style['row_height_mm'], + }; +} + +Map _componentFromBlock(Map block) { + final style = _cloneMap(_map(block['style'])); + final layoutType = (style['layout_type'] ?? 'grid').toString(); + final placement = layoutType == 'freeform' || layoutType == 'page_grid' + ? { + 'x_mm': (style['x_mm'] as num?)?.toDouble() ?? 0, + 'y_mm': (style['y_mm'] as num?)?.toDouble() ?? 0, + 'width_mm': (style['width_mm'] as num?)?.toDouble() ?? 30, + 'height_mm': (style['height_mm'] as num?)?.toDouble() ?? 15, + } + : { + 'column_span': (style['grid_span'] as num?)?.toInt() ?? 60, + }; + for (final key in const [ + 'row_id', + 'layout_type', + 'grid_span', + 'row_height_mode', + 'row_height_mm', + 'freeform_grid_mm', + 'freeform_snap', + 'freeform_height_mm', + 'page_grid_mm', + 'page_snap', + 'page_height_mm', + 'x_mm', + 'y_mm', + 'width_mm', + 'height_mm', + ]) { + style.remove(key); + } + return { + 'id': block['id'], + 'kind': 'component', + 'component': block['type'], + 'visible': block['visible'] != false, + 'props': _cloneMap(_map(block['props'])), + 'style': style, + 'placement': placement, + }; +} + +List> _rowsFromBlocks( + List> blocks, + String region, +) { + final rows = >[]; + var index = 0; + while (index < blocks.length) { + final block = blocks[index]; + final style = _map(block['style']); + final rowId = (style['row_id'] ?? 'row-${block['id']}').toString(); + final grouped = >[block]; + index++; + while (index < blocks.length && + (_map(blocks[index]['style'])['row_id'] ?? '').toString() == rowId) { + grouped.add(blocks[index]); + index++; + } + rows.add({ + 'id': rowId, + 'kind': 'container', + 'layout': _layoutFromBlocks(grouped), + 'children': grouped.map(_componentFromBlock).toList(), + }); + } + return rows; +} + +Iterable> _walk(Map node) sync* { + yield node; + for (final child in _maps(node['children'])) { + yield* _walk(child); + } +} + +/// Applies a flat editing projection back to the canonical tree and updates +/// only the active responsive variant. Other paper layouts stay explicit. +Map applyStudioProjectionToReportTemplateV4( + Map original, + Map projection, +) { + if (!isReportTemplateV4(original)) return _cloneMap(projection); + final design = _cloneMap(original); + final projectionRegions = _map(projection['regions']); + final root = _map(design['root']); + final existingRegions = >{ + for (final node in _maps(root['children'])) + if (node['region'] != null) node['region'].toString(): node, + }; + final regionNodes = >[]; + for (final region in const ['header', 'body', 'footer']) { + final existing = existingRegions[region]; + regionNodes.add({ + 'id': existing?['id'] ?? 'region-$region', + 'kind': 'container', + 'region': region, + 'layout': _cloneMap( + _map(existing?['layout']).isEmpty + ? {'type': 'flow', 'gap_mm': 2} + : _map(existing?['layout']), + ), + 'children': _rowsFromBlocks(_maps(projectionRegions[region]), region), + }); + } + final allBlocks = >[ + for (final region in const ['header', 'body', 'footer']) + ..._maps(projectionRegions[region]), + ]; + final firstStyle = allBlocks.isEmpty + ? {} + : _map(allBlocks.first['style']); + if (firstStyle['layout_type'] == 'page_grid') { + final media = _map(projection['media']); + root['layout'] = { + ..._map(root['layout']), + 'type': 'page_grid', + 'grid_mm': (firstStyle['page_grid_mm'] as num?)?.toInt() ?? 1, + 'snap': firstStyle['page_snap'] != false, + 'width_mm': _printableWidth(media), + 'height_mm': _number( + firstStyle['page_height_mm'], + _printableHeight(media), + ), + }; + } + root['children'] = regionNodes; + design['root'] = root; + for (final key in const [ + 'family_id', + 'layout', + 'theme', + 'branding', + 'custom_css', + 'media', + ]) { + if (projection.containsKey(key)) design[key] = projection[key]; + } + final nodes = >{ + for (final node in _walk(root)) (node['id'] ?? '').toString(): node, + }..remove(''); + final variants = _map(design['variants']); + final activeKey = reportTemplateV4ProfileKey(design); + final rootId = (root['id'] ?? 'invoice-root').toString(); + final activeRootLayout = _map(root['layout']); + final activeCanvasWidth = _number( + activeRootLayout['width_mm'], + _printableWidth(_map(design['media'])), + ); + final activeCanvasHeight = _number( + activeRootLayout['height_mm'], + _printableHeight(_map(design['media'])), + ); + for (final entry in variants.entries.toList()) { + final variant = _map(entry.value); + if (entry.key == activeKey) { + variant['media'] = _cloneMap(_map(design['media'])); + } + final oldOverrides = _map(variant['node_overrides']); + final nextOverrides = {}; + final narrow = entry.key.startsWith('roll_') || entry.key == 'custom_roll'; + final variantMedia = _map(variant['media']).isEmpty + ? _map(design['media']) + : _map(variant['media']); + final variantRootLayout = _map(_map(oldOverrides[rootId])['layout']); + final targetCanvasWidth = _number( + variantRootLayout['width_mm'], + _printableWidth(variantMedia), + ); + final targetCanvasHeight = _number( + variantRootLayout['height_mm'], + _printableHeight(variantMedia), + ); + for (final nodeEntry in nodes.entries) { + final node = nodeEntry.value; + final existing = _map(oldOverrides[nodeEntry.key]); + if (node['kind'] == 'container') { + nextOverrides[nodeEntry.key] = { + 'layout': entry.key == activeKey + ? _cloneMap(_map(node['layout'])) + : _cloneMap( + _map(existing['layout']).isEmpty + ? _map(node['layout']) + : _map(existing['layout']), + ), + }; + } else { + var placement = entry.key == activeKey + ? _cloneMap(_map(node['placement'])) + : _cloneMap( + _map(existing['placement']).isEmpty + ? _map(node['placement']) + : _map(existing['placement']), + ); + if (existing.isEmpty && + narrow && + placement.containsKey('column_span')) { + placement['column_span'] = 60; + } + if (entry.key != activeKey && + existing.isEmpty && + placement.containsKey('x_mm')) { + final sourceX = _number(placement['x_mm'], 0); + final sourceY = _number(placement['y_mm'], 0); + final sourceWidth = _number(placement['width_mm'], 30); + final sourceHeight = _number(placement['height_mm'], 20); + final widthRatio = + targetCanvasWidth / activeCanvasWidth.clamp(1, 1000); + final heightRatio = + targetCanvasHeight / activeCanvasHeight.clamp(1, 5000); + final width = (narrow ? targetCanvasWidth : sourceWidth * widthRatio) + .clamp(1, targetCanvasWidth) + .toDouble(); + final height = (sourceHeight * heightRatio) + .clamp(1, targetCanvasHeight) + .toDouble(); + placement = { + ...placement, + 'x_mm': narrow + ? 0.0 + : (sourceX * widthRatio) + .clamp(0, targetCanvasWidth - width) + .toDouble(), + 'y_mm': (sourceY * heightRatio) + .clamp(0, targetCanvasHeight - height) + .toDouble(), + 'width_mm': width, + 'height_mm': height, + }; + } + nextOverrides[nodeEntry.key] = { + 'placement': placement, + }; + } + } + variant['node_overrides'] = nextOverrides; + variants[entry.key] = variant; + } + design['variants'] = variants; + design['active_variant'] = activeKey; + return design; +} 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 bcb4f1b5..5e5a9279 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 @@ -216,6 +216,30 @@ void main() { .cast>(); expect(footer.map((block) => block['type']), contains('custom_text')); + final customId = footer.first['id'].toString(); + await tester.drag( + find.byKey(ValueKey('canvas-block-$customId')), + tester.getCenter( + find.byKey( + const ValueKey( + 'canvas-row-drop-legacy-body-invoice-lines-invoice-lines', + ), + ), + ) - + tester.getCenter(find.byKey(ValueKey('canvas-block-$customId'))), + ); + await tester.pumpAndSettle(); + final sideBySideBody = ((design['regions'] as Map)['body'] as List) + .cast>(); + expect(sideBySideBody, hasLength(2)); + final firstStyle = (sideBySideBody.first['style'] as Map) + .cast(); + final secondStyle = (sideBySideBody.last['style'] as Map) + .cast(); + expect(firstStyle['row_id'], secondStyle['row_id']); + expect(firstStyle['grid_span'], 30); + expect(secondStyle['grid_span'], 30); + await tester.tap(find.text('نمونه کالا 1')); await tester.pump(); @@ -240,6 +264,31 @@ void main() { .cast>(); expect((body.first['style'] as Map)['text_align'], 'center'); + await tester.drag( + find.byKey(const ValueKey('block-width-handle-invoice-lines')), + const Offset(40, 0), + ); + await tester.pump(); + final resizedBody = ((design['regions'] as Map)['body'] as List) + .cast>(); + expect( + ((resizedBody.first['style'] as Map)['grid_span'] as num), + lessThan(30), + ); + + final rowId = (resizedBody.first['style'] as Map)['row_id'].toString(); + await tester.drag( + find.byKey(ValueKey('row-height-handle-$rowId')), + const Offset(0, 30), + ); + await tester.pump(const Duration(milliseconds: 100)); + final resizedRowBody = ((design['regions'] as Map)['body'] as List) + .cast>(); + expect( + (resizedRowBody.first['style'] as Map)['row_height_mode'], + 'minimum', + ); + await tester.tap(find.text('خروجی')); await tester.pump(); expect(find.text('پیش‌نمایش آزمایشی'), findsOneWidget); diff --git a/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v4_test.dart b/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v4_test.dart new file mode 100644 index 00000000..98d1b7d8 --- /dev/null +++ b/hesabixUI/hesabix_ui/test/widgets/report_template_studio_v4_test.dart @@ -0,0 +1,252 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hesabix_ui/widgets/report_template/studio/report_template_snap_engine.dart'; +import 'package:hesabix_ui/widgets/report_template/studio/report_template_studio_v3_builder.dart'; +import 'package:hesabix_ui/widgets/report_template/studio/report_template_studio_v4_adapter.dart'; + +Map _design() { + const rowLayout = { + 'type': 'grid', + 'columns': 60, + 'gap_mm': 0, + }; + const placement = { + 'column_span': 30, + 'x_mm': 5, + 'y_mm': 8, + 'width_mm': 60, + 'height_mm': 24, + }; + final root = { + 'id': 'invoice-root', + 'kind': 'container', + 'layout': { + 'type': 'page_grid', + 'grid_mm': 1, + 'snap': true, + 'width_mm': 190, + 'height_mm': 277, + }, + 'children': [ + for (final region in const ['header', 'body', 'footer']) + { + 'id': 'region-$region', + 'kind': 'container', + 'region': region, + 'layout': {'type': 'flow'}, + 'children': region == 'body' + ? [ + { + 'id': 'row-text', + 'kind': 'container', + 'layout': rowLayout, + 'children': [ + { + 'id': 'text-one', + 'kind': 'component', + 'component': 'custom_text', + 'visible': true, + 'props': {'text': 'متن تست'}, + 'style': {}, + 'placement': placement, + }, + ], + }, + ] + : [], + }, + ], + }; + Map overrides(double x, double width) => { + 'invoice-root': { + 'layout': { + 'type': 'page_grid', + 'grid_mm': 1, + 'snap': true, + 'width_mm': width == 60 ? 190 : 76, + 'height_mm': 277, + }, + }, + 'region-header': { + 'layout': {'type': 'flow'}, + }, + 'region-body': { + 'layout': {'type': 'flow'}, + }, + 'region-footer': { + 'layout': {'type': 'flow'}, + }, + 'row-text': {'layout': rowLayout}, + 'text-one': { + 'placement': {...placement, 'x_mm': x, 'width_mm': width}, + }, + }; + return { + 'schema_version': 4, + 'family_id': 'invoice_classic', + 'layout': 'invoice_detail', + 'theme': {'direction': 'rtl'}, + 'branding': {}, + 'media': { + 'type': 'sheet', + 'preset': 'A4', + 'width_mm': 210, + 'height_mm': 297, + 'orientation': 'portrait', + 'margins_mm': {'top': 10, 'right': 10, 'bottom': 10, 'left': 10}, + }, + 'root': root, + 'variants': { + 'a4_portrait': { + 'media': {}, + 'node_overrides': overrides(5, 60), + }, + 'roll_80': { + 'media': {}, + 'node_overrides': overrides(2, 76), + }, + }, + }; +} + +void main() { + test('responsive paper variants are projected and edited independently', () { + final design = _design(); + var projection = reportTemplateV4StudioProjection(design); + var block = ((projection['regions'] as Map)['body'] as List).first as Map; + expect((block['style'] as Map)['x_mm'], 5); + + (block['style'] as Map)['x_mm'] = 20; + final updated = applyStudioProjectionToReportTemplateV4(design, projection); + final variants = updated['variants'] as Map; + expect( + (((variants['a4_portrait'] as Map)['node_overrides'] as Map)['text-one'] + as Map)['placement']['x_mm'], + 20, + ); + expect( + (((variants['roll_80'] as Map)['node_overrides'] as Map)['text-one'] + as Map)['placement']['x_mm'], + 2, + ); + + final bodyBlocks = (projection['regions'] as Map)['body'] as List; + bodyBlocks.add({ + 'id': 'text-new', + 'type': 'custom_text', + 'visible': true, + 'props': {'text': 'جدید'}, + 'style': { + 'row_id': 'row-new', + 'layout_type': 'page_grid', + 'page_grid_mm': 1, + 'page_snap': true, + 'page_height_mm': 277, + 'x_mm': 5, + 'y_mm': 220, + 'width_mm': 180, + 'height_mm': 20, + }, + }); + final withNewBlock = applyStudioProjectionToReportTemplateV4( + design, + projection, + ); + final rollVariant = (withNewBlock['variants'] as Map)['roll_80'] as Map; + final rollOverrides = rollVariant['node_overrides'] as Map; + final newRollNode = rollOverrides['text-new'] as Map; + final newRollPlacement = newRollNode['placement'] as Map; + expect(newRollPlacement['x_mm'], 0); + expect(newRollPlacement['width_mm'], 76); + + (updated['media'] as Map) + ..['type'] = 'roll' + ..['preset'] = '80mm' + ..['width_mm'] = 80; + projection = reportTemplateV4StudioProjection(updated); + block = ((projection['regions'] as Map)['body'] as List).first as Map; + expect((block['style'] as Map)['x_mm'], 2); + }); + + test('snap move prefers sibling edges and clamps inside container', () { + final result = snapStudioMove( + proposed: const StudioMmRect(19.4, 7.2, 10, 10), + siblings: const [StudioMmRect(30, 5, 12, 10)], + containerWidthMm: 80, + containerHeightMm: 40, + gridMm: 5, + thresholdMm: 1, + ); + expect(result.rect.right, 30); + expect(result.guides.any((guide) => guide.source == 'sibling'), isTrue); + + final clamped = snapStudioMove( + proposed: const StudioMmRect(78, 38, 10, 10), + siblings: const [], + containerWidthMm: 80, + containerHeightMm: 40, + gridMm: 1, + thresholdMm: 0, + enabled: false, + ); + expect(clamped.rect.x, 70); + expect(clamped.rect.y, 30); + }); + + testWidgets('v4 full-page grid keeps content visible and supports gestures', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1600, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + Map? changed; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 1500, + height: 900, + child: ReportTemplateStudioV3Builder( + design: _design(), + blockCatalog: const [ + { + 'type': 'custom_text', + 'label_fa': 'متن دلخواه', + 'allowed_regions': ['header', 'body', 'footer'], + 'default_props': {'text': 'متن'}, + }, + ], + onDesignChanged: (value) => changed = value, + previewPane: const ColoredBox(color: Colors.white), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final block = find.byKey(const ValueKey('freeform-block-text-one')); + expect(block, findsOneWidget); + expect(find.text('متن تست'), findsOneWidget); + final beforeMove = tester.getTopLeft(block); + final moveGesture = await tester.startGesture(tester.getCenter(block)); + await moveGesture.moveBy(const Offset(30, 0)); + await tester.pump(); + expect(tester.getTopLeft(block).dx, greaterThan(beforeMove.dx)); + await moveGesture.up(); + await tester.pump(); + expect(changed, isNotNull); + changed = null; + final handle = find.byKey( + const ValueKey('freeform-resize-handle-text-one'), + ); + expect(handle, findsOneWidget); + final before = tester.getSize(block); + final gesture = await tester.startGesture(tester.getCenter(handle)); + await gesture.moveBy(const Offset(36, 0)); + await tester.pump(); + expect(tester.getSize(block).width, greaterThan(before.width)); + await gesture.up(); + await tester.pump(); + expect(changed, isNotNull); + expect(changed!['schema_version'], 4); + }); +}