Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support template-based database automation assignments https://github.com/siyuan-note/siyuan/issues/20611

Danielef631ae8cdea
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 276663516b..346003673a 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "إدراج متغير",
+ "automationTemplateTip": "يُحسب وفق المنطقة الزمنية للقاعدة؛ النتيجة الفارغة تمسح الحقل والأخطاء تتراجع عن التغيير",
+ "automationTemplateExample": "مثال",
+ "automationTemplatePreview": "نتيجة المعاينة",
+ "automationPreviewData": "بيانات المعاينة",
+ "automationPreviewItem": "إدخال نموذجي",
+ "automationPreviewTime": "تاريخ المعاينة",
+ "automationPreviewOnly": "للمعاينة فقط؛ لن تُعدَّل الإدخالات",
+ "automationTimeZone": "المنطقة الزمنية للقاعدة",
"startupFailed": "تعذر بدء SiYuan",
"startupStage": "مرحلة الفشل: ${stage}",
"startupReload": "إعادة التحميل",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 00451725e3..392bf00a12 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Variable einfügen",
+ "automationTemplateTip": "Berechnung in der Zeitzone der Regel; leere Ergebnisse löschen das Feld, Fehler machen die Änderung rückgängig",
+ "automationTemplateExample": "Beispiel",
+ "automationTemplatePreview": "Vorschauergebnis",
+ "automationPreviewData": "Daten für die Vorschau",
+ "automationPreviewItem": "Beispieleintrag",
+ "automationPreviewTime": "Datum für die Vorschau",
+ "automationPreviewOnly": "Nur Vorschau; Einträge werden nicht geändert",
+ "automationTimeZone": "Zeitzone der Regel",
"startupFailed": "SiYuan konnte nicht gestartet werden",
"startupStage": "Fehlgeschlagener Schritt: ${stage}",
"startupReload": "Neu laden",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 075a99002e..c141dfd35d 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Insert variable",
+ "automationTemplateTip": "Calculated in the rule's time zone; empty output clears the field, and errors roll back the change",
+ "automationTemplateExample": "Example",
+ "automationTemplatePreview": "Preview result",
+ "automationPreviewData": "Data used for preview",
+ "automationPreviewItem": "Example entry",
+ "automationPreviewTime": "Date used for preview",
+ "automationPreviewOnly": "Preview only; entries are not modified",
+ "automationTimeZone": "Rule time zone",
"startupFailed": "SiYuan failed to start",
"startupStage": "Failed stage: ${stage}",
"startupReload": "Reload",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 947f812e36..0ddc2a7478 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Insertar variable",
+ "automationTemplateTip": "Se calcula en la zona horaria de la regla; un resultado vacío borra el campo y los errores revierten el cambio",
+ "automationTemplateExample": "Ejemplo",
+ "automationTemplatePreview": "Resultado de la vista previa",
+ "automationPreviewData": "Datos para la vista previa",
+ "automationPreviewItem": "Entrada de ejemplo",
+ "automationPreviewTime": "Fecha para la vista previa",
+ "automationPreviewOnly": "Solo vista previa; no se modifican las entradas",
+ "automationTimeZone": "Zona horaria de la regla",
"startupFailed": "SiYuan no pudo iniciarse",
"startupStage": "Etapa con error: ${stage}",
"startupReload": "Volver a cargar",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 2a60b6fb28..fb50d229e0 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Insérer une variable",
+ "automationTemplateTip": "Calcul dans le fuseau de la règle ; un résultat vide efface le champ et une erreur annule la modification",
+ "automationTemplateExample": "Exemple",
+ "automationTemplatePreview": "Résultat de l’aperçu",
+ "automationPreviewData": "Données utilisées pour l’aperçu",
+ "automationPreviewItem": "Entrée d’exemple",
+ "automationPreviewTime": "Date utilisée pour l’aperçu",
+ "automationPreviewOnly": "Aperçu uniquement ; les entrées ne sont pas modifiées",
+ "automationTimeZone": "Fuseau horaire de la règle",
"startupFailed": "SiYuan n’a pas pu démarrer",
"startupStage": "Étape en échec : ${stage}",
"startupReload": "Recharger",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index c2e4dd9333..c4dd893121 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "הוספת משתנה",
+ "automationTemplateTip": "החישוב לפי אזור הזמן של הכלל; תוצאה ריקה מנקה את השדה ושגיאות מבטלות את השינוי",
+ "automationTemplateExample": "דוגמה",
+ "automationTemplatePreview": "תוצאת התצוגה המקדימה",
+ "automationPreviewData": "נתונים לתצוגה מקדימה",
+ "automationPreviewItem": "רשומה לדוגמה",
+ "automationPreviewTime": "תאריך לתצוגה מקדימה",
+ "automationPreviewOnly": "תצוגה מקדימה בלבד; הרשומות לא משתנות",
+ "automationTimeZone": "אזור הזמן של הכלל",
"startupFailed": "לא ניתן להפעיל את SiYuan",
"startupStage": "השלב שנכשל: ${stage}",
"startupReload": "טעינה מחדש",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index f2567a35ef..61ac0bd4d1 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "चर डालें",
+ "automationTemplateTip": "नियम के समय क्षेत्र में गणना होती है; खाली परिणाम फ़ील्ड साफ़ करता है और त्रुटि होने पर बदलाव वापस होता है",
+ "automationTemplateExample": "उदाहरण",
+ "automationTemplatePreview": "पूर्वावलोकन परिणाम",
+ "automationPreviewData": "पूर्वावलोकन का डेटा",
+ "automationPreviewItem": "उदाहरण प्रविष्टि",
+ "automationPreviewTime": "पूर्वावलोकन की तारीख",
+ "automationPreviewOnly": "केवल पूर्वावलोकन; प्रविष्टियाँ नहीं बदलतीं",
+ "automationTimeZone": "नियम का समय क्षेत्र",
"startupFailed": "SiYuan शुरू नहीं हो सका",
"startupStage": "विफल चरण: ${stage}",
"startupReload": "फिर से लोड करें",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index d22db63e39..a43f29de01 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Sisipkan variabel",
+ "automationTemplateTip": "Dihitung dalam zona waktu aturan; hasil kosong mengosongkan kolom dan kesalahan membatalkan perubahan",
+ "automationTemplateExample": "Contoh",
+ "automationTemplatePreview": "Hasil pratinjau",
+ "automationPreviewData": "Data untuk pratinjau",
+ "automationPreviewItem": "Entri contoh",
+ "automationPreviewTime": "Tanggal untuk pratinjau",
+ "automationPreviewOnly": "Hanya pratinjau; entri tidak diubah",
+ "automationTimeZone": "Zona waktu aturan",
"startupFailed": "SiYuan gagal dimulai",
"startupStage": "Tahap yang gagal: ${stage}",
"startupReload": "Muat ulang",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 35df3348d4..a69febdd34 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Inserisci variabile",
+ "automationTemplateTip": "Calcolo nel fuso orario della regola; un risultato vuoto cancella il campo e gli errori annullano la modifica",
+ "automationTemplateExample": "Esempio",
+ "automationTemplatePreview": "Risultato dell’anteprima",
+ "automationPreviewData": "Dati per l’anteprima",
+ "automationPreviewItem": "Voce di esempio",
+ "automationPreviewTime": "Data per l’anteprima",
+ "automationPreviewOnly": "Solo anteprima; le voci non vengono modificate",
+ "automationTimeZone": "Fuso orario della regola",
"startupFailed": "Impossibile avviare SiYuan",
"startupStage": "Fase non riuscita: ${stage}",
"startupReload": "Ricarica",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index d18b5ae52e..470ede6455 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "変数を挿入",
+ "automationTemplateTip": "ルールのタイムゾーンで計算し、空の結果はフィールドを消去、エラー時は変更を取り消します",
+ "automationTemplateExample": "例",
+ "automationTemplatePreview": "プレビュー結果",
+ "automationPreviewData": "プレビューに使用するデータ",
+ "automationPreviewItem": "サンプル項目",
+ "automationPreviewTime": "プレビューに使用する日時",
+ "automationPreviewOnly": "プレビュー専用で、項目は変更しません",
+ "automationTimeZone": "ルールのタイムゾーン",
"startupFailed": "SiYuan を起動できませんでした",
"startupStage": "失敗した段階:${stage}",
"startupReload": "再読み込み",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 50792e7a2c..20405bcae8 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "변수 삽입",
+ "automationTemplateTip": "규칙의 시간대로 계산하며, 빈 결과는 필드를 지우고 오류가 발생하면 변경을 되돌립니다",
+ "automationTemplateExample": "예제",
+ "automationTemplatePreview": "미리보기 결과",
+ "automationPreviewData": "미리보기에 사용할 데이터",
+ "automationPreviewItem": "예제 항목",
+ "automationPreviewTime": "미리보기에 사용할 날짜",
+ "automationPreviewOnly": "미리보기 전용이며 항목을 수정하지 않습니다",
+ "automationTimeZone": "규칙 시간대",
"startupFailed": "SiYuan을 시작하지 못했습니다",
"startupStage": "실패한 단계: ${stage}",
"startupReload": "다시 불러오기",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index ed0c51a29e..da639c594b 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Variabele invoegen",
+ "automationTemplateTip": "Berekend in de tijdzone van de regel; lege uitvoer wist het veld en fouten draaien de wijziging terug",
+ "automationTemplateExample": "Voorbeeld",
+ "automationTemplatePreview": "Voorbeeldresultaat",
+ "automationPreviewData": "Gegevens voor het voorbeeld",
+ "automationPreviewItem": "Voorbeelditem",
+ "automationPreviewTime": "Datum voor het voorbeeld",
+ "automationPreviewOnly": "Alleen een voorbeeld; items worden niet gewijzigd",
+ "automationTimeZone": "Tijdzone van de regel",
"startupFailed": "SiYuan kon niet worden gestart",
"startupStage": "Mislukte stap: ${stage}",
"startupReload": "Opnieuw laden",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index a3514ea2f4..ddbea0bcd7 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Wstaw zmienną",
+ "automationTemplateTip": "Obliczanie w strefie czasowej reguły; pusty wynik czyści pole, a błędy cofają zmianę",
+ "automationTemplateExample": "Przykład",
+ "automationTemplatePreview": "Wynik podglądu",
+ "automationPreviewData": "Dane do podglądu",
+ "automationPreviewItem": "Przykładowy wpis",
+ "automationPreviewTime": "Data do podglądu",
+ "automationPreviewOnly": "Tylko podgląd; wpisy nie są zmieniane",
+ "automationTimeZone": "Strefa czasowa reguły",
"startupFailed": "Nie udało się uruchomić SiYuan",
"startupStage": "Etap błędu: ${stage}",
"startupReload": "Wczytaj ponownie",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index dc3c62ec3b..ef2bd9c50f 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Inserir variável",
+ "automationTemplateTip": "Calculado no fuso horário da regra; resultados vazios limpam o campo e erros revertem a alteração",
+ "automationTemplateExample": "Exemplo",
+ "automationTemplatePreview": "Resultado da prévia",
+ "automationPreviewData": "Dados usados na prévia",
+ "automationPreviewItem": "Item de exemplo",
+ "automationPreviewTime": "Data usada na prévia",
+ "automationPreviewOnly": "Somente prévia; os itens não são alterados",
+ "automationTimeZone": "Fuso horário da regra",
"startupFailed": "Não foi possível iniciar o SiYuan",
"startupStage": "Etapa com falha: ${stage}",
"startupReload": "Recarregar",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 6774b285ee..6b945cd489 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Вставить переменную",
+ "automationTemplateTip": "Расчёт в часовом поясе правила; пустой результат очищает поле, ошибки отменяют изменение",
+ "automationTemplateExample": "Пример",
+ "automationTemplatePreview": "Результат предпросмотра",
+ "automationPreviewData": "Данные для предпросмотра",
+ "automationPreviewItem": "Пример записи",
+ "automationPreviewTime": "Дата для предпросмотра",
+ "automationPreviewOnly": "Только предпросмотр; записи не изменяются",
+ "automationTimeZone": "Часовой пояс правила",
"startupFailed": "Не удалось запустить SiYuan",
"startupStage": "Этап сбоя: ${stage}",
"startupReload": "Перезагрузить",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 6a5741d350..e5fc52fc23 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Vložiť premennú",
+ "automationTemplateTip": "Výpočet v časovom pásme pravidla; prázdny výsledok vymaže pole a chyby vrátia zmenu späť",
+ "automationTemplateExample": "Príklad",
+ "automationTemplatePreview": "Výsledok náhľadu",
+ "automationPreviewData": "Údaje pre náhľad",
+ "automationPreviewItem": "Vzorová položka",
+ "automationPreviewTime": "Dátum pre náhľad",
+ "automationPreviewOnly": "Iba náhľad; položky sa nemenia",
+ "automationTimeZone": "Časové pásmo pravidla",
"startupFailed": "SiYuan sa nepodarilo spustiť",
"startupStage": "Neúspešný krok: ${stage}",
"startupReload": "Znova načítať",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 73e7dbe700..dcde1b7024 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Уметни променљиву",
+ "automationTemplateTip": "Израчунавање у временској зони правила; празан резултат брише поље, а грешке поништавају измену",
+ "automationTemplateExample": "Пример",
+ "automationTemplatePreview": "Резултат прегледа",
+ "automationPreviewData": "Подаци за преглед",
+ "automationPreviewItem": "Пример ставке",
+ "automationPreviewTime": "Датум за преглед",
+ "automationPreviewOnly": "Само преглед; ставке се не мењају",
+ "automationTimeZone": "Временска зона правила",
"startupFailed": "SiYuan није могао да се покрене",
"startupStage": "Неуспешна фаза: ${stage}",
"startupReload": "Учитај поново",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index abfa0d8e39..69ec994145 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "แทรกตัวแปร",
+ "automationTemplateTip": "คำนวณตามเขตเวลาของกฎ ผลลัพธ์ว่างจะล้างช่อง และข้อผิดพลาดจะย้อนการเปลี่ยนแปลง",
+ "automationTemplateExample": "ตัวอย่าง",
+ "automationTemplatePreview": "ผลการแสดงตัวอย่าง",
+ "automationPreviewData": "ข้อมูลที่ใช้แสดงตัวอย่าง",
+ "automationPreviewItem": "รายการตัวอย่าง",
+ "automationPreviewTime": "วันที่ที่ใช้แสดงตัวอย่าง",
+ "automationPreviewOnly": "ใช้แสดงตัวอย่างเท่านั้น ไม่แก้ไขรายการ",
+ "automationTimeZone": "เขตเวลาของกฎ",
"startupFailed": "ไม่สามารถเริ่ม SiYuan ได้",
"startupStage": "ขั้นตอนที่ล้มเหลว: ${stage}",
"startupReload": "โหลดใหม่",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 4b853859cc..062562be83 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Değişken ekle",
+ "automationTemplateTip": "Kuralın saat diliminde hesaplanır; boş sonuç alanı temizler ve hatalar değişikliği geri alır",
+ "automationTemplateExample": "Örnek",
+ "automationTemplatePreview": "Önizleme sonucu",
+ "automationPreviewData": "Önizleme verileri",
+ "automationPreviewItem": "Örnek kayıt",
+ "automationPreviewTime": "Önizleme tarihi",
+ "automationPreviewOnly": "Yalnızca önizleme; kayıtlar değiştirilmez",
+ "automationTimeZone": "Kuralın saat dilimi",
"startupFailed": "SiYuan başlatılamadı",
"startupStage": "Başarısız aşama: ${stage}",
"startupReload": "Yeniden yükle",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 5f80537d94..6b34057c48 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "Вставити змінну",
+ "automationTemplateTip": "Обчислення в часовому поясі правила; порожній результат очищає поле, помилки скасовують зміну",
+ "automationTemplateExample": "Приклад",
+ "automationTemplatePreview": "Результат попереднього перегляду",
+ "automationPreviewData": "Дані для попереднього перегляду",
+ "automationPreviewItem": "Приклад запису",
+ "automationPreviewTime": "Дата для попереднього перегляду",
+ "automationPreviewOnly": "Лише перегляд; записи не змінюються",
+ "automationTimeZone": "Часовий пояс правила",
"startupFailed": "Не вдалося запустити SiYuan",
"startupStage": "Етап збою: ${stage}",
"startupReload": "Перезавантажити",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 5de01ae997..e434d2bffb 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "插入变量",
+ "automationTemplateTip": "按规则时区计算;空结果清空字段,错误会回滚本次修改",
+ "automationTemplateExample": "示例",
+ "automationTemplatePreview": "预览结果",
+ "automationPreviewData": "预览使用的数据",
+ "automationPreviewItem": "示例条目",
+ "automationPreviewTime": "预览使用的日期",
+ "automationPreviewOnly": "仅用于预览,不会修改条目",
+ "automationTimeZone": "规则时区",
"startupFailed": "思源启动失败",
"startupStage": "失败阶段:${stage}",
"startupReload": "重新加载",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index c9ca27fad5..1338d75b5d 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,13 @@
{
+ "automationInsertVariable": "插入變數",
+ "automationTemplateTip": "依規則時區計算;空結果清空欄位,錯誤會復原本次修改",
+ "automationTemplateExample": "範例",
+ "automationTemplatePreview": "預覽結果",
+ "automationPreviewData": "預覽使用的資料",
+ "automationPreviewItem": "範例項目",
+ "automationPreviewTime": "預覽使用的日期",
+ "automationPreviewOnly": "僅供預覽,不會修改項目",
+ "automationTimeZone": "規則時區",
"startupFailed": "思源啟動失敗",
"startupStage": "失敗階段:${stage}",
"startupReload": "重新載入",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
index eb051fef4d..8f771abcb4 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
@@ -7,7 +7,7 @@
"id": "20240208172514-9dsv6na",
"title": "Database",
"type": "doc",
- "updated": "20261016130603"
+ "updated": "20261016165601"
},
"Children": [
{
@@ -3820,7 +3820,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261002224707-n5wvv5s",
- "updated": "20261016113125"
+ "updated": "20261016165601"
},
"Children": [
{
@@ -3898,12 +3898,177 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261002224707-x0qa1o9",
- "updated": "20261002224707"
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Action values can use a fixed value, a source field of a compatible type, the trigger time, a relation to the triggering item, or a calculated template. Trigger time applies to date fields; triggering-item relations require a relation field pointing to the source database. Editing primary text preserves the existing binding and icon"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-kcsjytv",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-kcsjytv",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Choose Template as the value source to edit a "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{...}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " template inline. Use the variable menu to insert the trigger time or source fields. Editing a template pauses the rule; enable it again after editing. Every editable field supports templates; computed fields such as creation time, update time, row number, rollup, and template fields cannot be assigned. Primary fields retain their existing binding"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-v82xurl",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-v82xurl",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "For example, when a watering task is completed, add the next task and set its date to "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{((now).AddDate 0 0 7).Format \"2006-01-02\"}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ". "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "now"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " is fixed to the trigger time, and "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "AddDate 0 0 7"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " advances seven calendar days. The rule saves the frontend time zone when templates are first used and keeps that zone across devices"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-r1dfdx7",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-r1dfdx7",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "field \"fieldID\""
+ },
+ {
+ "Type": "NodeText",
+ "Data": " reads a source item's stored value; dates support "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "AddDate"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ". Renaming a field does not change its ID reference. "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "value \"fieldID\""
+ },
+ {
+ "Type": "NodeText",
+ "Data": " reads a structured payload, and "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "toJson"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " outputs JSON. For example, "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{toJson (dateAdd 0 0 7 (value \"fieldID\"))}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " advances both ends of a date range while preserving its date-only or specific-time setting"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-l1uq6e6",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-l1uq6e6",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Text, URL, email, and phone fields use text. Numbers must be finite, and checkboxes use "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "true"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " or "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "false"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ". Dates accept ISO dates, date-times, or date payload JSON. Select uses an existing option name; multi-select uses a JSON array of names or option objects. Relations use existing item ID arrays; assets and locations use their existing payload JSON. Templates do not create options, related items, or assets"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-tphvdoa",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-tphvdoa",
+ "updated": "20261016165601"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Action values can use a fixed value, a source field of a compatible type, the trigger time, or a relation to the triggering item. Trigger time applies to date fields; triggering-item relations require a relation field pointing to the source database. Editing primary text preserves the existing binding and icon"
+ "Data": "Expand Data used for preview, select an actual example entry, and adjust the preview date or referenced fields before viewing the result. These inputs do not modify entries. Empty output clears the field; missing variables, empty source dates, invalid types, or invalid references roll back the triggering edit and all actions. Results are stored once, and redo reuses them. SQL, files, network access, loops, and recursion are unavailable. Source is limited to 8 KiB; each input and output to 64 KiB. Saving templates requires a client supporting automation format 2; older clients explicitly reject the database. Existing format 1 rules remain compatible"
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
index 9bfda29934..66ed9745e5 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
@@ -7,7 +7,7 @@
"id": "20240208113259-nykkvaq",
"title": "数据库",
"type": "doc",
- "updated": "20261016130603"
+ "updated": "20261016165601"
},
"Children": [
{
@@ -3820,7 +3820,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261002224707-l8jclpi",
- "updated": "20261016113125"
+ "updated": "20261016165601"
},
"Children": [
{
@@ -3898,12 +3898,177 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261002224707-zhikh2u",
- "updated": "20261002224707"
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "动作中的字段值可以是固定值、类型兼容的源字段、触发时间,或关联到触发条目,也可以使用模板计算。触发时间适用于日期字段;关联到触发条目适用于指向源数据库的关联字段。修改主键文本会保留原有绑定关系和图标"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-0p95j4w",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-0p95j4w",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "赋值方式选择「模板」后,可在行内编辑 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{...}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 模板,使用变量菜单插入触发时间或源字段。编辑模板会暂停规则,完成后请重新启用。所有可编辑字段均支持模板;创建时间、更新时间、行号、汇总和模板字段等计算字段不支持赋值。主键只修改文本,保留已有绑定"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-cgid9sj",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-cgid9sj",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "例如,将状态为已完成的浇花任务作为触发条目,新增下一次任务,并将日期设为 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{((now).AddDate 0 0 7).Format \"2006-01-02\"}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "now"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 固定为本次触发时间,"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "AddDate 0 0 7"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 按自然日期顺延七天。规则首次使用模板时保存当前前端时区,跨设备执行继续使用该时区"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-9k1r41o",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-9k1r41o",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "field \"字段ID\""
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 读取源条目的存储值,日期可参与 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "AddDate"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 运算;字段重命名不影响 ID 引用。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "value \"字段ID\""
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 读取结构化载荷,"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "toJson"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 输出 JSON。例如,"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{toJson (dateAdd 0 0 7 (value \"字段ID\"))}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 可同时顺延日期范围的起止时间,并保留纯日期或具体时间设置"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-6n3qtz0",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-6n3qtz0",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "文本、链接、邮箱和电话使用文本结果,数字必须是有效的有限数值,复选框使用 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "true"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 或 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "false"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。日期接受 ISO 日期、日期时间或日期载荷 JSON;单选使用已有选项名称,多选使用 JSON 名称数组或选项数组;关联使用已有条目 ID 数组;资源与位置使用现有载荷 JSON。不会自动创建选项、关联条目或资源"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-9odotkr",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-9odotkr",
+ "updated": "20261016165601"
},
"Children": [
{
"Type": "NodeText",
- "Data": "动作中的字段值可以是固定值、类型兼容的源字段、触发时间,或关联到触发条目。触发时间适用于日期字段;关联到触发条目适用于指向源数据库的关联字段。修改主键文本会保留原有绑定关系和图标"
+ "Data": "展开「预览使用的数据」,选择实际条目作为示例,修改预览日期或引用字段后,再查看预览结果。这些输入只影响预览,不修改实际条目。合法空输出清空字段;缺失变量、空源日期、类型或引用错误使触发修改和全部自动动作一起回滚。模板结果只在触发时写入,重做复用首次结果。模板不支持 SQL、文件、网络、循环或递归;源码最多 8 KiB,单个输入和输出最多 64 KiB。保存模板后,该数据库需要支持自动化版本 2 的客户端读取,旧版会明确拒绝读取;原有版本 1 的规则保持兼容"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
index 4bd7d61544..336c98b5cf 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
@@ -7,7 +7,7 @@
"id": "20240208171522-y7dxcno",
"title": "資料庫",
"type": "doc",
- "updated": "20261016130603"
+ "updated": "20261016165601"
},
"Children": [
{
@@ -3820,7 +3820,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261002224707-f9wjtlr",
- "updated": "20261016113125"
+ "updated": "20261016165601"
},
"Children": [
{
@@ -3898,12 +3898,177 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261002224707-vi6feb3",
- "updated": "20261002224707"
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "動作中的欄位值可以是固定值、類型相容的來源欄位、觸發時間,或關聯至觸發項目,也可使用模板計算。觸發時間適用於日期欄位;關聯至觸發項目適用於指向來源資料庫的關聯欄位。修改主鍵文字會保留原有繫結關係與圖示"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-zk0dnna",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-zk0dnna",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "賦值方式選擇「模板」後,可在行內編輯 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{...}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 模板,使用變數選單插入觸發時間或來源欄位。編輯模板會暫停規則,完成後請重新啟用。所有可編輯欄位均支援模板;建立時間、更新時間、行號、彙總及模板欄位等計算欄位不支援賦值。主鍵只修改文字,保留既有繫結"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-ay013u0",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-ay013u0",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "例如,以狀態為已完成的澆花任務作為觸發項目,新增下一次任務,並將日期設為 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{((now).AddDate 0 0 7).Format \"2006-01-02\"}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "now"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 固定為本次觸發時間,"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "AddDate 0 0 7"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 依自然日期順延七天。規則首次使用模板時儲存目前前端時區,跨裝置執行仍使用該時區"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-zvjhh4u",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-zvjhh4u",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "field \"欄位ID\""
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 讀取來源項目的儲存值,日期可參與 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "AddDate"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 運算;欄位重新命名不影響 ID 引用。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "value \"欄位ID\""
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 讀取結構化資料,"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "toJson"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 輸出 JSON。例如,"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{toJson (dateAdd 0 0 7 (value \"欄位ID\"))}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 可同時順延日期範圍的起訖時間,並保留純日期或具體時間設定"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-meihq9p",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-meihq9p",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "文字、連結、電子郵件和電話使用文字結果,數字必須為有效的有限數值,核取方塊使用 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "true"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 或 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "false"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。日期接受 ISO 日期、日期時間或日期資料 JSON;單選使用既有選項名稱,多選使用 JSON 名稱陣列或選項陣列;關聯使用既有項目 ID 陣列;資源與位置使用既有資料結構的 JSON。不會自動建立選項、關聯項目或資源"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-6akhx0e",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-6akhx0e",
+ "updated": "20261016165601"
},
"Children": [
{
"Type": "NodeText",
- "Data": "動作中的欄位值可以是固定值、類型相容的來源欄位、觸發時間,或關聯至觸發項目。觸發時間適用於日期欄位;關聯至觸發項目適用於指向來源資料庫的關聯欄位。修改主鍵文字會保留原有繫結關係與圖示"
+ "Data": "展開「預覽使用的資料」,選擇實際項目作為範例,修改預覽日期或引用欄位後,再查看預覽結果。這些輸入只影響預覽,不修改實際項目。合法空輸出清空欄位;缺少變數、空來源日期、類型或引用錯誤會讓觸發修改與全部自動動作一起復原。模板結果只在觸發時寫入,重做沿用首次結果。模板不支援 SQL、檔案、網路、迴圈或遞迴;原始碼最多 8 KiB,單一輸入與輸出最多 64 KiB。儲存模板後,該資料庫需要支援自動化版本 2 的用戶端讀取,舊版會明確拒絕讀取;既有版本 1 的規則保持相容"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
index feb989c594..99c941b8b8 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
@@ -8,7 +8,7 @@
"id": "20240530101000-3eaevtp",
"title": "データベース",
"type": "doc",
- "updated": "20261016130603"
+ "updated": "20261016165601"
},
"Children": [
{
@@ -3830,7 +3830,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20261002224707-2ctdjhm",
- "updated": "20261016113125"
+ "updated": "20261016165601"
},
"Children": [
{
@@ -3908,12 +3908,177 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261002224707-odr4vof",
- "updated": "20261002224707"
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "アクションの値には固定値、互換性のある型のソースフィールド、トリガー時刻、トリガー項目への関連、または計算用テンプレートを指定できます。トリガー時刻は日付フィールドに使用します。トリガー項目への関連には、ソースデータベースを参照する関連フィールドが必要です。主キーのテキストを編集しても既存のバインドとアイコンは維持されます"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-3mbpi7s",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-3mbpi7s",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "値の設定方法で「テンプレート」を選ぶと、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{...}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " をインラインで編集できます。変数メニューからトリガー時刻やソースフィールドを挿入します。テンプレートを編集するとルールが一時停止するため、編集後に再度有効にしてください。編集可能なすべてのフィールドに対応しますが、作成日時、更新日時、行番号、ロールアップ、テンプレートなどの計算フィールドには代入できません。主キーは既存のバインドを維持します"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-udw7gbs",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-udw7gbs",
+ "updated": "20261016165601"
},
"Children": [
{
"Type": "NodeText",
- "Data": "アクションの値には固定値、互換性のある型のソースフィールド、トリガー時刻、トリガー項目への関連を指定できます。トリガー時刻は日付フィールドに使用します。トリガー項目への関連には、ソースデータベースを参照する関連フィールドが必要です。主キーのテキストを編集しても既存のバインドとアイコンは維持されます"
+ "Data": "例えば、水やりタスクを完了したときに次のタスクを追加し、日付を "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{((now).AddDate 0 0 7).Format \"2006-01-02\"}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " に設定します。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "now"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " はトリガー時刻に固定され、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "AddDate 0 0 7"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " は暦上の七日後を計算します。テンプレートを初めて使用するときにフロントエンドのタイムゾーンを保存し、他の端末でも同じタイムゾーンで実行します"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-8ub6ywb",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-8ub6ywb",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "field \"フィールドID\""
+ },
+ {
+ "Type": "NodeText",
+ "Data": " はソース項目の保存値を読み取り、日付では "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "AddDate"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " を使用できます。フィールド名を変更しても ID 参照は維持されます。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "value \"フィールドID\""
+ },
+ {
+ "Type": "NodeText",
+ "Data": " は構造化データを読み取り、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "toJson"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " は JSON を出力します。例えば "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": ".action{toJson (dateAdd 0 0 7 (value \"フィールドID\"))}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " は日付範囲の開始と終了を進め、日付のみか時刻付きかの設定も維持します"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-vimxvf5",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-vimxvf5",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "テキスト、リンク、メール、電話には文字列を使用し、数値には有限の値、チェックボックスには "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "true"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " または "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "false"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " を使用します。日付には ISO 日付、日時、既存の日付データの JSON を使用できます。単一選択は既存の選択肢名、複数選択は名前または選択肢オブジェクトの JSON 配列、関連は既存項目 ID の配列を使用します。アセットと位置には既存のデータ構造の JSON を使用します。選択肢、関連項目、アセットは自動作成しません"
+ }
+ ]
+ },
+ {
+ "ID": "20261016165601-4qrtsdm",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261016165601-4qrtsdm",
+ "updated": "20261016165601"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "「プレビューに使用するデータ」を開き、実際の項目を選び、日付や参照フィールドを変更してから結果を確認します。入力はプレビュー専用で、項目を変更しません。空の出力はフィールドを消去し、変数の不足、空のソース日付、型や参照のエラーは元の編集と全アクションを取り消します。結果は一度だけ保存し、やり直しでも再利用します。SQL、ファイル、ネットワーク、ループ、再帰は使用できません。ソースは最大 8 KiB、各入力と出力は最大 64 KiB です。テンプレート保存後は自動化形式 2 に対応したクライアントが必要で、旧版はデータベースの読み込みを明示的に拒否します。既存の形式 1 のルールは引き続き使用できます"
}
]
},
@@ -4007,12 +4172,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261015141042-ag8e3p7",
- "updated": "20261015141042"
+ "updated": "20261016165601"
},
"Children": [
{
"Type": "NodeText",
- "Data": "タグはブロック自体と照合し、すべての親コンテナを自動収集しません。リスト項目は先頭段落のタグを使用し、段落の種類を明示的に選んだ場合にのみ先頭段落も個別に照合します。収集は元のブロックを現在のデータベースにバインドし、原文をコピーしたり移動したりしません。初期フィールドには固定値と日付フィールドのトリガー時刻を指定でき、主キーは元のブロックへのバインドを保持します"
+ "Data": "タグはブロック自体と照合し、すべての親コンテナを自動収集しません。リスト項目は先頭段落のタグを使用し、段落の種類を明示的に選んだ場合にのみ先頭段落も個別に照合します。収集は元のブロックを現在のデータベースにバインドし、原文をコピーしたり移動したりしません。初期フィールドには固定値、日付フィールドのトリガー時刻、テンプレートを指定でき、主キーは元のブロックへのバインドを保持します"
}
]
},
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scss
index 83deccdf7a..7e6b25e5f4 100644
--- a/app/src/assets/scss/business/_av.scss
+++ b/app/src/assets/scss/business/_av.scss
@@ -3221,6 +3221,31 @@ img.av__cellassetimg {
white-space: nowrap;
}
+ &-field[data-template-assignment] {
+ align-items: start;
+
+ > .av__automation-value {
+ grid-column: 1 / -1;
+ }
+ }
+
+ &-template,
+ &-template-data {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-width: 0;
+ }
+
+ &-template-data {
+ margin-top: 8px;
+ }
+
+ &-template-result {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ }
+
&-assignment {
display: flex;
align-items: center;
diff --git a/app/src/protyle/render/av/automation.test.ts b/app/src/protyle/render/av/automation.test.ts
index d1488fd63c..a51c7e21f5 100644
--- a/app/src/protyle/render/av/automation.test.ts
+++ b/app/src/protyle/render/av/automation.test.ts
@@ -156,6 +156,7 @@ test("empty automation settings persist an incomplete rule disabled on editing a
Lute: {NewNodeID: () => "draft-rule"},
window: {siyuan: {config: {}, languages: {databaseAutomations: "Automations", fields: "Fields", automationIncomplete: "Incomplete: ${1}"}}},
require: (name: string) => name === "./capabilities" || name === "../capabilities" ? capabilities : (({
+ "./automationTemplate": {automationTimeZone: () => "UTC"},
"../../../util/escape": {escapeAttr: String, escapeHtml: String},
"../../../util/fetch": {fetchSyncPost: async () => ({code: 0, data: {av: database}})},
"../../wysiwyg/transaction": {transaction: (_protyle: IProtyle, perform: IOperation[], undo: IOperation[]) => {
diff --git a/app/src/protyle/render/av/automation.ts b/app/src/protyle/render/av/automation.ts
index 5c18864085..58ed232270 100644
--- a/app/src/protyle/render/av/automation.ts
+++ b/app/src/protyle/render/av/automation.ts
@@ -10,6 +10,7 @@ import {bindFieldLunarDates, genFieldValue, getRelationOptions, getSelectedOptio
import {createAVLocationReplacement} from "./locationValue";
import {openSearchAV} from "./relation";
import {collectionSourceIncomplete, mountBlockCollectionSource, openBlockCollectionPreview} from "./blockCollection";
+import {automationTimeZone, mountAutomationTemplate} from "./automationTemplate";
interface AutomationValue extends Omit<AVAutomationValueInput, "value"> {
value?: IAVCellValue;
@@ -102,9 +103,10 @@ export const openAutomationMenu = async (options: {
goBack();
return;
}
- let previous: {spec: 1, rules: AutomationRule[]} = clone(database.automations || {spec: 1, rules: []});
+ let previous: {spec: number, rules: AutomationRule[]} = clone(database.automations || {spec: 1, rules: []});
const createRule = (): AutomationRule => ({
id: Lute.NewNodeID(), name: lang.databaseAutomations, enabled: false, trigger: "changed",
+ timeZone: automationTimeZone(),
actions: [{type: "edit", target: "current", fields: {}}],
});
const rules: AutomationRule[] = clone(previous.rules || []);
@@ -128,7 +130,7 @@ export const openAutomationMenu = async (options: {
const filtersAvailable = (source: AVAttributeViewData, filters: IAVFilter[] = []): boolean => filters.every(filter =>
filter.filters ? filtersAvailable(source, filter.filters) : fieldsOf(source).some(field => field.id === filter.column));
const incomplete = (rule: AutomationRule): string => {
- if (rule === rules[index] && Array.from(body.querySelectorAll<HTMLInputElement>("input")).some(input => !input.checkValidity())) {
+ if (rule === rules[index] && Array.from(body.querySelectorAll<HTMLInputElement>("input")).some(input => !input.closest("[data-template-preview]") && !input.checkValidity())) {
return lang.invalid;
}
if (!rule.name.trim()) {
@@ -199,7 +201,8 @@ export const openAutomationMenu = async (options: {
}
updateStatus();
onResize();
- const next = {spec: 1 as const, rules: clone(rules)};
+ const usesTemplates = rules.some(rule => rule.actions.some(action => Object.values(action.fields).some(value => value.mode === "template")));
+ const next = {spec: usesTemplates ? 2 : previous.spec, rules: clone(rules)};
if (JSON.stringify(next) === JSON.stringify(previous)) {
return;
}
@@ -357,7 +360,7 @@ ${target ? `${action.type === "edit" && action.target !== "current" ? `<div clas
const compatible = action.type === "collect" ? [] : compatibleFields(database, field);
const fieldName = field?.name || `${lang.invalid}: ${keyID}`;
row.innerHTML = `<span class="av__automation-field-name fn__ellipsis ariaLabel" aria-label="${escapeAttr(fieldName)}" data-position="north">${escapeHtml(fieldName)}</span>
-<div class="av__automation-assignment">${field ? `<select class="b3-select" data-mode aria-label="${escapeAttr(lang.automationValueMode)}">${optionHTML("static", lang.automationStaticValue, value.mode)}${compatible.length ? optionHTML("source", lang.automationSourceField, value.mode) : ""}${field.type === "date" ? optionHTML("currentTime", lang.automationTriggerTime, value.mode) : ""}${action.type !== "collect" && field.type === "relation" && field.relation?.avID === avID ? optionHTML("triggerItem", lang.automationTriggerItem, value.mode) : ""}</select><div class="av__automation-value" data-value></div>` : ""}</div>
+<div class="av__automation-assignment">${field ? `<select class="b3-select" data-mode aria-label="${escapeAttr(lang.automationValueMode)}">${optionHTML("static", lang.automationStaticValue, value.mode)}${compatible.length ? optionHTML("source", lang.automationSourceField, value.mode) : ""}${field.type === "date" ? optionHTML("currentTime", lang.automationTriggerTime, value.mode) : ""}${action.type !== "collect" && field.type === "relation" && field.relation?.avID === avID ? optionHTML("triggerItem", lang.automationTriggerItem, value.mode) : ""}${optionHTML("template", lang.template, value.mode)}</select><div class="av__automation-value" data-value></div>` : ""}</div>
${iconButton("remove-field", "iconClose", lang.delete, true, true)}`;
fieldsHost.append(row);
if (!field) {
@@ -368,6 +371,13 @@ ${iconButton("remove-field", "iconClose", lang.delete, true, true)}`;
mountValue(host, field, value);
} else if (value.mode === "source") {
host.innerHTML = `<select class="b3-select fn__block" data-source-field aria-label="${lang.automationSourceField}">${compatible.map(source => optionHTML(source.id, source.name, value.keyID)).join("")}</select>`;
+ } else if (value.mode === "template") {
+ row.dataset.templateAssignment = "true";
+ row.append(host);
+ mountAutomationTemplate({host, field, source: database, targetID: targetID(action), rule, value, save: () => {
+ rule.enabled = false;
+ save();
+ }, onResize});
}
});
});
@@ -440,7 +450,11 @@ ${iconButton("remove-field", "iconClose", lang.delete, true, true)}`;
const keyID = target.closest<HTMLElement>("[data-field-id]").dataset.fieldId;
const field = fieldsOf(databases.get(targetID(action))).find(item => item.id === keyID);
const value = action.fields[keyID];
- value.mode = target.value === "source" ? "source" : target.value === "currentTime" ? "currentTime" : target.value === "triggerItem" ? "triggerItem" : "static";
+ value.mode = target.value === "template" ? "template" : target.value === "source" ? "source" : target.value === "currentTime" ? "currentTime" : target.value === "triggerItem" ? "triggerItem" : "static";
+ if (value.mode === "template") {
+ rule.timeZone = rule.timeZone || automationTimeZone();
+ rule.enabled = false;
+ }
if (value.mode === "source") {
value.keyID = compatibleFields(database, field)[0]?.id;
} else if (value.mode === "static" && !value.value) {
diff --git a/app/src/protyle/render/av/automationTemplate.ts b/app/src/protyle/render/av/automationTemplate.ts
new file mode 100644
index 0000000000..49b2eb6a33
--- /dev/null
+++ b/app/src/protyle/render/av/automationTemplate.ts
@@ -0,0 +1,187 @@
+import type {AVAttributeViewData, AVAutomationRuleInput, AVAutomationValueInput, AVValue} from "../../../types/api";
+import {escapeAttr, escapeHtml} from "../../../util/escape";
+import {fetchSyncPost} from "../../../util/fetch";
+import {hasAVCapability} from "./capabilities";
+import {getSelectedOptionsHTML} from "./fieldValueEditor";
+import {getAVLocationDisplayText} from "./locationValue";
+
+export const automationTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+
+export const automationDateInput = (time: number, timeZone: string, dateOnly = false) => {
+ const parts = new Intl.DateTimeFormat("en-CA", {
+ timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23",
+ }).formatToParts(time);
+ const part = (name: string) => parts.find(part => part.type === name)?.value || "";
+ const date = `${part("year")}-${part("month")}-${part("day")}`;
+ return dateOnly ? date : `${date}T${part("hour")}:${part("minute")}`;
+};
+
+export const automationTemplateValueText = (value: AVValue, timeZone: string): string => {
+ switch (value?.type) {
+ case "block": return value.block?.content || "";
+ case "text": return value.text?.content || "";
+ case "url": return value.url?.content || "";
+ case "email": return value.email?.content || "";
+ case "phone": return value.phone?.content || "";
+ case "number": return value.number?.isNotEmpty ? String(value.number.content) : "";
+ case "checkbox": return String(!!value.checkbox?.checked);
+ case "date":
+ if (!value.date?.isNotEmpty) {
+ return "";
+ }
+ return value.date.hasEndDate ? JSON.stringify(value.date) :
+ automationDateInput(value.date.content, timeZone, value.date.isNotTime);
+ case "select": return value.mSelect?.[0]?.content || "";
+ case "mSelect": return JSON.stringify(value.mSelect?.map(item => item.content) || []);
+ case "relation": return JSON.stringify(value.relation?.blockIDs || []);
+ case "mAsset": return JSON.stringify(value.mAsset || []);
+ case "location": return JSON.stringify(value.location || {});
+ default: return "";
+ }
+};
+
+export const mountAutomationTemplate = (options: {
+ host: HTMLElement,
+ field: IAVColumn,
+ source: AVAttributeViewData,
+ targetID: string,
+ rule: Pick<AVAutomationRuleInput, "timeZone" | "trigger">,
+ value: Pick<AVAutomationValueInput, "template">,
+ save: () => void,
+ onResize: () => void,
+}) => {
+ const {host, field, source, targetID, rule, value, save, onResize} = options;
+ const lang = window.siyuan.languages;
+ const timeZone = rule.timeZone || automationTimeZone();
+ const fields = source.keyValues.filter(item => item?.key && hasAVCapability(item.key.type, "editable"));
+ const rows = fields.find(item => item.key.type === "block")?.values || [];
+ let version = 0;
+ const example = field.type === "date" ? '.action{((now).AddDate 0 0 7).Format "2006-01-02"}' :
+ field.type === "checkbox" ? "true" : field.type === "number" ? ".action{add 1 2}" :
+ field.type === "mSelect" || field.type === "relation" || field.type === "mAsset" ? "[]" :
+ field.type === "location" ? '{"name":"","latitude":0,"longitude":0}' : ".action{now | date \"2006-01-02\"}";
+ host.classList.add("av__automation-template");
+ host.innerHTML = `<textarea class="b3-text-field fn__block" data-template rows="3" maxlength="8192" aria-label="${escapeAttr(lang.template)}">${escapeHtml(value.template || "")}</textarea>
+<div class="av__automation-row"><label class="av__automation-control fn__flex-1"><span>${lang.variables}</span><select class="b3-select" data-template-variable><option value="">${lang.automationInsertVariable}</option><option value="now">${lang.automationTriggerTime}</option>${fields.map(item => `<option value="${escapeAttr(item.key.id)}">${escapeHtml(item.key.name)}</option><option value="value:${escapeAttr(item.key.id)}">${escapeHtml(item.key.name)} (JSON)</option>`).join("")}</select></label><button type="button" class="b3-button b3-button--cancel" data-template-example>${lang.automationTemplateExample}</button></div>
+<div class="ft__on-surface ft__smaller">${lang.automationTemplateTip}</div>
+<div class="ft__on-surface ft__smaller">${lang.automationTimeZone} ${escapeHtml(timeZone)}</div>
+<details data-template-preview><summary>${lang.automationPreviewData}</summary><div class="av__automation-template-data">
+<div class="ft__on-surface ft__smaller">${lang.automationPreviewOnly}</div>
+<label class="av__automation-control"><span>${lang.automationPreviewItem}</span><select class="b3-select" data-template-item><option value="">${lang.selectRelationItems}</option>${rows.map(row => `<option value="${escapeAttr(row.blockID)}">${escapeHtml(row.block?.content || row.blockID)}</option>`).join("")}</select></label>
+<label class="av__automation-control"><span>${lang.automationPreviewTime}</span><input class="b3-text-field" type="datetime-local" data-template-time value="${automationDateInput(Date.now(), timeZone)}"></label>
+<div class="av__automation-template-data" data-template-inputs></div>
+<button type="button" class="b3-button b3-button--outline" data-template-run>${lang.automationTemplatePreview}</button>
+<output class="av__automation-template-result" role="status" aria-live="polite" data-template-result></output></div></details>`;
+ const editor = host.querySelector<HTMLTextAreaElement>("[data-template]");
+ const item = host.querySelector<HTMLSelectElement>("[data-template-item]");
+ const triggerTime = host.querySelector<HTMLInputElement>("[data-template-time]");
+ const inputs = host.querySelector<HTMLElement>("[data-template-inputs]");
+ const result = host.querySelector<HTMLOutputElement>("[data-template-result]");
+ const invalidate = () => {
+ version++;
+ result.textContent = "";
+ };
+ const renderInputs = () => {
+ const references = new Set(Array.from(editor.value.matchAll(/\b(?:field|value)\s+"([^"]+)"/g), match => match[1]));
+ inputs.innerHTML = fields.filter(entry => references.has(entry.key.id)).map(entry => {
+ const stored = entry.values?.find(value => value.blockID === item.value);
+ const text = automationTemplateValueText(stored, timeZone);
+ const date = entry.key.type === "date" && !stored?.date?.hasEndDate;
+ const type = date ? (stored?.date?.isNotTime === false ? "datetime-local" : "date") : entry.key.type === "number" ? "number" : "text";
+ return `<label class="av__automation-control"><span>${escapeHtml(entry.key.name)}</span><input class="b3-text-field" data-template-input="${escapeAttr(entry.key.id)}" type="${type}"${type === "number" ? ' step="any"' : ""} value="${escapeAttr(text)}" maxlength="65536"></label>`;
+ }).join("");
+ invalidate();
+ onResize();
+ };
+ item.addEventListener("change", renderInputs);
+ editor.addEventListener("input", () => {
+ value.template = editor.value;
+ renderInputs();
+ });
+ editor.addEventListener("change", () => {
+ value.template = editor.value;
+ save();
+ });
+ host.querySelector<HTMLSelectElement>("[data-template-variable]").addEventListener("change", event => {
+ const select = event.target as HTMLSelectElement;
+ if (!select.value) {
+ return;
+ }
+ const variable = select.value;
+ const text = variable === "now" ? ".action{now}" : variable.startsWith("value:") ?
+ `.action{toJson (value ${JSON.stringify(variable.substring(6))})}` : `.action{field ${JSON.stringify(variable)}}`;
+ editor.setRangeText(text, editor.selectionStart, editor.selectionEnd, "end");
+ value.template = editor.value;
+ select.value = "";
+ save();
+ renderInputs();
+ editor.focus();
+ });
+ host.querySelector("[data-template-example]").addEventListener("click", () => {
+ editor.value = example;
+ value.template = example;
+ save();
+ renderInputs();
+ });
+ host.addEventListener("input", event => {
+ const input = event.target as HTMLInputElement;
+ if (input.matches("[data-template-input]")) {
+ input.dataset.modified = "true";
+ }
+ invalidate();
+ });
+ host.querySelector("[data-template-preview]").addEventListener("toggle", onResize);
+ host.querySelector<HTMLButtonElement>("[data-template-run]").addEventListener("click", async event => {
+ const button = event.currentTarget as HTMLButtonElement;
+ if (!item.value || !triggerTime.checkValidity() || !triggerTime.value) {
+ result.textContent = lang.automationPreviewItem;
+ return;
+ }
+ const requestVersion = ++version;
+ const overrides: Record<string, string> = {};
+ const invalid = inputs.querySelector<HTMLInputElement>("input:invalid");
+ if (invalid) {
+ invalid.reportValidity();
+ return;
+ }
+ inputs.querySelectorAll<HTMLInputElement>('[data-template-input][data-modified="true"]').forEach(input => {
+ overrides[input.dataset.templateInput] = input.value;
+ });
+ button.disabled = true;
+ try {
+ const response = await fetchSyncPost("/api/av/previewAttributeViewTemplate", {
+ avID: source.id, targetAvID: targetID, itemID: item.value, keyID: field.id,
+ template: editor.value, timeZone, triggerTime: triggerTime.value, inputs: overrides,
+ });
+ if (!host.isConnected || version !== requestVersion) {
+ return;
+ }
+ result.classList.toggle("ft__error", response.code !== 0);
+ if (response.code !== 0 || !response.data || !("type" in response.data)) {
+ result.textContent = response.msg;
+ return;
+ }
+ const output = response.data;
+ if (field.type === "select" || field.type === "mSelect") {
+ result.innerHTML = getSelectedOptionsHTML(field, output.mSelect?.map(option => option.content) || []) || escapeHtml(lang.empty);
+ return;
+ }
+ result.textContent = field.type === "relation" ?
+ output.relation?.contents?.map(value => value.block?.content).join(", ") || lang.empty :
+ field.type === "location" ? getAVLocationDisplayText(output.location) || lang.empty :
+ field.type === "mAsset" ? output.mAsset?.map(asset => asset.name || asset.content).join(", ") || lang.empty :
+ field.type === "date" && output.date?.hasEndDate ?
+ `${automationDateInput(output.date.content, timeZone, output.date.isNotTime)} - ${automationDateInput(output.date.content2, timeZone, output.date.isNotTime)}` :
+ automationTemplateValueText(output, timeZone) || lang.empty;
+ } catch (error) {
+ if (host.isConnected && version === requestVersion) {
+ result.classList.add("ft__error");
+ result.textContent = String(error);
+ }
+ } finally {
+ button.disabled = false;
+ onResize();
+ }
+ });
+ renderInputs();
+};
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 960f510f74..9d23f91b0a 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -260,17 +260,19 @@ export type AVAutomationBlockSource = { "attributes"?: Array<AVAutomationBlockAt
export type AVAutomationBlockSourceInput = { "attributes"?: Array<AVAutomationBlockAttributeInput | null>; "documentIDs"?: Array<string>; "notebookIDs"?: Array<string>; "tags"?: Array<string>; "types"?: Array<string>; };
-export type AVAutomationConfig = { "rules": Array<AVAutomationRule | null> | null; "spec": 1; };
+export type AVAutomationConfig = { "rules": Array<AVAutomationRule | null> | null; "spec": number; };
-export type AVAutomationConfigInput = { "rules": Array<AVAutomationRuleInput | null>; "spec": 1; };
+export type AVAutomationConfigInput = { "rules": Array<AVAutomationRuleInput | null>; "spec": number; };
-export type AVAutomationRule = { "actions": Array<AVAutomationAction | null> | null; "blockSource"?: AVAutomationBlockSource; "conditions"?: Array<AVViewFilter | null>; "enabled": boolean; "id": string; "keyID"?: string; "name": string; "trigger": "added" | "changed" | "block"; };
+export type AVAutomationRule = { "actions": Array<AVAutomationAction | null> | null; "blockSource"?: AVAutomationBlockSource; "conditions"?: Array<AVViewFilter | null>; "enabled": boolean; "id": string; "keyID"?: string; "name": string; "timeZone"?: string; "trigger": "added" | "changed" | "block"; };
-export type AVAutomationRuleInput = { "actions": Array<AVAutomationActionInput | null>; "blockSource"?: AVAutomationBlockSourceInput | null; "conditions"?: Array<AVViewFilterInput | null>; "enabled": boolean; "id": string; "keyID"?: string; "name": string; "trigger": "added" | "changed" | "block"; };
+export type AVAutomationRuleInput = { "actions": Array<AVAutomationActionInput | null>; "blockSource"?: AVAutomationBlockSourceInput | null; "conditions"?: Array<AVViewFilterInput | null>; "enabled": boolean; "id": string; "keyID"?: string; "name": string; "timeZone"?: string; "trigger": "added" | "changed" | "block"; };
-export type AVAutomationValue = { "keyID"?: string; "mode": "static" | "source" | "currentTime" | "triggerItem"; "value"?: AVValue; };
+export type AVAutomationTemplatePreviewRequestInput = { "avID": string; "inputs"?: Record<string, string>; "itemID": string; "keyID": string; "targetAvID"?: string; "template": string; "timeZone": string; "triggerTime"?: string; };
-export type AVAutomationValueInput = { "keyID"?: string; "mode": "static" | "source" | "currentTime" | "triggerItem"; "value"?: AVValueInput | null; };
+export type AVAutomationValue = { "keyID"?: string; "mode": "static" | "source" | "currentTime" | "triggerItem" | "template"; "template"?: string; "value"?: AVValue; };
+
+export type AVAutomationValueInput = { "keyID"?: string; "mode": "static" | "source" | "currentTime" | "triggerItem" | "template"; "template"?: string; "value"?: AVValueInput | null; };
export type AVAvSearchResult = { "avID": string; "avName": string; "blockID": string; "children"?: Array<AVAvSearchResult | null>; "hPath": string; "matched"?: boolean; "viewID": string; "viewLayout": "" | "table" | "list" | "gallery" | "kanban" | "calendar"; "viewName": string; };
@@ -3680,6 +3682,17 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin"];
};
+ /**
+ * 在实际条目快照上预览模板赋值,返回通过类型和引用校验的字段值,不写入数据。
+ * 使用规则时区和可选的预览输入;加密笔记本遵守请求租约及相同加密边界,失败返回 code -1。
+ */
+ "/api/av/previewAttributeViewTemplate": {
+ request: AVAutomationTemplatePreviewRequestInput;
+ response: { "code": 0; "data": AVValue | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "structJSON";
+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
+ authorization?: readonly ["authenticated","admin"];
+ };
"/api/av/removeAttributeViewBlocks": {
request: RemoveAttributeViewBlocksRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -7763,7 +7776,7 @@ export interface APIPOSTRoutes {
/**
* move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。
* 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。
- * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1,所有视图共享数据库级规则。
+ * 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 或 2,所有视图共享数据库级规则。
* addAttributeViewBlocks、setAttributeViewBlockAttr、batchSetAttributeViewBlockAttrs 触发启用的新增或字段变化规则。
* 自动操作与原修改一同提交,失败一起回滚;普通 API 写入不生成编辑器撤销记录。
* 自动化不串联,导入、同步、历史恢复和撤销重放不重新触发;重做保留原条目 ID 和触发时间。
diff --git a/app/tests/automationPanel.test.js b/app/tests/automationPanel.test.js
index 77d35c3a6b..d85afc31a7 100644
--- a/app/tests/automationPanel.test.js
+++ b/app/tests/automationPanel.test.js
@@ -23,6 +23,7 @@ const runCases = async (sources, css, mobile) => {
const lang = sources.languages;
const currentCondition = {column: "status", operator: "=", value: {type: "select", mSelect: [{content: "Done"}]}};
const database = {id: "source", name: "Tasks", keyValues: [
+ {key: {id: "primary", name: "Name", type: "block"}, values: [{blockID: "sample", type: "block", block: {content: "Watering"}}]},
{key: {id: "status", name: "Status", type: "select", options: [{name: "Done"}]}},
{key: {id: "tags", name: "Tags", type: "mSelect", options: [{name: "Work"}]}},
{key: {id: "finished", name: "Completion time", type: "date"}},
@@ -33,6 +34,7 @@ const runCases = async (sources, css, mobile) => {
conditions: [currentCondition], actions: [{type: "edit", target: "current", fields: {finished: {mode: "currentTime"}}}]}]}};
const targetDatabase = {...database, id: "target", name: "Time logs"};
const transactions = [];
+ const templatePreviews = [];
const searches = [];
let fieldMenu;
let nextID = 0;
@@ -40,7 +42,8 @@ const runCases = async (sources, css, mobile) => {
window.siyuan = {languages: lang, config: {}, notebooks: [], zIndex: 0, menus: {menu: {remove() {}}}};
const mocks = {
"plugin/Menu": {Menu: class {items = []; addItem(item) {this.items.push(item);} open() {fieldMenu = {items: this.items};}}},
- "util/fetch": {fetchSyncPost: async (url, request) => url.includes("getHPathByID") ? {code: 0, data: "/Tasks"} :
+ "util/fetch": {fetchSyncPost: async (url, request) => url.includes("previewAttributeViewTemplate") ?
+ (templatePreviews.push(request), {code: 0, data: {type: "date", date: {content: 1792713600000, isNotEmpty: true, isNotTime: true}}}) : url.includes("getHPathByID") ? {code: 0, data: "/Tasks"} :
{code: 0, data: {av: request.id === "source" ? database : targetDatabase}},
fetchPost: (_url, _request, callback) => searches.push(() => callback({code: 0, data: {rows: {values: [
{blockID: "related", block: {content: "Related"}},
@@ -280,6 +283,35 @@ const runCases = async (sources, css, mobile) => {
await tick();
await change("[data-mode]", "currentTime");
const theme = document.createElement("style");
+ await change("[data-mode]", "template");
+ assert.equal(transactions.at(-1).perform[0].data.spec, 2, "templates use the new format");
+ assert.ok(latest().timeZone, "the rule records the frontend timezone");
+ await click("[data-template-example]");
+ assert.match(latest().actions[0].fields.finished.template, /AddDate 0 0 7/);
+ get("[data-template-preview]").open = true;
+ await change("[data-template-item]", "sample");
+ await change("[data-template-time]", "2026-10-16T15:30");
+ const writesBeforePreview = transactions.length;
+ await click("[data-template-run]");
+ assert.equal(templatePreviews.length, 1);
+ assert.equal(templatePreviews[0].triggerTime, "2026-10-16T15:30");
+ assert.equal(transactions.length, writesBeforePreview, "preview never saves or changes entries");
+ assert.ok(get("[data-template-result]").textContent);
+ assert.ok(get("[data-template-time]").getBoundingClientRect().bottom < get("[data-template-result]").getBoundingClientRect().top,
+ "preview inputs precede the result");
+ const editor = get("[data-template]");
+ editor.value = '.action{field "finished"}';
+ editor.dispatchEvent(new Event("input", {bubbles: true}));
+ editor.dispatchEvent(new Event("change", {bubbles: true}));
+ assert.ok(get('[data-template-input="finished"]'));
+ assert.equal(get("[data-template-result]").textContent, "", "editing inputs invalidates old previews");
+ const previewDate = get('[data-template-input="finished"]');
+ previewDate.value = "2026-10-14";
+ previewDate.dispatchEvent(new Event("input", {bubbles: true}));
+ const writesBeforeInputPreview = transactions.length;
+ await click("[data-template-run]");
+ assert.equal(templatePreviews.at(-1).inputs.finished, "2026-10-14");
+ assert.equal(transactions.length, writesBeforeInputPreview, "editing sample dates never saves a rule or entry");
document.head.append(theme);
for (const width of mobile ? [360, 740] : [560, 1000]) {
await require("electron").ipcRenderer.invoke("automation-size", width, 900);
@@ -340,7 +372,7 @@ if (process.versions.electron && process.type === "browser") {
const sass = require("sass");
const sources = {icons: fs.readFileSync(path.join(__dirname, "../appearance/icons/litheness/icon.js"), "utf8"),
languages: JSON.parse(fs.readFileSync(path.join(__dirname, "../appearance/langs/zh-CN.json"), "utf8"))};
- for (const name of ["automation", "capabilities", "capabilities.generated", "filter", "filterTree", "fieldValueEditor", "blockCollection", "selectPosition", "filterDropdown"]) {
+ for (const name of ["automation", "automationTemplate", "capabilities", "capabilities.generated", "filter", "filterTree", "fieldValueEditor", "blockCollection", "selectPosition", "filterDropdown"]) {
sources[`protyle/render/av/${name}`] = ts.transpileModule(fs.readFileSync(path.join(__dirname, `../src/protyle/render/av/${name}.ts`), "utf8"), {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},
}).outputText;
diff --git a/kernel/api/av_contract_automation.go b/kernel/api/av_contract_automation.go
index ec95612f1d..ca7e698e7e 100644
--- a/kernel/api/av_contract_automation.go
+++ b/kernel/api/av_contract_automation.go
@@ -19,6 +19,18 @@ var previewAttributeViewCollection = contractHandler(apicontract.PreviewAttribut
return apicontract.Success(data)
})
+var previewAttributeViewTemplate = contractHandler(apicontract.PreviewAttributeViewTemplate,
+ func(c *gin.Context, request apicontract.AVAutomationTemplatePreviewRequest) apicontract.Response[*apicontract.AVValue] {
+ if err := holdAttributeViewRequest(c, "", request.AvID); err != nil {
+ return apicontract.Failure[*apicontract.AVValue](-1, err.Error())
+ }
+ value, err := model.PreviewAttributeViewTemplate(request)
+ if err != nil {
+ return apicontract.Failure[*apicontract.AVValue](-1, err.Error())
+ }
+ return apicontract.Success(toContractAVValue(value))
+ })
+
func toContractAVAutomationConfig(value *av.AutomationConfig) *apicontract.AVAutomationConfig {
if value == nil {
return nil
@@ -28,6 +40,7 @@ func toContractAVAutomationConfig(value *av.AutomationConfig) *apicontract.AVAut
return nil
}
return &apicontract.AVAutomationRule{ID: rule.ID, Name: rule.Name, Enabled: rule.Enabled, Trigger: rule.Trigger,
+ TimeZone: rule.TimeZone,
BlockSource: toContractAVAutomationBlockSource(rule.BlockSource),
KeyID: rule.KeyID, Conditions: avContractSlice(rule.Conditions, toContractAVViewFilter),
Actions: avContractSlice(rule.Actions, func(action *av.AutomationAction) *apicontract.AVAutomationAction {
@@ -40,7 +53,7 @@ func toContractAVAutomationConfig(value *av.AutomationConfig) *apicontract.AVAut
if field == nil {
return nil
}
- return &apicontract.AVAutomationValue{Mode: field.Mode, KeyID: field.KeyID, Value: toContractAVValue(field.Value)}
+ return &apicontract.AVAutomationValue{Mode: field.Mode, KeyID: field.KeyID, Value: toContractAVValue(field.Value), Template: field.Template}
})}
})}
})}
diff --git a/kernel/api/contract_av_automation_test.go b/kernel/api/contract_av_automation_test.go
index bea99f1a2e..15da1b6a3e 100644
--- a/kernel/api/contract_av_automation_test.go
+++ b/kernel/api/contract_av_automation_test.go
@@ -98,6 +98,9 @@ func TestAVContractAutomationWrites(t *testing.T) {
call("/api/av/addAttributeViewBlocks", map[string]any{"avID": database.ID,
"ignoreDefaultFill": true, "srcs": []map[string]any{{"id": itemID, "itemID": itemID, "isDetached": true, "content": "Entry"}},
}, addAttributeViewBlocks)
+ call("/api/av/previewAttributeViewTemplate", map[string]any{"avID": database.ID, "itemID": itemID,
+ "keyID": fixture.textKeyID, "timeZone": "Asia/Shanghai", "triggerTime": "2026-10-16T15:30",
+ "template": `.action{now | date "2006-01-02"}`}, previewAttributeViewTemplate)
stored, err := av.ParseAttributeView(database.ID)
if err != nil || stored.GetValue(fixture.textKeyID, itemID).Text.Content != "created" {
t.Fatalf("add API did not trigger automation: %v", err)
diff --git a/kernel/api/router.go b/kernel/api/router.go
index e251cc5a40..7c323bdd82 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -844,6 +844,7 @@ func registerAvRoutes(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/av/searchAttributeView", contractRouteHandlers(apicontract.SearchAttributeView, searchAttributeView)...)
ginServer.Handle("POST", "/api/av/getAttributeView", contractRouteHandlers(apicontract.GetAttributeView, getAttributeView)...)
ginServer.Handle("POST", "/api/av/previewAttributeViewCollection", contractRouteHandlers(apicontract.PreviewAttributeViewCollection, previewAttributeViewCollection)...)
+ ginServer.Handle("POST", "/api/av/previewAttributeViewTemplate", contractRouteHandlers(apicontract.PreviewAttributeViewTemplate, previewAttributeViewTemplate)...)
ginServer.Handle("POST", "/api/av/getAttributeViewPasteRows", contractRouteHandlers(apicontract.GetAttributeViewPasteRows, getAttributeViewPasteRows)...)
ginServer.Handle("POST", "/api/av/searchAttributeViewRelationKey", contractRouteHandlers(apicontract.SearchAttributeViewRelationKey, searchAttributeViewRelationKey)...)
ginServer.Handle("POST", "/api/av/searchAttributeViewRollupDestKeys", contractRouteHandlers(apicontract.SearchAttributeViewRollupDestKeys, searchAttributeViewRollupDestKeys)...)
diff --git a/kernel/apicontract/av_automation.go b/kernel/apicontract/av_automation.go
index 6cf075a23e..3e673a6061 100644
--- a/kernel/apicontract/av_automation.go
+++ b/kernel/apicontract/av_automation.go
@@ -1,14 +1,15 @@
package apicontract
// AVAutomationConfig 通过 setAttrViewAutomations 事务操作整体保存,所有镜像和视图共享。
-// spec 为 1;缺省配置不会触发自动化。普通条目新增、字段编辑及对应 API 会触发启用的规则,
+// spec 为 1 或 2;模板赋值必须使用 2,旧版本会拒绝读取,防止配置静默丢失。缺省配置不会触发自动化。
+// 普通条目新增、字段编辑及对应 API 会触发启用的规则,
// 导入、同步、历史恢复和撤销重放不会再次触发,自动化之间不串联。
// 自动操作与源修改一同提交、失败回滚及撤销;单笔事务最多产生 1000 个自动操作。
// 字段失效或目标数据库被删除时,后续条目写入会停用规则并保留配置,源修改仍可提交。
// 停用提示在提交后发送,包含规则名及失效引用;修复后需手动启用,撤销源修改不会重新启用规则。
// 跨库操作仅限同一加密边界,锁定、认证失败、损坏或实际写入失败仍使触发事务回滚。
type AVAutomationConfig struct {
- Spec int `json:"spec" api:"const=1"`
+ Spec int `json:"spec"`
Rules []*AVAutomationRule `json:"rules"`
}
@@ -21,6 +22,7 @@ type AVAutomationRule struct {
Conditions []*AVViewFilter `json:"conditions,omitempty" api:"optional"`
Actions []*AVAutomationAction `json:"actions"`
BlockSource *AVAutomationBlockSource `json:"blockSource,omitempty" api:"optional"`
+ TimeZone string `json:"timeZone,omitempty" api:"optional"`
}
// AVAutomationBlockSource 监听范围取笔记本与文档的并集,文档包含子文档;范围至少选择一项。
@@ -47,7 +49,7 @@ type AVAutomationBlockAttribute struct {
// AVAutomationAction 的 current 指触发条目所在数据库,related 通过源关联字段选择条目,
// filtered 在 avID 指定的数据库中按 filters 选择条目;空 filters 匹配全部条目。
// add 创建游离条目,edit 修改选中的条目;主键操作只修改文本并保留已有绑定。
-// collect 仅用于 block 触发器,target 必须为 current,fields 可为空,仅支持固定值和触发时间,不含主键。
+// collect 仅用于 block 触发器,target 必须为 current,fields 可为空,支持固定值、触发时间和模板,不含主键。
type AVAutomationAction struct {
Type string `json:"type" api:"enum=add|edit|collect"`
Target string `json:"target" api:"enum=current|related|filtered"`
@@ -60,10 +62,34 @@ type AVAutomationAction struct {
// AVAutomationValue 以固定值、源字段、触发时间或触发条目填充目标字段。
// currentTime 仅适用于日期,triggerItem 仅适用于关联到源数据库的字段。
// 重做使用首次执行的记录 ID 和日期值,不重新求值。
+// template 使用 .action{...} Go 模板;now 固定为事务触发时间,按规则的 IANA timeZone 计算。
+// field "字段ID" 返回标量或日期,value "字段ID" 返回结构化载荷,toJson 输出 JSON。
+// dateAdd 年 月 日 日期载荷保留日期范围;parseTime 严格解析日期,空日期和缺失变量报错。
+// 仅提供纯计算函数,禁止循环、模板递归、SQL、文件、网络及环境变量访问。
+// 源码上限 8 KiB,单个输入和结果上限 64 KiB,语法节点上限 512;失败随源修改整体回滚。
+// 空输出清空字段;数字必须有限,复选框仅接受 true/false,单选用名称,多选用 JSON 名称数组或选项数组。
+// 日期用 ISO 日期/时间或日期载荷 JSON;关联用条目 ID 数组,资源和位置用现有载荷 JSON。
+// 选项、关联条目和资源必须已存在并通过同一加密边界校验,不自动创建。
+// 单个关联或资源结果最多 1000 项;编辑模板的界面会暂停规则,完成后须手动启用。
type AVAutomationValue struct {
- Mode string `json:"mode" api:"enum=static|source|currentTime|triggerItem"`
- KeyID string `json:"keyID,omitempty" api:"optional"`
- Value *AVValue `json:"value,omitempty" api:"optional"`
+ Mode string `json:"mode" api:"enum=static|source|currentTime|triggerItem|template"`
+ KeyID string `json:"keyID,omitempty" api:"optional"`
+ Value *AVValue `json:"value,omitempty" api:"optional"`
+ Template string `json:"template,omitempty" api:"optional"`
+}
+
+// AVAutomationTemplatePreviewRequest 对实际源条目的快照求值,inputs 按目标类型转换后仅覆盖预览输入,不持久化或触发自动化。
+// targetAvID 缺省为 avID;目标和引用只能处于相同加密边界。无需先保存或启用规则。
+// triggerTime 缺省为当前时间,支持 ISO 日期/时间;无偏移量时使用必填 IANA timeZone。
+type AVAutomationTemplatePreviewRequest struct {
+ AvID string `json:"avID"`
+ TargetAvID string `json:"targetAvID,omitempty" api:"optional"`
+ ItemID string `json:"itemID"`
+ KeyID string `json:"keyID"`
+ Template string `json:"template"`
+ TimeZone string `json:"timeZone"`
+ TriggerTime string `json:"triggerTime,omitempty" api:"optional"`
+ Inputs map[string]string `json:"inputs,omitempty" api:"optional"`
}
// 预览已保存且启用的收集规则,不修改数据。只读取目标数据库所在加密边界内的源文档。
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 8f350d2861..829f9ceb22 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1225,6 +1225,10 @@ var GetAttributeView = define[GetAttributeViewRequest, AVData]("getAttributeView
// PreviewAttributeViewCollection 预览已保存且启用的普通块收集规则,不修改文档或数据库。
// 仅在目标数据库的加密边界内查询;page 从 1 开始,每页最多 100 个,hasMore 表示还有下一页。
var PreviewAttributeViewCollection = define[AVBlockCollectionPreviewRequest, *AVBlockCollectionPreview]("previewAttributeViewCollection", "/api/av/previewAttributeViewCollection", AuthenticatedAccess|AdminAccess, StructJSONBody, ResponseOptions{}, "POST")
+
+// PreviewAttributeViewTemplate 在实际条目快照上预览模板赋值,返回通过类型和引用校验的字段值,不写入数据。
+// 使用规则时区和可选的预览输入;加密笔记本遵守请求租约及相同加密边界,失败返回 code -1。
+var PreviewAttributeViewTemplate = define[AVAutomationTemplatePreviewRequest, *AVValue]("previewAttributeViewTemplate", "/api/av/previewAttributeViewTemplate", AuthenticatedAccess|AdminAccess, StructJSONBody, ResponseOptions{}, "POST")
var GetAttributeViewPasteRows = define[GetAttributeViewPasteRowsRequest, AVPasteRowsData]("getAttributeViewPasteRows", "/api/av/getAttributeViewPasteRows", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var GetAttributeViewFieldViews = define[GetAttributeViewFieldViewsRequest, AVFieldViewsData]("getAttributeViewFieldViews", "/api/av/getAttributeViewFieldViews", AuthenticatedAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var CreateAttributeViewItem = define[CreateAttributeViewItemRequest, AVCreateItemResult]("createAttributeViewItem", "/api/av/createAttributeViewItem", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{DataOnError: true, AdditionalCodes: []int{1}}, "POST")
@@ -1416,7 +1420,7 @@ var SystemAddUIProcess = define[EmptyRequest, Null]("addUIProcess", "/api/system
// move 操作支持 nextID,将块移到该同级锚点之前,优先于 previousID 和 parentID。
// 移动保留折叠标题下辖块顺序及源块身份,不将整列表自动拆成列表项;moveBlock 接口不接受 nextID。
-// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1,所有视图共享数据库级规则。
+// 数据库自动化通过 setAttrViewAutomations 操作整体保存,配置 spec 为 1 或 2,所有视图共享数据库级规则。
// addAttributeViewBlocks、setAttributeViewBlockAttr、batchSetAttributeViewBlockAttrs 触发启用的新增或字段变化规则。
// 自动操作与原修改一同提交,失败一起回滚;普通 API 写入不生成编辑器撤销记录。
// 自动化不串联,导入、同步、历史恢复和撤销重放不重新触发;重做保留原条目 ID 和触发时间。
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 8a619977ee..982be5631e 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -6760,10 +6760,7 @@
]
},
"spec": {
- "type": "integer",
- "enum": [
- 1
- ]
+ "type": "integer"
}
},
"required": [
@@ -6789,10 +6786,7 @@
}
},
"spec": {
- "type": "integer",
- "enum": [
- 1
- ]
+ "type": "integer"
}
},
"required": [
@@ -6852,6 +6846,9 @@
"name": {
"type": "string"
},
+ "timeZone": {
+ "type": "string"
+ },
"trigger": {
"type": "string",
"enum": [
@@ -6921,6 +6918,9 @@
"name": {
"type": "string"
},
+ "timeZone": {
+ "type": "string"
+ },
"trigger": {
"type": "string",
"enum": [
@@ -6939,6 +6939,46 @@
],
"additionalProperties": false
},
+ "AVAutomationTemplatePreviewRequestInput": {
+ "type": "object",
+ "properties": {
+ "avID": {
+ "type": "string"
+ },
+ "inputs": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "itemID": {
+ "type": "string"
+ },
+ "keyID": {
+ "type": "string"
+ },
+ "targetAvID": {
+ "type": "string"
+ },
+ "template": {
+ "type": "string"
+ },
+ "timeZone": {
+ "type": "string"
+ },
+ "triggerTime": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "avID",
+ "itemID",
+ "keyID",
+ "template",
+ "timeZone"
+ ],
+ "additionalProperties": false
+ },
"AVAutomationValue": {
"type": "object",
"properties": {
@@ -6951,9 +6991,13 @@
"static",
"source",
"currentTime",
- "triggerItem"
+ "triggerItem",
+ "template"
]
},
+ "template": {
+ "type": "string"
+ },
"value": {
"$ref": "#/$defs/AVValue"
}
@@ -6975,9 +7019,13 @@
"static",
"source",
"currentTime",
- "triggerItem"
+ "triggerItem",
+ "template"
]
},
+ "template": {
+ "type": "string"
+ },
"value": {
"anyOf": [
{
@@ -129040,6 +129088,92 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/av/previewAttributeViewTemplate",
+ "handler": "previewAttributeViewTemplate",
+ "authorization": [
+ "authenticated",
+ "admin"
+ ],
+ "body": "structJSON",
+ "request": {
+ "$ref": "#/$defs/AVAutomationTemplatePreviewRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/AVValue"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/av/removeAttributeViewBlocks",
diff --git a/kernel/av/automation.go b/kernel/av/automation.go
index 1a221c7a08..5cc17e3bd1 100644
--- a/kernel/av/automation.go
+++ b/kernel/av/automation.go
@@ -21,6 +21,7 @@ type AutomationRule struct {
Conditions []*ViewFilter `json:"conditions,omitempty"`
Actions []*AutomationAction `json:"actions"`
BlockSource *AutomationBlockSource `json:"blockSource,omitempty"`
+ TimeZone string `json:"timeZone,omitempty"`
}
// AutomationBlockSource 的范围取并集,各类条件取交集;文档范围包含其子文档。
@@ -48,9 +49,10 @@ type AutomationAction struct {
}
type AutomationValue struct {
- Mode string `json:"mode"` // static、source、currentTime 或 triggerItem
- KeyID string `json:"keyID,omitempty"`
- Value *Value `json:"value,omitempty"`
+ Mode string `json:"mode"` // static、source、currentTime、triggerItem 或 template
+ KeyID string `json:"keyID,omitempty"`
+ Value *Value `json:"value,omitempty"`
+ Template string `json:"template,omitempty"`
}
// visitAutomationValues 将规则中的条件及固定值纳入资源、颜色和富文本的持久化遍历。
@@ -267,6 +269,9 @@ func (view *AttributeView) remapAutomationKeys(originalID string, keyIDs map[str
}
action.RelationKeyID = keyIDs[action.RelationKeyID]
for _, value := range action.Fields {
+ if value != nil && value.Mode == "template" {
+ value.Template = RemapAutomationTemplate(value.Template, keyIDs)
+ }
if value != nil && value.Mode == "source" {
value.KeyID = keyIDs[value.KeyID]
}
diff --git a/kernel/av/automation_template.go b/kernel/av/automation_template.go
new file mode 100644
index 0000000000..b661abc7bf
--- /dev/null
+++ b/kernel/av/automation_template.go
@@ -0,0 +1,436 @@
+package av
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "math"
+ "sort"
+ "strconv"
+ "strings"
+ "text/template"
+ "text/template/parse"
+ "time"
+ _ "time/tzdata"
+
+ "github.com/Masterminds/sprig/v3"
+)
+
+const AutomationTemplateLimit = 65536
+
+// AutomationTemplateContext 只暴露本次触发的存储快照,不提供工作区查询或写入函数。
+type AutomationTemplateContext struct {
+ Source *AttributeView
+ ItemID string
+ Time time.Time
+ TimeZone string
+}
+
+type automationTemplateOutput struct{ bytes.Buffer }
+
+func (output *automationTemplateOutput) Write(data []byte) (int, error) {
+ if output.Len()+len(data) > AutomationTemplateLimit {
+ return 0, fmt.Errorf("automation template output exceeds 64 KiB")
+ }
+ return output.Buffer.Write(data)
+}
+
+// 自动化不执行循环、递归模板或可放大输入的函数,执行成本由源码、输入和输出上限共同约束。
+func automationTemplate(context AutomationTemplateContext, source string) (*template.Template, error) {
+ if len(source) > 8192 {
+ return nil, fmt.Errorf("automation template exceeds 8 KiB")
+ }
+ zone, err := time.LoadLocation(context.TimeZone)
+ if err != nil || context.TimeZone == "" || context.TimeZone == "Local" {
+ return nil, fmt.Errorf("invalid automation time zone [%s]", context.TimeZone)
+ }
+ functions := template.FuncMap{}
+ all := sprig.TxtFuncMap()
+ for _, name := range []string{"add", "add1", "sub", "mul", "div", "mod", "max", "min", "addf", "subf", "mulf", "divf", "maxf", "minf", "floor", "ceil", "round", "trim", "trimPrefix", "trimSuffix", "upper", "lower", "contains", "hasPrefix", "hasSuffix", "default", "empty", "coalesce", "ternary"} {
+ functions[name] = all[name]
+ }
+ functions["now"] = func() time.Time { return context.Time.In(zone) }
+ functions["parseTime"] = func(text string) (time.Time, error) { return ParseAutomationTime(text, zone) }
+ functions["date"] = func(layout string, date time.Time) string { return date.In(zone).Format(layout) }
+ functions["field"] = func(id string) (any, error) { return context.field(id, zone, false) }
+ functions["value"] = func(id string) (any, error) { return context.field(id, zone, true) }
+ functions["toJson"] = func(value any) (string, error) {
+ data, err := json.Marshal(value)
+ if len(data) > AutomationTemplateLimit {
+ return "", fmt.Errorf("automation template value exceeds 64 KiB")
+ }
+ return string(data), err
+ }
+ functions["dateAdd"] = func(years, months, days int, date *ValueDate) (*ValueDate, error) {
+ if date == nil || !date.IsNotEmpty {
+ return nil, fmt.Errorf("automation source date is empty")
+ }
+ result := *date
+ result.Content = time.UnixMilli(date.Content).In(zone).AddDate(years, months, days).UnixMilli()
+ if date.HasEndDate && date.IsNotEmpty2 {
+ result.Content2 = time.UnixMilli(date.Content2).In(zone).AddDate(years, months, days).UnixMilli()
+ }
+ result.FormattedContent = ""
+ return &result, nil
+ }
+ tpl, err := template.New("automation").Delims(".action{", "}").Option("missingkey=error").Funcs(functions).Parse(source)
+ if err != nil {
+ return nil, err
+ }
+ if len(tpl.Templates()) != 1 {
+ return nil, fmt.Errorf("automation template definitions are unavailable")
+ }
+ count := 0
+ var inspect func(parse.Node) error
+ inspect = func(node parse.Node) error {
+ if node == nil {
+ return nil
+ }
+ count++
+ if count > 512 {
+ return fmt.Errorf("automation template is too complex")
+ }
+ var children []parse.Node
+ switch node := node.(type) {
+ case *parse.ListNode:
+ if node == nil {
+ return nil
+ }
+ children = node.Nodes
+ case *parse.ActionNode:
+ children = []parse.Node{node.Pipe}
+ case *parse.PipeNode:
+ for _, command := range node.Cmds {
+ children = append(children, command)
+ }
+ case *parse.CommandNode:
+ children = node.Args
+ if len(node.Args) > 0 {
+ if name, ok := node.Args[0].(*parse.IdentifierNode); ok {
+ if functions[name.Ident] == nil && !strings.Contains("|and|or|not|eq|ne|lt|le|gt|ge|len|index|slice|", "|"+name.Ident+"|") {
+ return fmt.Errorf("automation function [%s] is unavailable", name.Ident)
+ }
+ if name.Ident == "field" || name.Ident == "value" {
+ if len(node.Args) != 2 {
+ return fmt.Errorf("field requires a literal field ID")
+ }
+ if _, ok = node.Args[1].(*parse.StringNode); !ok {
+ return fmt.Errorf("field requires a literal field ID")
+ }
+ }
+ }
+ }
+ case *parse.IfNode:
+ children = []parse.Node{node.Pipe, node.List, node.ElseList}
+ case *parse.WithNode:
+ children = []parse.Node{node.Pipe, node.List, node.ElseList}
+ case *parse.ChainNode:
+ for _, field := range node.Field {
+ if field == "Local" {
+ return fmt.Errorf("automation templates use the saved time zone")
+ }
+ }
+ children = []parse.Node{node.Node}
+ case *parse.FieldNode:
+ for _, field := range node.Ident {
+ if field == "Local" {
+ return fmt.Errorf("automation templates use the saved time zone")
+ }
+ }
+ case *parse.VariableNode:
+ for _, field := range node.Ident {
+ if field == "Local" {
+ return fmt.Errorf("automation templates use the saved time zone")
+ }
+ }
+ case *parse.RangeNode, *parse.TemplateNode:
+ return fmt.Errorf("automation template loops and recursion are unavailable")
+ }
+ for _, child := range children {
+ if err := inspect(child); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ if err = inspect(tpl.Tree.Root); err != nil {
+ return nil, err
+ }
+ return tpl, nil
+}
+
+func ValidateAutomationTemplate(source, timeZone string) error {
+ _, err := automationTemplate(AutomationTemplateContext{TimeZone: timeZone}, source)
+ return err
+}
+
+func (context AutomationTemplateContext) field(id string, zone *time.Location, raw bool) (any, error) {
+ if context.Source == nil {
+ return nil, fmt.Errorf("automation source is unavailable")
+ }
+ key, err := context.Source.GetKey(id)
+ if err != nil || !AutomationEditableKey(key.Type) {
+ return nil, fmt.Errorf("automation template source field [%s] is unavailable", id)
+ }
+ value := NormalizeAutomationValue(context.Source.GetValue(id, context.ItemID))
+ if value == nil {
+ value = NormalizeAutomationValue(&Value{Type: key.Type})
+ }
+ data, err := json.Marshal(value)
+ if err != nil || len(data) > AutomationTemplateLimit {
+ return nil, fmt.Errorf("automation source field exceeds 64 KiB")
+ }
+ switch key.Type {
+ case KeyTypeBlock:
+ return value.Block.Content, nil
+ case KeyTypeText:
+ return value.Text.Content, nil
+ case KeyTypeURL:
+ return value.URL.Content, nil
+ case KeyTypeEmail:
+ return value.Email.Content, nil
+ case KeyTypePhone:
+ return value.Phone.Content, nil
+ case KeyTypeNumber:
+ if raw {
+ return value.Number, nil
+ }
+ if !value.Number.IsNotEmpty {
+ return nil, fmt.Errorf("automation source number is empty")
+ }
+ return value.Number.Content, nil
+ case KeyTypeDate:
+ if !value.Date.IsNotEmpty {
+ return nil, fmt.Errorf("automation source date is empty")
+ }
+ if raw {
+ return value.Date, nil
+ }
+ return time.UnixMilli(value.Date.Content).In(zone), nil
+ case KeyTypeCheckbox:
+ return value.Checkbox.Checked, nil
+ case KeyTypeSelect, KeyTypeMSelect:
+ return value.MSelect, nil
+ case KeyTypeRelation:
+ return value.Relation.BlockIDs, nil
+ case KeyTypeMAsset:
+ return value.MAsset, nil
+ case KeyTypeLocation:
+ return value.Location, nil
+ }
+ return nil, fmt.Errorf("unsupported automation source field")
+}
+
+func EvaluateAutomationTemplate(context AutomationTemplateContext, key *Key, source string) (*Value, error) {
+ tpl, err := automationTemplate(context, source)
+ if err != nil {
+ return nil, err
+ }
+ output := &automationTemplateOutput{}
+ if err = tpl.Execute(output, map[string]any{"ItemID": context.ItemID}); err != nil {
+ return nil, err
+ }
+ zone, _ := time.LoadLocation(context.TimeZone)
+ return ParseAutomationTemplateValue(key, output.String(), zone)
+}
+
+func ParseAutomationTime(text string, zone *time.Location) (time.Time, error) {
+ for _, layout := range []string{time.RFC3339Nano, "2006-01-02 15:04:05 -0700 MST", "2006-01-02T15:04:05", "2006-01-02T15:04", "2006-01-02 15:04:05", "2006-01-02 15:04", "2006-01-02"} {
+ if value, err := time.ParseInLocation(layout, text, zone); err == nil {
+ return value, nil
+ }
+ }
+ return time.Time{}, fmt.Errorf("invalid automation date [%s]", text)
+}
+
+func decodeAutomationJSON(source string, value any) error {
+ decoder := json.NewDecoder(strings.NewReader(source))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(value); err != nil {
+ return err
+ }
+ if err := decoder.Decode(new(any)); err != io.EOF {
+ return fmt.Errorf("invalid trailing automation JSON")
+ }
+ return nil
+}
+
+// ParseAutomationTemplateValue 仅转换目标类型的载荷,引用存在性由事务在同一认证边界内检查。
+func ParseAutomationTemplateValue(key *Key, source string, zone *time.Location) (*Value, error) {
+ if len(source) > AutomationTemplateLimit {
+ return nil, fmt.Errorf("automation template value exceeds 64 KiB")
+ }
+ if !AutomationEditableKey(key.Type) {
+ return nil, fmt.Errorf("automation field is read-only")
+ }
+ value := NormalizeAutomationValue(&Value{Type: key.Type})
+ trimmed := strings.TrimSpace(source)
+ if trimmed == "" {
+ return value, nil
+ }
+ var err error
+ switch key.Type {
+ case KeyTypeBlock:
+ value.Block.Content = source
+ case KeyTypeText:
+ value.Text.Content = source
+ case KeyTypeURL:
+ value.URL.Content = source
+ case KeyTypeEmail:
+ value.Email.Content = source
+ case KeyTypePhone:
+ value.Phone.Content = source
+ case KeyTypeNumber:
+ value.Number.Content, err = strconv.ParseFloat(trimmed, 64)
+ value.Number.IsNotEmpty = err == nil
+ if math.IsNaN(value.Number.Content) || math.IsInf(value.Number.Content, 0) {
+ err = fmt.Errorf("automation number must be finite")
+ }
+ case KeyTypeCheckbox:
+ if trimmed != "true" && trimmed != "false" {
+ err = fmt.Errorf("automation checkbox requires true or false")
+ } else {
+ value.Checkbox.Checked = trimmed == "true"
+ }
+ case KeyTypeDate:
+ if strings.HasPrefix(trimmed, "{") {
+ err = decodeAutomationJSON(trimmed, value.Date)
+ if err == nil && (!value.Date.IsNotEmpty || value.Date.HasEndDate && (!value.Date.IsNotEmpty2 || value.Date.Content2 < value.Date.Content)) {
+ err = fmt.Errorf("invalid automation date range")
+ }
+ } else {
+ var date time.Time
+ date, err = ParseAutomationTime(trimmed, zone)
+ if err == nil {
+ value.Date = &ValueDate{Content: date.UnixMilli(), IsNotEmpty: true, IsNotTime: len(trimmed) == 10}
+ }
+ }
+ value.Date.FormattedContent = ""
+ if err == nil {
+ start := time.UnixMilli(value.Date.Content).In(zone)
+ end := time.UnixMilli(value.Date.Content2).In(zone)
+ if start.Year() < 1 || start.Year() > 9999 || value.Date.HasEndDate && (end.Year() < 1 || end.Year() > 9999) {
+ err = fmt.Errorf("automation date is outside the supported range")
+ }
+ }
+ case KeyTypeSelect, KeyTypeMSelect:
+ var names []string
+ if key.Type == KeyTypeSelect && !strings.HasPrefix(trimmed, "[") {
+ names = []string{source}
+ } else {
+ err = decodeAutomationJSON(trimmed, &value.MSelect)
+ if err != nil {
+ err = decodeAutomationJSON(trimmed, &names)
+ } else {
+ for _, option := range value.MSelect {
+ if option == nil {
+ err = fmt.Errorf("invalid automation option")
+ break
+ }
+ names = append(names, option.Content)
+ }
+ }
+ }
+ value.MSelect = nil
+ if key.Type == KeyTypeSelect && len(names) > 1 {
+ err = fmt.Errorf("automation select requires one option")
+ }
+ seen := map[string]bool{}
+ for _, name := range names {
+ option := key.GetOption(name)
+ if option == nil {
+ err = fmt.Errorf("automation option [%s] does not exist", name)
+ break
+ }
+ if !seen[name] {
+ value.MSelect = append(value.MSelect, &ValueSelect{Content: name, Color: option.Color})
+ seen[name] = true
+ }
+ }
+ case KeyTypeRelation:
+ err = decodeAutomationJSON(trimmed, &value.Relation.BlockIDs)
+ if len(value.Relation.BlockIDs) > 1000 {
+ err = fmt.Errorf("automation relation exceeds 1000 items")
+ }
+ case KeyTypeMAsset:
+ err = decodeAutomationJSON(trimmed, &value.MAsset)
+ if len(value.MAsset) > 1000 {
+ err = fmt.Errorf("automation assets exceed 1000 items")
+ }
+ case KeyTypeLocation:
+ err = decodeAutomationJSON(trimmed, value.Location)
+ if err == nil {
+ err = value.Location.Normalize()
+ }
+ }
+ if err != nil {
+ return nil, fmt.Errorf("automation template field [%s]: %w", key.Name, err)
+ }
+ return value, nil
+}
+
+// 只改写语法树中 field/value 的字面量参数,保留模板之外的同名文字。
+func RemapAutomationTemplate(source string, ids map[string]string) string {
+ tpl, err := automationTemplate(AutomationTemplateContext{TimeZone: "UTC"}, source)
+ if err != nil {
+ return source
+ }
+ type replacement struct {
+ offset, length int
+ text string
+ }
+ var replacements []replacement
+ var visit func(parse.Node)
+ visit = func(node parse.Node) {
+ if node == nil {
+ return
+ }
+ switch node := node.(type) {
+ case *parse.ListNode:
+ if node != nil {
+ for _, child := range node.Nodes {
+ visit(child)
+ }
+ }
+ case *parse.ActionNode:
+ visit(node.Pipe)
+ case *parse.PipeNode:
+ for _, command := range node.Cmds {
+ visit(command)
+ }
+ case *parse.CommandNode:
+ if len(node.Args) == 2 {
+ name, ok := node.Args[0].(*parse.IdentifierNode)
+ argument, literal := node.Args[1].(*parse.StringNode)
+ if ok && literal && (name.Ident == "field" || name.Ident == "value") {
+ if id := ids[argument.Text]; id != "" {
+ position := int(argument.Position())
+ if position >= 0 && position+len(argument.Quoted) <= len(source) && source[position:position+len(argument.Quoted)] == argument.Quoted {
+ replacements = append(replacements, replacement{position, len(argument.Quoted), strconv.Quote(id)})
+ }
+ }
+ }
+ }
+ for _, child := range node.Args {
+ visit(child)
+ }
+ case *parse.IfNode:
+ visit(node.Pipe)
+ visit(node.List)
+ visit(node.ElseList)
+ case *parse.WithNode:
+ visit(node.Pipe)
+ visit(node.List)
+ visit(node.ElseList)
+ case *parse.ChainNode:
+ visit(node.Node)
+ }
+ }
+ visit(tpl.Tree.Root)
+ sort.Slice(replacements, func(i, j int) bool { return replacements[i].offset > replacements[j].offset })
+ for _, replacement := range replacements {
+ source = source[:replacement.offset] + replacement.text + source[replacement.offset+replacement.length:]
+ }
+ return source
+}
diff --git a/kernel/av/automation_template_test.go b/kernel/av/automation_template_test.go
new file mode 100644
index 0000000000..4aa786832a
--- /dev/null
+++ b/kernel/av/automation_template_test.go
@@ -0,0 +1,118 @@
+package av
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestAutomationTemplateWritableTypes(t *testing.T) {
+ zone, _ := time.LoadLocation("Asia/Shanghai")
+ for _, test := range []struct {
+ typ KeyType
+ output string
+ }{
+ {KeyTypeBlock, "bound text"}, {KeyTypeText, "text"}, {KeyTypeURL, "https://example.com"},
+ {KeyTypeEmail, "[email protected]"}, {KeyTypePhone, "+12345"}, {KeyTypeNumber, "12.5"},
+ {KeyTypeCheckbox, "false"}, {KeyTypeDate, "2026-10-16"}, {KeyTypeSelect, "A,B"},
+ {KeyTypeMSelect, `["A,B","C"]`}, {KeyTypeRelation, `["20261016000000-abcdefg"]`},
+ {KeyTypeMAsset, `[{"type":"file","name":"a","content":"assets/a.pdf"}]`},
+ {KeyTypeLocation, `{"name":"zero","latitude":0,"longitude":0}`},
+ } {
+ t.Run(string(test.typ), func(t *testing.T) {
+ key := &Key{Type: test.typ, Options: []*SelectOption{{Name: "A,B", Color: "2"}, {Name: "C", Color: "3"}}}
+ value, err := ParseAutomationTemplateValue(key, test.output, zone)
+ if err != nil || value == nil || value.Type != test.typ {
+ t.Fatalf("conversion failed: %v %+v", err, value)
+ }
+ if _, err = ParseAutomationTemplateValue(key, "", zone); err != nil {
+ t.Fatal("clear failed", err)
+ }
+ })
+ }
+ for _, test := range []struct {
+ typ KeyType
+ output string
+ }{
+ {KeyTypeNumber, "nan"}, {KeyTypeNumber, "Inf"}, {KeyTypeNumber, "wrong"}, {KeyTypeCheckbox, "1"},
+ {KeyTypeDate, "2026-02-30"}, {KeyTypeDate, `{"content":0,"isNotEmpty":true,"hasEndDate":true}`},
+ {KeyTypeSelect, "new"}, {KeyTypeMSelect, "A,B"}, {KeyTypeMSelect, `[null]`},
+ {KeyTypeRelation, "id"}, {KeyTypeMAsset, `["asset"]`}, {KeyTypeLocation, `{"latitude":91,"longitude":0}`},
+ {KeyTypeLocation, `{"lat":0,"lng":0}`}, {KeyTypeTemplate, "anything"},
+ } {
+ if _, err := ParseAutomationTemplateValue(&Key{Type: test.typ}, test.output, zone); err == nil {
+ t.Fatalf("accepted invalid %s: %s", test.typ, test.output)
+ }
+ }
+}
+
+func TestAutomationTemplateSourceAndTime(t *testing.T) {
+ zone, _ := time.LoadLocation("America/New_York")
+ start := time.Date(2026, 3, 7, 12, 0, 0, 0, zone)
+ dateID := "20261016000000-abcdefg"
+ source := &AttributeView{KeyValues: []*KeyValues{{Key: &Key{ID: dateID, Type: KeyTypeDate}, Values: []*Value{{Type: KeyTypeDate, BlockID: "row", Date: &ValueDate{
+ Content: start.UnixMilli(), IsNotEmpty: true, HasEndDate: true, Content2: start.Add(time.Hour).UnixMilli(), IsNotEmpty2: true,
+ }}}}}}
+ context := AutomationTemplateContext{Source: source, ItemID: "row", Time: start, TimeZone: zone.String()}
+ key := &Key{Type: KeyTypeDate}
+ value, err := EvaluateAutomationTemplate(context, key, `.action{((now).AddDate 0 0 1).Format "2006-01-02T15:04:05Z07:00"}`)
+ if err != nil || value.Date.Content-start.UnixMilli() != int64(23*time.Hour/time.Millisecond) {
+ t.Fatal("DST offset ignored", value, err)
+ }
+ value, err = EvaluateAutomationTemplate(context, key, fmt.Sprintf(`.action{toJson (dateAdd 0 0 1 (value %q))}`, dateID))
+ if err != nil || value.Date.Content2-value.Date.Content != int64(time.Hour/time.Millisecond) || !value.Date.HasEndDate {
+ t.Fatal("range lost", value, err)
+ }
+ for _, test := range []struct {
+ at time.Time
+ days int
+ want string
+ }{
+ {time.Date(2024, 2, 28, 0, 0, 0, 0, zone), 1, "2024-02-29"},
+ {time.Date(2026, 12, 31, 0, 0, 0, 0, zone), 1, "2027-01-01"},
+ {time.Date(2026, 1, 31, 0, 0, 0, 0, zone), 7, "2026-02-07"},
+ } {
+ context.Time = test.at
+ value, err = EvaluateAutomationTemplate(context, key, fmt.Sprintf(`.action{((now).AddDate 0 0 %d).Format "2006-01-02"}`, test.days))
+ if err != nil || !value.Date.IsNotTime || time.UnixMilli(value.Date.Content).In(zone).Format("2006-01-02") != test.want {
+ t.Fatal("natural date failed", value, err)
+ }
+ }
+ for _, template := range []string{`.action{field "missing"}`, `.action{.Missing}`, `.action{field "20261016000000-abcdefg"}`} {
+ context.ItemID = "empty"
+ if _, err = EvaluateAutomationTemplate(context, key, template); err == nil {
+ t.Fatal("missing value became empty", template)
+ }
+ }
+ remapped := RemapAutomationTemplate(fmt.Sprintf(`.action{field %q}`, dateID), map[string]string{dateID: "20261016000001-abcdefg"})
+ if !strings.Contains(remapped, "20261016000001-abcdefg") {
+ t.Fatal("copied field ID was lost")
+ }
+ literal := `plain field "20261016000000-abcdefg" .action{field "20261016000000-abcdefg"}`
+ remapped = RemapAutomationTemplate(literal, map[string]string{dateID: "20261016000001-abcdefg"})
+ if !strings.HasPrefix(remapped, `plain field "20261016000000-abcdefg"`) || !strings.HasSuffix(remapped, `"20261016000001-abcdefg"}`) {
+ t.Fatal("copy changed literal text or missed a reference", remapped)
+ }
+}
+
+func TestAutomationTemplateSandbox(t *testing.T) {
+ for _, source := range []string{
+ `.action{env "HOME"}`, `.action{sql "select 1"}`, `.action{readFile "x"}`, `.action{getHostByName "example.com"}`,
+ `.action{range .}x.action{end}`, `.action{define "a"}x.action{end}`, `.action{template "automation" .}`,
+ `.action{printf "%1000000000s" "x"}`, `.action{repeat 1000000000 "x"}`, `.action{field .ItemID}`,
+ `.action{(now).Local}`, `.action{$t := now}.action{$t.Local}`,
+ strings.Repeat("x", 8193), strings.Repeat(".action{now}", 180),
+ } {
+ if err := ValidateAutomationTemplate(source, "UTC"); err == nil {
+ t.Fatal("accepted unsafe template", source[:min(len(source), 80)])
+ }
+ }
+ if err := ValidateAutomationTemplate("ok", "Local"); err == nil {
+ t.Fatal("host timezone accepted")
+ }
+ output := &automationTemplateOutput{}
+ if _, err := output.Write(make([]byte, AutomationTemplateLimit+1)); err == nil {
+ t.Fatal("output limit ignored")
+ }
+}
diff --git a/kernel/av/automation_test.go b/kernel/av/automation_test.go
index 8e0da6367f..9be36cbc83 100644
--- a/kernel/av/automation_test.go
+++ b/kernel/av/automation_test.go
@@ -112,7 +112,7 @@ func TestAutomationClonePreservesPausedRules(t *testing.T) {
if copiedRule.Actions[1].RelationKeyID == relationID || !rule.Enabled || rule.KeyID != primaryID {
t.Fatal("copy changed the original rule or retained its source field")
}
- source.Automations.Spec = 2
+ source.Automations.Spec = 3
future, _ := json.Marshal(source)
if _, err := ParseAttributeViewData(source.ID, future); err == nil {
t.Fatal("unknown automation format was accepted")
diff --git a/kernel/av/av.go b/kernel/av/av.go
index a7db172915..b1891ec941 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -959,9 +959,26 @@ func parseAttributeViewData(avID string, data []byte, normalizeRichText bool) (r
if nil == err {
err = CheckSpec(ret)
}
- if err == nil && ret.Automations != nil && ret.Automations.Spec != 1 {
+ if err == nil && ret.Automations != nil && ret.Automations.Spec != 1 && ret.Automations.Spec != 2 {
err = fmt.Errorf("unsupported database automation specification [%d]", ret.Automations.Spec)
}
+ if err == nil && ret.Automations != nil && ret.Automations.Spec == 1 {
+ for _, rule := range ret.Automations.Rules {
+ if rule == nil {
+ continue
+ }
+ for _, action := range rule.Actions {
+ if action == nil {
+ continue
+ }
+ for _, field := range action.Fields {
+ if field != nil && field.Mode == "template" {
+ err = fmt.Errorf("template assignments require automation spec 2")
+ }
+ }
+ }
+ }
+ }
if nil == err {
err = ret.ValidateLayouts()
}
diff --git a/kernel/model/attribute_view_automation.go b/kernel/model/attribute_view_automation.go
index 2b7f0f2844..5c716c7416 100644
--- a/kernel/model/attribute_view_automation.go
+++ b/kernel/model/attribute_view_automation.go
@@ -272,7 +272,7 @@ func (tx *Transaction) runAttributeViewAutomations() error {
// 先确定全部触发条件,关联关键词也不会读到前一自动动作修改后的标题。
for _, entry := range triggered {
for _, action := range entry.rule.Actions {
- if err := tx.runAutomationAction(entry.source, entry.current, entry.itemID, action); err != nil {
+ if err := tx.runAutomationAction(entry.source, entry.current, entry.itemID, action, entry.rule.TimeZone); err != nil {
return fmt.Errorf("automation [%s]: %w", entry.rule.ID, err)
}
}
@@ -501,6 +501,10 @@ func (tx *Transaction) validateAutomationRule(source *av.AttributeView, rule *av
fmt.Sprintf("automation action field [%s] is unavailable", keyID))
}
switch field.Mode {
+ case "template":
+ if err := av.ValidateAutomationTemplate(field.Template, rule.TimeZone); err != nil {
+ return err
+ }
case "currentTime":
if key.Type != av.KeyTypeDate {
return unavailableAutomationReference("fields", keyID, "automation trigger time requires a date field")
@@ -533,7 +537,7 @@ func (tx *Transaction) validateAutomationRule(source *av.AttributeView, rule *av
}
func (tx *Transaction) runAutomationAction(source *attributeViewAutomationSource, current *av.AttributeView,
- itemID string, action *av.AutomationAction) error {
+ itemID string, action *av.AutomationAction, timeZone string) error {
target, err := tx.automationTarget(current, action, source.boxID)
if err != nil {
return err
@@ -589,6 +593,7 @@ func (tx *Transaction) runAutomationAction(source *attributeViewAutomationSource
sort.Strings(keys)
ids = slices.Compact(ids)
relationValues := tx.automationRelationValues(source.boxID, nil)
+ computed := map[string]*av.Value{}
for _, id := range ids {
target, err = tx.readAttributeViewForMutation(target.ID, blockID, source.boxID)
if err != nil {
@@ -608,7 +613,20 @@ func (tx *Transaction) runAutomationAction(source *attributeViewAutomationSource
}
for _, keyID := range keys {
key, _ := target.GetKey(keyID)
- value, valueErr := tx.resolveAutomationValue(current, itemID, key, action.Fields[keyID])
+ value := computed[keyID]
+ var valueErr error
+ if value == nil {
+ value, valueErr = tx.resolveAutomationValue(current, itemID, key, action.Fields[keyID], timeZone)
+ if valueErr == nil && action.Fields[keyID].Mode == "template" {
+ valueErr = tx.validateAutomationTemplateReferences(current, target, key, value, source.boxID)
+ if value.Relation != nil {
+ value.Relation.Contents = nil
+ }
+ }
+ if valueErr == nil {
+ computed[keyID] = value
+ }
+ }
if valueErr != nil {
return valueErr
}
@@ -670,9 +688,12 @@ func automationValuePatch(value *av.Value) map[string]any {
}
func (tx *Transaction) resolveAutomationValue(source *av.AttributeView, itemID string, key *av.Key,
- field *av.AutomationValue) (*av.Value, error) {
+ field *av.AutomationValue, timeZone string) (*av.Value, error) {
var value *av.Value
switch field.Mode {
+ case "template":
+ return av.EvaluateAutomationTemplate(av.AutomationTemplateContext{Source: source, ItemID: itemID,
+ Time: time.UnixMilli(tx.attributeViewAutomations.time), TimeZone: timeZone}, key, field.Template)
case "currentTime":
value = &av.Value{Type: av.KeyTypeDate, Date: &av.ValueDate{Content: tx.attributeViewAutomations.time, IsNotEmpty: true}}
case "triggerItem":
@@ -743,7 +764,7 @@ func (tx *Transaction) doSetAttrViewAutomations(op *Operation) *TxErr {
if err = json.Unmarshal(data, &config); err != nil {
return fail(err)
}
- if config.Spec != 1 || len(config.Rules) > 100 {
+ if config.Spec != 1 && config.Spec != 2 || len(config.Rules) > 100 {
return fail(fmt.Errorf("unsupported automation configuration"))
}
if err = (&av.AttributeView{Automations: &config}).NormalizeLocations(); nil != err {
@@ -756,6 +777,16 @@ func (tx *Transaction) doSetAttrViewAutomations(op *Operation) *TxErr {
return fail(fmt.Errorf("invalid automation rule"))
}
seen[rule.ID] = true
+ for _, action := range rule.Actions {
+ if action == nil {
+ continue
+ }
+ for _, field := range action.Fields {
+ if field != nil && field.Mode == "template" && config.Spec < 2 {
+ return fail(fmt.Errorf("template assignments require automation spec 2"))
+ }
+ }
+ }
if rule.Enabled {
if err = tx.validateAutomationRule(view, rule, boxID); err != nil {
return fail(err)
diff --git a/kernel/model/attribute_view_automation_fts5_test.go b/kernel/model/attribute_view_automation_fts5_test.go
index 6900729649..a345e1d5c7 100644
--- a/kernel/model/attribute_view_automation_fts5_test.go
+++ b/kernel/model/attribute_view_automation_fts5_test.go
@@ -723,6 +723,11 @@ func TestAutomationRelationReplacementUndo(t *testing.T) {
func TestAutomationEncryptedExecutionAndFailures(t *testing.T) {
_, source, target, statusID, _ := setupAutomationTest(t)
+ source.Automations.Spec = 2
+ source.Automations.Rules[0].TimeZone = "Asia/Shanghai"
+ source.Automations.Rules[0].Actions[0].Fields[target.KeyValues[2].Key.ID] = &av.AutomationValue{
+ Mode: "template", Template: `.action{now | date "2006-01-02T15:04:05Z07:00"}`,
+ }
boxID := ast.NewNodeID()
markRuntimeEncryptedBox(boxID)
key := bytes.Repeat([]byte{0x71}, 32)
diff --git a/kernel/model/attribute_view_automation_template.go b/kernel/model/attribute_view_automation_template.go
new file mode 100644
index 0000000000..c1d1766e8c
--- /dev/null
+++ b/kernel/model/attribute_view_automation_template.go
@@ -0,0 +1,153 @@
+package model
+
+import (
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+func (tx *Transaction) validateAutomationTemplateReferences(source, target *av.AttributeView, key *av.Key, value *av.Value, boxID string) error {
+ if value.Relation != nil && len(value.Relation.BlockIDs) > 0 {
+ if key.Relation == nil || key.Relation.AvID == "" {
+ return fmt.Errorf("automation relation target is unavailable")
+ }
+ related, err := tx.readAttributeViewForMutation(key.Relation.AvID, "", boxID)
+ if err != nil {
+ return err
+ }
+ for _, id := range value.Relation.BlockIDs {
+ if !ast.IsNodeIDPattern(id) || related.GetBlockValue(id) == nil {
+ return fmt.Errorf("automation related item [%s] does not exist in the target database", id)
+ }
+ // 预览标签限制长度,避免短 ID 数组放大成无界的主键文本响应。
+ content := related.GetBlockValue(id).Block.Content
+ if len(content) > 1024 {
+ content = content[:1024]
+ }
+ value.Relation.Contents = append(value.Relation.Contents, &av.Value{Type: av.KeyTypeBlock, Block: &av.ValueBlock{Content: content}})
+ }
+ }
+ for _, asset := range value.MAsset {
+ if asset == nil || asset.Type != av.AssetTypeFile && asset.Type != av.AssetTypeImage {
+ return fmt.Errorf("invalid automation asset")
+ }
+ cleanPath, assetBox, err := assetPathAndBox(asset.Content, boxID)
+ if err != nil || !IsSameCryptoBoundary(boxID, assetBox) {
+ return fmt.Errorf("automation asset crosses its notebook boundary")
+ }
+ // 外部链接只允许复用源或目标中已保存的引用,不发起网络请求。
+ existing := false
+ for _, view := range []*av.AttributeView{source, target} {
+ view.VisitPersistedValues(func(stored *av.Value) {
+ for _, item := range stored.MAsset {
+ if item != nil && item.Content == asset.Content {
+ existing = true
+ }
+ }
+ })
+ }
+ if existing && !strings.HasPrefix(cleanPath, "assets/") {
+ continue
+ }
+ path, err := GetAssetAbsPathInBox(asset.Content, boxID)
+ if err != nil {
+ return err
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ return err
+ }
+ if !info.Mode().IsRegular() {
+ return fmt.Errorf("automation asset is not a file")
+ }
+ }
+ return nil
+}
+
+// PreviewAttributeViewTemplate 使用独立快照和覆盖值,不执行写事务、不保存配置、不执行自动动作。
+func PreviewAttributeViewTemplate(request apicontract.AVAutomationTemplatePreviewRequest) (*av.Value, error) {
+ FlushTxQueue()
+ _, boxID := av.FindAttributeViewPath(request.AvID)
+ tx := &Transaction{}
+ defer tx.finishAttributeViewMutation(false)
+ source, err := tx.readAttributeViewForMutation(request.AvID, "", boxID)
+ if err != nil {
+ return nil, err
+ }
+ if source.GetBlockValue(request.ItemID) == nil {
+ return nil, av.ErrItemNotFound
+ }
+ referenceSource := source
+ source, err = cloneAttributeViewForFieldMutation(source)
+ if err != nil {
+ return nil, err
+ }
+ target := source
+ if request.TargetAvID != "" && request.TargetAvID != source.ID {
+ target, err = tx.readAttributeViewForMutation(request.TargetAvID, "", boxID)
+ if err != nil {
+ return nil, err
+ }
+ }
+ key, err := target.GetKey(request.KeyID)
+ if err != nil {
+ return nil, err
+ }
+ zone, err := time.LoadLocation(request.TimeZone)
+ if err != nil {
+ return nil, err
+ }
+ if len(request.Inputs) > 100 {
+ return nil, fmt.Errorf("too many automation preview values")
+ }
+ for id, override := range request.Inputs {
+ field, fieldErr := source.GetKey(id)
+ if fieldErr != nil || !av.AutomationEditableKey(field.Type) {
+ return nil, fmt.Errorf("invalid automation preview field [%s]", id)
+ }
+ if len(override) > av.AutomationTemplateLimit {
+ return nil, fmt.Errorf("invalid automation preview value")
+ }
+ value, valueErr := av.ParseAutomationTemplateValue(field, override, zone)
+ if valueErr != nil {
+ return nil, valueErr
+ }
+ value.KeyID, value.BlockID = id, request.ItemID
+ for _, values := range source.KeyValues {
+ if values.Key.ID != id {
+ continue
+ }
+ filtered := values.Values[:0]
+ for _, old := range values.Values {
+ if old.BlockID != request.ItemID {
+ filtered = append(filtered, old)
+ }
+ }
+ values.Values = append(filtered, value)
+ }
+ }
+ now := time.Now()
+ if request.TriggerTime != "" {
+ now, err = av.ParseAutomationTime(request.TriggerTime, zone)
+ if err != nil {
+ return nil, err
+ }
+ }
+ value, err := av.EvaluateAutomationTemplate(av.AutomationTemplateContext{Source: source, ItemID: request.ItemID,
+ Time: now, TimeZone: request.TimeZone}, key, request.Template)
+ if err != nil {
+ return nil, err
+ }
+ if target.ID == referenceSource.ID {
+ target = referenceSource
+ }
+ if err = tx.validateAutomationTemplateReferences(referenceSource, target, key, value, boxID); err != nil {
+ return nil, err
+ }
+ return value, nil
+}
diff --git a/kernel/model/attribute_view_automation_template_fts5_test.go b/kernel/model/attribute_view_automation_template_fts5_test.go
new file mode 100644
index 0000000000..2afc1e2ff7
--- /dev/null
+++ b/kernel/model/attribute_view_automation_template_fts5_test.go
@@ -0,0 +1,196 @@
+//go:build fts5
+
+package model
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAutomationTemplateTransactionUndoRedo(t *testing.T) {
+ fixture, source, target, statusID, _ := setupAutomationTest(t)
+ source.Automations.Spec = 2
+ source.Automations.Rules = source.Automations.Rules[:1]
+ rule := source.Automations.Rules[0]
+ rule.TimeZone = "America/New_York"
+ rule.Actions[0].Fields[target.GetBlockKey().ID] = &av.AutomationValue{Mode: "template", Template: fmt.Sprintf(`Next: .action{field %q}`, source.GetBlockKey().ID)}
+ dateID := target.KeyValues[2].Key.ID
+ rule.Actions[0].Fields[dateID] = &av.AutomationValue{Mode: "template", Template: `.action{((now).AddDate 0 0 7).Format "2006-01-02"}`}
+ if err := av.SaveAttributeView(source); err != nil {
+ t.Fatal(err)
+ }
+ itemID := source.GetBlockKeyValues().Values[0].BlockID
+ tx := automationStatusTransaction(source, fixture.sourceID, statusID, itemID, "Active")
+ triggeredAt := time.Now()
+ if err := PerformTxSync(tx); err != nil {
+ t.Fatal(err)
+ }
+ stored := readAttributeViewItemsTest(t, target.ID)
+ row := stored.GetBlockKeyValues().Values[0]
+ date := stored.GetValue(dateID, row.BlockID).Date
+ zone, _ := time.LoadLocation(rule.TimeZone)
+ want := triggeredAt.In(zone).AddDate(0, 0, 7).Format("2006-01-02")
+ if row.Block.Content != "Next: Primary" || !date.IsNotTime || time.UnixMilli(date.Content).In(zone).Format("2006-01-02") != want {
+ t.Fatalf("incorrect stored result: %+v %+v", row, date)
+ }
+ if err := PerformTxSync(&Transaction{DoOperations: cloneOperations(tx.UndoOperations), isReplay: true}); err != nil {
+ t.Fatal(err)
+ }
+ if len(readAttributeViewItemsTest(t, target.ID).GetBlockKeyValues().Values) != 0 {
+ t.Fatal("undo retained generated row")
+ }
+ if err := PerformTxSync(&Transaction{DoOperations: cloneOperations(tx.DoOperations), isReplay: true}); err != nil {
+ t.Fatal(err)
+ }
+ restored := readAttributeViewItemsTest(t, target.ID)
+ if restored.GetBlockValue(row.BlockID) == nil || restored.GetValue(dateID, row.BlockID).Date.Content != date.Content {
+ t.Fatal("redo recomputed template or row ID")
+ }
+}
+
+func TestAutomationTemplateFailuresRollBackEarlierActions(t *testing.T) {
+ for _, output := range []string{"invalid date", `.action{field "missing"}`, `.action{.Missing}`, `{"content":1,"isNotEmpty":true,"hasEndDate":true}`} {
+ t.Run(output, func(t *testing.T) {
+ fixture, source, target, statusID, _ := setupAutomationTest(t)
+ source.Automations.Spec = 2
+ source.Automations.Rules = source.Automations.Rules[:1]
+ rule := source.Automations.Rules[0]
+ rule.TimeZone = "UTC"
+ rule.Actions = append(rule.Actions, &av.AutomationAction{Type: "edit", Target: "filtered", AvID: target.ID, Fields: map[string]*av.AutomationValue{
+ target.KeyValues[2].Key.ID: {Mode: "template", Template: output},
+ }})
+ if err := av.SaveAttributeView(source); err != nil {
+ t.Fatal(err)
+ }
+ itemID := source.GetBlockKeyValues().Values[0].BlockID
+ if err := PerformTxSync(automationStatusTransaction(source, fixture.sourceID, statusID, itemID, "Active")); err == nil {
+ t.Fatal("invalid output committed")
+ }
+ if len(readAttributeViewItemsTest(t, target.ID).GetBlockKeyValues().Values) != 0 {
+ t.Fatal("earlier action survived failure")
+ }
+ if readAttributeViewItemsTest(t, source.ID).GetValue(statusID, itemID).MSelect[0].Content != "Alpha" {
+ t.Fatal("source edit survived failure")
+ }
+ })
+ }
+}
+
+func TestAutomationTemplatePreviewIsReadOnly(t *testing.T) {
+ _, source, target, _, _ := setupAutomationTest(t)
+ itemID := source.GetBlockKeyValues().Values[0].BlockID
+ paths := map[string][]byte{}
+ for _, view := range []*av.AttributeView{source, target} {
+ path := filepath.Join(util.DataDir, "storage", "av", view.ID+".json")
+ paths[path], _ = os.ReadFile(path)
+ }
+ request := apicontract.AVAutomationTemplatePreviewRequest{AvID: source.ID, TargetAvID: target.ID, ItemID: itemID,
+ KeyID: target.GetBlockKey().ID, TimeZone: "Asia/Shanghai", TriggerTime: "2026-10-16T15:30",
+ Template: fmt.Sprintf(`.action{field %q}`, source.GetBlockKey().ID), Inputs: map[string]string{source.GetBlockKey().ID: "Preview only"}}
+ value, err := PreviewAttributeViewTemplate(request)
+ if err != nil || value.Block.Content != "Preview only" {
+ t.Fatal("preview failed", value, err)
+ }
+ request.KeyID = target.KeyValues[2].Key.ID
+ request.Template = `.action{((now).AddDate 0 0 7).Format "2006-01-02"}`
+ value, err = PreviewAttributeViewTemplate(request)
+ zone, _ := time.LoadLocation(request.TimeZone)
+ if err != nil || time.UnixMilli(value.Date.Content).In(zone).Format("2006-01-02") != "2026-10-23" {
+ t.Fatal("preview time ignored", value, err)
+ }
+ request.Template = `.action{.Missing}`
+ if _, err = PreviewAttributeViewTemplate(request); err == nil {
+ t.Fatal("preview hid missing variable")
+ }
+ for path, before := range paths {
+ after, _ := os.ReadFile(path)
+ if !bytes.Equal(before, after) {
+ t.Fatal("preview wrote database", path)
+ }
+ }
+}
+
+func TestAutomationTemplateReferencesAndConfigurationVersion(t *testing.T) {
+ fixture, source, target, _, _ := setupAutomationTest(t)
+ previousWorkspace := util.WorkspaceDir
+ util.WorkspaceDir = filepath.Dir(util.DataDir)
+ defer func() { util.WorkspaceDir = previousWorkspace }()
+ tx := &Transaction{}
+ defer tx.finishAttributeViewMutation(false)
+ relationKey := target.KeyValues[len(target.KeyValues)-1].Key
+ itemID := source.GetBlockKeyValues().Values[0].BlockID
+ for _, test := range []struct {
+ ids []string
+ valid bool
+ }{
+ {[]string{itemID}, true}, {[]string{target.ID}, false}, {[]string{"20261016000000-missing"}, false},
+ } {
+ value := &av.Value{Type: av.KeyTypeRelation, Relation: &av.ValueRelation{BlockIDs: test.ids}}
+ err := tx.validateAutomationTemplateReferences(source, target, relationKey, value, "")
+ if (err == nil) != test.valid {
+ t.Fatalf("reference validation mismatch: %v %v", test.ids, err)
+ }
+ }
+ assetKey := &av.Key{Type: av.KeyTypeMAsset}
+ for _, path := range []string{"assets/missing.pdf", "../conf/conf.json", "https://example.com/new.pdf"} {
+ value := &av.Value{Type: av.KeyTypeMAsset, MAsset: []*av.ValueAsset{{Type: av.AssetTypeFile, Content: path}}}
+ if err := tx.validateAutomationTemplateReferences(source, target, assetKey, value, ""); err == nil {
+ t.Fatal("invalid asset accepted", path)
+ }
+ }
+ assetPath := filepath.Join(util.DataDir, "assets", "template-fixture.pdf")
+ if err := os.MkdirAll(filepath.Dir(assetPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(assetPath, []byte("fixture"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.validateAutomationTemplateReferences(source, target, assetKey, &av.Value{MAsset: []*av.ValueAsset{{Type: av.AssetTypeFile, Content: "assets/template-fixture.pdf"}}}, ""); err != nil {
+ t.Fatal("existing asset rejected", err)
+ }
+ source.Automations.Rules = source.Automations.Rules[:1]
+ rule := source.Automations.Rules[0]
+ rule.TimeZone = "UTC"
+ rule.Actions[0].Fields[target.GetBlockKey().ID] = &av.AutomationValue{Mode: "template", Template: "test"}
+ operation := &Operation{Action: "setAttrViewAutomations", AvID: source.ID, BlockID: fixture.sourceID, Data: source.Automations}
+ if err := PerformAttributeViewOperations([]*Operation{operation}); err == nil {
+ t.Fatal("template accepted under old version")
+ }
+ source.Automations.Spec = 2
+ if err := PerformAttributeViewOperations([]*Operation{operation}); err != nil {
+ t.Fatal("new configuration rejected", err)
+ }
+ stored := readAttributeViewItemsTest(t, source.ID)
+ data, _ := json.Marshal(stored.Automations)
+ if !bytes.Contains(data, []byte(`"template":"test"`)) || stored.Automations.Rules[0].TimeZone != "UTC" {
+ t.Fatal("configuration lost template or time zone")
+ }
+}
+
+func TestAutomationTemplateBlockCollection(t *testing.T) {
+ fixture, view, keyID := setupBlockCollectionTest(t)
+ view.Automations.Spec = 2
+ rule := view.Automations.Rules[0]
+ rule.TimeZone = "UTC"
+ rule.Actions[0].Fields[keyID] = &av.AutomationValue{Mode: "template", Template: fmt.Sprintf(`Collected: .action{field %q}`, view.GetBlockKey().ID)}
+ if err := av.SaveAttributeView(view); err != nil {
+ t.Fatal(err)
+ }
+ if err := PerformTxSync(blockCollectionTags(t, fixture.sourceID, "todo")); err != nil {
+ t.Fatal(err)
+ }
+ stored := readAttributeViewItemsTest(t, view.ID)
+ row := stored.GetBlockValueByBoundID(fixture.sourceID)
+ if row == nil || stored.GetValue(keyID, row.BlockID).Text.Content != "Collected: "+row.Block.Content {
+ t.Fatal("collection template did not read the inserted source row", row)
+ }
+}
diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.go
index aea25ef8f0..707fc29be1 100644
--- a/kernel/model/attribute_view_collection.go
+++ b/kernel/model/attribute_view_collection.go
@@ -173,6 +173,12 @@ func (tx *Transaction) validateBlockCollectionRule(view *av.AttributeView, rule
if value.Mode == "currentTime" && key.Type == av.KeyTypeDate {
continue
}
+ if value.Mode == "template" {
+ if err = av.ValidateAutomationTemplate(value.Template, rule.TimeZone); err != nil {
+ return err
+ }
+ continue
+ }
if value.Mode != "static" || value.Value == nil || value.Value.Type != key.Type {
return unavailableAutomationReference("fields", keyID, fmt.Sprintf("invalid collection field value [%s]", keyID))
}
@@ -428,8 +434,16 @@ func (tx *Transaction) addCollectedItem(view *av.AttributeView, rule *av.Automat
if len(rule.Actions[0].Fields) == 0 {
return nil
}
- return tx.runAutomationAction(&attributeViewAutomationSource{before: view, boxID: boxID}, view, id,
- &av.AutomationAction{Type: "edit", Target: "current", Fields: rule.Actions[0].Fields})
+ current, err := tx.readAttributeViewForMutation(view.ID, "", boxID)
+ if err != nil {
+ return err
+ }
+ current, err = cloneAttributeViewForFieldMutation(current)
+ if err != nil {
+ return err
+ }
+ return tx.runAutomationAction(&attributeViewAutomationSource{before: view, boxID: boxID}, current, id,
+ &av.AutomationAction{Type: "edit", Target: "current", Fields: rule.Actions[0].Fields}, rule.TimeZone)
}
func (tx *Transaction) removeCollectedItem(view *av.AttributeView, row *av.Value, boxID string) error {