feat: Actions system — scheduled mutations on external services
Full-stack implementation of provider-scoped Actions with extensible executor architecture. First action type: Immich auto_organize (sort assets into albums by person, CLIP search, date range, favorites). Core: - ActionTypeDefinition registry + ActionExecutor ABC with execute/validate/dry-run - ImmichActionExecutor with multi-album support and client-side filtering - ImmichClient write methods: add/remove assets, create album, paginated search Server: - Action, ActionRule, ActionExecution DB models - Full CRUD API + manual execute + dry-run + execution history endpoints - APScheduler integration (interval + cron) for automated execution - Action type discovery API + provider people endpoint Frontend: - Actions page with CRUD, execute/dry-run buttons, inline rule editor - RuleEditor: person/album MultiEntitySelect pickers, criteria config - ExecutionHistory: expandable per-rule result details - MultiEntitySelect reusable component (searchable multi-pick palette) - Notification tracker album picker migrated to MultiEntitySelect - Fixed MdiIcon race condition (icons missing after cache-clearing reload)
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { getMdiPath, getAllMdiNames } from '$lib/mdi-lookup';
|
||||
import { getMdiPath, getAllMdiNames } from '$lib/mdi-lookup.svelte';
|
||||
|
||||
let { value = '', onselect } = $props<{
|
||||
value: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { getMdiPath } from '$lib/mdi-lookup';
|
||||
import { getMdiPath } from '$lib/mdi-lookup.svelte';
|
||||
|
||||
let { name = '', size = 18 } = $props<{ name: string; size?: number }>();
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
<script lang="ts">
|
||||
import MdiIcon from './MdiIcon.svelte';
|
||||
|
||||
export interface MultiEntityItem {
|
||||
value: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
desc?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
items = [],
|
||||
values = $bindable<string[]>(),
|
||||
placeholder = 'Select...',
|
||||
size = 'default',
|
||||
onchange,
|
||||
}: {
|
||||
items: MultiEntityItem[];
|
||||
values: string[];
|
||||
placeholder?: string;
|
||||
size?: 'sm' | 'default';
|
||||
onchange?: (values: string[]) => void;
|
||||
} = $props();
|
||||
|
||||
let open = $state(false);
|
||||
let query = $state('');
|
||||
let highlightIdx = $state(0);
|
||||
let inputEl: HTMLInputElement;
|
||||
let listEl: HTMLDivElement;
|
||||
|
||||
const selectedItems = $derived(items.filter(i => (values || []).includes(i.value)));
|
||||
|
||||
const filtered = $derived.by(() => {
|
||||
const q = query.toLowerCase().trim();
|
||||
return q
|
||||
? items.filter(i => i.label.toLowerCase().includes(q) || (i.desc || '').toLowerCase().includes(q))
|
||||
: items;
|
||||
});
|
||||
|
||||
function openPalette() {
|
||||
open = true;
|
||||
query = '';
|
||||
highlightIdx = 0;
|
||||
requestAnimationFrame(() => inputEl?.focus());
|
||||
}
|
||||
|
||||
function closePalette() {
|
||||
open = false;
|
||||
query = '';
|
||||
}
|
||||
|
||||
function toggleItem(item: MultiEntityItem) {
|
||||
const current = values || [];
|
||||
if (current.includes(item.value)) {
|
||||
values = current.filter(v => v !== item.value);
|
||||
} else {
|
||||
values = [...current, item.value];
|
||||
}
|
||||
onchange?.(values);
|
||||
}
|
||||
|
||||
function removeItem(value: string) {
|
||||
values = (values || []).filter(v => v !== value);
|
||||
onchange?.(values);
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') { closePalette(); return; }
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
highlightIdx = Math.min(highlightIdx + 1, filtered.length - 1);
|
||||
scrollToHighlight();
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
highlightIdx = Math.max(highlightIdx - 1, 0);
|
||||
scrollToHighlight();
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (filtered[highlightIdx]) toggleItem(filtered[highlightIdx]);
|
||||
}
|
||||
}
|
||||
|
||||
function scrollToHighlight() {
|
||||
requestAnimationFrame(() => {
|
||||
listEl?.querySelector('.mes-highlight')?.scrollIntoView({ block: 'nearest' });
|
||||
});
|
||||
}
|
||||
|
||||
$effect(() => { query; highlightIdx = 0; });
|
||||
</script>
|
||||
|
||||
<!-- Trigger: chips + button -->
|
||||
<div class="mes-trigger-wrap" class:mes-sm={size === 'sm'}>
|
||||
{#if selectedItems.length > 0}
|
||||
<div class="mes-chips">
|
||||
{#each selectedItems as item}
|
||||
<span class="mes-chip">
|
||||
{#if item.icon}<span class="mes-chip-icon"><MdiIcon name={item.icon} size={12} /></span>{/if}
|
||||
<span class="mes-chip-label">{item.label}</span>
|
||||
<button type="button" class="mes-chip-remove" onclick={() => removeItem(item.value)}>×</button>
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
<button type="button" class="mes-trigger" onclick={openPalette}>
|
||||
<MdiIcon name="mdiPlus" size={14} />
|
||||
<span>{(values || []).length === 0 ? placeholder : `${(values || []).length} selected`}</span>
|
||||
<span class="mes-trigger-arrow"><MdiIcon name="mdiChevronDown" size={14} /></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Palette overlay -->
|
||||
{#if open}
|
||||
<div class="mes-overlay" onclick={closePalette} role="presentation"></div>
|
||||
|
||||
<div class="mes-container">
|
||||
<div class="mes-search-row">
|
||||
<MdiIcon name="mdiMagnify" size={18} />
|
||||
<input
|
||||
bind:this={inputEl}
|
||||
bind:value={query}
|
||||
placeholder="Search..."
|
||||
class="mes-input"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
onkeydown={handleKeydown}
|
||||
/>
|
||||
<span class="mes-count">{(values || []).length}/{items.length}</span>
|
||||
<kbd class="mes-kbd">ESC</kbd>
|
||||
</div>
|
||||
|
||||
<div class="mes-list" bind:this={listEl} role="listbox">
|
||||
{#if filtered.length === 0}
|
||||
<div class="mes-empty">No matches</div>
|
||||
{:else}
|
||||
{#each filtered as item, i}
|
||||
{@const checked = (values || []).includes(item.value)}
|
||||
<button
|
||||
class="mes-item"
|
||||
class:mes-highlight={i === highlightIdx}
|
||||
class:mes-checked={checked}
|
||||
role="option"
|
||||
aria-selected={checked}
|
||||
onclick={() => toggleItem(item)}
|
||||
onmouseenter={() => highlightIdx = i}
|
||||
type="button"
|
||||
>
|
||||
<span class="mes-item-check">
|
||||
<MdiIcon name={checked ? 'mdiCheckboxMarked' : 'mdiCheckboxBlankOutline'} size={16} />
|
||||
</span>
|
||||
{#if item.icon}
|
||||
<span class="mes-item-icon"><MdiIcon name={item.icon} size={18} /></span>
|
||||
{/if}
|
||||
<span class="mes-item-label">{item.label}</span>
|
||||
{#if item.desc}
|
||||
<span class="mes-item-desc">{item.desc}</span>
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.mes-trigger-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
.mes-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
.mes-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.75rem;
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 9999px;
|
||||
background: color-mix(in srgb, var(--color-primary) 10%, transparent);
|
||||
color: var(--color-primary);
|
||||
border: 1px solid color-mix(in srgb, var(--color-primary) 30%, transparent);
|
||||
}
|
||||
.mes-chip-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.mes-chip-label {
|
||||
max-width: 12rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.mes-chip-remove {
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1;
|
||||
opacity: 0.6;
|
||||
transition: opacity 0.1s;
|
||||
}
|
||||
.mes-chip-remove:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.mes-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
width: 100%;
|
||||
padding: 0.375rem 0.625rem;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.8rem;
|
||||
background: var(--color-background);
|
||||
color: var(--color-muted-foreground);
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
.mes-sm .mes-trigger {
|
||||
padding: 0.25rem 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.mes-trigger:hover {
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
.mes-trigger-arrow {
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Overlay */
|
||||
.mes-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 9998;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
|
||||
/* Palette container */
|
||||
.mes-container {
|
||||
position: fixed;
|
||||
top: min(20vh, 120px);
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 9999;
|
||||
width: min(460px, 90vw);
|
||||
max-height: 60vh;
|
||||
background: var(--color-card);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.mes-search-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.625rem 0.875rem;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
color: var(--color-muted-foreground);
|
||||
}
|
||||
.mes-input {
|
||||
flex: 1;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
font-size: 0.9rem;
|
||||
color: var(--color-foreground);
|
||||
padding: 0;
|
||||
}
|
||||
.mes-count {
|
||||
font-size: 0.7rem;
|
||||
color: var(--color-muted-foreground);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.mes-kbd {
|
||||
font-size: 0.55rem;
|
||||
font-family: var(--font-mono);
|
||||
padding: 0.1rem 0.3rem;
|
||||
border-radius: 0.2rem;
|
||||
background: var(--color-muted);
|
||||
color: var(--color-muted-foreground);
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.mes-list {
|
||||
overflow-y: auto;
|
||||
scrollbar-width: thin;
|
||||
padding: 0.25rem 0;
|
||||
}
|
||||
.mes-empty {
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
color: var(--color-muted-foreground);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.mes-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
padding: 0.4rem 0.875rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--color-foreground);
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
.mes-item:hover, .mes-item.mes-highlight {
|
||||
background: var(--color-muted);
|
||||
}
|
||||
.mes-item-check {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
color: var(--color-muted-foreground);
|
||||
}
|
||||
.mes-item.mes-checked .mes-item-check {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
.mes-item-icon {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
color: var(--color-muted-foreground);
|
||||
}
|
||||
.mes-item-label {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.mes-item-desc {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-muted-foreground);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 40%;
|
||||
}
|
||||
</style>
|
||||
@@ -33,7 +33,9 @@
|
||||
"targetDiscord": "Discord",
|
||||
"targetSlack": "Slack",
|
||||
"targetNtfy": "ntfy",
|
||||
"targetMatrix": "Matrix"
|
||||
"targetMatrix": "Matrix",
|
||||
"automation": "Automation",
|
||||
"actions": "Actions"
|
||||
},
|
||||
"auth": {
|
||||
"signIn": "Sign in",
|
||||
@@ -138,6 +140,7 @@
|
||||
"server": "Provider",
|
||||
"selectServer": "Select provider...",
|
||||
"albums": "Albums",
|
||||
"selectAlbums": "Select albums...",
|
||||
"eventTypes": "Event Types",
|
||||
"notificationTargets": "Notification Targets",
|
||||
"scanInterval": "Scan Interval (seconds)",
|
||||
@@ -828,5 +831,59 @@
|
||||
"navigate": "navigate",
|
||||
"open": "open",
|
||||
"close": "close"
|
||||
},
|
||||
"actions": {
|
||||
"title": "Actions",
|
||||
"description": "Scheduled mutations on external services",
|
||||
"addAction": "Add Action",
|
||||
"noActions": "No actions configured yet.",
|
||||
"provider": "Provider",
|
||||
"selectProvider": "Select provider...",
|
||||
"actionType": "Action Type",
|
||||
"name": "Name",
|
||||
"schedule": "Schedule",
|
||||
"interval": "Interval",
|
||||
"seconds": "seconds",
|
||||
"cronHint": "Standard cron expression (e.g. 0 3 * * * for daily at 3 AM)",
|
||||
"enabled": "Enabled",
|
||||
"rules": "rules",
|
||||
"addRule": "Add Rule",
|
||||
"ruleName": "Rule Name",
|
||||
"ruleNamePlaceholder": "e.g. Alice → Family Album",
|
||||
"unnamedRule": "Unnamed rule",
|
||||
"noRules": "No rules yet. Add a rule to define what this action does.",
|
||||
"on": "ON",
|
||||
"off": "OFF",
|
||||
"criteria": "Criteria",
|
||||
"persons": "Persons",
|
||||
"addPerson": "Add person...",
|
||||
"searchQuery": "Smart Search Query",
|
||||
"searchQueryPlaceholder": "e.g. sunset, beach, birthday...",
|
||||
"assetType": "Asset type",
|
||||
"dateFrom": "From date",
|
||||
"dateTo": "To date",
|
||||
"favoritesOnly": "Favorites only",
|
||||
"targetAlbum": "Target Album",
|
||||
"selectAlbum": "Album",
|
||||
"selectAlbumPlaceholder": "— Select album —",
|
||||
"albumId": "Album ID",
|
||||
"createAlbumIfMissing": "Create album if it doesn't exist",
|
||||
"newAlbumName": "New album name",
|
||||
"execute": "Execute",
|
||||
"dryRun": "Dry Run",
|
||||
"history": "History",
|
||||
"affected": "affected",
|
||||
"executeResult": "Action executed: {affected} items affected",
|
||||
"dryRunResult": "Dry run: {affected} items would be affected",
|
||||
"saved": "Action saved",
|
||||
"deleted": "Action deleted",
|
||||
"ruleSaved": "Rule saved",
|
||||
"ruleDeleted": "Rule deleted",
|
||||
"confirmDelete": "Are you sure you want to delete this action? All rules and execution history will be lost.",
|
||||
"loadError": "Failed to load actions",
|
||||
"noExecutions": "No executions yet.",
|
||||
"triggerManual": "manual",
|
||||
"triggerDryRun": "dry-run",
|
||||
"triggerScheduled": "scheduled"
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,9 @@
|
||||
"targetDiscord": "Discord",
|
||||
"targetSlack": "Slack",
|
||||
"targetNtfy": "ntfy",
|
||||
"targetMatrix": "Matrix"
|
||||
"targetMatrix": "Matrix",
|
||||
"automation": "Автоматизация",
|
||||
"actions": "Действия"
|
||||
},
|
||||
"auth": {
|
||||
"signIn": "Войти",
|
||||
@@ -138,6 +140,7 @@
|
||||
"server": "Провайдер",
|
||||
"selectServer": "Выберите провайдер...",
|
||||
"albums": "Альбомы",
|
||||
"selectAlbums": "Выберите альбомы...",
|
||||
"eventTypes": "Типы событий",
|
||||
"notificationTargets": "Получатели уведомлений",
|
||||
"scanInterval": "Интервал проверки (секунды)",
|
||||
@@ -828,5 +831,59 @@
|
||||
"navigate": "навигация",
|
||||
"open": "открыть",
|
||||
"close": "закрыть"
|
||||
},
|
||||
"actions": {
|
||||
"title": "Действия",
|
||||
"description": "Запланированные операции над внешними сервисами",
|
||||
"addAction": "Добавить действие",
|
||||
"noActions": "Действия ещё не настроены.",
|
||||
"provider": "Провайдер",
|
||||
"selectProvider": "Выберите провайдер...",
|
||||
"actionType": "Тип действия",
|
||||
"name": "Название",
|
||||
"schedule": "Расписание",
|
||||
"interval": "Интервал",
|
||||
"seconds": "секунд",
|
||||
"cronHint": "Стандартное cron-выражение (напр. 0 3 * * * — ежедневно в 3:00)",
|
||||
"enabled": "Включено",
|
||||
"rules": "правил",
|
||||
"addRule": "Добавить правило",
|
||||
"ruleName": "Название правила",
|
||||
"ruleNamePlaceholder": "напр. Алиса → Семейный альбом",
|
||||
"unnamedRule": "Без названия",
|
||||
"noRules": "Правил пока нет. Добавьте правило, чтобы определить, что делает это действие.",
|
||||
"on": "ВКЛ",
|
||||
"off": "ВЫКЛ",
|
||||
"criteria": "Критерии",
|
||||
"persons": "Люди",
|
||||
"addPerson": "Добавить человека...",
|
||||
"searchQuery": "Умный поиск",
|
||||
"searchQueryPlaceholder": "напр. закат, пляж, день рождения...",
|
||||
"assetType": "Тип файла",
|
||||
"dateFrom": "С даты",
|
||||
"dateTo": "По дату",
|
||||
"favoritesOnly": "Только избранное",
|
||||
"targetAlbum": "Целевой альбом",
|
||||
"selectAlbum": "Альбом",
|
||||
"selectAlbumPlaceholder": "— Выберите альбом —",
|
||||
"albumId": "ID альбома",
|
||||
"createAlbumIfMissing": "Создать альбом, если не существует",
|
||||
"newAlbumName": "Название нового альбома",
|
||||
"execute": "Выполнить",
|
||||
"dryRun": "Пробный запуск",
|
||||
"history": "История",
|
||||
"affected": "затронуто",
|
||||
"executeResult": "Действие выполнено: затронуто {affected} объектов",
|
||||
"dryRunResult": "Пробный запуск: было бы затронуто {affected} объектов",
|
||||
"saved": "Действие сохранено",
|
||||
"deleted": "Действие удалено",
|
||||
"ruleSaved": "Правило сохранено",
|
||||
"ruleDeleted": "Правило удалено",
|
||||
"confirmDelete": "Вы уверены, что хотите удалить это действие? Все правила и история выполнений будут потеряны.",
|
||||
"loadError": "Не удалось загрузить действия",
|
||||
"noExecutions": "Выполнений пока нет.",
|
||||
"triggerManual": "вручную",
|
||||
"triggerDryRun": "пробный",
|
||||
"triggerScheduled": "по расписанию"
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,13 @@
|
||||
* Instead of `import * as mdi from '@mdi/js'` (which loads ~5MB of SVG paths
|
||||
* into memory), this module loads the full set once on first use and caches it.
|
||||
* Vite only processes the import once, reducing HMR memory pressure.
|
||||
*
|
||||
* Uses $state so that components re-render once the icon module finishes loading
|
||||
* (fixes icons not appearing until page reload after cache-clearing navigations).
|
||||
*/
|
||||
|
||||
let _cache: Record<string, string> | null = null;
|
||||
let _ready = $state<Record<string, string> | null>(null);
|
||||
|
||||
async function _load(): Promise<Record<string, string>> {
|
||||
if (_cache) return _cache;
|
||||
@@ -16,7 +20,6 @@ async function _load(): Promise<Record<string, string>> {
|
||||
}
|
||||
|
||||
// Eagerly load on module init (runs once)
|
||||
let _ready: Record<string, string> | null = null;
|
||||
_load().then(m => { _ready = m; });
|
||||
|
||||
/**
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
CommandConfig,
|
||||
CommandTemplateConfig,
|
||||
CommandTracker,
|
||||
Action,
|
||||
} from '$lib/types';
|
||||
|
||||
/** Service providers — used by Dashboard, Trackers, Command Trackers, Providers page. */
|
||||
@@ -53,6 +54,9 @@ export const commandTemplateConfigsCache = createEntityCache<CommandTemplateConf
|
||||
/** Command trackers — used by Command Trackers page. */
|
||||
export const commandTrackersCache = createEntityCache<CommandTracker>('/command-trackers');
|
||||
|
||||
/** Actions — used by Actions page. */
|
||||
export const actionsCache = createEntityCache<Action>('/actions');
|
||||
|
||||
/** Provider capabilities — used by Template Configs, Command Configs. */
|
||||
export const capabilitiesCache = (() => {
|
||||
let data = $state<Record<string, any>>({});
|
||||
@@ -85,6 +89,7 @@ export const allCaches = {
|
||||
command_configs: commandConfigsCache,
|
||||
command_template_configs: commandTemplateConfigsCache,
|
||||
command_trackers: commandTrackersCache,
|
||||
actions: actionsCache,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
||||
@@ -219,6 +219,55 @@ export interface CommandTracker {
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ActionRule {
|
||||
id: number;
|
||||
action_id: number;
|
||||
name: string;
|
||||
rule_config: Record<string, any>;
|
||||
enabled: boolean;
|
||||
order: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Action {
|
||||
id: number;
|
||||
name: string;
|
||||
icon: string;
|
||||
provider_id: number;
|
||||
action_type: string;
|
||||
config: Record<string, any>;
|
||||
schedule_type: string;
|
||||
schedule_interval: number;
|
||||
schedule_cron: string;
|
||||
enabled: boolean;
|
||||
last_run_at: string | null;
|
||||
last_run_status: string;
|
||||
rules: ActionRule[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ActionExecution {
|
||||
id: number;
|
||||
action_id: number;
|
||||
started_at: string;
|
||||
finished_at: string | null;
|
||||
status: string;
|
||||
rules_processed: number;
|
||||
rules_succeeded: number;
|
||||
rules_failed: number;
|
||||
total_items_affected: number;
|
||||
summary: Record<string, any>;
|
||||
error: string;
|
||||
trigger: string;
|
||||
}
|
||||
|
||||
export interface ActionTypeInfo {
|
||||
key: string;
|
||||
name: string;
|
||||
description: string;
|
||||
provider_type: string;
|
||||
}
|
||||
|
||||
export interface DashboardStatus {
|
||||
providers: number;
|
||||
trackers: { total: number; active: number };
|
||||
|
||||
@@ -84,6 +84,12 @@
|
||||
{ href: '/command-template-configs', key: 'nav.templates', icon: 'mdiCodeBracesBox', countKey: 'command_template_configs' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'nav.automation', icon: 'mdiRobotOutline',
|
||||
children: [
|
||||
{ href: '/actions', key: 'nav.actions', icon: 'mdiPlayCircleOutline', countKey: 'actions' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'nav.bots', icon: 'mdiRobot',
|
||||
children: [
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { slide } from 'svelte/transition';
|
||||
import { api } from '$lib/api';
|
||||
import { t } from '$lib/i18n';
|
||||
import { actionsCache, providersCache, capabilitiesCache } from '$lib/stores/caches.svelte';
|
||||
import PageHeader from '$lib/components/PageHeader.svelte';
|
||||
import Card from '$lib/components/Card.svelte';
|
||||
import Loading from '$lib/components/Loading.svelte';
|
||||
import IconPicker from '$lib/components/IconPicker.svelte';
|
||||
import MdiIcon from '$lib/components/MdiIcon.svelte';
|
||||
import EmptyState from '$lib/components/EmptyState.svelte';
|
||||
import ConfirmModal from '$lib/components/ConfirmModal.svelte';
|
||||
import IconButton from '$lib/components/IconButton.svelte';
|
||||
import EntitySelect from '$lib/components/EntitySelect.svelte';
|
||||
import { snackSuccess, snackError } from '$lib/stores/snackbar.svelte';
|
||||
import { highlightFromUrl } from '$lib/highlight';
|
||||
import RuleEditor from './RuleEditor.svelte';
|
||||
import ExecutionHistory from './ExecutionHistory.svelte';
|
||||
import type { Action, ActionRule } from '$lib/types';
|
||||
|
||||
let allActions = $derived(actionsCache.items);
|
||||
let providers = $derived(providersCache.items);
|
||||
let filterText = $state('');
|
||||
let actions = $derived(allActions.filter((a: Action) =>
|
||||
!filterText || a.name.toLowerCase().includes(filterText.toLowerCase()) || a.action_type.toLowerCase().includes(filterText.toLowerCase())
|
||||
));
|
||||
|
||||
let showForm = $state(false);
|
||||
let editing = $state<number | null>(null);
|
||||
let form = $state({
|
||||
name: '', provider_id: 0, action_type: 'auto_organize', icon: '',
|
||||
config: {} as Record<string, any>,
|
||||
schedule_type: 'interval', schedule_interval: 3600, schedule_cron: '',
|
||||
enabled: false,
|
||||
});
|
||||
let error = $state('');
|
||||
let loadError = $state('');
|
||||
let submitting = $state(false);
|
||||
let loaded = $state(false);
|
||||
let confirmDelete = $state<Action | null>(null);
|
||||
let executing = $state<Record<number, boolean>>({});
|
||||
let historyActionId = $state<number | null>(null);
|
||||
|
||||
// Providers that support actions
|
||||
let actionProviders = $derived(providers.filter((p: any) => {
|
||||
const caps = capabilitiesCache.items[p.type];
|
||||
return caps && caps.action_types && caps.action_types.length > 0;
|
||||
}));
|
||||
|
||||
let providerItems = $derived(actionProviders.map((p: any) => ({
|
||||
value: p.id, label: p.name, icon: p.icon || 'mdiServer', desc: p.type,
|
||||
})));
|
||||
|
||||
// Action types for selected provider
|
||||
let selectedProviderType = $derived(providers.find((p: any) => p.id === form.provider_id)?.type || '');
|
||||
let actionTypes = $derived((() => {
|
||||
const caps = capabilitiesCache.items[selectedProviderType];
|
||||
return caps?.action_types || [];
|
||||
})());
|
||||
|
||||
onMount(load);
|
||||
async function load() {
|
||||
try {
|
||||
await Promise.all([
|
||||
actionsCache.fetch(true),
|
||||
providersCache.fetch(),
|
||||
capabilitiesCache.fetch(),
|
||||
]);
|
||||
loadError = '';
|
||||
} catch (err: any) {
|
||||
loadError = err.message || t('actions.loadError');
|
||||
} finally { loaded = true; highlightFromUrl(); }
|
||||
}
|
||||
|
||||
function openNew() {
|
||||
const defaultProvider = actionProviders[0]?.id || 0;
|
||||
form = {
|
||||
name: '', provider_id: defaultProvider, action_type: 'auto_organize', icon: '',
|
||||
config: {}, schedule_type: 'interval', schedule_interval: 3600, schedule_cron: '',
|
||||
enabled: false,
|
||||
};
|
||||
editing = null; showForm = true;
|
||||
}
|
||||
|
||||
function edit(action: Action) {
|
||||
form = {
|
||||
name: action.name, provider_id: action.provider_id,
|
||||
action_type: action.action_type, icon: action.icon || '',
|
||||
config: { ...action.config }, schedule_type: action.schedule_type,
|
||||
schedule_interval: action.schedule_interval,
|
||||
schedule_cron: action.schedule_cron, enabled: action.enabled,
|
||||
};
|
||||
editing = action.id; showForm = true;
|
||||
}
|
||||
|
||||
async function save(e: SubmitEvent) {
|
||||
e.preventDefault(); error = ''; submitting = true;
|
||||
try {
|
||||
const payload = { ...form };
|
||||
if (editing) {
|
||||
await api(`/actions/${editing}`, { method: 'PUT', body: JSON.stringify(payload) });
|
||||
} else {
|
||||
await api('/actions', { method: 'POST', body: JSON.stringify(payload) });
|
||||
}
|
||||
showForm = false; editing = null; actionsCache.invalidate(); await load();
|
||||
snackSuccess(t('actions.saved'));
|
||||
} catch (err: any) { error = err.message; snackError(err.message); }
|
||||
submitting = false;
|
||||
}
|
||||
|
||||
function startDelete(action: Action) { confirmDelete = action; }
|
||||
async function doDelete() {
|
||||
if (!confirmDelete) return;
|
||||
const id = confirmDelete.id;
|
||||
confirmDelete = null;
|
||||
try {
|
||||
await api(`/actions/${id}`, { method: 'DELETE' });
|
||||
actionsCache.invalidate(); await load();
|
||||
snackSuccess(t('actions.deleted'));
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
}
|
||||
|
||||
async function executeAction(id: number, dryRun = false) {
|
||||
executing = { ...executing, [id]: true };
|
||||
try {
|
||||
const endpoint = dryRun ? `/actions/${id}/dry-run` : `/actions/${id}/execute`;
|
||||
const result = await api<any>(endpoint, { method: 'POST' });
|
||||
const affected = result.total_items_affected || 0;
|
||||
const msg = dryRun
|
||||
? `${t('actions.dryRun')}: ${affected} ${t('actions.affected')}`
|
||||
: `${t('actions.execute')}: ${affected} ${t('actions.affected')}`;
|
||||
snackSuccess(msg);
|
||||
actionsCache.invalidate(); await load();
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
executing = { ...executing, [id]: false };
|
||||
}
|
||||
|
||||
function getProviderName(providerId: number): string {
|
||||
return providers.find((p: any) => p.id === providerId)?.name || '?';
|
||||
}
|
||||
|
||||
function formatSchedule(action: Action): string {
|
||||
if (action.schedule_type === 'cron' && action.schedule_cron) {
|
||||
return `cron: ${action.schedule_cron}`;
|
||||
}
|
||||
const h = Math.floor(action.schedule_interval / 3600);
|
||||
const m = Math.floor((action.schedule_interval % 3600) / 60);
|
||||
if (h > 0 && m > 0) return `${h}h ${m}m`;
|
||||
if (h > 0) return `${h}h`;
|
||||
return `${action.schedule_interval}s`;
|
||||
}
|
||||
|
||||
function statusColor(status: string): string {
|
||||
if (status === 'success') return '#059669';
|
||||
if (status === 'partial') return '#f59e0b';
|
||||
if (status === 'failed') return '#ef4444';
|
||||
return 'var(--color-muted-foreground)';
|
||||
}
|
||||
</script>
|
||||
|
||||
<PageHeader title={t('actions.title')} description={t('actions.description')}>
|
||||
<button onclick={() => { showForm ? (showForm = false, editing = null) : openNew(); }}
|
||||
class="px-3 py-1.5 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-sm font-medium hover:opacity-90">
|
||||
{showForm ? t('common.cancel') : t('actions.addAction')}
|
||||
</button>
|
||||
</PageHeader>
|
||||
|
||||
{#if !loaded}
|
||||
<Loading />
|
||||
{:else}
|
||||
|
||||
{#if loadError}
|
||||
<Card class="mb-6">
|
||||
<div class="flex items-center gap-2 text-sm" style="color: var(--color-error-fg);">
|
||||
<MdiIcon name="mdiAlertCircle" size={18} />
|
||||
{loadError}
|
||||
</div>
|
||||
</Card>
|
||||
{/if}
|
||||
|
||||
{#if showForm}
|
||||
<div in:slide={{ duration: 200 }}>
|
||||
<Card class="mb-6">
|
||||
{#if error}
|
||||
<div class="bg-[var(--color-error-bg)] text-[var(--color-error-fg)] text-sm rounded-md p-3 mb-4">{error}</div>
|
||||
{/if}
|
||||
<form onsubmit={save} class="space-y-3">
|
||||
<div>
|
||||
<label class="block text-sm font-medium mb-1">{t('actions.provider')}</label>
|
||||
<EntitySelect items={providerItems} bind:value={form.provider_id}
|
||||
placeholder={t('actions.selectProvider')} disabled={!!editing} />
|
||||
</div>
|
||||
|
||||
{#if actionTypes.length > 0}
|
||||
<div>
|
||||
<label class="block text-sm font-medium mb-1">{t('actions.actionType')}</label>
|
||||
{#if !editing}
|
||||
<div class="space-y-1">
|
||||
{#each actionTypes as at}
|
||||
<label class="flex items-center gap-2 p-2 rounded border cursor-pointer
|
||||
{form.action_type === at.key ? 'border-[var(--color-primary)] bg-[var(--color-primary)]/5' : 'border-[var(--color-border)]'}">
|
||||
<input type="radio" name="action_type" value={at.key} bind:group={form.action_type} class="accent-[var(--color-primary)]" />
|
||||
<div>
|
||||
<span class="text-sm font-medium">{at.name}</span>
|
||||
<p class="text-xs text-[var(--color-muted-foreground)]">{at.description}</p>
|
||||
</div>
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-sm text-[var(--color-muted-foreground)]">{form.action_type}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div>
|
||||
<label for="act-name" class="block text-sm font-medium mb-1">{t('actions.name')}</label>
|
||||
<div class="flex gap-2">
|
||||
<IconPicker value={form.icon} onselect={(v: string) => form.icon = v} />
|
||||
<input id="act-name" bind:value={form.name} required
|
||||
class="flex-1 px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium mb-1">{t('actions.schedule')}</label>
|
||||
<div class="flex gap-2 items-center mb-2">
|
||||
<label class="flex items-center gap-1 text-sm">
|
||||
<input type="radio" name="schedule_type" value="interval" bind:group={form.schedule_type} class="accent-[var(--color-primary)]" />
|
||||
{t('actions.interval')}
|
||||
</label>
|
||||
<label class="flex items-center gap-1 text-sm">
|
||||
<input type="radio" name="schedule_type" value="cron" bind:group={form.schedule_type} class="accent-[var(--color-primary)]" />
|
||||
Cron
|
||||
</label>
|
||||
</div>
|
||||
{#if form.schedule_type === 'interval'}
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number" bind:value={form.schedule_interval} min="60" step="60"
|
||||
class="w-28 px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
<span class="text-sm text-[var(--color-muted-foreground)]">{t('actions.seconds')}</span>
|
||||
</div>
|
||||
{:else}
|
||||
<input bind:value={form.schedule_cron} placeholder="0 3 * * *"
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)] font-mono" />
|
||||
<p class="text-xs text-[var(--color-muted-foreground)] mt-1">{t('actions.cronHint')}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="checkbox" id="act-enabled" bind:checked={form.enabled} class="accent-[var(--color-primary)]" />
|
||||
<label for="act-enabled" class="text-sm">{t('actions.enabled')}</label>
|
||||
</div>
|
||||
|
||||
<button type="submit" disabled={submitting}
|
||||
class="px-4 py-2 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50">
|
||||
{submitting ? t('common.loading') : (editing ? t('common.save') : t('actions.addAction'))}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{#if editing}
|
||||
<hr class="my-4 border-[var(--color-border)]" />
|
||||
<RuleEditor actionId={editing} actionType={form.action_type} providerId={form.provider_id} />
|
||||
{/if}
|
||||
</Card>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !showForm && allActions.length > 0}
|
||||
<div class="flex items-center gap-2 mb-3">
|
||||
<input type="text" bind:value={filterText} placeholder={t('common.filterByName')}
|
||||
class="flex-1 px-3 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if allActions.length === 0 && !showForm}
|
||||
<Card>
|
||||
<EmptyState icon="mdiPlayCircleOutline" message={t('actions.noActions')} />
|
||||
</Card>
|
||||
{:else if actions.length === 0 && !showForm}
|
||||
<Card>
|
||||
<EmptyState icon="mdiFilterOff" message={t('common.noFilterResults')} />
|
||||
</Card>
|
||||
{:else if !showForm}
|
||||
<div class="space-y-3 stagger-children">
|
||||
{#each actions as action}
|
||||
<Card hover entityId={action.id}>
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="w-2.5 h-2.5 rounded-full flex-shrink-0"
|
||||
style="background: {action.enabled ? '#059669' : 'var(--color-muted-foreground)'}"></div>
|
||||
<span style="color: var(--color-primary);"><MdiIcon name={action.icon || 'mdiPlayCircleOutline'} size={20} /></span>
|
||||
<div>
|
||||
<div class="flex items-center gap-2">
|
||||
<p class="font-medium">{action.name}</p>
|
||||
<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{action.action_type}</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-3 text-xs text-[var(--color-muted-foreground)]">
|
||||
<span>{getProviderName(action.provider_id)}</span>
|
||||
<span>{formatSchedule(action)}</span>
|
||||
<span>{action.rules?.length || 0} {t('actions.rules')}</span>
|
||||
{#if action.last_run_status}
|
||||
<span style="color: {statusColor(action.last_run_status)}">
|
||||
{action.last_run_status}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<IconButton icon="mdiPlay" title={t('actions.execute')}
|
||||
onclick={() => executeAction(action.id)}
|
||||
disabled={executing[action.id]} />
|
||||
<IconButton icon="mdiEyeOutline" title={t('actions.dryRun')}
|
||||
onclick={() => executeAction(action.id, true)}
|
||||
disabled={executing[action.id]} />
|
||||
<IconButton icon="mdiHistory" title={t('actions.history')}
|
||||
onclick={() => historyActionId = historyActionId === action.id ? null : action.id} />
|
||||
<IconButton icon="mdiPencil" title={t('common.edit')} onclick={() => edit(action)} />
|
||||
<IconButton icon="mdiDelete" title={t('common.delete')} onclick={() => startDelete(action)} variant="danger" />
|
||||
</div>
|
||||
</div>
|
||||
{#if historyActionId === action.id}
|
||||
<div class="mt-3 pt-3 border-t border-[var(--color-border)]" in:slide={{ duration: 200 }}>
|
||||
<ExecutionHistory actionId={action.id} />
|
||||
</div>
|
||||
{/if}
|
||||
</Card>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{/if}
|
||||
|
||||
<ConfirmModal open={!!confirmDelete} message={t('actions.confirmDelete')}
|
||||
onconfirm={doDelete} oncancel={() => confirmDelete = null} />
|
||||
@@ -0,0 +1,114 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import { t } from '$lib/i18n';
|
||||
import MdiIcon from '$lib/components/MdiIcon.svelte';
|
||||
import type { ActionExecution } from '$lib/types';
|
||||
|
||||
let { actionId }: { actionId: number } = $props();
|
||||
|
||||
let executions = $state<ActionExecution[]>([]);
|
||||
let loading = $state(true);
|
||||
let expandedId = $state<number | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
loadExecutions();
|
||||
});
|
||||
|
||||
async function loadExecutions() {
|
||||
loading = true;
|
||||
try {
|
||||
executions = await api<ActionExecution[]>(`/actions/${actionId}/executions?limit=10`);
|
||||
} catch { /* ignore */ }
|
||||
loading = false;
|
||||
}
|
||||
|
||||
function statusIcon(status: string): string {
|
||||
if (status === 'success') return 'mdiCheckCircle';
|
||||
if (status === 'partial') return 'mdiAlertCircle';
|
||||
if (status === 'failed') return 'mdiCloseCircle';
|
||||
if (status === 'running') return 'mdiLoading';
|
||||
return 'mdiCircleOutline';
|
||||
}
|
||||
|
||||
function statusColor(status: string): string {
|
||||
if (status === 'success') return '#059669';
|
||||
if (status === 'partial') return '#f59e0b';
|
||||
if (status === 'failed') return '#ef4444';
|
||||
if (status === 'running') return '#3b82f6';
|
||||
return 'var(--color-muted-foreground)';
|
||||
}
|
||||
|
||||
function triggerLabel(trigger: string): string {
|
||||
if (trigger === 'manual') return t('actions.triggerManual');
|
||||
if (trigger === 'dry_run') return t('actions.triggerDryRun');
|
||||
return t('actions.triggerScheduled');
|
||||
}
|
||||
|
||||
function formatDate(iso: string | null): string {
|
||||
if (!iso) return '-';
|
||||
try {
|
||||
return new Date(iso).toLocaleString();
|
||||
} catch { return iso; }
|
||||
}
|
||||
|
||||
function formatDuration(start: string, end: string | null): string {
|
||||
if (!end) return '-';
|
||||
try {
|
||||
const ms = new Date(end).getTime() - new Date(start).getTime();
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
return `${(ms / 1000).toFixed(1)}s`;
|
||||
} catch { return '-'; }
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="space-y-2">
|
||||
<h4 class="text-xs font-semibold text-[var(--color-muted-foreground)] uppercase tracking-wide">
|
||||
{t('actions.history')}
|
||||
</h4>
|
||||
|
||||
{#if loading}
|
||||
<p class="text-xs text-[var(--color-muted-foreground)]">{t('common.loading')}...</p>
|
||||
{:else if executions.length === 0}
|
||||
<p class="text-xs text-[var(--color-muted-foreground)]">{t('actions.noExecutions')}</p>
|
||||
{:else}
|
||||
<div class="space-y-1">
|
||||
{#each executions as exec}
|
||||
<button onclick={() => expandedId = expandedId === exec.id ? null : exec.id}
|
||||
class="w-full text-left px-2 py-1.5 rounded text-xs hover:bg-[var(--color-muted)]/50 flex items-center gap-2">
|
||||
<span style="color: {statusColor(exec.status)}">
|
||||
<MdiIcon name={statusIcon(exec.status)} size={14} />
|
||||
</span>
|
||||
<span class="flex-1">{formatDate(exec.started_at)}</span>
|
||||
<span class="text-[var(--color-muted-foreground)]">{triggerLabel(exec.trigger)}</span>
|
||||
<span class="font-mono">{exec.rules_succeeded}/{exec.rules_processed}</span>
|
||||
<span class="text-[var(--color-muted-foreground)]">{exec.total_items_affected} {t('actions.affected')}</span>
|
||||
<span class="text-[var(--color-muted-foreground)]">{formatDuration(exec.started_at, exec.finished_at)}</span>
|
||||
</button>
|
||||
|
||||
{#if expandedId === exec.id}
|
||||
<div class="ml-6 px-2 py-1.5 text-xs space-y-1 border-l-2 border-[var(--color-border)]">
|
||||
{#if exec.error}
|
||||
<p class="text-[var(--color-error-fg)]">{exec.error}</p>
|
||||
{/if}
|
||||
{#if exec.summary?.rule_results}
|
||||
{#each exec.summary.rule_results as rr}
|
||||
<div class="flex items-center gap-2">
|
||||
<span style="color: {rr.success ? '#059669' : '#ef4444'}">
|
||||
<MdiIcon name={rr.success ? 'mdiCheck' : 'mdiClose'} size={12} />
|
||||
</span>
|
||||
<span class="font-medium">{rr.rule_name}</span>
|
||||
<span class="text-[var(--color-muted-foreground)]">
|
||||
{rr.items_matched} matched, {rr.items_affected} affected, {rr.items_skipped} skipped
|
||||
</span>
|
||||
{#if rr.error}
|
||||
<span class="text-[var(--color-error-fg)]">{rr.error}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,310 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import { t } from '$lib/i18n';
|
||||
import { providersCache } from '$lib/stores/caches.svelte';
|
||||
import { snackSuccess, snackError } from '$lib/stores/snackbar.svelte';
|
||||
import MdiIcon from '$lib/components/MdiIcon.svelte';
|
||||
import IconButton from '$lib/components/IconButton.svelte';
|
||||
import EntitySelect from '$lib/components/EntitySelect.svelte';
|
||||
import MultiEntitySelect from '$lib/components/MultiEntitySelect.svelte';
|
||||
import type { ActionRule } from '$lib/types';
|
||||
|
||||
let { actionId, actionType, providerId }: { actionId: number; actionType: string; providerId: number } = $props();
|
||||
|
||||
let rules = $state<ActionRule[]>([]);
|
||||
let loading = $state(true);
|
||||
let expandedRule = $state<number | null>(null);
|
||||
let showAddForm = $state(false);
|
||||
let submitting = $state(false);
|
||||
|
||||
// People and albums from Immich provider
|
||||
let people = $state<{ id: string; name: string }[]>([]);
|
||||
let albums = $state<{ id: string; name: string }[]>([]);
|
||||
|
||||
// EntitySelect items
|
||||
let personItems = $derived(people.map(p => ({ value: p.id, label: p.name, icon: 'mdiAccount' })));
|
||||
let albumItems = $derived(albums.map(a => ({ value: a.id, label: a.name, icon: 'mdiImageMultiple' })));
|
||||
|
||||
// Temp value for person picker (add-one-at-a-time flow)
|
||||
let personPickerValue = $state<string | null>(null);
|
||||
|
||||
let newRule = $state({
|
||||
name: '',
|
||||
rule_config: {
|
||||
criteria: { person_ids: [] as string[], person_names: [] as string[], query: '', asset_type: 'all', date_from: '', date_to: '', favorite_only: false },
|
||||
target_album_ids: [] as string[], target_album_names: [] as string[],
|
||||
target_album_id: '', target_album_name: '',
|
||||
create_album_if_missing: false, create_album_name: '',
|
||||
},
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
loadRules();
|
||||
loadProviderData();
|
||||
});
|
||||
|
||||
async function loadRules() {
|
||||
loading = true;
|
||||
try {
|
||||
rules = await api<ActionRule[]>(`/actions/${actionId}/rules`);
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
loading = false;
|
||||
}
|
||||
|
||||
async function loadProviderData() {
|
||||
if (actionType !== 'auto_organize') return;
|
||||
const provider = providersCache.items.find((p: any) => p.id === providerId);
|
||||
if (!provider || provider.type !== 'immich') return;
|
||||
try {
|
||||
const [p, a] = await Promise.all([
|
||||
api<any>(`/providers/${providerId}/people`),
|
||||
api<any>(`/providers/${providerId}/collections`),
|
||||
]);
|
||||
people = Array.isArray(p) ? p : [];
|
||||
albums = Array.isArray(a) ? a : [];
|
||||
} catch {
|
||||
// People/album endpoints may not exist yet — degrade gracefully
|
||||
}
|
||||
}
|
||||
|
||||
async function addRule() {
|
||||
submitting = true;
|
||||
try {
|
||||
const maxOrder = rules.reduce((max, r) => Math.max(max, r.order), -1);
|
||||
await api(`/actions/${actionId}/rules`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name: newRule.name, rule_config: newRule.rule_config, order: maxOrder + 1 }),
|
||||
});
|
||||
showAddForm = false;
|
||||
resetNewRule();
|
||||
await loadRules();
|
||||
snackSuccess(t('actions.ruleSaved'));
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
submitting = false;
|
||||
}
|
||||
|
||||
async function updateRule(rule: ActionRule) {
|
||||
try {
|
||||
await api(`/actions/${actionId}/rules/${rule.id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ name: rule.name, rule_config: rule.rule_config, enabled: rule.enabled }),
|
||||
});
|
||||
await loadRules();
|
||||
snackSuccess(t('actions.ruleSaved'));
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
}
|
||||
|
||||
async function deleteRule(ruleId: number) {
|
||||
try {
|
||||
await api(`/actions/${actionId}/rules/${ruleId}`, { method: 'DELETE' });
|
||||
await loadRules();
|
||||
snackSuccess(t('actions.ruleDeleted'));
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
}
|
||||
|
||||
async function toggleRule(rule: ActionRule) {
|
||||
rule.enabled = !rule.enabled;
|
||||
await updateRule(rule);
|
||||
}
|
||||
|
||||
function resetNewRule() {
|
||||
newRule = {
|
||||
name: '',
|
||||
rule_config: {
|
||||
criteria: { person_ids: [], person_names: [], query: '', asset_type: 'all', date_from: '', date_to: '', favorite_only: false },
|
||||
target_album_id: '', target_album_name: '',
|
||||
create_album_if_missing: false, create_album_name: '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function selectPerson(ruleConfig: any, personId: string, personName: string) {
|
||||
const ids = ruleConfig.criteria.person_ids || [];
|
||||
const names = ruleConfig.criteria.person_names || [];
|
||||
if (ids.includes(personId)) {
|
||||
ruleConfig.criteria.person_ids = ids.filter((id: string) => id !== personId);
|
||||
ruleConfig.criteria.person_names = names.filter((n: string) => n !== personName);
|
||||
} else {
|
||||
ruleConfig.criteria.person_ids = [...ids, personId];
|
||||
ruleConfig.criteria.person_names = [...names, personName];
|
||||
}
|
||||
}
|
||||
|
||||
function selectAlbum(ruleConfig: any, albumId: string, albumName: string) {
|
||||
ruleConfig.target_album_id = albumId;
|
||||
ruleConfig.target_album_name = albumName;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="space-y-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 class="text-sm font-semibold">{t('actions.rules')} ({rules.length})</h3>
|
||||
<button onclick={() => { showAddForm = !showAddForm; if (showAddForm) resetNewRule(); }}
|
||||
class="text-xs px-2 py-1 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded hover:opacity-90">
|
||||
{showAddForm ? t('common.cancel') : t('actions.addRule')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<p class="text-sm text-[var(--color-muted-foreground)]">{t('common.loading')}...</p>
|
||||
{/if}
|
||||
|
||||
{#if showAddForm}
|
||||
<div class="border border-[var(--color-border)] rounded-md p-3 space-y-2 bg-[var(--color-muted)]/30">
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">{t('actions.ruleName')}</label>
|
||||
<input bind:value={newRule.name} placeholder={t('actions.ruleNamePlaceholder')}
|
||||
class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
|
||||
{#if actionType === 'auto_organize'}
|
||||
{@render criteriaFields(newRule.rule_config)}
|
||||
{/if}
|
||||
|
||||
<button onclick={addRule} disabled={submitting}
|
||||
class="text-xs px-3 py-1.5 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded hover:opacity-90 disabled:opacity-50">
|
||||
{submitting ? t('common.loading') : t('actions.addRule')}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#each rules as rule}
|
||||
<div class="border border-[var(--color-border)] rounded-md p-3 {!rule.enabled ? 'opacity-60' : ''}">
|
||||
<div class="flex items-center justify-between">
|
||||
<button onclick={() => expandedRule = expandedRule === rule.id ? null : rule.id}
|
||||
class="flex items-center gap-2 text-sm font-medium text-left flex-1">
|
||||
<MdiIcon name={expandedRule === rule.id ? 'mdiChevronDown' : 'mdiChevronRight'} size={16} />
|
||||
{rule.name || t('actions.unnamedRule')}
|
||||
</button>
|
||||
<div class="flex items-center gap-1">
|
||||
<button onclick={() => toggleRule(rule)}
|
||||
class="text-xs px-1.5 py-0.5 rounded {rule.enabled ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'}">
|
||||
{rule.enabled ? t('actions.on') : t('actions.off')}
|
||||
</button>
|
||||
<IconButton icon="mdiDelete" title={t('common.delete')} onclick={() => deleteRule(rule.id)} variant="danger" size={16} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if expandedRule === rule.id}
|
||||
<div class="mt-2 pt-2 border-t border-[var(--color-border)] space-y-2">
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">{t('actions.ruleName')}</label>
|
||||
<input bind:value={rule.name}
|
||||
class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
|
||||
{#if actionType === 'auto_organize'}
|
||||
{@render criteriaFields(rule.rule_config)}
|
||||
{/if}
|
||||
|
||||
<button onclick={() => updateRule(rule)}
|
||||
class="text-xs px-3 py-1.5 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded hover:opacity-90">
|
||||
{t('common.save')}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#if rules.length === 0 && !loading && !showAddForm}
|
||||
<p class="text-sm text-[var(--color-muted-foreground)] text-center py-2">{t('actions.noRules')}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#snippet criteriaFields(ruleConfig: any)}
|
||||
<fieldset class="space-y-2 pl-2 border-l-2 border-[var(--color-border)]">
|
||||
<legend class="text-xs font-semibold text-[var(--color-muted-foreground)] mb-1">{t('actions.criteria')}</legend>
|
||||
|
||||
<!-- Person selector -->
|
||||
{#if personItems.length > 0}
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">{t('actions.persons')}</label>
|
||||
<MultiEntitySelect items={personItems}
|
||||
bind:values={ruleConfig.criteria.person_ids}
|
||||
placeholder={t('actions.addPerson')}
|
||||
size="sm"
|
||||
onchange={(ids) => {
|
||||
ruleConfig.criteria.person_names = ids.map(id => people.find(p => p.id === id)?.name || id);
|
||||
}} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Smart search query -->
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">{t('actions.searchQuery')}</label>
|
||||
<input bind:value={ruleConfig.criteria.query} placeholder={t('actions.searchQueryPlaceholder')}
|
||||
class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
|
||||
<!-- Asset type -->
|
||||
<div class="flex items-center gap-3">
|
||||
<label class="text-xs font-medium">{t('actions.assetType')}:</label>
|
||||
{#each ['all', 'image', 'video'] as at}
|
||||
<label class="flex items-center gap-1 text-xs">
|
||||
<input type="radio"
|
||||
checked={ruleConfig.criteria.asset_type === at}
|
||||
onchange={() => { ruleConfig.criteria.asset_type = at; }}
|
||||
class="accent-[var(--color-primary)]" />
|
||||
{at}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<!-- Date range -->
|
||||
<div class="flex gap-2">
|
||||
<div class="flex-1">
|
||||
<label class="block text-xs font-medium mb-1">{t('actions.dateFrom')}</label>
|
||||
<input type="date" bind:value={ruleConfig.criteria.date_from}
|
||||
class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<label class="block text-xs font-medium mb-1">{t('actions.dateTo')}</label>
|
||||
<input type="date" bind:value={ruleConfig.criteria.date_to}
|
||||
class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Favorites only -->
|
||||
<label class="flex items-center gap-2 text-xs">
|
||||
<input type="checkbox" bind:checked={ruleConfig.criteria.favorite_only} class="accent-[var(--color-primary)]" />
|
||||
{t('actions.favoritesOnly')}
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<!-- Target album -->
|
||||
<fieldset class="space-y-2 pl-2 border-l-2 border-[var(--color-border)]">
|
||||
<legend class="text-xs font-semibold text-[var(--color-muted-foreground)] mb-1">{t('actions.targetAlbum')}</legend>
|
||||
|
||||
{#if albumItems.length > 0}
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">{t('actions.selectAlbum')}</label>
|
||||
<MultiEntitySelect items={albumItems}
|
||||
bind:values={ruleConfig.target_album_ids}
|
||||
placeholder={t('actions.selectAlbumPlaceholder')}
|
||||
size="sm"
|
||||
onchange={(ids) => {
|
||||
ruleConfig.target_album_names = ids.map(id => albums.find(a => a.id === id)?.name || id);
|
||||
}} />
|
||||
</div>
|
||||
{:else}
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">{t('actions.albumId')}</label>
|
||||
<input bind:value={ruleConfig.target_album_id}
|
||||
class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)] font-mono" />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<label class="flex items-center gap-2 text-xs">
|
||||
<input type="checkbox" bind:checked={ruleConfig.create_album_if_missing} class="accent-[var(--color-primary)]" />
|
||||
{t('actions.createAlbumIfMissing')}
|
||||
</label>
|
||||
|
||||
{#if ruleConfig.create_album_if_missing}
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">{t('actions.newAlbumName')}</label>
|
||||
<input bind:value={ruleConfig.create_album_name}
|
||||
class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
{/if}
|
||||
</fieldset>
|
||||
{/snippet}
|
||||
@@ -5,6 +5,7 @@
|
||||
import IconPicker from '$lib/components/IconPicker.svelte';
|
||||
import Hint from '$lib/components/Hint.svelte';
|
||||
import EntitySelect from '$lib/components/EntitySelect.svelte';
|
||||
import MultiEntitySelect from '$lib/components/MultiEntitySelect.svelte';
|
||||
|
||||
interface Props {
|
||||
form: {
|
||||
@@ -18,15 +19,15 @@
|
||||
};
|
||||
providerItems: { value: number; label: string; icon: string; desc: string }[];
|
||||
collections: any[];
|
||||
collectionFilter: string;
|
||||
collectionFilter?: string;
|
||||
editing: number | null;
|
||||
submitting: boolean;
|
||||
linkCheckLoading: boolean;
|
||||
error: string;
|
||||
providerType: string;
|
||||
onsave: (e: SubmitEvent) => void;
|
||||
ontoggleCollection: (collectionId: string) => void;
|
||||
formatDate: (dateStr: string) => string;
|
||||
ontoggleCollection?: (collectionId: string) => void;
|
||||
formatDate?: (dateStr: string) => string;
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -91,22 +92,17 @@
|
||||
</div>
|
||||
{#if !isScheduler && collections.length > 0}
|
||||
<div>
|
||||
<label class="block text-sm font-medium mb-1">{t('notificationTracker.albums')} ({collections.length})</label>
|
||||
<input type="text" bind:value={collectionFilter} placeholder="Filter..."
|
||||
class="w-full px-3 py-1.5 mb-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
<div class="max-h-56 overflow-y-auto border border-[var(--color-border)] rounded-md p-2 space-y-1">
|
||||
{#each collections.filter(a => !collectionFilter || (a.albumName || a.name || '').toLowerCase().includes(collectionFilter.toLowerCase())) as col}
|
||||
<label class="flex items-center justify-between text-sm cursor-pointer hover:bg-[var(--color-muted)] px-2 py-1 rounded">
|
||||
<span class="flex items-center gap-2">
|
||||
<input type="checkbox" checked={form.collection_ids.includes(col.id)} onchange={() => ontoggleCollection(col.id)} />
|
||||
{col.albumName || col.name} <span class="text-[var(--color-muted-foreground)]">({col.assetCount ?? col.asset_count ?? 0})</span>
|
||||
</span>
|
||||
{#if col.updatedAt || col.updated_at}
|
||||
<span class="text-xs text-[var(--color-muted-foreground)] whitespace-nowrap ml-2">{formatDate(col.updatedAt || col.updated_at)}</span>
|
||||
{/if}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
<label class="block text-sm font-medium mb-1">{t('notificationTracker.albums')}</label>
|
||||
<MultiEntitySelect
|
||||
items={collections.map(col => ({
|
||||
value: col.id,
|
||||
label: col.albumName || col.name,
|
||||
icon: 'mdiImageMultiple',
|
||||
desc: `${col.assetCount ?? col.asset_count ?? 0} assets`,
|
||||
}))}
|
||||
bind:values={form.collection_ids}
|
||||
placeholder={t('notificationTracker.selectAlbums')}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user