feat(report-templates): add resizable grid layout #25

Merged
morrning merged 2 commits from Seyyed/Seyyed_arc:feature/report-template-studio into master 2026-10-22 12:40:42 +03:30
15 changed files with 4382 additions and 133 deletions

View file

@ -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
<section
class="rt-node rt-party-info"
data-template-node-id="buyer-info"
>
...
</section>
```
برای بازتولید خروجی منتشرشده بهتر است 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 روی آن قرار بگیرند.

View file

@ -23,6 +23,10 @@ from app.services.report_template_v3_service import (
migrate_v2_design_to_v3, migrate_v2_design_to_v3,
studio_block_catalog, 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 from app.services.template_design_v3_compiler import compile_template_design_to_jinja_html
router = APIRouter(prefix="/report-templates", tags=["قالب‌های گزارش", "گزارش‌ها"]) 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) items = list_gallery_items(module_key=module_key, subtype=subtype)
for item in items: for item in items:
try: 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: except ValueError:
# Scopeهایی که هنوز وارد Studio v3 نشده‌اند، با ویرایشگر v2 باز می‌شوند. # Scopeهایی که هنوز وارد Studio v3 نشده‌اند، با ویرایشگر v2 باز می‌شوند.
pass pass
@ -1129,6 +1135,22 @@ async def report_template_studio_blocks(
return {"items": studio_block_catalog(module_key, subtype)} 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( @router.post(
"/business/{business_id}/validate-v2-design", "/business/{business_id}/validate-v2-design",
summary="اعتبارسنجی طراحی Studio v2", summary="اعتبارسنجی طراحی Studio v2",
@ -1259,6 +1281,31 @@ async def migrate_v2_to_v3_endpoint(
return {"design": migrated} 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( @router.post(
"/business/{business_id}/migrate-builder-to-v2", "/business/{business_id}/migrate-builder-to-v2",
summary="تبدیل طراحی Builder قدیمی به Studio v2", summary="تبدیل طراحی Builder قدیمی به Studio v2",

View file

@ -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_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_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_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__) logger = logging.getLogger(__name__)
@ -220,6 +221,8 @@ class ReportTemplateService:
subtype: Optional[str], subtype: Optional[str],
design: Dict[str, Any], design: Dict[str, Any],
) -> Dict[str, List[str]]: ) -> Dict[str, List[str]]:
if is_v4_design(design):
return validate_v4_design(module_key, subtype, design)
if is_v3_design(design): if is_v3_design(design):
return validate_v3_design(module_key, subtype, design) return validate_v3_design(module_key, subtype, design)
return validate_v2_design(module_key, subtype, design) return validate_v2_design(module_key, subtype, design)

View file

@ -186,7 +186,11 @@ def _block(block_id: str, block_type: str, props: dict[str, Any] | None = None)
"type": block_type, "type": block_type,
"visible": True, "visible": True,
"props": deepcopy(props or {}), "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): if not isinstance(blocks, list):
errors.append(f"regions.{region_name} must be a list") errors.append(f"regions.{region_name} must be a list")
continue continue
row_spans: dict[str, int] = {}
for index, block in enumerate(blocks): for index, block in enumerate(blocks):
if not isinstance(block, dict): if not isinstance(block, dict):
errors.append(f"Invalid block in {region_name} at index {index}") 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() text_align = str(style.get("text_align") or "").strip().lower()
if text_align and text_align not in ("right", "center", "left"): if text_align and text_align not in ("right", "center", "left"):
errors.append(f"Invalid text alignment in block '{block_id}'") 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() width_mode = str(style.get("width_mode") or "full").strip().lower()
if width_mode not in ("full", "percentage", "fixed", "content"): if width_mode not in ("full", "percentage", "fixed", "content"):
errors.append(f"Invalid width mode in block '{block_id}'") 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}") 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: 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}'") 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(): for block_type, definition in _BLOCKS.items():
count = counts.get(block_type, 0) count = counts.get(block_type, 0)

View file

@ -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))}

View file

@ -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() align = str((block.get("props") or {}).get("align") or "").strip().lower()
if align in ("right", "center", "left"): if align in ("right", "center", "left"):
classes.append(f"rt-block-align-{align}") 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_mode = str(style.get("width_mode") or "full").strip().lower()
width_css = "width:100%;" 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: try:
width_css = f"width:{max(10, min(100, float(style.get('width_value') or 100))):g}%;" width_css = f"width:{max(10, min(100, float(style.get('width_value') or 100))):g}%;"
except (TypeError, ValueError): except (TypeError, ValueError):
@ -276,6 +283,42 @@ def _compile_block(design: dict[str, Any], block: dict[str, Any], *, receipt: bo
return f'<div class="{" ".join(classes)}" style="{width_css}">{content}</div>' return f'<div class="{" ".join(classes)}" style="{width_css}">{content}</div>'
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'<div class="{row_class}" style="{height_css}">{content}</div>')
return "".join(compiled_rows)
def compile_v3_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, str, str]: def compile_v3_design_to_jinja_html(design: dict[str, Any]) -> tuple[str, str, str, str]:
if not is_v3_design(design): if not is_v3_design(design):
raise ValueError("Not a v3 design schema") 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 table { width: 100%; table-layout: auto; }
.rt-layout img { max-width: 100%; height: auto; } .rt-layout img { max-width: 100%; height: auto; }
.rt-block { max-width: 100%; } .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-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-custom-text { white-space: pre-wrap; margin: 6px 0; }
.rt-block-align-right, .rt-block-align-right * { text-align: right !important; } .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-center, .rt-block-align-center * { text-align: center !important; }
.rt-block-align-left, .rt-block-align-left * { text-align: left !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")) header_html = _compile_region(design, "header", receipt=receipt)
body = "".join(_compile_block(design, block, receipt=receipt) for block in _blocks(design, "body")) body = _compile_region(design, "body", receipt=receipt)
footer_html = "".join(_compile_block(design, block, receipt=receipt) for block in _blocks(design, "footer")) footer_html = _compile_region(design, "footer", receipt=receipt)
body_html = f'<div class="rt-layout">{body}</div>' body_html = f'<div class="rt-layout">{body}</div>'
html_doc = f'<!doctype html><html dir="{direction}"><head></head><body>{body_html}</body></html>' html_doc = f'<!doctype html><html dir="{direction}"><head></head><body>{body_html}</body></html>'
return html_doc, css.strip(), header_html, footer_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]: 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): if is_v3_design(design):
return compile_v3_design_to_jinja_html(design) return compile_v3_design_to_jinja_html(design)
return v2.compile_v2_design_to_jinja_html(design) return v2.compile_v2_design_to_jinja_html(design)

View file

@ -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'<div class="{" ".join(classes)}" '
f'data-template-node-id="{escape(str(node.get("id") or ""), quote=True)}">{content}</div>'
)
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'<div class="rt-grid-cell" style="grid-column:span {span};">{child_html}</div>')
return (
f'<div class="rt-node rt-container rt-container-grid" data-template-node-id="{escape(str(node.get("id") or ""), quote=True)}" '
f'style="gap:{gap:g}mm;{height_css}">{"".join(children)}</div>'
)
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'<div class="rt-freeform-item" style="left:{x:g}mm;top:{y:g}mm;width:{width:g}mm;height:{child_height:g}mm;">{child_html}</div>'
)
return (
f'<div class="rt-node rt-container rt-container-freeform" data-template-node-id="{escape(str(node.get("id") or ""), quote=True)}" '
f'style="height:{height:g}mm;">{"".join(children)}</div>'
)
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'<div class="rt-node rt-container rt-container-{layout_type}" data-template-node-id="{escape(str(node.get("id") or ""), quote=True)}" '
f'style="gap:{gap:g}mm;">{children}</div>'
)
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'<div class="rt-page-grid-item{dynamic_class}" data-template-region="{escape(region, quote=True)}" '
f'style="grid-column:{column_start}/span {column_span};grid-row:{row_start}/span {row_span};'
f'min-height:{height:g}mm;">{component_html}</div>'
)
return (
f'<main class="rt-layout rt-layout-v4 rt-page-grid" data-template-node-id="{escape(str(root.get("id") or ""), quote=True)}" '
f'style="--rt-page-grid-mm:{grid_mm};--rt-page-grid-width:{width_mm:g}mm;--rt-page-grid-height:{height_mm:g}mm;'
f'grid-template-columns:repeat({columns},minmax(0,1fr));grid-template-rows:repeat({rows},minmax({grid_mm:g}mm,auto));">'
f'{"".join(items)}</main>'
)
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'<main class="rt-layout rt-layout-v4">{body}</main>'
html = (
f'<!doctype html><html dir="{direction}" data-template-schema="4" '
f'data-template-variant="{escape(profile, quote=True)}"><head></head><body>'
f'{rendered_body}</body></html>'
)
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

View file

@ -11,8 +11,15 @@ from app.services.report_template_v3_service import (
studio_block_catalog, studio_block_catalog,
validate_v3_design, 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_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_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: 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 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(): def test_v3_render_uses_hesabix_persian_font_in_css():
design_v2 = default_design_for_family("invoice_classic") design_v2 = default_design_for_family("invoice_classic")
assert design_v2 is not None assert design_v2 is not None
@ -308,3 +341,151 @@ def test_migrate_and_render_invoice_receipt_v3():
rendered = env.from_string(f"<style>{css}</style>{header}{html}{footer}").render(**_sample_invoice_context()) rendered = env.from_string(f"<style>{css}</style>{header}{html}{footer}").render(**_sample_invoice_context())
assert "INV-1" in rendered assert "INV-1" in rendered
assert "rt-receipt-items" 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"<style>{css}</style>{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

View file

@ -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_media_settings.dart';
import '../../widgets/report_template/studio/report_template_studio_preview_panel.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_v3_builder.dart';
import '../../widgets/report_template/studio/report_template_studio_v4_adapter.dart';
import '../../core/hesabix_back.dart'; import '../../core/hesabix_back.dart';
import 'report_template_html_editor_page.dart'; import 'report_template_html_editor_page.dart';
@ -69,6 +70,7 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
String? _moduleKey; String? _moduleKey;
String? _subtype; String? _subtype;
int? _templateId; int? _templateId;
bool _legacyTemplateCopied = false;
String _lastSavedFingerprint = ''; String _lastSavedFingerprint = '';
List<Map<String, dynamic>> _galleryItems = const []; List<Map<String, dynamic>> _galleryItems = const [];
@ -280,7 +282,7 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
} }
final hadStoredMedia = _design?['media'] is Map; final hadStoredMedia = _design?['media'] is Map;
await _upgradeDesignToV3IfSupported(); await _upgradeDesignToV4IfSupported();
if (hadStoredMedia) { if (hadStoredMedia) {
_applyMediaToLegacyFields( _applyMediaToLegacyFields(
normalizedReportTemplateMedia(_design!, preferRoll: _isReceiptScope), normalizedReportTemplateMedia(_design!, preferRoll: _isReceiptScope),
@ -293,18 +295,38 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
_lastSavedFingerprint = _fingerprint(); _lastSavedFingerprint = _fingerprint();
} }
Future<void> _upgradeDesignToV3IfSupported() async { Future<void> _upgradeDesignToV4IfSupported() async {
final design = _design; var design = _design;
if (design == null || (design['schema_version'] as num?)?.toInt() != 2) if (design == null) return;
return;
if (_moduleKey != 'invoices' || if (_moduleKey != 'invoices' ||
!const {'detail', 'receipt'}.contains(_subtype)) !const {'detail', 'receipt'}.contains(_subtype)) {
return; return;
final out = await _service.migrateV2ToV3( }
businessId: widget.businessId, final originalSchema = (design['schema_version'] as num?)?.toInt();
design: design, if (originalSchema == 2) {
); final out = await _service.migrateV2ToV3(
_design = (out['design'] as Map?)?.cast<String, dynamic>() ?? design; businessId: widget.businessId,
design: design,
);
design = (out['design'] as Map?)?.cast<String, dynamic>() ?? 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<String, dynamic>() ?? 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) { void _onScopeChanged(String? scopeId) {
@ -316,6 +338,7 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
_subtype = scopeId.substring(idx + 1); _subtype = scopeId.substring(idx + 1);
_step = _StudioStep.gallery; _step = _StudioStep.gallery;
_design = null; _design = null;
_legacyTemplateCopied = false;
_previewHtml = null; _previewHtml = null;
_previewPdfBytes = null; _previewPdfBytes = null;
_showPdfPreview = false; _showPdfPreview = false;
@ -350,6 +373,7 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
); );
setState(() { setState(() {
_design = nextDesign; _design = nextDesign;
_legacyTemplateCopied = false;
_step = _StudioStep.customize; _step = _StudioStep.customize;
_previewHtml = null; _previewHtml = null;
_previewPdfBytes = null; _previewPdfBytes = null;
@ -535,6 +559,7 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
preferRoll: _isReceiptScope, preferRoll: _isReceiptScope,
); );
_design = Map<String, dynamic>.from(design)..['media'] = media; _design = Map<String, dynamic>.from(design)..['media'] = media;
syncReportTemplateV4ActiveMedia(_design!);
_applyMediaToLegacyFields(media); _applyMediaToLegacyFields(media);
} }
@ -1080,7 +1105,7 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
return const Center(child: Text('قالبی انتخاب نشده است.')); 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( return ReportTemplateStudioV3Builder(
design: design, design: design,
blockCatalog: _blockCatalog, blockCatalog: _blockCatalog,
@ -1152,6 +1177,17 @@ class _ReportTemplateStudioPageState extends State<ReportTemplateStudioPage> {
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0), padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Column( child: Column(
children: [ 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( TextField(
controller: _nameCtrl, controller: _nameCtrl,
decoration: const InputDecoration( decoration: const InputDecoration(

View file

@ -347,6 +347,17 @@ class ReportTemplateService {
return res.data ?? const <String, dynamic>{}; return res.data ?? const <String, dynamic>{};
} }
Future<Map<String, dynamic>> migrateV3ToV4({
required int businessId,
required Map<String, dynamic> design,
}) async {
final res = await _api.post<Map<String, dynamic>>(
'/report-templates/business/$businessId/migrate-v3-to-v4',
data: {'design': design},
);
return res.data ?? const <String, dynamic>{};
}
Future<Map<String, dynamic>> validateV2Design({ Future<Map<String, dynamic>> validateV2Design({
required int businessId, required int businessId,
required String moduleKey, required String moduleKey,
@ -408,8 +419,10 @@ class ReportTemplateService {
query: { query: {
if (status != null && status.trim().isNotEmpty) 'status': status.trim(), if (status != null && status.trim().isNotEmpty) 'status': status.trim(),
if (actorUserId != null) 'actor_user_id': actorUserId, if (actorUserId != null) 'actor_user_id': actorUserId,
if (fromDate != null && fromDate.trim().isNotEmpty) 'from_date': fromDate.trim(), if (fromDate != null && fromDate.trim().isNotEmpty)
if (toDate != null && toDate.trim().isNotEmpty) 'to_date': toDate.trim(), 'from_date': fromDate.trim(),
if (toDate != null && toDate.trim().isNotEmpty)
'to_date': toDate.trim(),
'offset': offset, 'offset': offset,
'sort_by': sortBy, 'sort_by': sortBy,
'sort_order': sortOrder, 'sort_order': sortOrder,

View file

@ -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<StudioSnapGuide> 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<StudioMmRect> 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<StudioMmRect> 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,
),
]);
}

View file

@ -0,0 +1,482 @@
import 'dart:convert';
Map<String, dynamic> _cloneMap(Map<String, dynamic> value) =>
(jsonDecode(jsonEncode(value)) as Map).cast<String, dynamic>();
Map<String, dynamic> _map(dynamic value) =>
value is Map ? value.cast<String, dynamic>() : <String, dynamic>{};
List<Map<String, dynamic>> _maps(dynamic value) => value is List
? value
.whereType<Map>()
.map((item) => item.cast<String, dynamic>())
.toList()
: <Map<String, dynamic>>[];
double _number(dynamic value, double fallback) =>
value is num ? value.toDouble() : double.tryParse('$value') ?? fallback;
double _printableWidth(Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> design) =>
(design['schema_version'] as num?)?.toInt() == 4;
String reportTemplateV4ProfileKey(Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> _activeOverrides(Map<String, dynamic> design) {
final variants = _map(design['variants']);
final variant = _map(variants[reportTemplateV4ProfileKey(design)]);
return _map(variant['node_overrides']);
}
Map<String, dynamic> _mergedNode(
Map<String, dynamic> node,
Map<String, dynamic> 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] = <String, dynamic>{
..._map(result[key]),
..._map(override[key]),
};
}
}
return result;
}
/// Produces the flat, v3-shaped editing projection. It is never persisted.
Map<String, dynamic> reportTemplateV4StudioProjection(
Map<String, dynamic> design,
) {
if (!isReportTemplateV4(design)) return _cloneMap(design);
final overrides = _activeOverrides(design);
final regions = <String, dynamic>{
'header': <Map<String, dynamic>>[],
'body': <Map<String, dynamic>>[],
'footer': <Map<String, dynamic>>[],
};
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<Map<String, dynamic>>;
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<double>(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 = <String, dynamic>{
..._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(<String, dynamic>{
'id': component['id'],
'type': component['component'],
'visible': component['visible'] != false,
'props': _cloneMap(_map(component['props'])),
'style': style,
});
fallbackX += fallbackWidth;
}
fallbackY += fallbackHeight + 3;
}
}
return <String, dynamic>{
'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<String, dynamic> _layoutFromBlocks(List<Map<String, dynamic>> blocks) {
final style = _map(blocks.first['style']);
final type = (style['layout_type'] ?? 'grid').toString();
if (type == 'freeform') {
return <String, dynamic>{
'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 <String, dynamic>{
'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<String, dynamic> _componentFromBlock(Map<String, dynamic> block) {
final style = _cloneMap(_map(block['style']));
final layoutType = (style['layout_type'] ?? 'grid').toString();
final placement = layoutType == 'freeform' || layoutType == 'page_grid'
? <String, dynamic>{
'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,
}
: <String, dynamic>{
'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 <String, dynamic>{
'id': block['id'],
'kind': 'component',
'component': block['type'],
'visible': block['visible'] != false,
'props': _cloneMap(_map(block['props'])),
'style': style,
'placement': placement,
};
}
List<Map<String, dynamic>> _rowsFromBlocks(
List<Map<String, dynamic>> blocks,
String region,
) {
final rows = <Map<String, dynamic>>[];
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 = <Map<String, dynamic>>[block];
index++;
while (index < blocks.length &&
(_map(blocks[index]['style'])['row_id'] ?? '').toString() == rowId) {
grouped.add(blocks[index]);
index++;
}
rows.add(<String, dynamic>{
'id': rowId,
'kind': 'container',
'layout': _layoutFromBlocks(grouped),
'children': grouped.map(_componentFromBlock).toList(),
});
}
return rows;
}
Iterable<Map<String, dynamic>> _walk(Map<String, dynamic> 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<String, dynamic> applyStudioProjectionToReportTemplateV4(
Map<String, dynamic> original,
Map<String, dynamic> projection,
) {
if (!isReportTemplateV4(original)) return _cloneMap(projection);
final design = _cloneMap(original);
final projectionRegions = _map(projection['regions']);
final root = _map(design['root']);
final existingRegions = <String, Map<String, dynamic>>{
for (final node in _maps(root['children']))
if (node['region'] != null) node['region'].toString(): node,
};
final regionNodes = <Map<String, dynamic>>[];
for (final region in const ['header', 'body', 'footer']) {
final existing = existingRegions[region];
regionNodes.add(<String, dynamic>{
'id': existing?['id'] ?? 'region-$region',
'kind': 'container',
'region': region,
'layout': _cloneMap(
_map(existing?['layout']).isEmpty
? <String, dynamic>{'type': 'flow', 'gap_mm': 2}
: _map(existing?['layout']),
),
'children': _rowsFromBlocks(_maps(projectionRegions[region]), region),
});
}
final allBlocks = <Map<String, dynamic>>[
for (final region in const ['header', 'body', 'footer'])
..._maps(projectionRegions[region]),
];
final firstStyle = allBlocks.isEmpty
? <String, dynamic>{}
: _map(allBlocks.first['style']);
if (firstStyle['layout_type'] == 'page_grid') {
final media = _map(projection['media']);
root['layout'] = <String, dynamic>{
..._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 = <String, Map<String, dynamic>>{
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 = <String, dynamic>{};
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] = <String, dynamic>{
'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 = <String, dynamic>{
...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] = <String, dynamic>{
'placement': placement,
};
}
}
variant['node_overrides'] = nextOverrides;
variants[entry.key] = variant;
}
design['variants'] = variants;
design['active_variant'] = activeKey;
return design;
}

View file

@ -216,6 +216,30 @@ void main() {
.cast<Map<String, dynamic>>(); .cast<Map<String, dynamic>>();
expect(footer.map((block) => block['type']), contains('custom_text')); 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<Map<String, dynamic>>();
expect(sideBySideBody, hasLength(2));
final firstStyle = (sideBySideBody.first['style'] as Map)
.cast<String, dynamic>();
final secondStyle = (sideBySideBody.last['style'] as Map)
.cast<String, dynamic>();
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.tap(find.text('نمونه کالا 1'));
await tester.pump(); await tester.pump();
@ -240,6 +264,31 @@ void main() {
.cast<Map<String, dynamic>>(); .cast<Map<String, dynamic>>();
expect((body.first['style'] as Map)['text_align'], 'center'); 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<Map<String, dynamic>>();
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<Map<String, dynamic>>();
expect(
(resizedRowBody.first['style'] as Map)['row_height_mode'],
'minimum',
);
await tester.tap(find.text('خروجی')); await tester.tap(find.text('خروجی'));
await tester.pump(); await tester.pump();
expect(find.text('پیش‌نمایش آزمایشی'), findsOneWidget); expect(find.text('پیش‌نمایش آزمایشی'), findsOneWidget);

View file

@ -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<String, dynamic> _design() {
const rowLayout = <String, dynamic>{
'type': 'grid',
'columns': 60,
'gap_mm': 0,
};
const placement = <String, dynamic>{
'column_span': 30,
'x_mm': 5,
'y_mm': 8,
'width_mm': 60,
'height_mm': 24,
};
final root = <String, dynamic>{
'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'])
<String, dynamic>{
'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': <String, dynamic>{},
'placement': placement,
},
],
},
]
: <dynamic>[],
},
],
};
Map<String, dynamic> overrides(double x, double width) => <String, dynamic>{
'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 <String, dynamic>{
'schema_version': 4,
'family_id': 'invoice_classic',
'layout': 'invoice_detail',
'theme': {'direction': 'rtl'},
'branding': <String, dynamic>{},
'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': <String, dynamic>{},
'node_overrides': overrides(5, 60),
},
'roll_80': {
'media': <String, dynamic>{},
'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<String, dynamic>? 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);
});
}