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