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:
@@ -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}
|
||||
Reference in New Issue
Block a user